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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
use alloc::string::String;
use thiserror_no_std::Error;
#[cfg(feature = "std")]
mod std_cli;
#[cfg(feature = "std")]
pub use std_cli::run;
/// Default mainnet URL for JSON-RPC requests
pub const DEFAULT_MAINNET_URL: &str = "https://xrplcluster.com/";
/// Default testnet URL for faucet functionality
pub const DEFAULT_TESTNET_URL: &str = "https://s.altnet.rippletest.net:51234";
/// Default WebSocket URL
pub const DEFAULT_WEBSOCKET_URL: &str = "wss://xrplcluster.com/";
/// Default limit for paginated results
pub const DEFAULT_PAGINATION_LIMIT: u32 = 10;
// CLI commands with subcommand hierarchy
#[cfg_attr(feature = "std", derive(clap::Parser))]
#[derive(Debug, Clone)]
#[cfg_attr(
feature = "std",
command(name = "xrpl", about = "XRPL command line utility")
)]
pub struct Cli {
#[cfg_attr(feature = "std", command(subcommand))]
pub command: Commands,
}
#[cfg_attr(feature = "std", derive(clap::Subcommand))]
#[derive(Debug, Clone)]
pub enum Commands {
/// Wallet operations
#[cfg_attr(feature = "std", command(subcommand))]
Wallet(WalletCommands),
/// Account operations
#[cfg_attr(feature = "std", command(subcommand))]
Account(AccountCommands),
/// Transaction operations
#[cfg_attr(feature = "std", command(subcommand))]
Transaction(TransactionCommands),
/// Server operations
#[cfg_attr(feature = "std", command(subcommand))]
Server(ServerCommands),
/// Ledger operations
#[cfg_attr(feature = "std", command(subcommand))]
Ledger(LedgerCommands),
}
#[cfg_attr(feature = "std", derive(clap::Subcommand))]
#[derive(Debug, Clone)]
pub enum WalletCommands {
/// Generate a new wallet
Generate {
/// Save the wallet to a file
#[cfg_attr(feature = "std", arg(long))]
save: bool,
/// Generate a BIP39 mnemonic phrase
#[cfg_attr(feature = "std", arg(long))]
mnemonic: bool,
/// Number of words for the mnemonic (12, 15, 18, 21, 24)
#[cfg_attr(feature = "std", arg(long, default_value_t = 12))]
words: usize,
},
/// Get wallet info from seed
FromSeed {
/// The seed to use
#[cfg_attr(feature = "std", arg(long))]
seed: String,
/// The sequence number
#[cfg_attr(feature = "std", arg(long, default_value = "0"))]
sequence: u64,
},
/// Generate a wallet funded by the testnet faucet
#[cfg(feature = "std")]
Faucet {
/// The XRPL node URL
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_TESTNET_URL.into()))]
url: String,
},
/// Validate an address
Validate {
/// The address to validate
#[cfg_attr(feature = "std", arg(long))]
address: String,
},
}
#[cfg_attr(feature = "std", derive(clap::Subcommand))]
#[derive(Debug, Clone)]
pub enum AccountCommands {
/// Get account info
Info {
/// The account address
#[cfg_attr(feature = "std", arg(long))]
address: String,
/// The XRPL node URL
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_MAINNET_URL.into()))]
url: String,
},
/// Get account transactions
Tx {
/// The account address
#[cfg_attr(feature = "std", arg(long))]
address: String,
/// The XRPL node URL
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_MAINNET_URL.into()))]
url: String,
/// Limit the number of transactions returned
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_PAGINATION_LIMIT))]
limit: u32,
},
/// Get account objects (trust lines, offers, etc.)
Objects {
/// The account address
#[cfg_attr(feature = "std", arg(long))]
address: String,
/// The XRPL node URL
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_MAINNET_URL.into()))]
url: String,
/// Type of objects to return (all, offer, state, etc.)
#[cfg_attr(feature = "std", arg(long))]
type_filter: Option<String>,
/// Limit the number of objects returned
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_PAGINATION_LIMIT as u16))]
limit: u16,
},
/// Get account channels
Channels {
/// The account address
#[cfg_attr(feature = "std", arg(long))]
address: String,
/// The XRPL node URL
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_MAINNET_URL.into()))]
url: String,
/// Destination account to filter channels
#[cfg_attr(feature = "std", arg(long))]
destination_account: Option<String>,
/// Limit the number of channels returned
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_PAGINATION_LIMIT as u16))]
limit: u16,
},
/// Get account currencies
Currencies {
/// The account address
#[cfg_attr(feature = "std", arg(long))]
address: String,
/// The XRPL node URL
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_MAINNET_URL.into()))]
url: String,
},
/// Get account trust lines
Lines {
/// The account address
#[cfg_attr(feature = "std", arg(long))]
address: String,
/// The XRPL node URL
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_MAINNET_URL.into()))]
url: String,
/// Peer account to filter trust lines
#[cfg_attr(feature = "std", arg(long))]
peer: Option<String>,
/// Limit the number of trust lines returned
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_PAGINATION_LIMIT as u16))]
limit: u16,
},
/// Get account NFTs (XLS-20)
Nfts {
/// The account address
#[cfg_attr(feature = "std", arg(long))]
address: String,
/// The XRPL node URL
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_MAINNET_URL.into()))]
url: String,
},
/// Set an account flag
SetFlag {
/// The seed to use for signing
#[cfg_attr(feature = "std", arg(short, long))]
seed: String,
/// The flag to set (e.g., asfRequireAuth, asfDisableMaster, etc.)
#[cfg_attr(feature = "std", arg(short, long))]
flag: String,
/// The XRPL node URL
#[cfg_attr(feature = "std", arg(short, long, default_value_t = DEFAULT_MAINNET_URL.into()))]
url: String,
},
/// Clear an account flag
ClearFlag {
/// The seed to use for signing
#[cfg_attr(feature = "std", arg(short, long))]
seed: String,
/// The flag to clear (e.g., asfRequireAuth, asfDisableMaster, etc.)
#[cfg_attr(feature = "std", arg(short, long))]
flag: String,
/// The XRPL node URL
#[cfg_attr(feature = "std", arg(short, long, default_value_t = DEFAULT_MAINNET_URL.into()))]
url: String,
},
}
#[cfg_attr(feature = "std", derive(clap::Subcommand))]
#[derive(Debug, Clone)]
pub enum TransactionCommands {
/// Sign a transaction
Sign {
/// The seed to use for signing
#[cfg_attr(feature = "std", arg(short, long))]
seed: String,
/// The transaction type (Payment, AccountSet, etc.)
#[cfg_attr(feature = "std", arg(short, long))]
r#type: String,
/// The transaction JSON
#[cfg_attr(feature = "std", arg(short, long))]
json: String,
},
/// Submit a transaction
Submit {
/// The signed transaction blob or JSON
#[cfg_attr(feature = "std", arg(short, long))]
tx_blob: String,
/// The XRPL node URL
#[cfg_attr(feature = "std", arg(short, long, default_value_t = DEFAULT_MAINNET_URL.into()))]
url: String,
},
/// Set or modify a trust line
TrustSet {
/// The seed to use for signing
#[cfg_attr(feature = "std", arg(short, long))]
seed: String,
/// The issuer account
#[cfg_attr(feature = "std", arg(short, long))]
issuer: String,
/// The currency code (3-letter or 40-char hex)
#[cfg_attr(feature = "std", arg(short, long))]
currency: String,
/// The trust line limit (amount)
#[cfg_attr(feature = "std", arg(short, long))]
limit: String,
/// The XRPL node URL
#[cfg_attr(feature = "std", arg(short, long, default_value_t = DEFAULT_MAINNET_URL.into()))]
url: String,
},
/// Mint an NFT (XLS-20)
NftMint {
/// The seed to use for signing
#[cfg_attr(feature = "std", arg(short, long))]
seed: String,
/// URI for the NFT (hex-encoded)
#[cfg_attr(feature = "std", arg(long))]
uri: String,
/// Flags (optional)
#[cfg_attr(feature = "std", arg(long))]
flags: Option<u32>,
/// Transfer fee (optional)
#[cfg_attr(feature = "std", arg(long))]
transfer_fee: Option<u16>,
/// XRPL node URL
#[cfg_attr(feature = "std", arg(short, long, default_value_t = DEFAULT_MAINNET_URL.into()))]
url: String,
},
/// Burn an NFT (XLS-20)
NftBurn {
/// The seed to use for signing
#[cfg_attr(feature = "std", arg(short, long))]
seed: String,
/// NFT Token ID to burn
#[cfg_attr(feature = "std", arg(short, long))]
nftoken_id: String,
/// XRPL node URL
#[cfg_attr(feature = "std", arg(short, long, default_value_t = DEFAULT_MAINNET_URL.into()))]
url: String,
},
}
#[cfg_attr(feature = "std", derive(clap::Subcommand))]
#[derive(Debug, Clone)]
pub enum ServerCommands {
/// Get current network fee
Fee {
/// The XRPL node URL
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_MAINNET_URL.into()))]
url: String,
},
/// Get server info
Info {
/// The XRPL node URL
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_MAINNET_URL.into()))]
url: String,
},
/// Subscribe to ledger events
Subscribe {
/// The XRPL node WebSocket URL
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_WEBSOCKET_URL.into()))]
url: String,
/// Stream type to subscribe to (ledger, transactions, validations)
#[cfg_attr(feature = "std", arg(long, default_value = "ledger"))]
stream: String,
/// Number of events to receive before exiting (0 for unlimited)
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_PAGINATION_LIMIT))]
limit: u32,
},
}
#[cfg_attr(feature = "std", derive(clap::Subcommand))]
#[derive(Debug, Clone)]
pub enum LedgerCommands {
/// Get ledger data
Data {
/// The XRPL node URL
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_MAINNET_URL.into()))]
url: String,
/// Ledger index (empty for latest)
#[cfg_attr(feature = "std", arg(long))]
ledger_index: Option<String>,
/// Ledger hash (empty for latest)
#[cfg_attr(feature = "std", arg(long))]
ledger_hash: Option<String>,
/// Limit the number of objects returned
#[cfg_attr(feature = "std", arg(long, default_value_t = DEFAULT_PAGINATION_LIMIT as u16))]
limit: u16,
},
}
/// Define a custom error type for CLI operations
#[derive(Debug, Error)]
pub enum CliError {
#[error("Wallet error: {0}")]
WalletError(#[from] crate::wallet::exceptions::XRPLWalletException),
#[error("Client error: {0}")]
ClientError(#[from] crate::asynch::clients::exceptions::XRPLClientException),
#[error("URL parse error: {0}")]
UrlParseError(#[from] url::ParseError),
#[error("JSON error: {0}")]
JsonError(#[from] serde_json::Error),
#[error("IO error: {0}")]
IoError(#[from] std::io::Error),
#[error("Helper error: {0}")]
HelperError(#[from] crate::asynch::exceptions::XRPLHelperException),
#[error("Core error: {0}")]
CoreError(#[from] crate::core::exceptions::XRPLCoreException),
#[error("Other error: {0}")]
Other(String),
}
/// Helper function to parse a URL string with proper error handling
#[cfg(feature = "std")]
fn parse_url(url_str: &str) -> Result<url::Url, CliError> {
url_str.parse().map_err(CliError::UrlParseError)
}
/// Helper function to create a JSON-RPC client with proper error handling
#[cfg(feature = "std")]
fn create_json_rpc_client(
url_str: &str,
) -> Result<crate::clients::json_rpc::JsonRpcClient, CliError> {
use crate::clients::json_rpc::JsonRpcClient;
Ok(JsonRpcClient::connect(parse_url(url_str)?))
}
/// Helper function to handle response display and error conversion
#[cfg(feature = "std")]
fn handle_response<T: core::fmt::Debug>(
result: Result<T, crate::asynch::clients::exceptions::XRPLClientException>,
response_type: &str,
) -> Result<(), CliError> {
match result {
Ok(response) => {
alloc::println!("{}: {:#?}", response_type, response);
Ok(())
}
Err(e) => Err(CliError::ClientError(e)),
}
}
/// Helper function to get or create a Tokio runtime
#[cfg(feature = "std")]
fn get_or_create_runtime() -> Result<tokio::runtime::Runtime, CliError> {
use tokio::runtime::Runtime;
Runtime::new().map_err(CliError::IoError)
}
/// Helper function to handle common transaction encoding and output steps
#[cfg(feature = "std")]
fn encode_and_print_tx<T: serde::Serialize>(tx: &T) -> Result<String, CliError> {
let tx_blob = crate::core::binarycodec::encode(tx)?;
alloc::println!("Signed transaction blob: {}", tx_blob);
Ok(tx_blob)
}
pub fn execute_command(command: &Commands) -> Result<(), CliError> {
match command {
Commands::Wallet(wallet_cmd) => match wallet_cmd {
WalletCommands::Generate {
save,
mnemonic,
words,
} => {
if *mnemonic {
use bip39::{Language, Mnemonic};
let mut rng = rand::thread_rng();
let mnemonic = Mnemonic::generate_in_with(&mut rng, Language::English, *words)
.expect("Invalid word count (must be 12, 15, 18, 21, or 24)");
let seed = mnemonic.to_seed(""); // Returns [u8; 64]
let phrase = mnemonic.words().collect::<Vec<_>>().join(" ");
alloc::println!(
"Generated wallet with mnemonic:\nMnemonic: {}\nSeed: {}",
phrase,
hex::encode(seed)
);
// Print derived address, public key, etc.
} else {
let wallet = crate::wallet::Wallet::create(None)?;
alloc::println!("Generated wallet: {:#?}", wallet);
if *save {
alloc::println!("Saving wallet functionality not implemented yet");
}
}
Ok(())
}
WalletCommands::FromSeed { seed, sequence } => {
let wallet = crate::wallet::Wallet::new(seed, *sequence)?;
alloc::println!("Wallet from seed: {:#?}", wallet);
Ok(())
}
#[cfg(feature = "std")]
WalletCommands::Faucet { url } => {
use crate::asynch::clients::AsyncJsonRpcClient;
use crate::asynch::wallet::generate_faucet_wallet;
// Get or create a runtime
let rt = get_or_create_runtime()?;
// Execute within the runtime
let result = rt.block_on(async {
let client = AsyncJsonRpcClient::connect(url.parse()?);
generate_faucet_wallet(&client, None, None, None, None).await
});
match result {
Ok(wallet) => {
alloc::println!("Generated faucet wallet: {:#?}", wallet);
Ok(())
}
Err(e) => Err(CliError::Other(format!(
"Failed to generate faucet wallet: {}",
e
))),
}
}
WalletCommands::Validate { address } => {
use crate::core::addresscodec::{is_valid_classic_address, is_valid_xaddress};
let is_valid_classic = is_valid_classic_address(address);
let is_valid_x = is_valid_xaddress(address);
if is_valid_classic {
alloc::println!("Valid classic address: {}", address);
Ok(())
} else if is_valid_x {
use crate::core::addresscodec::xaddress_to_classic_address;
let (classic_address, tag, is_test) = xaddress_to_classic_address(address)?;
alloc::println!("Valid X-address: {}", address);
alloc::println!(" Classic address: {}", classic_address);
alloc::println!(" Destination tag: {:?}", tag);
alloc::println!(" Test network: {}", is_test);
Ok(())
} else {
Err(CliError::Other(format!("Invalid address: {}", address)))
}
}
},
Commands::Account(account_cmd) => match account_cmd {
#[cfg(feature = "std")]
AccountCommands::Info { address, url } => {
use crate::clients::XRPLSyncClient;
use crate::models::requests::account_info::AccountInfo;
// Create client with standardized helper function
let client = create_json_rpc_client(url)?;
// Create request
let account_info = AccountInfo::new(
None, // id
address.clone().into(), // account
None, // strict
None, // ledger_index
None, // ledger_hash
None, // queue
None, // signer_lists
);
// Execute request and handle response
handle_response(client.request(account_info.into()), "Account info")
}
#[cfg(feature = "std")]
AccountCommands::Tx {
address,
url,
limit,
} => {
use crate::clients::XRPLSyncClient;
use crate::models::requests::account_tx::AccountTx;
// Create client with standardized helper function
let client = create_json_rpc_client(url)?;
// Create request
let account_tx = AccountTx::new(
None,
address.clone().into(),
None,
None,
None,
None,
Some(*limit),
None,
None,
None,
);
// Execute request and handle response
handle_response(client.request(account_tx.into()), "Account transactions")
}
#[cfg(feature = "std")]
AccountCommands::Objects {
address,
url,
type_filter,
limit,
} => {
use std::str::FromStr;
use crate::clients::XRPLSyncClient;
use crate::models::requests::account_objects::{AccountObjectType, AccountObjects};
// Parse the type_filter into AccountObjectType if provided
let object_type = if let Some(filter) = type_filter.as_deref() {
match AccountObjectType::from_str(filter) {
Ok(obj_type) => Some(obj_type),
Err(_) => {
return Err(CliError::Other(format!(
"Invalid object type: {}",
filter
)));
}
}
} else {
None
};
// Create client with standardized helper function
let client = create_json_rpc_client(url)?;
// Create request
let account_objects = AccountObjects::new(
None,
address.clone().into(),
None,
None,
object_type,
None,
Some(*limit),
None,
);
// Execute request and handle response
handle_response(client.request(account_objects.into()), "Account objects")
}
#[cfg(feature = "std")]
AccountCommands::Channels {
address,
url,
destination_account,
limit,
} => {
use crate::clients::XRPLSyncClient;
use crate::models::requests::account_channels::AccountChannels;
// Create client with standardized helper function
let client = create_json_rpc_client(url)?;
// Create request
let account_channels = AccountChannels::new(
None,
address.clone().into(),
destination_account.as_deref().map(Into::into),
None,
None,
Some(*limit),
None,
);
// Execute request and handle response
handle_response(client.request(account_channels.into()), "Account channels")
}
#[cfg(feature = "std")]
AccountCommands::Currencies { address, url } => {
use crate::clients::XRPLSyncClient;
use crate::models::requests::account_currencies::AccountCurrencies;
// Create client with standardized helper function
let client = create_json_rpc_client(url)?;
// Create request
let account_currencies =
AccountCurrencies::new(None, address.clone().into(), None, None, None);
// Execute request and handle response
handle_response(
client.request(account_currencies.into()),
"Account currencies",
)
}
#[cfg(feature = "std")]
AccountCommands::Lines {
address,
url,
peer,
limit,
} => {
use crate::clients::XRPLSyncClient;
use crate::models::requests::account_lines::AccountLines;
// Create client with standardized helper function
let client = create_json_rpc_client(url)?;
// Create request
let account_lines = AccountLines::new(
None,
address.clone().into(),
None,
None,
Some(*limit),
peer.as_deref().map(Into::into),
);
// Execute request and handle response
handle_response(client.request(account_lines.into()), "Account trust lines")
}
#[cfg(feature = "std")]
AccountCommands::Nfts { address, url } => {
use crate::clients::XRPLSyncClient;
use crate::models::requests::account_nfts::AccountNfts;
let client = create_json_rpc_client(url)?;
let req = AccountNfts::new(
None, // id
address.clone().into(), // account
None, // limit
None, // marker
);
handle_response(client.request(req.into()), "Account NFTs")
}
#[cfg(feature = "std")]
AccountCommands::SetFlag { seed, flag, url } => {
use alloc::borrow::Cow;
use core::str::FromStr;
use crate::asynch::transaction::sign;
use crate::models::transactions::account_set::{AccountSet, AccountSetFlag};
use crate::wallet::Wallet;
let wallet = Wallet::new(seed, 0)?;
let flag_enum = AccountSetFlag::from_str(flag)
.map_err(|_| CliError::Other(format!("Invalid flag: {}", flag)))?;
let mut tx = AccountSet::new(
Cow::Owned(wallet.classic_address.clone()),
None, // account_txn_id
None, // fee
None, // flags
None, // last_ledger_sequence
None, // memos
None, // sequence
None, // signers
None, // source_tag
None, // ticket_sequence
None, // clear_flag
None, // domain
None, // email_hash
None, // message_key
Some(flag_enum), // set_flag
None, // transfer_rate
None, // tick_size
None, // nftoken_minter
);
sign(&mut tx, &wallet, false)?;
let tx_blob = encode_and_print_tx(&tx)?;
alloc::println!(
"To submit, use: xrpl transaction submit --tx-blob {} --url {}",
tx_blob,
url
);
Ok(())
}
#[cfg(feature = "std")]
AccountCommands::ClearFlag { seed, flag, url } => {
use alloc::borrow::Cow;
use core::str::FromStr;
use crate::asynch::transaction::sign;
use crate::models::transactions::account_set::{AccountSet, AccountSetFlag};
use crate::wallet::Wallet;
let wallet = Wallet::new(seed, 0)?;
let flag_enum = AccountSetFlag::from_str(flag)
.map_err(|_| CliError::Other(format!("Invalid flag: {}", flag)))?;
let mut tx = AccountSet::new(
Cow::Owned(wallet.classic_address.clone()),
None, // account_txn_id
None, // fee
None, // flags
None, // last_ledger_sequence
None, // memos
None, // sequence
None, // signers
None, // source_tag
None, // ticket_sequence
None, // clear_flag
None, // domain
None, // email_hash
None, // message_key
Some(flag_enum), // set_flag
None, // transfer_rate
None, // tick_size
None, // nftoken_minter
);
sign(&mut tx, &wallet, false)?;
let tx_blob = encode_and_print_tx(&tx)?;
alloc::println!(
"To submit, use: xrpl transaction submit --tx-blob {} --url {}",
tx_blob,
url
);
Ok(())
}
},
Commands::Transaction(tx_cmd) => match tx_cmd {
#[cfg(feature = "std")]
TransactionCommands::Sign { seed, r#type, json } => {
use serde_json::Value;
use crate::models::transactions::{
account_set::AccountSet, offer_cancel::OfferCancel, offer_create::OfferCreate,
payment::Payment, trust_set::TrustSet,
};
use crate::wallet::Wallet;
// Create wallet from seed
let wallet = Wallet::new(seed, 0)?;
// Parse the JSON
let json_value: Value = serde_json::from_str(json)?;
use crate::asynch::transaction::sign;
// Handle different transaction types
match r#type.to_lowercase().as_str() {
"payment" => {
let mut tx: Payment = serde_json::from_value(json_value)?;
sign(&mut tx, &wallet, false)?;
encode_and_print_tx(&tx)?;
}
"accountset" => {
let mut tx: AccountSet = serde_json::from_value(json_value)?;
sign(&mut tx, &wallet, false)?;
encode_and_print_tx(&tx)?;
}
"offercreate" => {
let mut tx: OfferCreate = serde_json::from_value(json_value)?;
sign(&mut tx, &wallet, false)?;
encode_and_print_tx(&tx)?;
}
"offercancel" => {
let mut tx: OfferCancel = serde_json::from_value(json_value)?;
sign(&mut tx, &wallet, false)?;
encode_and_print_tx(&tx)?;
}
"trustset" => {
let mut tx: TrustSet = serde_json::from_value(json_value)?;
sign(&mut tx, &wallet, false)?;
encode_and_print_tx(&tx)?;
}
_ => {
return Err(CliError::Other(format!(
"Unsupported transaction type: {}",
r#type
)));
}
}
Ok(())
}
#[cfg(feature = "std")]
TransactionCommands::Submit { tx_blob, url } => {
use crate::clients::XRPLSyncClient;
use crate::models::requests::submit::Submit;
// Create client with standardized helper function
let client = create_json_rpc_client(url)?;
// Create request
let submit_request = Submit::new(None, tx_blob.into(), None);
// Execute request and handle response
handle_response(
client.request(submit_request.into()),
"Transaction submission result",
)
}
#[cfg(feature = "std")]
TransactionCommands::TrustSet {
seed,
issuer,
currency,
limit,
url,
} => {
use alloc::borrow::Cow;
use crate::models::transactions::trust_set::TrustSet;
use crate::models::IssuedCurrencyAmount;
use crate::wallet::Wallet;
// Create wallet from seed
let wallet = Wallet::new(seed, 0)?;
// Build IssuedCurrencyAmount for the trust line limit
let amount = IssuedCurrencyAmount::new(
currency.clone().into(), // currency code
issuer.clone().into(), // issuer address
limit.clone().into(), // value as string
);
// Build TrustSet transaction
let mut tx = TrustSet::new(
Cow::Owned(wallet.classic_address.clone()),
None, // account_txn_id
None, // fee
None, // flags
None, // last_ledger_sequence
None, // memos
None, // sequence
None, // signers
None, // source_tag
None, // ticket_sequence
amount,
None, // quality_in
None, // quality_out
);
// Sign the transaction
use crate::asynch::transaction::sign;
sign(&mut tx, &wallet, false)?;
// Encode and print the transaction blob
let tx_blob = encode_and_print_tx(&tx)?;
alloc::println!(
"To submit, use: xrpl transaction submit --tx-blob {} --url {}",
tx_blob,
url
);
Ok(())
}
#[cfg(feature = "std")]
TransactionCommands::NftMint {
seed,
uri,
flags,
transfer_fee,
url,
} => {
use crate::asynch::transaction::sign;
use crate::models::transactions::nftoken_mint::{NFTokenMint, NFTokenMintFlag};
use crate::wallet::Wallet;
use alloc::borrow::Cow;
let wallet = Wallet::new(seed, 0)?;
// Support multiple flags via bitmask
let flag_collection = flags.map(|f| NFTokenMintFlag::from_bits(f).into());
let mut tx = NFTokenMint::new(
Cow::Owned(wallet.classic_address.clone()),
None, // account_txn_id
None, // fee
flag_collection,
None, // last_ledger_sequence
None, // memos
None, // sequence
None, // signers
None, // source_tag
None, // ticket_sequence
0, // nftoken_taxon (0 for default, or expose as CLI param)
None, // issuer
transfer_fee.map(|v| v as u32),
Some(uri.clone().into()),
);
sign(&mut tx, &wallet, false)?;
let tx_blob = encode_and_print_tx(&tx)?;
alloc::println!(
"To submit, use: xrpl transaction submit --tx-blob {} --url {}",
tx_blob,
url
);
Ok(())
}
#[cfg(feature = "std")]
TransactionCommands::NftBurn {
seed,
nftoken_id,
url,
} => {
use crate::asynch::transaction::sign;
use crate::models::transactions::nftoken_burn::NFTokenBurn;
use crate::wallet::Wallet;
use alloc::borrow::Cow;
let wallet = Wallet::new(seed, 0)?;
let mut tx = NFTokenBurn::new(
Cow::Owned(wallet.classic_address.clone()),
None, // account_txn_id
None, // fee
None, // last_ledger_sequence
None, // memos
None, // sequence
None, // signers
None, // source_tag
None, // ticket_sequence
nftoken_id.clone().into(),
None, // owner (optional, only needed if burning on behalf of another)
);
sign(&mut tx, &wallet, false)?;
let tx_blob = encode_and_print_tx(&tx)?;
alloc::println!(
"To submit, use: xrpl transaction submit --tx-blob {} --url {}",
tx_blob,
url
);
Ok(())
}
},
Commands::Server(server_cmd) => match server_cmd {
#[cfg(feature = "std")]
ServerCommands::Fee { url } => {
use crate::ledger::{get_fee, FeeType};
// Create a runtime and client
let rt = get_or_create_runtime()?;
let client = create_json_rpc_client(url)?;
// Get the current fee within the Tokio runtime
match rt.block_on(async { get_fee(&client, None, Some(FeeType::Open)) }) {
Ok(fee) => {
alloc::println!("Current network fee: {} drops", fee);
Ok(())
}
Err(e) => Err(CliError::HelperError(e)),
}
}
#[cfg(feature = "std")]
ServerCommands::Info { url } => {
use crate::clients::XRPLSyncClient;
use crate::models::requests::server_info::ServerInfo;
// Create client with standardized helper function
let client = create_json_rpc_client(url)?;
// Create request
let server_info = ServerInfo::new(None);
// Execute request and handle response
handle_response(client.request(server_info.into()), "Server info")
}
#[cfg(feature = "std")]
ServerCommands::Subscribe { url, stream, limit } => {
use crate::clients::websocket::WebSocketClient;
use crate::clients::{SingleExecutorMutex, XRPLSyncWebsocketIO};
use crate::models::requests::subscribe::{StreamParameter, Subscribe};
// Parse the stream type
let stream_param = match stream.to_lowercase().as_str() {
"ledger" => StreamParameter::Ledger,
"transactions" => StreamParameter::Transactions,
"validations" => StreamParameter::Validations,
_ => return Err(CliError::Other(format!("Unknown stream type: {}", stream))),
};
// Open a websocket connection with consistent URL parsing
let mut websocket: WebSocketClient<SingleExecutorMutex, _> =
WebSocketClient::open(parse_url(url)?)?;
// Subscribe to the stream
let subscribe = Subscribe::new(
None,
None,
None,
None,
Some(vec![stream_param]),
None,
None,
None,
);
websocket.xrpl_send(subscribe.into())?;
// Listen for messages
let mut count = 0;
loop {
if *limit > 0 && count >= *limit {
break;
}
match websocket.xrpl_receive() {
Ok(Some(response)) => {
alloc::println!("Received: {:#?}", response);
count += 1;
}
Ok(None) => {
std::thread::sleep(std::time::Duration::from_millis(100));
}
Err(e) => {
return Err(CliError::ClientError(e));
}
}
}
Ok(())
}
},
Commands::Ledger(ledger_cmd) => match ledger_cmd {
#[cfg(feature = "std")]
LedgerCommands::Data {
url,
ledger_index,
ledger_hash,
limit,
} => {
use crate::clients::XRPLSyncClient;
use crate::models::requests::ledger_data::LedgerData;
// Create client with standardized helper function
let client = create_json_rpc_client(url)?;
// Create request
let ledger_data = LedgerData::new(
None,
None,
ledger_index.as_deref().map(Into::into),
ledger_hash.as_deref().map(Into::into),
Some(*limit),
None,
);
// Execute request and handle response
handle_response(client.request(ledger_data.into()), "Ledger data")
}
},
}
}