/
Types.hs
1624 lines (1387 loc) · 56.3 KB
/
Types.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 AllowAmbiguousTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- API type representations of various types. We define here pretty much all our
-- user-facing types that are mostly composed with internal / primitive types.
--
-- This module also define required API instances (JSON, HttpApiData...) for all
-- those types, making sure to match the specification document:
--
-- <https://github.com/input-output-hk/cardano-wallet/blob/master/specifications/api/swagger.yaml Wallet API Specification>
module Cardano.Wallet.Api.Types
(
-- * Wallet Styles
WalletStyle (..)
, ByronWalletStyle (..)
, StyleSymbol
, AllowedMnemonics
, fmtAllowedWords
-- * API Types
, ApiAddress (..)
, ApiEpochInfo (..)
, ApiSelectCoinsData (..)
, ApiCoinSelection (..)
, ApiCoinSelectionInput (..)
, ApiStakePool (..)
, ApiStakePoolMetrics (..)
, ApiWallet (..)
, ApiWalletPassphrase (..)
, ApiWalletPassphraseInfo (..)
, ApiUtxoStatistics (..)
, toApiUtxoStatistics
, WalletBalance (..)
, WalletPostData (..)
, WalletPutData (..)
, WalletPutPassphraseData (..)
, PostTransactionData (..)
, PostTransactionFeeData (..)
, PostExternalTransactionData (..)
, ApiTimeReference (..)
, ApiTransaction (..)
, ApiWithdrawalPostData (..)
, ApiFee (..)
, ApiTxId (..)
, ApiTxInput (..)
, ApiTxMetadata (..)
, AddressAmount (..)
, ApiErrorCode (..)
, ApiNetworkInformation (..)
, ApiNtpStatus (..)
, NtpSyncingStatus (..)
, ApiNetworkClock (..)
, ApiBlockReference (..)
, ApiNetworkTip (..)
, Iso8601Time (..)
, MinWithdrawal (..)
, ApiNetworkParameters (..)
, toApiNetworkParameters
, ApiWalletDelegation (..)
, ApiWalletDelegationStatus (..)
, ApiWalletDelegationNext (..)
, ApiPoolId (..)
, ApiWalletMigrationPostData (..)
, ApiWalletMigrationInfo (..)
, ApiWithdrawal (..)
-- * API Types (Byron)
, ApiByronWallet (..)
, ApiByronWalletBalance (..)
, ByronWalletPostData (..)
, SomeByronWalletPostData (..)
, ByronWalletFromXPrvPostData (..)
, ByronWalletPutPassphraseData (..)
, ApiPostRandomAddressData (..)
, ApiWalletDiscovery (..)
, KnownDiscovery(..)
, ApiPutAddressesData (..)
-- * API Types (Hardware)
, AccountPostData (..)
, ApiAccountPublicKey (..)
, WalletOrAccountPostData (..)
-- * User-Facing Address Encoding/Decoding
, EncodeAddress (..)
, DecodeAddress (..)
, EncodeStakeAddress (..)
, DecodeStakeAddress (..)
-- * Polymorphic Types
, ApiT (..)
, ApiMnemonicT (..)
-- * Type families
, ApiAddressT
, ApiPutAddressesDataT
, ApiAddressIdT
, ApiCoinSelectionT
, ApiSelectCoinsDataT
, ApiTransactionT
, PostTransactionDataT
, PostTransactionFeeDataT
, ApiWalletMigrationPostDataT
) where
import Prelude
import Cardano.Address.Derivation
( XPrv, XPub, xpubToBytes )
import Cardano.Api.MetaData
( TxMetadataJsonSchema (..), metadataFromJson, metadataToJson )
import Cardano.Api.Typed
( displayError )
import Cardano.Mnemonic
( MkSomeMnemonic (..)
, MkSomeMnemonicError (..)
, SomeMnemonic (..)
, mnemonicToText
, natVals
)
import Cardano.Wallet.Primitive.AddressDerivation
( Depth (..)
, DerivationType (..)
, Index (..)
, NetworkDiscriminant (..)
, Passphrase (..)
, PassphraseMaxLength (..)
, PassphraseMinLength (..)
, hex
)
import Cardano.Wallet.Primitive.AddressDerivation.Jormungandr
( xpubFromText )
import Cardano.Wallet.Primitive.AddressDiscovery.Random
( RndState )
import Cardano.Wallet.Primitive.AddressDiscovery.Sequential
( AddressPoolGap, SeqState, getAddressPoolGap )
import Cardano.Wallet.Primitive.SyncProgress
( SyncProgress (..) )
import Cardano.Wallet.Primitive.Types
( ActiveSlotCoefficient (..)
, Address (..)
, AddressState (..)
, BoundType
, ChimericAccount (..)
, Coin (..)
, DecentralizationLevel (..)
, Direction (..)
, EpochLength (..)
, EpochNo (..)
, GenesisParameters (..)
, Hash (..)
, HistogramBar (..)
, NetworkParameters (..)
, PoolId (..)
, ShowFmt (..)
, SlotInEpoch (..)
, SlotLength (..)
, StakePoolMetadata
, StartTime (..)
, TxIn (..)
, TxMetadata
, TxStatus (..)
, UTxOStatistics (..)
, WalletBalance (..)
, WalletId (..)
, WalletName (..)
, decodePoolIdBech32
, encodePoolIdBech32
, isValidCoin
, txMetadataIsNull
, unsafeEpochNo
)
import Control.Applicative
( optional, (<|>) )
import Control.Arrow
( left )
import Control.Monad
( guard, (>=>) )
import Data.Aeson
( FromJSON (..)
, SumEncoding (..)
, ToJSON (..)
, Value (Object)
, camelTo2
, constructorTagModifier
, fieldLabelModifier
, genericParseJSON
, genericToJSON
, object
, omitNothingFields
, sumEncoding
, tagSingleConstructors
, withObject
, (.:)
, (.:?)
, (.=)
)
import Data.Bifunctor
( bimap, first )
import Data.ByteArray.Encoding
( Base (Base16), convertFromBase, convertToBase )
import Data.ByteString
( ByteString )
import Data.Either.Extra
( maybeToEither )
import Data.Function
( (&) )
import Data.Generics.Internal.VL.Lens
( view )
import Data.List
( intercalate )
import Data.List.NonEmpty
( NonEmpty (..) )
import Data.Map.Strict
( Map )
import Data.Proxy
( Proxy (..) )
import Data.Quantity
( Percentage, Quantity (..) )
import Data.Text
( Text, split )
import Data.Text.Class
( CaseStyle (..)
, FromText (..)
, TextDecodingError (..)
, ToText (..)
, fromTextToBoundedEnum
, toTextFromBoundedEnum
)
import Data.Time.Clock
( NominalDiffTime, UTCTime )
import Data.Time.Text
( iso8601, iso8601ExtendedUtc, utcTimeFromText, utcTimeToText )
import Data.Word
( Word16, Word32, Word64 )
import Data.Word.Odd
( Word31 )
import Fmt
( pretty )
import GHC.Generics
( Generic )
import GHC.TypeLits
( Nat, Symbol )
import Numeric.Natural
( Natural )
import Servant.API
( MimeRender (..), MimeUnrender (..), OctetStream )
import Web.HttpApiData
( FromHttpApiData (..), ToHttpApiData (..) )
import qualified Cardano.Crypto.Wallet as CC
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Types as Aeson
import qualified Data.ByteString.Lazy as BL
import qualified Data.HashMap.Strict as HM
import qualified Data.Map as Map
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
{-------------------------------------------------------------------------------
Styles of Wallets
-------------------------------------------------------------------------------}
data WalletStyle
= Shelley
| Byron
data ByronWalletStyle
= Random
| Icarus
| Trezor
| Ledger
deriving (Show, Generic, Eq, Bounded, Enum)
instance FromText ByronWalletStyle where
fromText = fromTextToBoundedEnum SnakeLowerCase
instance ToText ByronWalletStyle where
toText = toTextFromBoundedEnum SnakeLowerCase
data SndFactor
= SndFactor
type family StyleSymbol (style :: ByronWalletStyle) :: Symbol where
StyleSymbol 'Random = "random"
StyleSymbol 'Icarus = "icarus"
StyleSymbol 'Trezor = "trezor"
StyleSymbol 'Ledger = "ledger"
type family AllowedMnemonics (style :: k) :: [Nat]
type instance AllowedMnemonics 'Random = '[12,15,18,21,24]
type instance AllowedMnemonics 'Icarus = '[12,15,18,21,24]
type instance AllowedMnemonics 'Trezor = '[12,15,18,21,24]
type instance AllowedMnemonics 'Ledger = '[12,15,18,21,24]
type instance AllowedMnemonics 'Shelley = '[15,18,21,24]
type instance AllowedMnemonics 'SndFactor = '[9,12]
fmtAllowedWords :: ByronWalletStyle -> String
fmtAllowedWords =
(++ " mnemonic words") . formatEnglishEnumeration . allowedWordLengths
where
allowedWordLengths = \case
Random -> map show $ natVals $ Proxy @(AllowedMnemonics 'Random)
Icarus -> map show $ natVals $ Proxy @(AllowedMnemonics 'Icarus)
Trezor -> map show $ natVals $ Proxy @(AllowedMnemonics 'Trezor)
Ledger -> map show $ natVals $ Proxy @(AllowedMnemonics 'Ledger)
-- >>> formatEnglishEnumeration ["a", "b", "c"]
-- "a, b or c"
--
-- >>> formatEnglishEnumeration ["a", "b"]
-- "a or b"
--
-- >>> formatEnglishEnumeration ["a"]
-- "a"
formatEnglishEnumeration = formatEnglishEnumerationRev . reverse
formatEnglishEnumerationRev [ult, penult]
= penult ++ " or " ++ ult
formatEnglishEnumerationRev (ult:penult:revBeginning)
= intercalate ", " (reverse revBeginning)
++ ", "
++ penult
++ " or "
++ ult
formatEnglishEnumerationRev xs = intercalate ", " (reverse xs)
{-------------------------------------------------------------------------------
API Types
-------------------------------------------------------------------------------}
data ApiAddress (n :: NetworkDiscriminant) = ApiAddress
{ id :: !(ApiT Address, Proxy n)
, state :: !(ApiT AddressState)
} deriving (Eq, Generic, Show)
data ApiEpochInfo = ApiEpochInfo
{ epochNumber :: !(ApiT EpochNo)
, epochStartTime :: !UTCTime
} deriving (Eq, Generic, Show)
newtype ApiSelectCoinsData (n :: NetworkDiscriminant) = ApiSelectCoinsData
{ payments :: NonEmpty (AddressAmount (ApiT Address, Proxy n))
} deriving (Eq, Generic, Show)
data ApiCoinSelection (n :: NetworkDiscriminant) = ApiCoinSelection
{ inputs :: !(NonEmpty (ApiCoinSelectionInput n))
, outputs :: !(NonEmpty (AddressAmount (ApiT Address, Proxy n)))
} deriving (Eq, Generic, Show)
data ApiCoinSelectionInput (n :: NetworkDiscriminant) = ApiCoinSelectionInput
{ id :: !(ApiT (Hash "Tx"))
, index :: !Word32
, address :: !(ApiT Address, Proxy n)
, amount :: !(Quantity "lovelace" Natural)
} deriving (Eq, Generic, Show)
data ApiWallet = ApiWallet
{ id :: !(ApiT WalletId)
, addressPoolGap :: !(ApiT AddressPoolGap)
, balance :: !(ApiT WalletBalance)
, delegation :: !ApiWalletDelegation
, name :: !(ApiT WalletName)
, passphrase :: !(Maybe ApiWalletPassphraseInfo)
, state :: !(ApiT SyncProgress)
, tip :: !ApiBlockReference
} deriving (Eq, Generic, Show)
newtype ApiWalletPassphraseInfo = ApiWalletPassphraseInfo
{ lastUpdatedAt :: UTCTime
} deriving (Eq, Generic, Show)
data ApiWalletDelegation = ApiWalletDelegation
{ active :: !ApiWalletDelegationNext
, next :: ![ApiWalletDelegationNext]
} deriving (Eq, Generic, Show)
data ApiWalletDelegationNext = ApiWalletDelegationNext
{ status :: !ApiWalletDelegationStatus
, target :: !(Maybe (ApiT PoolId))
, changesAt :: !(Maybe ApiEpochInfo)
} deriving (Eq, Generic, Show)
data ApiWalletDelegationStatus
= NotDelegating
| Delegating
deriving (Eq, Generic, Show)
newtype ApiWalletPassphrase = ApiWalletPassphrase
{ passphrase :: ApiT (Passphrase "lenient")
} deriving (Eq, Generic, Show)
data ApiStakePool = ApiStakePool
{ id :: !(ApiT PoolId)
, metrics :: !ApiStakePoolMetrics
, metadata :: !(Maybe (ApiT StakePoolMetadata))
, cost :: !(Quantity "lovelace" Natural)
, margin :: !(Quantity "percent" Percentage)
, pledge :: !(Quantity "lovelace" Natural)
, retirement :: !(Maybe ApiEpochInfo)
} deriving (Eq, Generic, Show)
data ApiStakePoolMetrics = ApiStakePoolMetrics
{ nonMyopicMemberRewards :: !(Quantity "lovelace" Natural)
, relativeStake :: !(Quantity "percent" Percentage)
, saturation :: !Double
, producedBlocks :: !(Quantity "block" Natural)
} deriving (Eq, Generic, Show)
data ApiUtxoStatistics = ApiUtxoStatistics
{ total :: !(Quantity "lovelace" Natural)
, scale :: !(ApiT BoundType)
, distribution :: !(Map Word64 Word64)
} deriving (Eq, Generic, Show)
toApiUtxoStatistics :: UTxOStatistics -> ApiUtxoStatistics
toApiUtxoStatistics (UTxOStatistics histo totalStakes bType) =
ApiUtxoStatistics
{ total = Quantity (fromIntegral totalStakes)
, scale = ApiT bType
, distribution = Map.fromList $ map (\(HistogramBar k v)-> (k,v)) histo
}
data WalletPostData = WalletPostData
{ addressPoolGap :: !(Maybe (ApiT AddressPoolGap))
, mnemonicSentence :: !(ApiMnemonicT (AllowedMnemonics 'Shelley))
, mnemonicSecondFactor :: !(Maybe (ApiMnemonicT (AllowedMnemonics 'SndFactor)))
, name :: !(ApiT WalletName)
, passphrase :: !(ApiT (Passphrase "raw"))
} deriving (Eq, Generic, Show)
data SomeByronWalletPostData
= RandomWalletFromMnemonic (ByronWalletPostData (AllowedMnemonics 'Random))
| RandomWalletFromXPrv ByronWalletFromXPrvPostData
| SomeIcarusWallet (ByronWalletPostData (AllowedMnemonics 'Icarus))
| SomeTrezorWallet (ByronWalletPostData (AllowedMnemonics 'Trezor))
| SomeLedgerWallet (ByronWalletPostData (AllowedMnemonics 'Ledger))
| SomeAccount AccountPostData
deriving (Eq, Generic, Show)
data ByronWalletPostData mw = ByronWalletPostData
{ mnemonicSentence :: !(ApiMnemonicT mw)
, name :: !(ApiT WalletName)
, passphrase :: !(ApiT (Passphrase "raw"))
} deriving (Eq, Generic, Show)
data ByronWalletFromXPrvPostData = ByronWalletFromXPrvPostData
{ name :: !(ApiT WalletName)
, encryptedRootPrivateKey :: !(ApiT XPrv)
-- ^ A root private key hex-encoded, encrypted using a given passphrase.
-- The underlying key should contain: private key, chain code, and public key
, passphraseHash :: !(ApiT (Hash "encryption"))
-- ^ A hash of master passphrase. The hash should be an output of a
-- Scrypt function with the following parameters:
-- - logN = 14
-- - r = 8
-- - p = 1
} deriving (Eq, Generic, Show)
newtype ApiAccountPublicKey = ApiAccountPublicKey
{ key :: (ApiT XPub)
} deriving (Eq, Generic, Show)
newtype WalletOrAccountPostData = WalletOrAccountPostData
{ postData :: Either WalletPostData AccountPostData
} deriving (Eq, Generic, Show)
data AccountPostData = AccountPostData
{ name :: !(ApiT WalletName)
, accountPublicKey :: !ApiAccountPublicKey
, addressPoolGap :: !(Maybe (ApiT AddressPoolGap))
} deriving (Eq, Generic, Show)
newtype WalletPutData = WalletPutData
{ name :: (Maybe (ApiT WalletName))
} deriving (Eq, Generic, Show)
data WalletPutPassphraseData = WalletPutPassphraseData
{ oldPassphrase :: !(ApiT (Passphrase "raw"))
, newPassphrase :: !(ApiT (Passphrase "raw"))
} deriving (Eq, Generic, Show)
data ByronWalletPutPassphraseData = ByronWalletPutPassphraseData
{ oldPassphrase :: !(Maybe (ApiT (Passphrase "lenient")))
, newPassphrase :: !(ApiT (Passphrase "raw"))
} deriving (Eq, Generic, Show)
data PostTransactionData (n :: NetworkDiscriminant) = PostTransactionData
{ payments :: !(NonEmpty (AddressAmount (ApiT Address, Proxy n)))
, passphrase :: !(ApiT (Passphrase "lenient"))
, withdrawal :: !(Maybe ApiWithdrawalPostData)
, metadata :: !(Maybe (ApiT TxMetadata))
} deriving (Eq, Generic, Show)
data PostTransactionFeeData (n :: NetworkDiscriminant) = PostTransactionFeeData
{ payments :: (NonEmpty (AddressAmount (ApiT Address, Proxy n)))
, withdrawal :: !(Maybe ApiWithdrawalPostData)
, metadata :: !(Maybe (ApiT TxMetadata))
} deriving (Eq, Generic, Show)
newtype PostExternalTransactionData = PostExternalTransactionData
{ payload :: ByteString
} deriving (Eq, Generic, Show)
data ApiFee = ApiFee
{ estimatedMin :: !(Quantity "lovelace" Natural)
, estimatedMax :: !(Quantity "lovelace" Natural)
} deriving (Eq, Generic, Show)
data ApiNetworkParameters = ApiNetworkParameters
{ genesisBlockHash :: !(ApiT (Hash "Genesis"))
, blockchainStartTime :: !(ApiT StartTime)
, slotLength :: !(Quantity "second" NominalDiffTime)
, epochLength :: !(Quantity "slot" Word32)
, epochStability :: !(Quantity "block" Word32)
, activeSlotCoefficient :: !(Quantity "percent" Double)
, decentralizationLevel :: !(Quantity "percent" Percentage)
, desiredPoolNumber :: !Word16
, minimumUtxoValue :: !(Quantity "lovelace" Natural)
, hardforkAt :: !(Maybe ApiEpochInfo)
} deriving (Eq, Generic, Show)
toApiNetworkParameters
:: NetworkParameters
-> (ApiNetworkParameters, Maybe EpochNo)
toApiNetworkParameters (NetworkParameters gp pp) = (ApiNetworkParameters
(ApiT $ getGenesisBlockHash gp)
(ApiT $ getGenesisBlockDate gp)
(Quantity $ unSlotLength $ getSlotLength gp)
(Quantity $ unEpochLength $ getEpochLength gp)
(getEpochStability gp)
(Quantity
$ (*100)
$ unActiveSlotCoefficient
$ getActiveSlotCoefficient gp)
(Quantity $ unDecentralizationLevel $ view #decentralizationLevel pp)
(view #desiredNumberOfStakePools pp)
(Quantity $ fromIntegral $ getCoin $ view #minimumUTxOvalue pp)
Nothing, view #hardforkEpochNo pp)
newtype ApiTxId = ApiTxId
{ id :: ApiT (Hash "Tx")
} deriving (Eq, Generic, Show)
data ApiTransaction (n :: NetworkDiscriminant) = ApiTransaction
{ id :: !(ApiT (Hash "Tx"))
, amount :: !(Quantity "lovelace" Natural)
, insertedAt :: !(Maybe ApiTimeReference)
, pendingSince :: !(Maybe ApiTimeReference)
, depth :: !(Maybe (Quantity "block" Natural))
, direction :: !(ApiT Direction)
, inputs :: ![ApiTxInput n]
-- TODO: Investigate whether the list of outputs should be non-empty, and
-- if so, whether the 'outputs' field can be encoded as a non-empty list.
-- See: https://jira.iohk.io/browse/ADP-400
, outputs :: ![AddressAmount (ApiT Address, Proxy n)]
, withdrawals :: ![ApiWithdrawal n]
, status :: !(ApiT TxStatus)
, metadata :: !ApiTxMetadata
} deriving (Eq, Generic, Show)
newtype ApiTxMetadata = ApiTxMetadata
{ getApiTxMetadata :: Maybe (ApiT TxMetadata)
} deriving (Eq, Generic, Show)
data ApiWithdrawal n = ApiWithdrawal
{ stakeAddress :: !(ApiT ChimericAccount, Proxy n)
, amount :: !(Quantity "lovelace" Natural)
} deriving (Eq, Generic, Show)
data ApiWithdrawalPostData
= SelfWithdrawal
| ExternalWithdrawal (ApiMnemonicT '[15,18,21,24])
deriving (Eq, Generic, Show)
data ApiTxInput (n :: NetworkDiscriminant) = ApiTxInput
{ source :: !(Maybe (AddressAmount (ApiT Address, Proxy n)))
, input :: !(ApiT TxIn)
} deriving (Eq, Generic, Show)
data AddressAmount addr = AddressAmount
{ address :: !addr
, amount :: !(Quantity "lovelace" Natural)
} deriving (Eq, Generic, Show)
data ApiTimeReference = ApiTimeReference
{ time :: !UTCTime
, block :: !ApiBlockReference
} deriving (Eq, Generic, Show)
data ApiBlockReference = ApiBlockReference
{ epochNumber :: !(ApiT EpochNo)
, slotNumber :: !(ApiT SlotInEpoch)
, height :: !(Quantity "block" Natural)
} deriving (Eq, Generic, Show)
data ApiNetworkTip = ApiNetworkTip
{ epochNumber :: !(ApiT EpochNo)
, slotNumber :: !(ApiT SlotInEpoch)
} deriving (Eq, Generic, Show)
data ApiNetworkInformation = ApiNetworkInformation
{ syncProgress :: !(ApiT SyncProgress)
, nextEpoch :: !(Maybe ApiEpochInfo)
, nodeTip :: !ApiBlockReference
, networkTip :: !(Maybe ApiNetworkTip)
} deriving (Eq, Generic, Show)
data NtpSyncingStatus =
NtpSyncingStatusUnavailable
| NtpSyncingStatusPending
| NtpSyncingStatusAvailable
deriving (Eq, Generic, Show)
data ApiNtpStatus = ApiNtpStatus
{ status :: !NtpSyncingStatus
, offset :: !(Maybe (Quantity "microsecond" Integer))
} deriving (Eq, Generic, Show)
newtype ApiNetworkClock = ApiNetworkClock
{ ntpStatus :: ApiNtpStatus
} deriving (Eq, Generic, Show)
data ApiPostRandomAddressData = ApiPostRandomAddressData
{ passphrase :: !(ApiT (Passphrase "lenient"))
, addressIndex :: !(Maybe (ApiT (Index 'Hardened 'AddressK)))
} deriving (Eq, Generic, Show)
data ApiWalletMigrationPostData (n :: NetworkDiscriminant) (s :: Symbol) =
ApiWalletMigrationPostData
{ passphrase :: !(ApiT (Passphrase s))
, addresses :: ![(ApiT Address, Proxy n)]
} deriving (Eq, Generic, Show)
newtype ApiPutAddressesData (n :: NetworkDiscriminant) = ApiPutAddressesData
{ addresses :: [(ApiT Address, Proxy n)]
} deriving (Eq, Generic, Show)
data ApiWalletMigrationInfo = ApiWalletMigrationInfo
{ migrationCost :: Quantity "lovelace" Natural
, leftovers :: Quantity "lovelace" Natural
} deriving (Eq, Generic, Show)
newtype ApiWithdrawRewards = ApiWithdrawRewards Bool
deriving (Eq, Generic, Show)
-- | Error codes returned by the API, in the form of snake_cased strings
data ApiErrorCode
= NoSuchWallet
| NoSuchTransaction
| TransactionNotPending
| WalletAlreadyExists
| NoRootKey
| WrongEncryptionPassphrase
| MalformedTxPayload
| KeyNotFoundForAddress
| NotEnoughMoney
| UtxoNotEnoughFragmented
| TransactionIsTooBig
| InputsDepleted
| CannotCoverFee
| InvalidCoinSelection
| NetworkUnreachable
| NetworkMisconfigured
| NetworkTipNotFound
| CreatedInvalidTransaction
| RejectedByCoreNode
| BadRequest
| NotFound
| MethodNotAllowed
| NotAcceptable
| StartTimeLaterThanEndTime
| UnableToDetermineCurrentEpoch
| UnsupportedMediaType
| UnexpectedError
| NotSynced
| NothingToMigrate
| NoSuchPool
| PoolAlreadyJoined
| NotDelegatingTo
| InvalidRestorationParameters
| RejectedTip
| InvalidDelegationDiscovery
| NotImplemented
| WalletNotResponding
| AddressAlreadyExists
| InvalidWalletType
| QueryParamMissing
| NonNullRewards
| UtxoTooSmall
| MinWithdrawalWrong
| AlreadyWithdrawing
| WithdrawalNotWorth
| PastHorizon
deriving (Eq, Generic, Show)
-- | Defines a point in time that can be formatted as and parsed from an
-- ISO 8601-compliant string.
--
newtype Iso8601Time = Iso8601Time
{ getIso8601Time :: UTCTime
} deriving (Eq, Ord, Show)
instance ToText Iso8601Time where
toText = utcTimeToText iso8601ExtendedUtc . getIso8601Time
instance FromText Iso8601Time where
fromText t =
Iso8601Time <$> maybeToEither err (utcTimeFromText iso8601 t)
where
err = TextDecodingError $ mempty
<> "Unable to parse time argument: '"
<> T.unpack t
<> "'. Expecting ISO 8601 date-and-time format (basic or extended)"
<> ", e.g. 2012-09-25T10:15:00Z."
instance FromHttpApiData Iso8601Time where
parseUrlPiece = first (T.pack . getTextDecodingError) . fromText
instance ToHttpApiData Iso8601Time where
toUrlPiece = toText
newtype MinWithdrawal = MinWithdrawal
{ getMinWithdrawal :: Natural
} deriving (Show)
instance FromHttpApiData MinWithdrawal where
parseUrlPiece = bimap (T.pack . getTextDecodingError) MinWithdrawal . fromText
instance ToHttpApiData MinWithdrawal where
toUrlPiece = toText . getMinWithdrawal
instance ToText NtpSyncingStatus where
toText NtpSyncingStatusUnavailable = "unavailable"
toText NtpSyncingStatusPending = "pending"
toText NtpSyncingStatusAvailable = "available"
instance FromText NtpSyncingStatus where
fromText txt = case txt of
"unavailable" -> Right NtpSyncingStatusUnavailable
"pending" -> Right NtpSyncingStatusPending
"available" -> Right NtpSyncingStatusAvailable
_ -> Left $ TextDecodingError $ unwords
[ "I couldn't parse the given ntp syncing status."
, "I am expecting one of the words 'unavailable', 'pending' or"
, "'available'."]
data ApiPoolId
= ApiPoolIdPlaceholder
| ApiPoolId PoolId
deriving (Eq, Generic, Show)
instance FromText ApiAccountPublicKey where
fromText txt = case xpubFromText (T.encodeUtf8 txt) of
Left _ ->
Left $ TextDecodingError $ unwords
[ "Invalid account public key: expecting a hex-encoded value"
, "that is 64 bytes in length."]
Right pubkey ->
Right $ ApiAccountPublicKey $ ApiT pubkey
instance FromText (ApiT XPrv) where
fromText t = case convertFromBase Base16 $ T.encodeUtf8 t of
Left _ ->
textDecodingError
Right (bytes :: ByteString) -> case CC.xprv bytes of
Left _ -> textDecodingError
Right val -> Right $ ApiT val
where
textDecodingError = Left $ TextDecodingError $ unwords
[ "Invalid encrypted root private key:"
, "expecting a hex-encoded value that is 128 "
, "bytes in length."
]
instance {-# OVERLAPPING #-} Show (ApiT XPrv) where
show _ = "<xprv>"
instance {-# OVERLAPPING #-} Eq (ApiT XPrv) where
(ApiT val1) == (ApiT val2) = CC.unXPrv val1 == CC.unXPrv val2
instance ToText (ApiT XPrv) where
toText = T.decodeUtf8
. convertToBase Base16
. CC.unXPrv
. getApiT
instance FromText (ApiT (Hash "encryption")) where
fromText txt = case convertFromBase Base16 $ T.encodeUtf8 txt of
Right bytes -> Right $ ApiT $ Hash bytes
Left _ -> textDecodingError
where
textDecodingError = Left $ TextDecodingError $ unwords
[ "Invalid encrypted passphrase:"
, "expecting a hex-encoded value."
]
instance DecodeAddress n => FromHttpApiData (ApiT Address, Proxy n) where
parseUrlPiece txt = do
let proxy = Proxy @n
addr <- bimap (T.pack . getTextDecodingError) ApiT (decodeAddress @n txt)
return (addr, proxy)
instance EncodeAddress n => ToHttpApiData (ApiT Address, Proxy n) where
toUrlPiece = encodeAddress @n . getApiT . fst
{-------------------------------------------------------------------------------
API Types: Byron
-------------------------------------------------------------------------------}
data ApiByronWallet = ApiByronWallet
{ id :: !(ApiT WalletId)
, balance :: !(ApiByronWalletBalance)
, discovery :: !ApiWalletDiscovery
, name :: !(ApiT WalletName)
, passphrase :: !(Maybe ApiWalletPassphraseInfo)
, state :: !(ApiT SyncProgress)
, tip :: !ApiBlockReference
} deriving (Eq, Generic, Show)
data ApiWalletDiscovery
= DiscoveryRandom
| DiscoverySequential
deriving (Eq, Generic, Show)
class KnownDiscovery s where
knownDiscovery :: ApiWalletDiscovery
instance KnownDiscovery (RndState network) where
knownDiscovery = DiscoveryRandom
instance KnownDiscovery (SeqState network key) where
knownDiscovery = DiscoverySequential
{-------------------------------------------------------------------------------
Polymorphic Types
-------------------------------------------------------------------------------}
-- | Polymorphic wrapper type to put around primitive types and, 3rd party lib
-- types to avoid defining orphan instances and/or, undesirable instances on
-- primitive types. It helps to keep a nice separation of concerns between the
-- API layer and other modules.
newtype ApiT a =
ApiT { getApiT :: a }
deriving (Generic, Show, Eq, Functor)
deriving instance Ord a => Ord (ApiT a)
-- | Representation of mnemonics at the API-level, using a polymorphic type in
-- the lengths of mnemonics that are supported (and an underlying purpose). In
-- practice, mnemonics correspond to passphrases or seeds, and although they're
-- nice to manipulate as mnemonics from a user-perspective, carrying around a
-- list of words doesn't really make sense for the business logic, which prefers
-- manipulating scrubbed bytes directly.
--
-- @
-- data MyWallet
-- { mnemonic :: ApiMnemonicT '[15,18,21,24]
-- }
-- @
--
-- Note that the given 'Nat's **have** to be valid mnemonic sizes, otherwise the
-- underlying code won't even compile, with not-so-friendly error messages.
--
-- Also, the internal representation holds a @[Text]@ which contains the list of
-- mnemonic words that was parsed. This is only to be able to implement the
-- 'ToJSON' instances and roundtrip, which is a very dubious argument. In
-- practice, we'll NEVER peek at the mnemonic, output them and whatnot.
newtype ApiMnemonicT (sizes :: [Nat]) =
ApiMnemonicT { getApiMnemonicT :: SomeMnemonic }
deriving (Generic, Show, Eq)
{-------------------------------------------------------------------------------
JSON Instances
-------------------------------------------------------------------------------}
instance DecodeAddress n => FromJSON (ApiAddress n) where
parseJSON = genericParseJSON defaultRecordTypeOptions
instance EncodeAddress n => ToJSON (ApiAddress n) where
toJSON = genericToJSON defaultRecordTypeOptions
instance FromJSON ApiEpochInfo where
parseJSON = genericParseJSON defaultRecordTypeOptions
instance ToJSON ApiEpochInfo where
toJSON = genericToJSON defaultRecordTypeOptions
instance DecodeAddress n => FromJSON (ApiSelectCoinsData n) where
parseJSON = genericParseJSON defaultRecordTypeOptions
instance EncodeAddress n => ToJSON (ApiSelectCoinsData n) where
toJSON = genericToJSON defaultRecordTypeOptions
instance DecodeAddress n => FromJSON (ApiCoinSelection n) where
parseJSON = genericParseJSON defaultRecordTypeOptions
instance EncodeAddress n => ToJSON (ApiCoinSelection n) where
toJSON = genericToJSON defaultRecordTypeOptions
instance DecodeAddress n => FromJSON (ApiCoinSelectionInput n) where
parseJSON = genericParseJSON defaultRecordTypeOptions
instance EncodeAddress n => ToJSON (ApiCoinSelectionInput n) where
toJSON = genericToJSON defaultRecordTypeOptions
instance {-# OVERLAPS #-} DecodeAddress n => FromJSON (ApiT Address, Proxy n)
where
parseJSON x = do
let proxy = Proxy @n
addr <- parseJSON x >>= eitherToParser
. bimap ShowFmt ApiT
. decodeAddress @n
return (addr, proxy)
instance {-# OVERLAPS #-} EncodeAddress n => ToJSON (ApiT Address, Proxy n)
where
toJSON (addr, _) = toJSON . encodeAddress @n . getApiT $ addr
instance FromJSON (ApiT AddressState) where
parseJSON = fmap ApiT . genericParseJSON defaultSumTypeOptions
instance ToJSON (ApiT AddressState) where
toJSON = genericToJSON defaultSumTypeOptions . getApiT
instance FromJSON ApiWallet where
parseJSON = genericParseJSON defaultRecordTypeOptions
instance ToJSON ApiWallet where
toJSON = genericToJSON defaultRecordTypeOptions
instance FromJSON ApiWalletPassphrase where
parseJSON = genericParseJSON defaultRecordTypeOptions
instance ToJSON ApiWalletPassphrase where
toJSON = genericToJSON defaultRecordTypeOptions
instance FromJSON WalletPostData where
parseJSON = genericParseJSON defaultRecordTypeOptions
instance ToJSON WalletPostData where
toJSON = genericToJSON defaultRecordTypeOptions
instance FromJSON ApiAccountPublicKey where
parseJSON =
parseJSON >=> eitherToParser . first ShowFmt . fromText
instance ToJSON ApiAccountPublicKey where
toJSON =
toJSON . T.decodeUtf8 . hex . xpubToBytes . getApiT . key
instance FromJSON WalletOrAccountPostData where
parseJSON obj = do
passwd <-
(withObject "postData" $
\o -> o .:? "passphrase" :: Aeson.Parser (Maybe Text)) obj
mnemonic <-
(withObject "postData" $
\o -> o .:? "mnemonic_sentence" :: Aeson.Parser (Maybe [Text])) obj
case (passwd, mnemonic) of
(Nothing, Nothing) -> do
xs <- parseJSON obj :: Aeson.Parser AccountPostData
pure $ WalletOrAccountPostData $ Right xs
_ -> do
xs <- parseJSON obj :: Aeson.Parser WalletPostData
pure $ WalletOrAccountPostData $ Left xs
instance ToJSON WalletOrAccountPostData where
toJSON (WalletOrAccountPostData (Left c))= toJSON c
toJSON (WalletOrAccountPostData (Right c))= toJSON c
instance FromJSON AccountPostData where
parseJSON = genericParseJSON defaultRecordTypeOptions
instance ToJSON AccountPostData where
toJSON = genericToJSON defaultRecordTypeOptions
instance ToJSON SomeByronWalletPostData where
toJSON = \case
RandomWalletFromMnemonic w -> toJSON w
& withExtraField (fieldName, toJSON $ toText Random)
RandomWalletFromXPrv w -> toJSON w
& withExtraField (fieldName, toJSON $ toText Random)
SomeIcarusWallet w -> toJSON w
& withExtraField (fieldName, toJSON $ toText Icarus)
SomeTrezorWallet w -> toJSON w
& withExtraField (fieldName, toJSON $ toText Trezor)
SomeLedgerWallet w -> toJSON w
& withExtraField (fieldName, toJSON $ toText Ledger)
SomeAccount w -> toJSON w
where