/
CLI.hs
2006 lines (1829 loc) · 65.9 KB
/
CLI.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 ApplicativeDo #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- Shared types and helpers for CLI parsing
module Cardano.CLI
(
-- * CLI Execution
cli
, runCli
-- * Commands
, cmdMnemonic
, cmdWallet
, cmdWalletCreate
, cmdByronWalletCreate
, cmdTransaction
, cmdAddress
, cmdStakePool
, cmdNetwork
, cmdVersion
, cmdKey
-- * Option & Argument Parsers
, optionT
, argumentT
, cacheListPoolsOption
, databaseOption
, hostPreferenceOption
, listenOption
, shutdownHandlerFlag
, stateDirOption
, syncToleranceOption
, tlsOption
, poolMetadataSourceOption
, tokenMetadataSourceOption
, metadataOption
, timeToLiveOption
-- * Option parsers for configuring tracing
, LoggingOptions (..)
, LogOutput (..)
, helperTracing
, loggingOptions
, loggingSeverities
, parseLoggingSeverity
, loggingSeverityOrOffReader
, loggingSeverityReader
-- * Types
, Service
, TxId
, Port (..)
-- * Logging
, withLogging
, withLoggingNamed
-- * ANSI Terminal Helpers
, putErrLn
, hPutErrLn
, enableWindowsANSI
-- * Working with Sensitive Data
, getLine
, hGetLine
, getSensitiveLine
, hGetSensitiveLine
-- * Helpers
, decodeError
, requireFilePath
, getDataDir
, setupDirectory
, getPrometheusURL
, getEKGURL
, ekgEnabled
) where
import Prelude hiding
( getLine )
import Cardano.BM.Backend.Switchboard
( Switchboard )
import Cardano.BM.Configuration.Static
( defaultConfigStdout )
import Cardano.BM.Counters
( readCounters )
import Cardano.BM.Data.Configuration
( Endpoint (..) )
import Cardano.BM.Data.Counter
( Counter (..), nameCounter )
import Cardano.BM.Data.LogItem
( LOContent (..), LoggerName, PrivacyAnnotation (..), mkLOMeta )
import Cardano.BM.Data.Output
( ScribeDefinition (..)
, ScribeFormat (..)
, ScribeId
, ScribeKind (..)
, ScribePrivacy (..)
)
import Cardano.BM.Data.Severity
( Severity (..) )
import Cardano.BM.Data.SubTrace
( SubTrace (..) )
import Cardano.BM.Setup
( setupTrace_, shutdown )
import Cardano.BM.Trace
( Trace, appendName, logDebug, traceNamedObject )
import Cardano.Mnemonic
( MkSomeMnemonic (..), SomeMnemonic (..) )
import Cardano.Wallet.Api.Client
( AddressClient (..)
, NetworkClient (..)
, StakePoolClient (..)
, TransactionClient (..)
, WalletClient (..)
)
import Cardano.Wallet.Api.Server
( HostPreference, Listen (..), TlsConfiguration (..) )
import Cardano.Wallet.Api.Types
( AccountPostData (..)
, AddressAmount
, AllowedMnemonics
, ApiAccountPublicKey
, ApiByronWallet
, ApiBytesT (..)
, ApiMnemonicT (..)
, ApiPostRandomAddressData (..)
, ApiT (..)
, ApiTxId (ApiTxId)
, ApiTxMetadata (..)
, ApiWallet
, Base (Base16)
, ByronWalletPostData (..)
, ByronWalletStyle (..)
, Iso8601Time (..)
, SomeByronWalletPostData (..)
, WalletOrAccountPostData (..)
, WalletPostData (..)
, WalletPutData (..)
, WalletPutPassphraseData (..)
, fmtAllowedWords
)
import Cardano.Wallet.Orphans
()
import Cardano.Wallet.Primitive.AddressDerivation
( Depth (..)
, DerivationType (..)
, Index (..)
, Passphrase (..)
, PassphraseMaxLength
, PassphraseMinLength
)
import Cardano.Wallet.Primitive.AddressDiscovery.Sequential
( AddressPoolGap, defaultAddressPoolGap )
import Cardano.Wallet.Primitive.SyncProgress
( SyncTolerance (..) )
import Cardano.Wallet.Primitive.Types
( PoolMetadataSource (..)
, SortOrder
, TokenMetadataServer
, WalletId
, WalletName
)
import Cardano.Wallet.Primitive.Types.Address
( AddressState )
import Cardano.Wallet.Primitive.Types.Coin
( Coin (..) )
import Cardano.Wallet.Primitive.Types.Hash
( Hash (..) )
import Cardano.Wallet.Primitive.Types.Tx
( SerialisedTx (..) )
import Cardano.Wallet.Version
( gitRevision, showFullVersion, version )
import Control.Applicative
( optional, some, (<|>) )
import Control.Arrow
( first, left )
import Control.Cache
( CacheConfig (..) )
import Control.Monad
( forM_, forever, join, unless, void, when )
import Control.Monad.IO.Class
( MonadIO )
import Data.Aeson
( ToJSON (..), (.:), (.=) )
import Data.Bifunctor
( bimap )
import Data.Char
( toLower )
import Data.Coerce
( coerce )
import Data.List.NonEmpty
( NonEmpty (..) )
import Data.Maybe
( fromMaybe, isJust )
import Data.Quantity
( Quantity (..) )
import Data.String
( IsString )
import Data.Text
( Text )
import Data.Text.Class
( FromText (..), TextDecodingError (..), ToText (..), showT )
import Data.Text.Read
( decimal )
import Data.Time.Clock
( NominalDiffTime )
import Data.Void
( Void )
import Fmt
( Buildable, pretty )
import GHC.Generics
( Generic )
import GHC.TypeLits
( Symbol )
import Network.HTTP.Client
( defaultManagerSettings
, managerResponseTimeout
, newManager
, responseTimeoutNone
)
import Options.Applicative
( ArgumentFields
, CommandFields
, Mod
, OptionFields
, ParseError (InfoMsg)
, Parser
, ParserInfo
, abortOption
, argument
, auto
, command
, customExecParser
, eitherReader
, flag
, flag'
, header
, help
, helpDoc
, helper
, hidden
, info
, long
, metavar
, option
, prefs
, progDesc
, showDefaultWith
, showHelpOnEmpty
, str
, strOption
, subparser
, switch
, value
)
import Options.Applicative.Help.Pretty
( string, vsep )
import Options.Applicative.Types
( ReadM (..), readerAsk )
import Servant.Client
( BaseUrl (..), ClientM, Scheme (..), mkClientEnv, runClientM )
import Servant.Client.Core
( ClientError (..), responseBody )
import System.Console.ANSI
( Color (..)
, ColorIntensity (..)
, ConsoleLayer (..)
, SGR (..)
, hCursorBackward
, hSetSGR
, hSupportsANSIWithoutEmulation
)
import System.Directory
( XdgDirectory (..)
, createDirectoryIfMissing
, doesDirectoryExist
, doesFileExist
, getXdgDirectory
)
import System.Environment
( lookupEnv )
import System.Exit
( exitFailure, exitSuccess )
import System.FilePath
( (</>) )
import System.Info
( os )
import System.IO
( BufferMode (..)
, Handle
, hGetBuffering
, hGetChar
, hGetEcho
, hIsTerminalDevice
, hPutChar
, hSetBuffering
, hSetEcho
, stderr
, stdin
, stdout
)
import UnliftIO.Concurrent
( threadDelay )
import UnliftIO.Exception
( bracket )
import qualified Cardano.BM.Configuration.Model as CM
import qualified Cardano.BM.Data.BackendKind as CM
import qualified Cardano.BM.Data.Observable as Obs
import qualified Command.Key as Key
import qualified Command.RecoveryPhrase as RecoveryPhrase
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Encode.Pretty as Aeson
import qualified Data.Aeson.Types as Aeson
import qualified Data.Bifunctor as Bi
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BL8
import qualified Data.List.NonEmpty as NE
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as TIO
import qualified UnliftIO.Async as Async
{-------------------------------------------------------------------------------
CLI
-------------------------------------------------------------------------------}
-- | Construct a CLI from a list of a commands
--
-- >>> runCli $ cli $ cmdA <> cmdB <> cmdC
--
cli :: Mod CommandFields a -> ParserInfo a
cli cmds = info (helper <*> subparser cmds) $ mempty
<> progDesc "Cardano Wallet Command-Line Interface (CLI)"
<> header (mconcat
[ "The CLI is a proxy to the wallet server, which is required for most "
, "commands. Commands are turned into corresponding API calls, and "
, "submitted to an up-and-running server. Some commands do not require "
, "an active server and can be run offline (e.g. 'recovery-phrase generate')."
])
-- | Runs a specific command parser using appropriate preferences
runCli :: ParserInfo (IO ()) -> IO ()
runCli = join . customExecParser preferences
where
preferences = prefs showHelpOnEmpty
{-------------------------------------------------------------------------------
Commands - 'key'
-------------------------------------------------------------------------------}
cmdKey :: Mod CommandFields (IO ())
cmdKey = Key.mod Key.run
{-------------------------------------------------------------------------------
Commands - 'recovery-phrase'
-------------------------------------------------------------------------------}
cmdMnemonic :: Mod CommandFields (IO ())
cmdMnemonic = RecoveryPhrase.mod RecoveryPhrase.run
{-------------------------------------------------------------------------------
Commands - 'wallet'
-------------------------------------------------------------------------------}
type CmdWalletCreate wallet = WalletClient wallet -> Mod CommandFields (IO ())
cmdWallet
:: ToJSON wallet
=> CmdWalletCreate wallet
-> WalletClient wallet
-> Mod CommandFields (IO ())
cmdWallet cmdCreate mkClient =
command "wallet" $ info (helper <*> cmds) $ mempty
<> progDesc "About wallets"
where
cmds = subparser $ mempty
<> cmdWalletList mkClient
<> cmdCreate mkClient
<> cmdWalletGet mkClient
<> cmdWalletUpdate mkClient
<> cmdWalletDelete mkClient
<> cmdWalletGetUtxoStatistics mkClient
<> cmdWalletGetUtxoSnapshot mkClient
-- | Arguments for 'wallet list' command
newtype WalletListArgs = WalletListArgs
{ _port :: Port "Wallet"
}
cmdWalletList
:: ToJSON wallet
=> WalletClient wallet
-> Mod CommandFields (IO ())
cmdWalletList mkClient =
command "list" $ info (helper <*> cmd) $ mempty
<> progDesc "List all known wallets."
where
cmd = fmap exec $ WalletListArgs
<$> portOption
exec (WalletListArgs wPort) = do
runClient wPort Aeson.encodePretty $ listWallets mkClient
cmdWalletCreate
:: WalletClient ApiWallet
-> Mod CommandFields (IO ())
cmdWalletCreate mkClient =
command "create" $ info (helper <*> cmds) $ mempty
<> progDesc "Create a new wallet."
where
cmds = subparser $ mempty
<> cmdWalletCreateFromMnemonic mkClient
<> cmdWalletCreateFromPublicKey mkClient
cmdByronWalletCreate
:: WalletClient ApiByronWallet
-> Mod CommandFields (IO ())
cmdByronWalletCreate mkClient =
command "create" $ info (helper <*> cmds) $ mempty
<> progDesc "Create a new Byron wallet."
where
cmds = subparser $ mempty
<> cmdByronWalletCreateFromMnemonic mkClient
data ByronWalletCreateFromMnemonicArgs = ByronWalletCreateFromMnemonicArgs
{ _port :: Port "Wallet"
, _name :: WalletName
, _style :: ByronWalletStyle
}
cmdByronWalletCreateFromMnemonic
:: WalletClient ApiByronWallet
-> Mod CommandFields (IO ())
cmdByronWalletCreateFromMnemonic mkClient =
command "from-recovery-phrase" $ info (helper <*> cmd) $ mempty
<> progDesc "Create a new wallet using a recovery phrase."
where
cmd = fmap exec $ ByronWalletCreateFromMnemonicArgs
<$> portOption
<*> walletNameArgument
<*> walletStyleOption Icarus [Random,Icarus,Trezor,Ledger]
exec (ByronWalletCreateFromMnemonicArgs wPort wName wStyle) = case wStyle of
Random -> do
wSeed <- do
let prompt = "Please enter " ++ fmtAllowedWords wStyle ++ " : "
let parser = mkSomeMnemonic @(AllowedMnemonics 'Random) . T.words
fst <$> getLine @SomeMnemonic (T.pack prompt) (left show . parser)
wPwd <- getPassphraseWithConfirm "Please enter a passphrase: "
runClient wPort Aeson.encodePretty $ postWallet mkClient $
RandomWalletFromMnemonic $ ByronWalletPostData
(ApiMnemonicT wSeed)
(ApiT wName)
(ApiT wPwd)
Icarus -> do
wSeed <- do
let prompt = "Please enter " ++ fmtAllowedWords wStyle ++ " : "
let parser = mkSomeMnemonic @(AllowedMnemonics 'Icarus) . T.words
fst <$> getLine @SomeMnemonic (T.pack prompt) (left show . parser)
wPwd <- getPassphraseWithConfirm "Please enter a passphrase: "
runClient wPort Aeson.encodePretty $ postWallet mkClient $
SomeIcarusWallet $ ByronWalletPostData
(ApiMnemonicT wSeed)
(ApiT wName)
(ApiT wPwd)
Trezor -> do
wSeed <- do
let prompt = "Please enter " ++ fmtAllowedWords wStyle ++ " : "
let parser = mkSomeMnemonic @(AllowedMnemonics 'Trezor) . T.words
fst <$> getLine @SomeMnemonic (T.pack prompt) (left show . parser)
wPwd <- getPassphraseWithConfirm "Please enter a passphrase: "
runClient wPort Aeson.encodePretty $ postWallet mkClient $
SomeTrezorWallet $ ByronWalletPostData
(ApiMnemonicT wSeed)
(ApiT wName)
(ApiT wPwd)
Ledger -> do
wSeed <- do
let prompt = "Please enter " ++ fmtAllowedWords wStyle ++ " : "
let parser = mkSomeMnemonic @(AllowedMnemonics 'Ledger) . T.words
fst <$> getLine @SomeMnemonic (T.pack prompt) (left show . parser)
wPwd <- getPassphraseWithConfirm "Please enter a passphrase: "
runClient wPort Aeson.encodePretty $ postWallet mkClient $
SomeLedgerWallet $ ByronWalletPostData
(ApiMnemonicT wSeed)
(ApiT wName)
(ApiT wPwd)
-- | Arguments for 'wallet create' command
data WalletCreateArgs = WalletCreateArgs
{ _port :: Port "Wallet"
, _name :: WalletName
, _gap :: AddressPoolGap
}
cmdWalletCreateFromMnemonic
:: WalletClient ApiWallet
-> Mod CommandFields (IO ())
cmdWalletCreateFromMnemonic mkClient =
command "from-recovery-phrase" $ info (helper <*> cmd) $ mempty
<> progDesc "Create a new wallet using a recovery phrase."
where
cmd = fmap exec $ WalletCreateArgs
<$> portOption
<*> walletNameArgument
<*> poolGapOption
exec (WalletCreateArgs wPort wName wGap) = do
wSeed <- do
let prompt = "Please enter a 15–24 word recovery phrase: "
let parser = mkSomeMnemonic @'[15,18,21,24] . T.words
fst <$> getLine @SomeMnemonic prompt (left show . parser)
wSndFactor <- do
let prompt =
"(Enter a blank line if you do not wish to use a second " <>
"factor.)\n" <>
"Please enter a 9–12 word second factor: "
let parser =
optionalE (mkSomeMnemonic @'[9,12]) . T.words
fst <$> getLine @(Maybe SomeMnemonic) prompt (left show . parser)
wPwd <- getPassphraseWithConfirm "Please enter a passphrase: "
runClient wPort Aeson.encodePretty $ postWallet mkClient $
WalletOrAccountPostData $ Left $ WalletPostData
(Just $ ApiT wGap)
(ApiMnemonicT wSeed)
(ApiMnemonicT <$> wSndFactor)
(ApiT wName)
(ApiT wPwd)
-- | Arguments for 'wallet create from-public-key' command
data WalletCreateFromPublicKeyArgs = WalletCreateFromPublicKeyArgs
{ _port :: Port "Wallet"
, _name :: WalletName
, _gap :: AddressPoolGap
, _key :: ApiAccountPublicKey
}
cmdWalletCreateFromPublicKey
:: WalletClient ApiWallet
-> Mod CommandFields (IO ())
cmdWalletCreateFromPublicKey mkClient =
command "from-public-key" $ info (helper <*> cmd) $ mempty
<> progDesc "Create a wallet using a public account key."
where
cmd = fmap exec $ WalletCreateFromPublicKeyArgs
<$> portOption
<*> walletNameArgument
<*> poolGapOption
<*> accPubKeyArgument
exec (WalletCreateFromPublicKeyArgs wPort wName wGap wAccPubKey) =
runClient wPort Aeson.encodePretty $ postWallet mkClient $
WalletOrAccountPostData $ Right $ AccountPostData
(ApiT wName)
wAccPubKey
(Just $ ApiT wGap)
-- | Arguments for 'wallet get' command
data WalletGetArgs = WalletGetArgs
{ _port :: Port "Wallet"
, _id :: WalletId
}
cmdWalletGet
:: ToJSON wallet
=> WalletClient wallet
-> Mod CommandFields (IO ())
cmdWalletGet mkClient =
command "get" $ info (helper <*> cmd) $ mempty
<> progDesc "Fetch the wallet with specified id."
where
cmd = fmap exec $ WalletGetArgs
<$> portOption
<*> walletIdArgument
exec (WalletGetArgs wPort wId) = do
runClient wPort Aeson.encodePretty $ getWallet mkClient $
ApiT wId
cmdWalletUpdate
:: ToJSON wallet
=> WalletClient wallet
-> Mod CommandFields (IO ())
cmdWalletUpdate mkClient =
command "update" $ info (helper <*> cmds) $ mempty
<> progDesc "Update a wallet."
where
cmds = subparser $ mempty
<> cmdWalletUpdateName mkClient
<> cmdWalletUpdatePassphrase mkClient
-- | Arguments for 'wallet update name' command
data WalletUpdateNameArgs = WalletUpdateNameArgs
{ _port :: Port "Wallet"
, _id :: WalletId
, _name :: WalletName
}
cmdWalletUpdateName
:: ToJSON wallet
=> WalletClient wallet
-> Mod CommandFields (IO ())
cmdWalletUpdateName mkClient =
command "name" $ info (helper <*> cmd) $ mempty
<> progDesc "Update a wallet's name."
where
cmd = fmap exec $ WalletUpdateNameArgs
<$> portOption
<*> walletIdArgument
<*> walletNameArgument
exec (WalletUpdateNameArgs wPort wId wName) = do
runClient wPort Aeson.encodePretty $ putWallet mkClient
(ApiT wId)
(WalletPutData $ Just (ApiT wName))
-- | Arguments for 'wallet update passphrase' command
data WalletUpdatePassphraseArgs = WalletUpdatePassphraseArgs
{ _port :: Port "Wallet"
, _id :: WalletId
}
cmdWalletUpdatePassphrase
:: ToJSON wallet
=> WalletClient wallet
-> Mod CommandFields (IO ())
cmdWalletUpdatePassphrase mkClient =
command "passphrase" $ info (helper <*> cmd) $ mempty
<> progDesc "Update a wallet's passphrase."
where
cmd = fmap exec $ WalletUpdatePassphraseArgs
<$> portOption
<*> walletIdArgument
exec (WalletUpdatePassphraseArgs wPort wId) = do
res <- sendRequest wPort $ getWallet mkClient $ ApiT wId
case res of
Right _ -> do
wPassphraseOld <- getPassphrase
"Please enter your current passphrase: "
wPassphraseNew <- getPassphraseWithConfirm
"Please enter a new passphrase: "
runClient wPort (const mempty) $
putWalletPassphrase mkClient (ApiT wId) $
WalletPutPassphraseData
(ApiT wPassphraseOld)
(ApiT wPassphraseNew)
Left _ ->
handleResponse Aeson.encodePretty res
-- | Arguments for 'wallet delete' command
data WalletDeleteArgs = WalletDeleteArgs
{ _port :: Port "Wallet"
, _id :: WalletId
}
cmdWalletDelete
:: WalletClient wallet
-> Mod CommandFields (IO ())
cmdWalletDelete mkClient =
command "delete" $ info (helper <*> cmd) $ mempty
<> progDesc "Deletes wallet with specified wallet id."
where
cmd = fmap exec $ WalletDeleteArgs
<$> portOption
<*> walletIdArgument
exec (WalletDeleteArgs wPort wId) = do
runClient wPort (const "") $ deleteWallet mkClient $
ApiT wId
cmdWalletGetUtxoSnapshot
:: ToJSON wallet
=> WalletClient wallet
-> Mod CommandFields (IO ())
cmdWalletGetUtxoSnapshot mkClient =
command "utxo-snapshot" $ info (helper <*> cmd) $ mempty
<> progDesc "Get UTxO snapshot for wallet with specified id."
where
cmd = fmap exec $ WalletGetArgs
<$> portOption
<*> walletIdArgument
exec (WalletGetArgs wPort wId) = do
res <- sendRequest wPort $ getWallet mkClient $ ApiT wId
case res of
Right _ -> do
runClient wPort Aeson.encodePretty $
getWalletUtxoSnapshot mkClient (ApiT wId)
Left _ ->
handleResponse Aeson.encodePretty res
cmdWalletGetUtxoStatistics
:: ToJSON wallet
=> WalletClient wallet
-> Mod CommandFields (IO ())
cmdWalletGetUtxoStatistics mkClient =
command "utxo" $ info (helper <*> cmd) $ mempty
<> progDesc "Get UTxO statistics for the wallet with specified id."
where
cmd = fmap exec $ WalletGetArgs
<$> portOption
<*> walletIdArgument
exec (WalletGetArgs wPort wId) = do
res <- sendRequest wPort $ getWallet mkClient $ ApiT wId
case res of
Right _ -> do
runClient wPort Aeson.encodePretty $
getWalletUtxoStatistics mkClient (ApiT wId)
Left _ ->
handleResponse Aeson.encodePretty res
{-------------------------------------------------------------------------------
Commands - 'transaction'
-------------------------------------------------------------------------------}
data TransactionFeatures = NoShelleyFeatures | ShelleyFeatures
deriving (Show, Eq)
-- | cardano-wallet transaction
cmdTransaction
:: ToJSON wallet
=> TransactionClient
-> WalletClient wallet
-> Mod CommandFields (IO ())
cmdTransaction = cmdTransactionBase ShelleyFeatures
cmdTransactionBase
:: ToJSON wallet
=> TransactionFeatures
-> TransactionClient
-> WalletClient wallet
-> Mod CommandFields (IO ())
cmdTransactionBase isShelley mkTxClient mkWalletClient =
command "transaction" $ info (helper <*> cmds) $ mempty
<> progDesc "About transactions"
where
cmds = subparser $ mempty
<> cmdTransactionCreate isShelley mkTxClient mkWalletClient
<> cmdTransactionFees isShelley mkTxClient mkWalletClient
<> cmdTransactionList mkTxClient
<> cmdTransactionSubmit mkTxClient
<> cmdTransactionForget mkTxClient
<> cmdTransactionGet mkTxClient
-- | Arguments for 'transaction create' command
data TransactionCreateArgs t = TransactionCreateArgs
{ _port :: Port "Wallet"
, _id :: WalletId
, _payments :: NonEmpty Text
, _metadata :: ApiTxMetadata
, _timeToLive :: Maybe (Quantity "second" NominalDiffTime)
}
whenShelley :: a -> Parser a -> TransactionFeatures -> Parser a
whenShelley j s = \case
NoShelleyFeatures -> pure j
ShelleyFeatures -> s
cmdTransactionCreate
:: ToJSON wallet
=> TransactionFeatures
-> TransactionClient
-> WalletClient wallet
-> Mod CommandFields (IO ())
cmdTransactionCreate isShelley mkTxClient mkWalletClient =
command "create" $ info (helper <*> cmd) $ mempty
<> progDesc "Create and submit a new transaction."
where
cmd = fmap exec $ TransactionCreateArgs
<$> portOption
<*> walletIdArgument
<*> fmap NE.fromList (some paymentOption)
<*> whenShelley (ApiTxMetadata Nothing) metadataOption isShelley
<*> whenShelley Nothing timeToLiveOption isShelley
exec (TransactionCreateArgs wPort wId wAddressAmounts md ttl) = do
wPayments <- either (fail . getTextDecodingError) pure $
traverse (fromText @(AddressAmount Text)) wAddressAmounts
res <- sendRequest wPort $ getWallet mkWalletClient $ ApiT wId
case res of
Right _ -> do
wPwd <- getPassphrase @"raw" "Please enter your passphrase: "
runClient wPort Aeson.encodePretty $ postTransaction
mkTxClient
(ApiT wId)
(Aeson.object
[ "payments" .= wPayments
, "passphrase" .= ApiT wPwd
, "metadata" .= md
, "time_to_live" .= ttl
]
)
Left _ ->
handleResponse Aeson.encodePretty res
cmdTransactionFees
:: ToJSON wallet
=> TransactionFeatures
-> TransactionClient
-> WalletClient wallet
-> Mod CommandFields (IO ())
cmdTransactionFees isShelley mkTxClient mkWalletClient =
command "fees" $ info (helper <*> cmd) $ mempty
<> progDesc "Estimate fees for a transaction."
where
cmd = fmap exec $ TransactionCreateArgs
<$> portOption
<*> walletIdArgument
<*> fmap NE.fromList (some paymentOption)
<*> whenShelley (ApiTxMetadata Nothing) metadataOption isShelley
<*> whenShelley Nothing timeToLiveOption isShelley
exec (TransactionCreateArgs wPort wId wAddressAmounts md ttl) = do
wPayments <- either (fail . getTextDecodingError) pure $
traverse (fromText @(AddressAmount Text)) wAddressAmounts
res <- sendRequest wPort $ getWallet mkWalletClient $ ApiT wId
case res of
Right _ -> do
runClient wPort Aeson.encodePretty $ postTransactionFee
mkTxClient
(ApiT wId)
(Aeson.object
[ "payments" .= wPayments
, "metadata" .= md
, "time_to_live" .= ttl
])
Left _ ->
handleResponse Aeson.encodePretty res
-- | Arguments for 'transaction list' command.
data TransactionListArgs = TransactionListArgs
{ _port :: Port "Wallet"
, _walletId :: WalletId
, _timeRangeStart :: Maybe Iso8601Time
, _timeRangeEnd :: Maybe Iso8601Time
, _sortOrder :: Maybe SortOrder
}
cmdTransactionList
:: TransactionClient
-> Mod CommandFields (IO ())
cmdTransactionList mkTxClient =
command "list" $ info (helper <*> cmd) $ mempty
<> progDesc "List the transactions associated with a wallet."
where
cmd = fmap exec $ TransactionListArgs
<$> portOption
<*> walletIdArgument
<*> optional timeRangeStartOption
<*> optional timeRangeEndOption
<*> optional sortOrderOption
exec (TransactionListArgs wPort wId mTimeRangeStart mTimeRangeEnd mOrder) =
runClient wPort Aeson.encodePretty $ listTransactions
mkTxClient
(ApiT wId)
mTimeRangeStart
mTimeRangeEnd
(ApiT <$> mOrder)
-- | Arguments for 'transaction submit' command
data TransactionSubmitArgs = TransactionSubmitArgs
{ _port :: Port "Wallet"
, _payload :: ApiBytesT 'Base16 SerialisedTx
}
cmdTransactionSubmit
:: TransactionClient
-> Mod CommandFields (IO ())
cmdTransactionSubmit mkTxClient =
command "submit" $ info (helper <*> cmd) $ mempty
<> progDesc "Submit an externally-signed transaction."
where
cmd = fmap exec $ TransactionSubmitArgs
<$> portOption
<*> transactionSubmitPayloadArgument
exec (TransactionSubmitArgs wPort wPayload) = do
runClient wPort Aeson.encodePretty $
postExternalTransaction mkTxClient (coerce wPayload)
-- | Arguments for 'transaction forget' command
data TransactionForgetArgs = TransactionForgetArgs
{ _port :: Port "Wallet"
, _wid :: WalletId
, _txid :: TxId
}
cmdTransactionForget
:: TransactionClient
-> Mod CommandFields (IO ())
cmdTransactionForget mkClient =
command "forget" $ info (helper <*> cmd) $ mempty
<> progDesc "Forget a pending transaction with specified id."
where
cmd = fmap exec $ TransactionForgetArgs
<$> portOption
<*> walletIdArgument
<*> transactionIdArgument
exec (TransactionForgetArgs wPort wId txId) = do
runClient wPort (const mempty) $ deleteTransaction mkClient
(ApiT wId)
(ApiTxId $ ApiT $ getTxId txId)
-- | Arguments for 'transaction get' command
data TransactionGetArgs = TransactionGetArgs
{ _port :: Port "Wallet"
, _wid :: WalletId
, _txid :: TxId
}
cmdTransactionGet
:: TransactionClient
-> Mod CommandFields (IO ())
cmdTransactionGet mkClient =
command "get" $ info (helper <*> cmd) $ mempty
<> progDesc "Get a transaction with specified id."
where
cmd = fmap exec $ TransactionGetArgs
<$> portOption
<*> walletIdArgument
<*> transactionIdArgument
exec (TransactionGetArgs wPort wId txId) = do
runClient wPort Aeson.encodePretty $ getTransaction mkClient
(ApiT wId)
(ApiTxId $ ApiT $ getTxId txId)
{-------------------------------------------------------------------------------
Commands - 'address'
-------------------------------------------------------------------------------}
cmdAddress
:: AddressClient
-> Mod CommandFields (IO ())
cmdAddress mkClient =
command "address" $ info (helper <*> cmds) $ mempty
<> progDesc "About addresses"
where
cmds = subparser $ mempty
<> cmdAddressList mkClient
<> cmdAddressCreate mkClient
<> cmdAddressImport mkClient
-- | Arguments for 'address list' command
data AddressListArgs = AddressListArgs
{ _port :: Port "Wallet"
, _state :: Maybe AddressState
, _id :: WalletId
}
cmdAddressList
:: AddressClient
-> Mod CommandFields (IO ())
cmdAddressList mkClient =
command "list" $ info (helper <*> cmd) $ mempty
<> progDesc "List all known addresses of a given wallet."
where
cmd = fmap exec $ AddressListArgs
<$> portOption
<*> optional addressStateOption
<*> walletIdArgument
exec (AddressListArgs wPort wState wId) = do
runClient wPort Aeson.encodePretty $ listAddresses mkClient
(ApiT wId)
(ApiT <$> wState)
-- | Arguments for 'address create' command
data AddressCreateArgs = AddressCreateArgs
{ _port :: Port "Wallet"
, _addressIndex :: Maybe (Index 'Hardened 'AddressK)
, _id :: WalletId
}
cmdAddressCreate
:: AddressClient
-> Mod CommandFields (IO ())
cmdAddressCreate mkClient =
command "create" $ info (helper <*> cmd) $ mempty
<> progDesc "Create a new random address. Only available for random wallets. \
\The address index is optional, give none to let the wallet generate \
\a random one."
where
cmd = fmap exec $ AddressCreateArgs
<$> portOption