forked from iotaledger/iota-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
1797 lines (1579 loc) · 63.5 KB
/
mod.rs
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
// Copyright 2020-2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
mod completer;
use std::str::FromStr;
use clap::{CommandFactory, Parser, Subcommand};
use colored::Colorize;
use eyre::Error;
use iota_sdk::{
client::{api::options::TransactionOptions, request_funds_from_faucet, secret::SecretManager},
types::block::{
address::{AccountAddress, Bech32Address, ToBech32Ext},
mana::ManaAllotment,
output::{
feature::{BlockIssuerKeySource, Ed25519PublicKeyHashBlockIssuerKey, MetadataFeature},
unlock_condition::AddressUnlockCondition,
AccountId, BasicOutputBuilder, DelegationId, FoundryId, NativeToken, NativeTokensBuilder, NftId, Output,
OutputId, TokenId,
},
payload::signed_transaction::TransactionId,
slot::{EpochIndex, SlotIndex},
IdentifierError,
},
utils::ConvertTo,
wallet::{
types::OutputData, BeginStakingParams, ConsolidationParams, CreateDelegationParams, CreateNativeTokenParams,
MintNftParams, ModifyAccountBlockIssuerKey, OutputsToClaim, ReturnStrategy, SendManaParams,
SendNativeTokenParams, SendNftParams, SendParams, SyncOptions, Wallet, WalletError,
},
U256,
};
use rustyline::{error::ReadlineError, history::MemHistory, Config, Editor};
use self::completer::WalletCommandHelper;
use crate::{
helper::{bytes_from_hex_or_file, enter_password, to_utc_date_time},
println_log_error, println_log_info,
};
const DEFAULT_FAUCET_URL: &str = "http://localhost:8088/api/enqueue";
#[derive(Debug, Parser)]
#[command(author, version, about, long_about = None, propagate_version = true)]
pub struct WalletCli {
#[command(subcommand)]
pub command: WalletCommand,
}
impl WalletCli {
pub fn print_help() -> Result<(), Error> {
Self::command().bin_name("Wallet:").print_help()?;
Ok(())
}
}
/// Commands
#[derive(Debug, Subcommand, strum::VariantNames)]
#[strum(serialize_all = "kebab-case")]
#[allow(clippy::large_enum_variant)]
pub enum WalletCommand {
/// Lists the accounts of the wallet.
Accounts,
/// Print the wallet address.
Address,
/// Allots mana to an account.
AllotMana { mana: u64, account_id: Option<AccountId> },
/// Announces that a staking account wants to be a validator for the current epoch.
AnnounceCandidacy {
/// The account ID which will announce its candidacy to be a validator.
account_id: AccountId,
},
/// Print the wallet balance.
Balance,
BeginStaking {
/// The Account ID which will begin staking.
account_id: AccountId,
/// The amount of tokens to stake.
staked_amount: u64,
/// The fixed cost of the validator, which it receives as part of its Mana rewards.
fixed_cost: u64,
/// The staking period (in epochs). Will default to the staking unbonding period.
staking_period: Option<u32>,
},
/// Burn an amount of native token.
BurnNativeToken {
/// Token ID to be burnt, e.g. 0x087d205988b733d97fb145ae340e27a8b19554d1ceee64574d7e5ff66c45f69e7a0100000000.
token_id: TokenId,
/// Amount to be burnt, e.g. 100.
#[arg(value_parser = parse_u256)]
amount: U256,
},
/// Burn an NFT.
BurnNft {
/// NFT ID to be burnt, e.g. 0xecadf10e6545aa82da4df2dfd2a496b457c8850d2cab49b7464cb273d3dffb07.
nft_id: NftId,
},
/// Claim outputs with storage deposit return, expiration or timelock unlock conditions.
Claim {
/// Output ID to be claimed.
output_id: Option<OutputId>,
},
/// Print details about claimable outputs - if there are any.
ClaimableOutputs,
/// Get the committee for the given epoch.
Committee { epoch: Option<EpochIndex> },
/// Checks if an account is ready to issue a block.
Congestion {
account_id: Option<AccountId>,
work_score: Option<u32>,
},
/// Consolidate all basic outputs into one address.
Consolidate,
/// Create a new account output.
CreateAccountOutput,
/// Create a delegation.
CreateDelegation {
/// The amount to delegate.
delegated_amount: u64,
/// The account ID of the validator.
validator_account_id: AccountId,
/// The address that will control the delegation. Defaults to the wallet address.
address: Option<Bech32Address>,
},
/// Create a native token.
CreateNativeToken {
/// Circulating supply of the native token to be minted, e.g. 100.
#[arg(value_parser = parse_u256)]
circulating_supply: U256,
/// Maximum supply of the native token to be minted, e.g. 500.
#[arg(value_parser = parse_u256)]
maximum_supply: U256,
/// Metadata key, e.g. --foundry-metadata-key data.
#[arg(long, default_value = "data")]
foundry_metadata_key: String,
/// Metadata to attach to the associated foundry, e.g. --foundry-metadata-hex 0xdeadbeef.
#[arg(long, group = "foundry_metadata")]
foundry_metadata_hex: Option<String>,
/// Metadata to attach to the associated foundry, e.g. --foundry-metadata-file ./foundry-metadata.json.
#[arg(long, group = "foundry_metadata")]
foundry_metadata_file: Option<String>,
},
/// Delay the claiming of a delegation.
DelayDelegationClaiming {
/// ID of the delegation to be delayed.
delegation_id: DelegationId,
/// Whether excess amount above the minimum storage requirement should be reclaimed.
/// Otherwise the excess will be transferred into a new delegation.
reclaim_excess: bool,
},
/// Destroy an account output.
DestroyAccount {
/// Account ID to be destroyed, e.g. 0xed5a90106ae5d402ebaecb9ba36f32658872df789f7a29b9f6d695b912ec6a1e.
account_id: AccountId,
},
/// Destroy a delegation.
DestroyDelegation {
/// ID of the delegation to be destroyed.
delegation_id: DelegationId,
},
/// Destroy a foundry.
DestroyFoundry {
/// Foundry ID to be destroyed, e.g.
/// 0x08cb54928954c3eb7ece1bf1cc0c68eb179dc1c4634ae5d23df1c70643d0911c3d0200000000.
foundry_id: FoundryId,
},
/// End a staking and claim the rewards.
EndStaking {
/// The Account ID of the staking account.
account_id: AccountId,
},
/// Exit the CLI wallet.
Exit,
/// Extend a staking by some additional epochs.
ExtendStaking {
/// The Account ID of the staking account.
account_id: AccountId,
/// The number of additional epochs to add to the staking period.
additional_epochs: u32,
},
/// Request funds from the faucet.
Faucet {
/// Address the faucet sends the funds to. If not provided, the command defaults to the wallet address.
address: Option<Bech32Address>,
/// URL of the faucet.
#[arg(short, long, value_name = "URL", env = "FAUCET_URL", default_value = DEFAULT_FAUCET_URL)]
url: String,
},
/// Returns the implicit account creation address of the wallet if it is Ed25519 based.
ImplicitAccountCreationAddress,
/// Transitions an implicit account to an account.
ImplicitAccountTransition {
/// Identifier of the implicit account output.
output_id: OutputId,
},
/// Lists the implicit accounts of the wallet.
ImplicitAccounts,
/// Adds a block issuer key to an account.
AddBlockIssuerKey {
/// The account to which the key should be added.
account_id: AccountId,
/// The hex-encoded public key to add.
// TODO: Use the actual type somehow?
block_issuer_key: String,
},
/// Removes a block issuer key from an account.
RemoveBlockIssuerKey {
/// The account from which the key should be removed.
account_id: AccountId,
/// The hex-encoded public key to remove.
// TODO: Use the actual type somehow?
block_issuer_key: String,
},
/// Mint additional native tokens.
MintNativeToken {
/// Token ID to be minted, e.g. 0x087d205988b733d97fb145ae340e27a8b19554d1ceee64574d7e5ff66c45f69e7a0100000000.
token_id: TokenId,
/// Amount to be minted, e.g. 100.
#[arg(value_parser = parse_u256)]
amount: U256,
},
/// Mint an NFT.
/// IOTA NFT Standard - TIP27: <https://github.com/iotaledger/tips/blob/main/tips/TIP-0027/tip-0027.md>.
MintNft {
/// Address to send the NFT to, e.g. rms1qztwng6cty8cfm42nzvq099ev7udhrnk0rw8jt8vttf9kpqnxhpsx869vr3.
address: Option<Bech32Address>,
/// Immutable metadata key, e.g. --immutable-metadata-key data.
#[arg(long, default_value = "data")]
immutable_metadata_key: String,
#[arg(long, group = "immutable_metadata")]
/// Immutable metadata to attach to the NFT, e.g. --immutable-metadata-hex 0xdeadbeef.
immutable_metadata_hex: Option<String>,
/// Immutable metadata to attach to the NFT, e.g. --immutable-metadata-file ./nft-immutable-metadata.json.
#[arg(long, group = "immutable_metadata")]
immutable_metadata_file: Option<String>,
/// Metadata key, e.g. --metadata-key data.
#[arg(long, default_value = "data")]
metadata_key: String,
/// Metadata to attach to the NFT, e.g. --metadata-hex 0xdeadbeef.
#[arg(long, group = "metadata")]
metadata_hex: Option<String>,
/// Metadata to attach to the NFT, e.g. --metadata-file ./nft-metadata.json.
#[arg(long, group = "metadata")]
metadata_file: Option<String>,
#[arg(long)]
/// Tag feature to attach to the NFT, e.g. 0xdeadbeef.
tag: Option<String>,
/// Sender feature to attach to the NFT, e.g. rms1qztwng6cty8cfm42nzvq099ev7udhrnk0rw8jt8vttf9kpqnxhpsx869vr3.
#[arg(long)]
sender: Option<Bech32Address>,
/// Issuer feature to attach to the NFT, e.g. rms1qztwng6cty8cfm42nzvq099ev7udhrnk0rw8jt8vttf9kpqnxhpsx869vr3.
#[arg(long)]
issuer: Option<Bech32Address>,
},
/// Melt an amount of native token.
MeltNativeToken {
/// Token ID to be melted, e.g. 0x087d205988b733d97fb145ae340e27a8b19554d1ceee64574d7e5ff66c45f69e7a0100000000.
token_id: TokenId,
/// Amount to be melted, e.g. 100.
#[arg(value_parser = parse_u256)]
amount: U256,
},
/// Get information about currently set node.
NodeInfo,
/// Display an output.
Output {
/// Selector for output.
/// Either by ID (e.g. 0xbce525324af12eda02bf7927e92cea3a8e8322d0f41966271443e6c3b245a4400000) or index.
selector: OutputSelector,
#[arg(short, long)]
metadata: bool,
},
/// List all outputs.
Outputs,
/// Send an amount.
Send {
/// Address to send funds to, e.g. rms1qztwng6cty8cfm42nzvq099ev7udhrnk0rw8jt8vttf9kpqnxhpsx869vr3.
address: Bech32Address,
/// Amount to send, e.g. 1000000.
amount: u64,
/// Bech32 encoded return address, to which the storage deposit will be returned if one is necessary
/// given the provided amount. If a storage deposit is needed and a return address is not provided, it will
/// default to the wallet address.
#[arg(long)]
return_address: Option<Bech32Address>,
/// Expiration in slot indices, after which the output will be available for the sender again, if not spent by
/// the receiver already. The expiration will only be used if one is necessary given the provided
/// amount. If an expiration is needed but not provided, it will default to one day.
#[arg(long)]
expiration: Option<SlotIndex>,
/// Whether to send micro amounts. This will automatically add Storage Deposit Return and Expiration unlock
/// conditions if necessary. This flag is implied by the existence of a return address or expiration.
#[arg(long, default_value_t = false)]
allow_micro_amount: bool,
},
/// Send mana.
SendMana {
/// Recipient address, e.g. rms1qztwng6cty8cfm42nzvq099ev7udhrnk0rw8jt8vttf9kpqnxhpsx869vr3.
address: Bech32Address,
/// Amount of mana to send, e.g. 1000000.
mana: u64,
/// Whether to gift the storage deposit or not.
#[arg(short, long, default_value_t = false)]
gift: bool,
},
/// Send a native token.
/// This will create an output with an expiration and storage deposit return unlock condition.
SendNativeToken {
/// Address to send the native tokens to, e.g. rms1qztwng6cty8cfm42nzvq099ev7udhrnk0rw8jt8vttf9kpqnxhpsx869vr3.
address: Bech32Address,
/// Token ID to be sent, e.g. 0x087d205988b733d97fb145ae340e27a8b19554d1ceee64574d7e5ff66c45f69e7a0100000000.
token_id: TokenId,
/// Amount to send, e.g. 1000000.
#[arg(value_parser = parse_u256)]
amount: U256,
/// Whether to gift the storage deposit for the output or not, e.g. `true`.
#[arg(short, long)]
gift_storage_deposit: Option<bool>,
},
/// Send an NFT.
SendNft {
/// Address to send the NFT to, e.g. rms1qztwng6cty8cfm42nzvq099ev7udhrnk0rw8jt8vttf9kpqnxhpsx869vr3.
address: Bech32Address,
/// NFT ID to be sent, e.g. 0xecadf10e6545aa82da4df2dfd2a496b457c8850d2cab49b7464cb273d3dffb07.
nft_id: NftId,
},
/// Synchronize the wallet.
Sync,
/// Show the details of a transaction.
#[clap(visible_alias = "tx")]
Transaction {
/// Selector for transaction.
/// Either by ID (e.g. 0x84fe6b1796bddc022c9bc40206f0a692f4536b02aa8c13140264e2e01a3b7e4b) or index.
selector: TransactionSelector,
},
/// List the wallet transactions.
#[clap(visible_alias = "txs")]
Transactions {
/// List wallet transactions with all details.
#[arg(long, default_value_t = false)]
show_details: bool,
},
/// List the unspent outputs.
UnspentOutputs,
/// Get information of a validator.
Validator { account_id: AccountId },
/// List all validators known to the node.
Validators,
// /// Cast votes for an event.
// Vote {
// /// Event ID for which to cast votes, e.g.
// 0xdc049a721dc65ec342f836c876ec15631ed915cd55213cee39e8d1c821c751f2. event_id: ParticipationEventId,
// /// Answers to the event questions.
// answers: Vec<u8>,
// },
// /// Stop participating to an event.
// StopParticipating {
// /// Event ID for which to stop participation, e.g.
// /// 0xdc049a721dc65ec342f836c876ec15631ed915cd55213cee39e8d1c821c751f2.
// event_id: ParticipationEventId,
// },
// /// Get the participation overview of the wallet.
// ParticipationOverview {
// /// Event IDs for which to get the participation overview, e.g.
// /// 0xdc049a721dc65ec342f836c876ec15631ed915cd55213cee39e8d1c821c751f2...
// #[arg(short, long, num_args = 1.., value_delimiter = ' ')]
// event_ids: Vec<ParticipationEventId>,
// },
// /// Get the voting power of the wallet.
// VotingPower,
// /// Increase the voting power of the wallet.
// IncreaseVotingPower {
// /// Amount to increase the voting power by, e.g. 100.
// amount: u64,
// },
// /// Decrease the voting power of the wallet.
// DecreaseVotingPower {
// /// Amount to decrease the voting power by, e.g. 100.
// amount: u64,
// },
// /// Get the voting output of the wallet.
// VotingOutput,
}
fn parse_u256(s: &str) -> Result<U256, Error> {
Ok(U256::from_dec_str(s)?)
}
/// Select by transaction ID or list index
#[derive(Debug, Copy, Clone)]
pub enum TransactionSelector {
Id(TransactionId),
Index(usize),
}
impl FromStr for TransactionSelector {
type Err = IdentifierError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(if let Ok(index) = s.parse() {
Self::Index(index)
} else {
Self::Id(s.parse()?)
})
}
}
/// Select by output ID or list index
#[derive(Debug, Copy, Clone)]
pub enum OutputSelector {
Id(OutputId),
Index(usize),
}
impl FromStr for OutputSelector {
type Err = IdentifierError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(if let Ok(index) = s.parse() {
Self::Index(index)
} else {
Self::Id(s.parse()?)
})
}
}
// `accounts` command
pub async fn accounts_command(wallet: &Wallet) -> Result<(), Error> {
let wallet_ledger = wallet.ledger().await;
let accounts = wallet_ledger.accounts();
let hrp = wallet.client().get_bech32_hrp().await?;
println_log_info!("Accounts:\n");
for account in accounts {
let output_id = account.output_id;
let account_id = account.output.as_account().account_id_non_null(&output_id);
let account_address = account_id.to_bech32(hrp);
let bic = wallet
.client()
.get_account_congestion(&account_id, None)
.await
.map(|r| r.block_issuance_credits)
.ok();
println_log_info!(
"{:<16} {output_id}\n{:<16} {account_id}\n{:<16} {account_address}\n{:<16} {bic:?}\n",
"Output ID:",
"Account ID:",
"Account Address:",
"BIC:"
);
}
Ok(())
}
// `address` command
pub async fn address_command(wallet: &Wallet) -> Result<(), Error> {
print_wallet_address(wallet).await?;
Ok(())
}
// `allot-mana` command
pub async fn allot_mana_command(wallet: &Wallet, mana: u64, account_id: Option<AccountId>) -> Result<(), Error> {
let account_id = match account_id {
Some(account_id) => account_id,
None => wallet
.first_block_issuer_account_id()
.await?
.ok_or(WalletError::AccountNotFound)?,
};
let transaction = wallet.allot_mana([ManaAllotment::new(account_id, mana)?], None).await?;
println_log_info!(
"Mana allotment transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
Ok(())
}
// `announce-candidacy` command
pub async fn announce_candidacy_command(wallet: &Wallet, account_id: AccountId) -> Result<(), Error> {
println_log_info!("Announcing candidacy for account {account_id}");
let block_id = wallet.announce_candidacy(account_id).await?;
println_log_info!("Block submitted: {block_id}");
Ok(())
}
// `balance` command
pub async fn balance_command(wallet: &Wallet) -> Result<(), Error> {
let balance = wallet.balance().await?;
println_log_info!("{balance:#?}");
Ok(())
}
// `begin-staking` command
pub async fn begin_staking_command(
wallet: &Wallet,
account_id: AccountId,
staked_amount: u64,
fixed_cost: u64,
staking_period: Option<u32>,
) -> Result<(), Error> {
println_log_info!("Begin staking for {account_id}.");
let transaction = wallet
.begin_staking(
BeginStakingParams {
account_id,
staked_amount,
fixed_cost,
staking_period,
},
None,
)
.await?;
println_log_info!(
"Begin staking transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
Ok(())
}
// `burn-native-token` command
pub async fn burn_native_token_command(wallet: &Wallet, token_id: TokenId, amount: U256) -> Result<(), Error> {
println_log_info!("Burning native token {token_id} {amount}.");
let transaction = wallet.burn(NativeToken::new(token_id, amount)?, None).await?;
println_log_info!(
"Burning transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
Ok(())
}
// `burn-nft` command
pub async fn burn_nft_command(wallet: &Wallet, nft_id: NftId) -> Result<(), Error> {
println_log_info!("Burning nft {nft_id}.");
let transaction = wallet.burn(nft_id, None).await?;
println_log_info!(
"Burning transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
Ok(())
}
// `claim` command
pub async fn claim_command(wallet: &Wallet, output_id: Option<OutputId>) -> Result<(), Error> {
if let Some(output_id) = output_id {
println_log_info!("Claiming output {output_id}");
let transaction = wallet.claim_outputs([output_id]).await?;
println_log_info!(
"Claiming transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
} else {
println_log_info!("Claiming outputs.");
let output_ids = wallet.claimable_outputs(OutputsToClaim::All).await?;
if output_ids.is_empty() {
println_log_info!("No outputs available to claim.");
}
// Doing chunks of only 60, because we might need to create the double amount of outputs, because of potential
// storage deposit return unlock conditions and also consider the remainder output.
for output_ids_chunk in output_ids.chunks(60) {
let transaction = wallet.claim_outputs(output_ids_chunk.to_vec()).await?;
println_log_info!(
"Claiming transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
}
};
Ok(())
}
/// `claimable-outputs` command
pub async fn claimable_outputs_command(wallet: &Wallet) -> Result<(), Error> {
for output_id in wallet.claimable_outputs(OutputsToClaim::All).await? {
let wallet_ledger = wallet.ledger().await;
// Unwrap: for the iterated `OutputId`s this call will always return `Some(...)`.
let output = &wallet_ledger.get_output(&output_id).unwrap().output;
let kind = match output {
Output::Nft(_) => "Nft",
Output::Basic(_) => "Basic",
_ => unreachable!(),
};
println_log_info!("{output_id:?} ({kind})");
if let Some(native_token) = output.native_token() {
println_log_info!(" - native token amount:");
println_log_info!(" + {} {}", native_token.amount(), native_token.token_id());
}
let deposit_return = output
.unlock_conditions()
.storage_deposit_return()
.map(|deposit_return| deposit_return.amount())
.unwrap_or(0);
let amount = output.amount() - deposit_return;
println_log_info!(" - base coin amount: {}", amount);
if let Some(expiration) = output.unlock_conditions().expiration() {
let slot_index = wallet.client().get_slot_index().await?;
if *expiration.slot_index() > *slot_index {
println_log_info!(" - expires in {} slot indices", *expiration.slot_index() - *slot_index);
} else {
println_log_info!(
" - expired {} slot indices ago",
*slot_index - *expiration.slot_index()
);
}
}
}
Ok(())
}
/// `committee` command
pub async fn committee_command(wallet: &Wallet, epoch: Option<EpochIndex>) -> Result<(), Error> {
let committee = wallet.client().get_committee(epoch).await?;
println_log_info!("{committee:#?}");
Ok(())
}
// `congestion` command
pub async fn congestion_command(
wallet: &Wallet,
account_id: Option<AccountId>,
work_score: Option<u32>,
) -> Result<(), Error> {
let account_id = match account_id {
Some(account_id) => account_id,
None => wallet
.first_block_issuer_account_id()
.await?
.ok_or(WalletError::AccountNotFound)?,
};
let congestion = wallet.client().get_account_congestion(&account_id, work_score).await?;
println_log_info!("{congestion:#?}");
Ok(())
}
// `consolidate` command
pub async fn consolidate_command(wallet: &Wallet) -> Result<(), Error> {
println_log_info!("Consolidating outputs.");
let transaction = wallet
.consolidate_outputs(ConsolidationParams::new().with_force(true))
.await?;
println_log_info!(
"Consolidation transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
Ok(())
}
// `create-account-output` command
pub async fn create_account_output_command(wallet: &Wallet) -> Result<(), Error> {
println_log_info!("Creating account output.");
let transaction = wallet.create_account_output(None, None).await?;
println_log_info!(
"Account output creation transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
Ok(())
}
// `create-delegation` command
pub async fn create_delegation_command(
wallet: &Wallet,
address: Option<Bech32Address>,
delegated_amount: u64,
validator_account_id: AccountId,
) -> Result<(), Error> {
println_log_info!("Creating delegation output.");
let transaction = wallet
.create_delegation_output(
CreateDelegationParams {
address,
delegated_amount,
validator_address: AccountAddress::new(validator_account_id),
},
None,
)
.await?;
println_log_info!(
"Delegation creation transaction sent:\n{:?}\n{:?}\n{:?}",
transaction.transaction.transaction_id,
transaction.transaction.block_id,
transaction.delegation_id
);
Ok(())
}
// `create-native-token` command
pub async fn create_native_token_command(
wallet: &Wallet,
circulating_supply: U256,
maximum_supply: U256,
foundry_metadata: Option<MetadataFeature>,
) -> Result<(), Error> {
// If no account output exists, create one first
if wallet.balance().await?.accounts().is_empty() {
let transaction = wallet.create_account_output(None, None).await?;
println_log_info!(
"Account output minting transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
wallet
.wait_for_transaction_acceptance(&transaction.transaction_id, None, None)
.await?;
// Sync wallet after the transaction got confirmed, so the account output is available
wallet.sync(None).await?;
}
let params = CreateNativeTokenParams {
account_id: None,
circulating_supply,
maximum_supply,
foundry_metadata,
};
let create_transaction = wallet.create_native_token(params, None).await?;
println_log_info!(
"Transaction to create native token sent:\n{:?}\n{:?}",
create_transaction.transaction.transaction_id,
create_transaction.transaction.block_id
);
Ok(())
}
// `delay-delegation-claiming` command
pub async fn delay_delegation_claiming_command(
wallet: &Wallet,
delegation_id: DelegationId,
reclaim_excess: bool,
) -> Result<(), Error> {
println_log_info!("Delaying delegation claiming.");
let transaction = wallet.delay_delegation_claiming(delegation_id, reclaim_excess).await?;
println_log_info!(
"Delay delegation claiming transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
Ok(())
}
// `destroy-account` command
pub async fn destroy_account_command(wallet: &Wallet, account_id: AccountId) -> Result<(), Error> {
println_log_info!("Destroying account {account_id}.");
let transaction = wallet.burn(account_id, None).await?;
println_log_info!(
"Destroying account transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
Ok(())
}
// `destroy-delegation` command
pub async fn destroy_delegation_command(wallet: &Wallet, delegation_id: DelegationId) -> Result<(), Error> {
println_log_info!("Destroying delegation {delegation_id}.");
let transaction = wallet.burn(delegation_id, None).await?;
println_log_info!(
"Destroying delegation transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
Ok(())
}
// `destroy-foundry` command
pub async fn destroy_foundry_command(wallet: &Wallet, foundry_id: FoundryId) -> Result<(), Error> {
println_log_info!("Destroying foundry {foundry_id}.");
let transaction = wallet.burn(foundry_id, None).await?;
println_log_info!(
"Destroying foundry transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
Ok(())
}
// `end-staking` command
pub async fn end_staking_command(wallet: &Wallet, account_id: AccountId) -> Result<(), Error> {
println_log_info!("Ending staking for {account_id}.");
let transaction = wallet.end_staking(account_id, None).await?;
println_log_info!(
"End staking transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
Ok(())
}
// `extend-staking` command
pub async fn extend_staking_command(
wallet: &Wallet,
account_id: AccountId,
additional_epochs: u32,
) -> Result<(), Error> {
println_log_info!("Extending staking for {account_id} by {additional_epochs} epochs.");
let transaction = wallet.extend_staking(account_id, additional_epochs, None).await?;
println_log_info!(
"Extend staking transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
Ok(())
}
// `faucet` command
pub async fn faucet_command(wallet: &Wallet, address: Option<Bech32Address>, url: &str) -> Result<(), Error> {
let address = if let Some(address) = address {
address
} else {
wallet.address().await
};
let response = request_funds_from_faucet(url, &address).await?;
println_log_info!("{response}");
Ok(())
}
// `implicit-account-creation-address` command
pub async fn implicit_account_creation_address_command(wallet: &Wallet) -> Result<(), Error> {
let address = wallet.implicit_account_creation_address().await?;
println_log_info!("{address}");
Ok(())
}
// `implicit-account-transition` command
pub async fn implicit_account_transition_command(wallet: &Wallet, output_id: OutputId) -> Result<(), Error> {
let transaction = wallet
.implicit_account_transition(&output_id, BlockIssuerKeySource::ImplicitAccountAddress)
.await?;
println_log_info!(
"Implicit account transition transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
Ok(())
}
// `implicit-accounts` command
pub async fn implicit_accounts_command(wallet: &Wallet) -> Result<(), Error> {
let wallet_ledger = wallet.ledger().await;
let implicit_accounts = wallet_ledger.implicit_accounts();
let hrp = wallet.client().get_bech32_hrp().await?;
println_log_info!("Implicit accounts:\n");
for implicit_account in implicit_accounts {
let output_id = implicit_account.output_id;
let account_id = AccountId::from(&output_id);
let account_address = account_id.to_bech32(hrp);
let bic = wallet
.client()
.get_account_congestion(&account_id, None)
.await
.map(|r| r.block_issuance_credits)
.ok();
println_log_info!(
"{:<16} {output_id}\n{:<16} {account_id}\n{:<16} {account_address}\n{:<16} {bic:?}\n",
"Output ID:",
"Account ID:",
"Account Address:",
"BIC:"
);
}
Ok(())
}
// `add-block-issuer-key` command
pub async fn add_block_issuer_key(wallet: &Wallet, account_id: AccountId, issuer_key: &str) -> Result<(), Error> {
let issuer_key: [u8; Ed25519PublicKeyHashBlockIssuerKey::LENGTH] = prefix_hex::decode(issuer_key)?;
let params = ModifyAccountBlockIssuerKey {
account_id,
keys_to_add: vec![Ed25519PublicKeyHashBlockIssuerKey::new(issuer_key).into()],
keys_to_remove: vec![],
};
let transaction = wallet.modify_account_output_block_issuer_keys(params, None).await?;
println_log_info!(
"Block issuer key adding transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
Ok(())
}
// `remove-block-issuer-key` command
pub async fn remove_block_issuer_key(wallet: &Wallet, account_id: AccountId, issuer_key: &str) -> Result<(), Error> {
let issuer_key: [u8; Ed25519PublicKeyHashBlockIssuerKey::LENGTH] = prefix_hex::decode(issuer_key)?;
let params = ModifyAccountBlockIssuerKey {
account_id,
keys_to_add: vec![],
keys_to_remove: vec![Ed25519PublicKeyHashBlockIssuerKey::new(issuer_key).into()],
};
let transaction = wallet.modify_account_output_block_issuer_keys(params, None).await?;
println_log_info!(
"Block issuer key removing transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
Ok(())
}
// `melt-native-token` command
pub async fn melt_native_token_command(wallet: &Wallet, token_id: TokenId, amount: U256) -> Result<(), Error> {
let transaction = wallet.melt_native_token(token_id, amount, None).await?;
println_log_info!(
"Native token melting transaction sent:\n{:?}\n{:?}",
transaction.transaction_id,
transaction.block_id
);
Ok(())
}
// `mint-native-token` command
pub async fn mint_native_token_command(wallet: &Wallet, token_id: TokenId, amount: U256) -> Result<(), Error> {
let mint_transaction = wallet.mint_native_token(token_id, amount, None).await?;
println_log_info!(