This repository was archived by the owner on Aug 18, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 631
/
Copy pathSwagger.hs
1106 lines (904 loc) · 42.4 KB
/
Swagger.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Cardano.Wallet.API.V1.Swagger where
import Universum hiding (get, put)
import Cardano.Wallet.API.Indices (ParamNames)
import Cardano.Wallet.API.Request.Filter
import Cardano.Wallet.API.Request.Pagination
import Cardano.Wallet.API.Request.Sort
import Cardano.Wallet.API.Response
import Cardano.Wallet.API.Types
import Cardano.Wallet.API.V1.Generic (gconsName)
import Cardano.Wallet.API.V1.Migration.Types (MigrationError (..))
import Cardano.Wallet.API.V1.Parameters
import Cardano.Wallet.API.V1.Swagger.Example
import Cardano.Wallet.API.V1.Types
import Cardano.Wallet.TypeLits (KnownSymbols (..))
import Pos.Chain.Update (SoftwareVersion)
import Pos.Util.CompileInfo (CompileTimeInfo, ctiGitRevision)
import Pos.Util.Servant (CustomQueryFlag, LoggingApi)
import Pos.Wallet.Web.Swagger.Instances.Schema ()
import Control.Lens (At, Index, IxValue, at, (?~))
import Data.Aeson (encode)
import Data.Aeson.Encode.Pretty
import Data.Map (Map)
import Data.Swagger hiding (Example)
import Data.Typeable
import Formatting (build, sformat)
import GHC.TypeLits (KnownSymbol)
import NeatInterpolation
import Servant (Handler, QueryFlag, ServantErr (..), Server,
StdMethod (..))
import Servant.API.Sub
import Servant.Swagger
import Servant.Swagger.UI (SwaggerSchemaUI')
import Servant.Swagger.UI.Core (swaggerSchemaUIServerImpl)
import Servant.Swagger.UI.ReDoc (redocFiles)
import qualified Data.ByteString.Lazy as BL
import qualified Data.Map.Strict as M
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Pos.Core as Core
import qualified Pos.Core.Attributes as Core
import qualified Pos.Crypto.Hashing as Crypto
--
-- Helper functions
--
-- | Surround a Text with another
surroundedBy :: Text -> Text -> Text
surroundedBy wrap context = wrap <> context <> wrap
-- | Display a multi-line code-block inline (e.g. in tables)
inlineCodeBlock :: Text -> Text
inlineCodeBlock txt = "<pre>" <> replaceNewLines (replaceWhiteSpaces txt) <> "</pre>"
where
replaceNewLines = T.replace "\n" "<br/>"
replaceWhiteSpaces = T.replace " " " "
-- | Drill in the 'Swagger' file in an unsafe way to modify a specific operation
-- identified by a tuple (verb, path). The function looks a bit scary to use
-- but is actually rather simple (see example below).
--
-- Note that if the identified path doesn't exist, the function will throw
-- at runtime when trying to read the underlying swagger structure!
--
-- Example:
--
-- swagger
-- & paths %~ (POST, "/api/v1/wallets") `alterOperation` (description ?~ "foo")
-- & paths %~ (GET, "/api/v1/wallets/{walletId}") `alterOperation` (description ?~ "bar")
--
alterOperation ::
( IxValue m ~ item
, Index m ~ FilePath
, At m
, HasGet item (Maybe Operation)
, HasPut item (Maybe Operation)
, HasPatch item (Maybe Operation)
, HasPost item (Maybe Operation)
, HasDelete item (Maybe Operation)
)
=> (StdMethod, FilePath)
-> (Operation -> Operation)
-> m
-> m
alterOperation (verb, path) alter =
at path %~ (Just . unsafeAlterItem)
where
errUnreachableEndpoint :: Text
errUnreachableEndpoint =
"Unreachable endpoint: " <> show verb <> " " <> show path
errUnsupportedVerb :: Text
errUnsupportedVerb =
"Used unsupported verb to identify an endpoint: " <> show verb
unsafeAlterItem ::
( HasGet item (Maybe Operation)
, HasPut item (Maybe Operation)
, HasPatch item (Maybe Operation)
, HasPost item (Maybe Operation)
, HasDelete item (Maybe Operation)
)
=> Maybe item
-> item
unsafeAlterItem = maybe
(error errUnreachableEndpoint)
(unsafeLensFor verb %~ (Just . unsafeAlterOperation))
unsafeAlterOperation :: Maybe Operation -> Operation
unsafeAlterOperation = maybe
(error errUnreachableEndpoint)
alter
unsafeLensFor ::
( Functor f
, HasGet item (Maybe Operation)
, HasPut item (Maybe Operation)
, HasPatch item (Maybe Operation)
, HasPost item (Maybe Operation)
, HasDelete item (Maybe Operation)
)
=> StdMethod
-> (Maybe Operation -> f (Maybe Operation))
-> item
-> f item
unsafeLensFor = \case
GET -> get
PUT -> put
PATCH -> patch
POST -> post
DELETE -> delete
_ -> error errUnsupportedVerb
-- | A combinator to modify the description of an operation, using
-- 'alterOperation' under the hood.
--
--
-- Example:
--
-- swagger
-- & paths %~ (POST, "/api/v1/wallets") `setDescription` "foo"
-- & paths %~ (GET, "/api/v1/wallets/{walletId}") `setDescription` "bar"
setDescription
:: (IxValue m ~ PathItem, Index m ~ FilePath, At m)
=> (StdMethod, FilePath)
-> Text
-> m
-> m
setDescription endpoint str =
endpoint `alterOperation` (description ?~ str)
--
-- Instances
--
instance HasSwagger a => HasSwagger (LoggingApi config a) where
toSwagger _ = toSwagger (Proxy @a)
instance HasSwagger (apiType a :> res) =>
HasSwagger (WithDefaultApiArg apiType a :> res) where
toSwagger _ = toSwagger (Proxy @(apiType a :> res))
instance HasSwagger (argA a :> argB a :> res) =>
HasSwagger (AlternativeApiArg argA argB a :> res) where
toSwagger _ = toSwagger (Proxy @(argA a :> argB a :> res))
instance (KnownSymbols tags, HasSwagger subApi) => HasSwagger (Tags tags :> subApi) where
toSwagger _ =
let newTags = map toText (symbolVals (Proxy @tags))
swgr = toSwagger (Proxy @subApi)
in swgr & over (operationsOf swgr . tags) (mappend (Set.fromList newTags))
instance
( Typeable res
, KnownSymbols syms
, HasSwagger subApi
, syms ~ ParamNames res params
) => HasSwagger (FilterBy params res :> subApi) where
toSwagger _ =
let swgr = toSwagger (Proxy @subApi)
allOps = map toText $ symbolVals (Proxy @syms)
in swgr & over (operationsOf swgr . parameters) (addFilterOperations allOps)
where
addFilterOperations :: [Text] -> [Referenced Param] -> [Referenced Param]
addFilterOperations ops xs = map (Inline . newParam) ops <> xs
newParam :: Text -> Param
newParam opName =
let typeOfRes = fromString $ show $ typeRep (Proxy @ res)
in Param {
_paramName = opName
, _paramRequired = Nothing
, _paramDescription = Just $ filterDescription typeOfRes
, _paramSchema = ParamOther ParamOtherSchema {
_paramOtherSchemaIn = ParamQuery
, _paramOtherSchemaAllowEmptyValue = Nothing
, _paramOtherSchemaParamSchema = mempty
}
}
filterDescription :: Text -> Text
filterDescription typeOfRes = mconcat
[ "A **FILTER** operation on a " <> typeOfRes <> ". "
, "Filters support a variety of queries on the resource. "
, "These are: \n\n"
, "- `EQ[value]` : only allow values equal to `value`\n"
, "- `LT[value]` : allow resource with attribute less than the `value`\n"
, "- `GT[value]` : allow objects with an attribute greater than the `value`\n"
, "- `GTE[value]` : allow objects with an attribute at least the `value`\n"
, "- `LTE[value]` : allow objects with an attribute at most the `value`\n"
, "- `RANGE[lo,hi]` : allow objects with the attribute in the range between `lo` and `hi`\n"
, "- `IN[a,b,c,d]` : allow objects with the attribute belonging to one provided.\n\n"
]
instance
( Typeable res
, KnownSymbols syms
, syms ~ ParamNames res params
, HasSwagger subApi
) => HasSwagger (SortBy params res :> subApi) where
toSwagger _ =
let swgr = toSwagger (Proxy @subApi)
in swgr & over (operationsOf swgr . parameters) addSortOperation
where
addSortOperation :: [Referenced Param] -> [Referenced Param]
addSortOperation xs = Inline newParam : xs
newParam :: Param
newParam =
let typeOfRes = fromString $ show $ typeRep (Proxy @ res)
allowedKeys = T.intercalate "," (map toText $ symbolVals (Proxy @syms))
in Param {
_paramName = "sort_by"
, _paramRequired = Just False
, _paramDescription = Just (sortDescription typeOfRes allowedKeys)
, _paramSchema = ParamOther ParamOtherSchema {
_paramOtherSchemaIn = ParamQuery
, _paramOtherSchemaAllowEmptyValue = Just True
, _paramOtherSchemaParamSchema = mempty
}
}
instance (HasSwagger subApi) => HasSwagger (WalletRequestParams :> subApi) where
toSwagger _ =
let swgr = toSwagger (Proxy @(WithWalletRequestParams subApi))
in swgr & over (operationsOf swgr . parameters) (map toDescription)
where
toDescription :: Referenced Param -> Referenced Param
toDescription (Inline p@(_paramName -> pName)) =
case M.lookup pName requestParameterToDescription of
Nothing -> Inline p
Just d -> Inline (p & description .~ Just d)
toDescription x = x
instance ToParamSchema WalletId
instance ToParamSchema PublicKeyAsBase58 where
toParamSchema _ = mempty
& type_ .~ SwaggerString
instance ToSchema Core.Address where
declareNamedSchema = pure . paramSchemaToNamedSchema defaultSchemaOptions
instance ToParamSchema Core.Address where
toParamSchema _ = mempty
& type_ .~ SwaggerString
instance ToParamSchema (V1 Core.Address) where
toParamSchema _ = toParamSchema (Proxy @Core.Address)
instance ( KnownSymbol sym
, HasSwagger sub
) =>
HasSwagger (CustomQueryFlag sym flag :> sub) where
toSwagger _ =
let swgr = toSwagger (Proxy @(QueryFlag sym :> sub))
in swgr & over (operationsOf swgr . parameters) (map toDescription)
where
toDescription :: Referenced Param -> Referenced Param
toDescription (Inline p@(_paramName -> pName)) =
case M.lookup pName customQueryFlagToDescription of
Nothing -> Inline p
Just d -> Inline (p & description .~ Just d)
toDescription x = x
--
-- Descriptions
--
customQueryFlagToDescription :: Map T.Text T.Text
customQueryFlagToDescription = M.fromList [
("force_ntp_check", forceNtpCheckDescription)
]
requestParameterToDescription :: Map T.Text T.Text
requestParameterToDescription = M.fromList [
("page", pageDescription)
, ("per_page", perPageDescription (fromString $ show maxPerPageEntries) (fromString $ show defaultPerPageEntries))
]
-- TODO: it would be nice to read ntp configuration directly here to fetch
-- 30 seconds wait time instead of hardcoding it here.
forceNtpCheckDescription :: T.Text
forceNtpCheckDescription = [text|
In some cases, API Clients need to force a new NTP check as a previous result gets cached. A typical use-case is after asking a user to fix its system clock. If this flag is set, request will block until NTP server responds or it will timout if NTP server is not available within **30** seconds.
|]
pageDescription :: T.Text
pageDescription = [text|
The page number to fetch for this request. The minimum is **1**. If nothing is specified, **this value defaults to 1** and always shows the first entries in the requested collection.
|]
perPageDescription :: T.Text -> T.Text -> T.Text
perPageDescription maxValue defaultValue = [text|
The number of entries to display for each page. The minimum is **1**, whereas the maximum is **$maxValue**. If nothing is specified, **this value defaults to $defaultValue**.
|]
sortDescription :: Text -> Text -> Text
sortDescription resource allowedKeys = [text|
A **SORT** operation on this $resource. Allowed keys: `$allowedKeys`.
|]
errorsDescription :: Text
errorsDescription = [text|
Error Name / Description | HTTP Error code | Example
-------------------------|-----------------|---------
$errors
|] where
errors = T.intercalate "\n" rows
rows =
-- 'WalletError'
[ mkRow fmtErr $ NotEnoughMoney (ErrAvailableBalanceIsInsufficient 1400)
, mkRow fmtErr $ OutputIsRedeem sampleAddress
, mkRow fmtErr $ UnknownError "Unknown error."
, mkRow fmtErr $ InvalidAddressFormat "Invalid Base58 representation."
, mkRow fmtErr WalletNotFound
, mkRow fmtErr $ WalletAlreadyExists exampleWalletId
, mkRow fmtErr AddressNotFound
, mkRow fmtErr $ InvalidPublicKey "Invalid root public key for external wallet."
, mkRow fmtErr UnsignedTxCreationError
, mkRow fmtErr $ SignedTxSubmitError "Cannot submit externally-signed transaction."
, mkRow fmtErr TooBigTransaction
, mkRow fmtErr TxFailedToStabilize
, mkRow fmtErr TxRedemptionDepleted
, mkRow fmtErr $ TxSafeSignerNotFound sampleAddress
, mkRow fmtErr $ MissingRequiredParams (("wallet_id", "walletId") :| [])
, mkRow fmtErr $ WalletIsNotReadyToProcessPayments genExample
, mkRow fmtErr $ NodeIsStillSyncing genExample
, mkRow fmtErr $ CannotCreateAddress "Cannot create derivation path for new address in external wallet."
, mkRow fmtErr $ RequestThrottled 42
-- 'MigrationError'
, mkRow fmtErr $ MigrationFailed "Migration failed."
-- 'JSONValidationError'
, mkRow fmtErr $ JSONValidationFailed "Expected String, found Null."
-- 'UnsupportedMimeTypeError'
, mkRow fmtErr $ UnsupportedMimeTypePresent "Expected Content-Type's main MIME-type to be 'application/json'."
-- TODO 'MnemonicError' ?
]
mkRow fmt err = T.intercalate "|" (fmt err)
fmtErr err =
[ surroundedBy "`" (gconsName err) <> "<br/>" <> toText (sformat build err)
, show $ errHTTPCode $ toServantError err
, inlineCodeBlock (T.decodeUtf8 $ BL.toStrict $ encodePretty err)
]
sampleAddress = V1 Core.Address
{ Core.addrRoot =
Crypto.unsafeAbstractHash ("asdfasdf" :: String)
, Core.addrAttributes =
Core.mkAttributes $ Core.AddrAttributes Nothing Core.BootstrapEraDistr
, Core.addrType =
Core.ATPubKey
}
-- | Shorter version of the doc below, only for Dev & V0 documentations
highLevelShortDescription :: DescriptionEnvironment -> T.Text
highLevelShortDescription DescriptionEnvironment{..} = [text|
This is the specification for the Cardano Wallet API, automatically generated as a [Swagger](https://swagger.io/) spec from the [Servant](http://haskell-servant.readthedocs.io/en/stable/) API of [Cardano](https://github.com/input-output-hk/cardano-sl).
Software Version | Git Revision
-------------------|-------------------
$deSoftwareVersion | $deGitRevision
|]
-- | Provide additional insights on V1 documentation
highLevelDescription :: DescriptionEnvironment -> T.Text
highLevelDescription DescriptionEnvironment{..} = [text|
This is the specification for the Cardano Wallet API, automatically generated as a [Swagger](https://swagger.io/) spec from the [Servant](http://haskell-servant.readthedocs.io/en/stable/) API of [Cardano](https://github.com/input-output-hk/cardano-sl).
Software Version | Git Revision
-------------------|-------------------
$deSoftwareVersion | $deGitRevision
Getting Started
===============
In the following examples, we will use *curl* to illustrate request to an API running on the default port **8090**.
Please note that wallet web API uses TLS for secure communication. Requests to the API need to
send a client CA certificate that was used when launching the node and identifies the client as
being permitted to invoke the server API.
Creating a New Wallet
---------------------
You can create your first wallet using the [`POST /api/v1/wallets`](#tag/Wallets%2Fpaths%2F~1api~1v1~1wallets%2Fpost) endpoint as follow:
```
curl -X POST https://localhost:8090/api/v1/wallets \
-H "Accept: application/json; charset=utf-8" \
-H "Content-Type: application/json; charset=utf-8" \
--cert ./scripts/tls-files/client.pem \
--cacert ./scripts/tls-files/ca.crt \
-d '{
"operation": "create",
"backupPhrase": [$deMnemonicExample],
"assuranceLevel": "normal",
"name": "MyFirstWallet",
"spendingPassword": "5416b2988745725998907addf4613c9b0764f04959030e1b81c603b920a115d0"
}'
```
> **Warning**: Those 12 mnemonic words given for the backup phrase act as an example. **Do
> not** use them on a production system. See the section below about mnemonic codes for more
> information.
The `spendingPassword` is optional but highly recommended. It a string of 32
characters, encoded in base 16, yielding to an hexadecimal sequence of 64 bytes.
This passphrase is required for sensitive operations on the wallet and adds
an extra security layer to it.
To generate a valid `spendingPassword`, please follow the following steps:
- Pick a long sentence using a wide variety of characters (uppercase, lowercase,
whitespace, punctuation, etc). Using a computer to randomly generate
a passphrase is best, as humans aren't a good source of randomness.
- Compute an appropriate hash of this passphrase. You'll need to use an
algorithm that yields a 32-byte long string (e.g. *SHA256* or *BLAKE2b*).
- Hex-encode the 32-byte hash into a 64-byte sequence of bytes.
As a response, the API provides you with a unique wallet `id` to be used in subsequent
requests. Make sure to store it / write it down. Note that every API response is
[jsend-compliant](https://labs.omniti.com/labs/jsend); Cardano also augments responses with
meta-data specific to pagination. More details in the section below about [Pagination](#section/Pagination)
```json
$createWallet
```
You have just created your first wallet. Information about this wallet can be retrieved using the [`GET /api/v1/wallets/{walletId}`](#tag/Wallets%2Fpaths%2F~1api~1v1~1wallets~1{walletId}%2Fget)
endpoint as follows:
```
curl -X GET https://localhost:8090/api/v1/wallets/{{walletId}} \
-H "Accept: application/json; charset=utf-8" \
--cacert ./scripts/tls-files/ca.crt \
--cert ./scripts/tls-files/client.pem
```
Receiving ADA
-------------
To receive _ADA_ from other users you should provide your address. This address can be obtained
from an account. Each wallet contains at least one account. An account is like a pocket inside
of your wallet. Vew all existing accounts of a wallet by using the [`GET /api/v1/wallets/{{walletId}}/accounts`](#tag/Accounts%2Fpaths%2F~1api~1v1~1wallets~1{walletId}~1accounts%2Fget)
endpoint:
```
curl -X GET https://localhost:8090/api/v1/wallets/{{walletId}}/accounts?page=1&per_page=10 \
-H "Accept: application/json; charset=utf-8" \
--cacert ./scripts/tls-files/ca.crt \
--cert ./scripts/tls-files/client.pem
```
Since you have, for now, only a single wallet, you'll see something like this:
```json
$readAccounts
```
All the wallet's accounts are listed under the `addresses` field. You can communicate one of
these addresses to receive _ADA_ on the associated account.
Sending ADA
-----------
In order to send _ADA_ from one of your accounts to another address, you must create a new
payment transaction using the [`POST /api/v1/transactions`](#tag/Transactions%2Fpaths%2F~1api~1v1~1transactions%2Fpost)
endpoint as follows:
```
curl -X POST https://localhost:8090/api/v1/transactions \
-H "Accept: application/json; charset=utf-8" \
-H "Content-Type: application/json; charset=utf-8" \
--cacert ./scripts/tls-files/ca.crt \
--cert ./scripts/tls-files/client.pem \
-d '{
"destinations": [{
"amount": 14,
"address": "A7k5bz1QR2...Tx561NNmfF"
}],
"source": {
"accountIndex": 0,
"walletId": "Ae2tdPwUPE...8V3AVTnqGZ"
},
"spendingPassword": "5416b2988745725998907addf4613c9b0764f04959030e1b81c603b920a115d0"
}'
```
Note that, in order to perform a transaction, you need to have enough existing _ADA_ on the
source account! The Cardano API is designed to accomodate multiple recipients payments
out-of-the-box; notice how `destinations` is a list of addresses (and corresponding amounts).
When the transaction succeeds, funds are no longer available in the sources addresses, and are
soon made available to the destinations within a short delay. Note that, you can at any time see
the status of your wallets by using the [`GET /api/v1/transactions`](#tag/Transactions%2Fpaths%2F~1api~1v1~1transactions%2Fget)
endpoint as follows:
```
curl -X GET https://localhost:8090/api/v1/transactions?wallet_id=Ae2tdPwUPE...8V3AVTnqGZ\
-H "Accept: application/json; charset=utf-8" \
--cacert ./scripts/tls-files/ca.crt \
--cert ./scripts/tls-files/client.pem
```
Here we constrained the request to a specific account. After our previous transaction the output
should look roughly similar to this:
```json
$readTransactions
```
In addition, and because it is not possible to _preview_ a transaction, one can lookup a
transaction's fees using the [`POST /api/v1/transactions/fees`](#tag/Transactions%2Fpaths%2F~1api~1v1~1transactions~1fees%2Fpost)
endpoint to get an estimation of those fees.
See [Estimating Transaction Fees](#section/Common-Use-Cases/Estimating-Transaction-Fees) for more details.
Pagination
==========
**All GET requests of the API are paginated by default**. Whilst this can be a source of
surprise, is the best way of ensuring the performance of GET requests is not affected by the
size of the data storage.
Version `V1` introduced a different way of requesting information to the API. In particular,
GET requests which returns a _collection_ (i.e. typically a JSON array of resources) lists
extra parameters which can be used to modify the shape of the response. In particular, those
are:
* `page`: (Default value: **1**).
* `per_page`: (Default value: **$deDefaultPerPage**)
For a more accurate description, see the section `Parameters` of each GET request, but as a
brief overview the first two control how many results and which results to access in a
paginated request.
Filtering and Sorting
=====================
`GET` endpoints which list collection of resources supports filters & sort operations, which
are clearly marked in the swagger docs with the `FILTER` or `SORT` labels. The query format is
quite simple, and it goes this way:
Filter Operators
----------------
| Operator | Description | Example |
|----------|---------------------------------------------------------------------------|------------------------|
| - | If **no operator** is passed, this is equivalent to `EQ` (see below). | `balance=10` |
| `EQ` | Retrieves the resources with index _equal_ to the one provided. | `balance=EQ[10]` |
| `LT` | Retrieves the resources with index _less than_ the one provided. | `balance=LT[10]` |
| `LTE` | Retrieves the resources with index _less than equal_ the one provided. | `balance=LTE[10]` |
| `GT` | Retrieves the resources with index _greater than_ the one provided. | `balance=GT[10]` |
| `GTE` | Retrieves the resources with index _greater than equal_ the one provided. | `balance=GTE[10]` |
| `RANGE` | Retrieves the resources with index _within the inclusive range_ [k,k]. | `balance=RANGE[10,20]` |
Sort Operators
--------------
| Operator | Description | Example |
|----------|---------------------------------------------------------------------------|------------------------|
| `ASC` | Sorts the resources with the given index in _ascending_ order. | `sort_by=ASC[balance]` |
| `DES` | Sorts the resources with the given index in _descending_ order. | `sort_by=DES[balance]` |
| - | If **no operator** is passed, this is equivalent to `DES` (see above). | `sort_by=balance` |
Errors
======
In case a request cannot be served by the API, a non-2xx HTTP response will be issued, together
with a [JSend-compliant](https://labs.omniti.com/labs/jsend) JSON Object describing the error
in detail together with a numeric error code which can be used by API consumers to implement
proper error handling in their application. For example, here's a typical error which might be
issued:
``` json
$deErrorExample
```
Existing Wallet Errors
----------------------
$deWalletErrorTable
Monetary Denomination & Units
=============================
Cardano's currency is called _ADA_ ( ₳ ). _ADA_ has up to **6** decimal places; hence the
smallest monetary unit that can be represented in the Cardano's blockhain is: 0.000001₳. This
is also called a _Lovelace_ (Cardano's currency is named after the mathematician and computer
scientist [Ada Lovelace](https://en.wikipedia.org/wiki/Ada_Lovelace)). Put in another way, one
_ADA_ is equal to one million _Lovelace_.
ADA | Lovelace
-----------|----------
`1` | `1 000 000`
`.000 001` | `1`
> **Warning**: All amounts manipulated in the API are given and expected in Lovelace.
Mnemonic Codes
==============
The full list of accepted mnemonic codes to secure a wallet is defined by the [BIP-39
specifications](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki). Note that
picking up 12 random words from the list **is not enough** and leads to poor security. Make
sure to carefully follow the steps described in the protocol when you generate words for a new
wallet.
Versioning & Legacy
===================
The API is **versioned**, meaning that is possible to access different versions of the API by adding the _version number_ in the URL.
**For the sake of backward compatibility, we expose the legacy version of the API, available simply as unversioned endpoints.**
This means that _omitting_ the version number would call the old version of the API. Deprecated
endpoints are currently grouped under an appropriate section; they would be removed in upcoming
released, if you're starting a new integration with Cardano-SL, please ignore these.
Note that Compatibility between major versions is not _guaranteed_, i.e. the request & response formats might differ.
Disable TLS (Not Recommended)
-----------------------------
If needed, you can disable TLS by providing the `--no-tls` flag to the wallet or by running a wallet in debug mode with `--wallet-debug` turned on.
Common Use-Cases
================
Sending Money to Multiple Recipients
------------------------------------
As seen in [Sending ADA](#section/Getting-Started/Sending-ADA), you can send _ADA_ to
another party using the [`POST /api/v1/transactions`](#tag/Transactions%2Fpaths%2F~1api~1v1~1transactions%2Fpost) endpoint.
Important to notice is the type of the field `destinations`: it's a list, enabling you to provide more
than one destination. Each destination is composed of:
- An address
- A corresponding amount
The overall transaction corresponds to the sum of each outputs. For instance, to send money to
two parties simultaneously:
```
curl -X POST https://localhost:8090/api/v1/transactions \
-H "Accept: application/json; charset=utf-8" \
-H "Content-Type: application/json; charset=utf-8" \
--cacert ./scripts/tls-files/ca.crt \
--cert ./scripts/tls-files/client.pem \
-d '{
"destinations": [
{
"amount": 14,
"address": "A7k5bz1QR2...Tx561NNmfF"
},
{
"amount": 42,
"address": "B56n78WKE8...jXAa34NUFz"
}
],
"source": {
"accountIndex": 0,
"walletId": "Ae2tdPwUPE...8V3AVTnqGZ"
},
"spendingPassword": "5416b2988745725998907addf4613c9b0764f04959030e1b81c603b920a115d0"
}'
```
Estimating Transaction Fees
---------------------------
When you submit a transaction to the network, some fees apply depending on, but not only, the
selected grouping policy and the available inputs on the source wallet. There's actually a
trade-off between fees, cryptographic security, throughput and privacy. The more inputs are
selected, the bigger is the payload, the bigger are the fees.
The API lets you estimate fees for a given transaction via the [`POST /api/v1/transaction/fees`](#tag/Transactions%2Fpaths%2F~1api~1v1~1transactions~1fees%2Fpost)
endpoint. The request payload is identical to the one you would make to create a transaction:
```
curl -X POST https://localhost:8090/api/v1/transactions/fees \
-H "Accept: application/json; charset=utf-8" \
-H "Content-Type: application/json; charset=utf-8" \
--cacert ./scripts/tls-files/ca.crt \
--cert ./scripts/tls-files/client.pem \
-d '{
"destinations": [{
"amount": 14,
"address": "A7k5bz1QR2...Tx561NNmfF"
}],
"source": {
"accountIndex": 0,
"walletId": "Ae2tdPwUPE...8V3AVTnqGZ"
}
}'
```
The API resolves with an estimated amount in _ADA_. This estimation highly depends on the
current state of the ledger and diverges with time.
```json
$readFees
```
Managing Accounts
-----------------
A wallet isn't limited to one account. It can actually be useful to have more than one account
in order to separate business activities. With the API, you can retrieve a specific account,
create new ones, list all existing accounts of a wallet or edit a few things on an existing
account. By default, your wallet comes with a provided account. Let's see how to create a fresh
new account on a wallet using [`POST /api/v1/wallets/{{walletId}}/accounts`](#tag/Accounts%2Fpaths%2F~1api~1v1~1wallets~1{walletId}~1accounts%2Fpost):
```
curl -X POST \
https://localhost:8090/api/v1/Ae2tdPwUPE...8V3AVTnqGZ/accounts \
-H 'Content-Type: application/json;charset=utf-8' \
-H 'Accept: application/json;charset=utf-8' \
--cacert ./scripts/tls-files/ca.crt \
--cert ./scripts/tls-files/client.pem \
-d '{
"name": "MyOtherAccount",
"spendingPassword": "5416b2988745725998907addf4613c9b0764f04959030e1b81c603b920a115d0"
}'
```
Note that the `spendingPassword` here should match the one provided earlier in [Creating a
New Wallet](#section/Getting-Started/Creating-a-New-Wallet).
```json
$createAccount
```
You can always retrieve this account description later if needed via [`GET /api/v1/wallets/{{walletId}}/accounts/{{accountId}}`](#tag/Accounts%2Fpaths%2F~1api~1v1~1wallets~1{walletId}~1accounts~1{accountId}%2Fget).
For example:
```
curl -X GET \
https://127.0.0.1:8090/api/v1/wallets/Ae2tdPwUPE...8V3AVTnqGZ/accounts/2902829384 \
-H 'Accept: application/json;charset=utf-8' \
--cacert ./scripts/tls-files/ca.crt \
--cert ./scripts/tls-files/client.pem
```
For a broader view, the full list of accounts of a given wallet can be retrieved using [`GET /api/v1/wallets/{{walletId}}/accounts`](#tag/Accounts%2Fpaths%2F~1api~1v1~1wallets~1{walletId}~1accounts%2Fget)
```
curl -X GET \
https://127.0.0.1:8090/api/v1/wallets/Ae2tdPwUPE...8V3AVTnqGZ/accounts \
-H 'Accept: application/json;charset=utf-8' \
--cacert ./scripts/tls-files/ca.crt \
--cert ./scripts/tls-files/client.pem
```
```json
$readAccounts
```
Partial Representations
-----------------------
The previous endpoint gives you a list of full representations. However, in some cases, it might be interesting to retrieve only a partial representation of an account (e.g. only the balance). There are two extra endpoints one could use to either fetch a given account's balance, and another to retrieve the list of addresses associated to a specific account.
[`GET /api/v1/wallets/{{walletId}}/accounts/{{accountId}}/addresses`](#tag/Accounts%2Fpaths%2F~1api~1v1~1wallets~1%7BwalletId%7D~1accounts~1%7BaccountId%7D~1addresses%2Fget)
```json
$readAccountAddresses
```
Note that this endpoint is paginated and allow basic filtering and sorting on
addresses. Similarly, you can retrieve only the account balance with:
[`GET /api/v1/wallets/{{walletId}}/accounts/{{accountId}}/amount`](#tag/Accounts%2Fpaths%2F~1api~1v1~1wallets~1%7BwalletId%7D~1accounts~1%7BaccountId%7D~1amount%2Fget)
```json
$readAccountBalance
```
Managing Addresses
------------------
By default, wallets you create are provided with an account which has one default address. It
is possible (and recommended) for an account to manage multiple addresses. Address reuse
actually reduces privacy for it tights more transactions to a small set of addresses.
When paying, the wallet makes many of these choices for you. Addresses are
selected from a wallet's account based on several different strategies and
policies.
To create a new address, use the [`POST /api/v1/addresses`](#tag/Addresses%2Fpaths%2F~1api~1v1~1addresses%2Fpost)
endpoint:
```
curl -X POST \
https://localhost:8090/api/v1/addresses \
-H 'Content-Type: application/json;charset=utf-8' \
-H 'Accept: application/json;charset=utf-8' \
--cacert ./scripts/tls-files/ca.crt \
--cert ./scripts/tls-files/client.pem \
-d '{
"walletId": "Ae2tdPwUPE...V3AVTnqGZ4",
"accountIndex": 2147483648
}'
```
```json
$createAddress
```
If your wallet is protected with a password, this password is also required in order to create
new addresses for that wallet. In such case, the field `spendingPassword` should match the one
defined earlier to protect your wallet.
Addresses generated as just described are always valid. When the API encounters
an invalid address however (e.g. when provided by another party), it will fail with a
client error.
You can always view all your available addresses across all your wallets by using
[`GET /api/v1/addresses`](#tag/Addresses%2Fpaths%2F~1api~1v1~1addresses%2Fget):
```
curl -X GET https://localhost:8090/api/v1/addresses \
-H 'Accept: application/json;charset=utf-8' \
--cacert ./scripts/tls-files/ca.crt \
--cert ./scripts/tls-files/client.pem
```
```json
$readAddresses
```
Checking Synchronization Progress
---------------------------------
You can control the synchronization progress of the underlying node hosting the wallet's server
via [`GET /api/v1/node-info`](#tag/Info%2Fpaths%2F~1api~1v1~1node-info%2Fget). The output is
rather verbose and gives real-time progress updates about the current node.
```
curl -X GET https://localhost:8090/api/v1/node-info \
-H 'Accept: application/json;charset=utf-8' \
--cacert ./scripts/tls-files/ca.crt \
--cert ./scripts/tls-files/client.pem
```
```json
$readNodeInfo
```
Retrieving Transaction History
------------------------------
If needed, applications may regularly poll the wallet's backend to retrieve the history of
transactions of a given wallet. Using the [`GET /api/v1/transactions`](#tag/Transactions%2Fpaths%2F~1api~1v1~1transactions%2Fget)
endpoint, you can view the status of all transactions that ever sent or took money from the
wallet.
The following table sums up the available filters (also detailed in the endpoint documentation details):
Filter On | Corresponding Query Parameter(s)
----------------------------| ------------------------------
Wallet | `wallet_id`
Wallet's account | `account_index` + `wallet_id`
Address | `address`
Transaction's creation time | `created_at`
Transaction's id | `id`
For example, in order to retrieve the last 50 transactions of a particular account,
ordered by descending date:
```
curl -X GET https://127.0.0.1:8090/api/v1/transactions?wallet_id=Ae2tdPwU...3AVTnqGZ&account_index=2902829384&sort_by=DES\[created_at\]&per_page=50' \
-H 'Accept: application/json;charset=utf-8' \
--cacert ./scripts/tls-files/ca.crt \
--cert ./scripts/tls-files/client.pem
```
For example, in order to retrieve the last 50 transactions, ordered by descending date:
```
curl -X GET 'https://127.0.0.1:8090/api/v1/transactions?wallet_id=Ae2tdPwU...3AVTnqGZ &sort_by=DES\[created_at\]&per_page=50' \
-H 'Accept: application/json;charset=utf-8' \
--cacert ./scripts/tls-files/ca.crt \
--cert ./scripts/tls-files/client.pem
```
Another example, if you were to look for all transactions made since the 1st of January 2018:
```
curl -X GET 'https://127.0.0.1:8090/api/v1/transactions?wallet_id=Ae2tdPwU...3AVTnqGZ&created_at=GT\[2018-01-01T00:00:00.00000\]' \
-H 'Accept: application/json;charset=utf-8' \
--cacert ./scripts/tls-files/ca.crt \
--cert ./scripts/tls-files/client.pem
```
Getting Utxo statistics
---------------------------------
You can get Utxo statistics of a given wallet using
[`GET /api/v1/wallets/{{walletId}}/statistics/utxos`](#tag/Accounts%2Fpaths%2F~1api~1v1~1wallets~1{walletId}~1statistics~1utxos%2Fget)
```
curl -X GET \
https://127.0.0.1:8090/api/v1/wallets/Ae2tdPwUPE...8V3AVTnqGZ/statistics/utxos \
-H 'Accept: application/json;charset=utf-8' \
--cacert ./scripts/tls-files/ca.crt \
--cert ./scripts/tls-files/client.pem
```
```json
$readUtxoStatistics
```
Make sure to carefully read the section about [Pagination](#section/Pagination) to fully
leverage the API capabilities.
|]
where
createAccount = decodeUtf8 $ encodePretty $ genExample @(WalletResponse Account)
createAddress = decodeUtf8 $ encodePretty $ genExample @(WalletResponse WalletAddress)
createWallet = decodeUtf8 $ encodePretty $ genExample @(WalletResponse Wallet)
readAccounts = decodeUtf8 $ encodePretty $ genExample @(WalletResponse [Account])
readAccountBalance = decodeUtf8 $ encodePretty $ genExample @(WalletResponse AccountBalance)
readAccountAddresses = decodeUtf8 $ encodePretty $ genExample @(WalletResponse AccountAddresses)
readAddresses = decodeUtf8 $ encodePretty $ genExample @(WalletResponse [Address])
readFees = decodeUtf8 $ encodePretty $ genExample @(WalletResponse EstimatedFees)
readNodeInfo = decodeUtf8 $ encodePretty $ genExample @(WalletResponse NodeInfo)
readTransactions = decodeUtf8 $ encodePretty $ genExample @(WalletResponse [Transaction])
readUtxoStatistics = decodeUtf8 $ encodePretty $ genExample @(WalletResponse UtxoStatistics)
-- | Provide an alternative UI (ReDoc) for rendering Swagger documentation.
swaggerSchemaUIServer
:: (Server api ~ Handler Swagger)
=> Swagger -> Server (SwaggerSchemaUI' dir api)
swaggerSchemaUIServer =