quantus-cli 2.1.1

Command line interface and library for interacting with the Quantus Network
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
1110
1111
//! `quantus wallet` subcommand - wallet operations
use crate::{
	chain::quantus_subxt,
	cli::address_format::QuantusSS58,
	error::QuantusError,
	log_error, log_print, log_success, log_verbose,
	wallet::{
		default_derivation_path,
		password::{get_mnemonic_from_user, get_new_wallet_password},
		DilithiumScheme, WalletManager,
	},
};
use clap::Subcommand;
use colored::Colorize;
use sp_core::crypto::{AccountId32 as SpAccountId32, Ss58Codec};
use std::io::{self, Write};
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;

/// Wallet management commands
#[derive(Subcommand, Debug)]
pub enum WalletCommands {
	/// Create a new wallet with quantum-safe keys
	Create {
		/// Wallet name
		#[arg(short, long)]
		name: String,

		/// Password to encrypt the wallet (unsupported on argv; use --password-file or prompt)
		#[arg(short, long, hide = true)]
		password: Option<String>,

		/// Read encryption password from file (owner-only on Unix)
		#[arg(long)]
		password_file: Option<String>,

		/// Allow creating a wallet with an empty password (development only)
		#[arg(long)]
		allow_empty_password: bool,

		/// Derivation path (default depends on --scheme: ML-DSA-65 →
		/// m/44'/189189'/0'/0'/1', ML-DSA-87 → m/44'/189189'/0'/0'/0')
		#[arg(short = 'd', long)]
		derivation_path: Option<String>,

		/// Disable HD derivation (use master seed directly, like quantus-node --no-derivation)
		#[arg(long)]
		no_derivation: bool,

		/// Dilithium signature scheme (default: ml-dsa-65)
		#[arg(long, value_enum, default_value_t = DilithiumScheme::MlDsa65)]
		scheme: DilithiumScheme,
	},

	/// View wallet information
	View {
		/// Wallet name to view
		#[arg(short, long)]
		name: Option<String>,

		/// Show all wallets if no name specified
		#[arg(short, long)]
		all: bool,
	},

	/// Export wallet (private key or mnemonic)
	Export {
		/// Wallet name to export
		#[arg(short, long)]
		name: String,

		/// Password to decrypt the wallet (optional, will prompt if not provided)
		#[arg(short, long, hide = true)]
		password: Option<String>,

		/// Export format: mnemonic, private-key
		#[arg(short, long, default_value = "mnemonic")]
		format: String,

		/// Write the mnemonic to this file instead of printing it (created with owner-only
		/// permissions)
		#[arg(short, long)]
		output: Option<std::path::PathBuf>,
	},

	/// Import wallet from mnemonic phrase
	Import {
		/// Wallet name
		#[arg(short, long)]
		name: String,

		/// Password to encrypt the wallet (unsupported on argv; use --password-file or prompt)
		#[arg(short, long, hide = true)]
		password: Option<String>,

		/// Read encryption password from file (owner-only on Unix)
		#[arg(long)]
		password_file: Option<String>,

		/// Allow encrypting the imported wallet with an empty password (development only)
		#[arg(long)]
		allow_empty_password: bool,

		/// Derivation path (default depends on --scheme: ML-DSA-65 →
		/// m/44'/189189'/0'/0'/1', ML-DSA-87 → m/44'/189189'/0'/0'/0')
		#[arg(short = 'd', long)]
		derivation_path: Option<String>,

		/// Disable HD derivation (use master seed directly, like quantus-node --no-derivation)
		#[arg(long)]
		no_derivation: bool,

		/// Dilithium signature scheme (default: ml-dsa-65)
		#[arg(long, value_enum, default_value_t = DilithiumScheme::MlDsa65)]
		scheme: DilithiumScheme,
	},

	/// Create wallet from 32-byte seed
	FromSeed {
		/// Wallet name
		#[arg(short, long)]
		name: String,

		/// Password to encrypt the wallet (unsupported on argv; use --password-file or prompt)
		#[arg(short, long, hide = true)]
		password: Option<String>,

		/// Read encryption password from file (owner-only on Unix)
		#[arg(long)]
		password_file: Option<String>,

		/// Allow encrypting the new wallet with an empty password (development only)
		#[arg(long)]
		allow_empty_password: bool,

		/// Dilithium signature scheme (default: ml-dsa-65)
		#[arg(long, value_enum, default_value_t = DilithiumScheme::MlDsa65)]
		scheme: DilithiumScheme,
	},

	/// List all wallets
	List,

	/// Delete a wallet
	Delete {
		/// Wallet name to delete
		#[arg(short, long)]
		name: String,

		/// Skip confirmation prompt
		#[arg(short, long)]
		force: bool,
	},

	/// Get the nonce (transaction count) of an account
	Nonce {
		/// Account address to query (optional, uses wallet address if not provided)
		#[arg(short, long)]
		address: Option<String>,

		/// Wallet name (used for address if --address not provided)
		#[arg(short, long, required_unless_present("address"))]
		wallet: Option<String>,

		/// Password for the wallet
		#[arg(short, long, hide = true)]
		password: Option<String>,
	},
}

/// Get the nonce (transaction count) of an account
pub async fn get_account_nonce(
	quantus_client: &crate::chain::client::QuantusClient,
	account_address: &str,
) -> crate::error::Result<u32> {
	log_verbose!("#️⃣ Querying nonce for account: {}", account_address.bright_green());

	// Parse the SS58 address to AccountId32 (sp-core)
	let (account_id_sp, _) = SpAccountId32::from_ss58check_with_version(account_address)
		.map_err(|e| QuantusError::NetworkError(format!("Invalid SS58 address: {e:?}")))?;

	log_verbose!("🔍 SP Account ID: {:?}", account_id_sp);

	// Convert to subxt_core AccountId32 for storage query
	let account_bytes: [u8; 32] = *account_id_sp.as_ref();
	let account_id = subxt::ext::subxt_core::utils::AccountId32::from(account_bytes);

	log_verbose!("🔍 SubXT Account ID: {:?}", account_id);

	// Use SubXT to query System::Account storage directly (like send_subxt.rs)
	use quantus_subxt::api;
	let storage_addr = api::storage().system().account(account_id);

	// Get the latest block hash to read from the latest state (not finalized)
	let latest_block_hash = quantus_client.get_latest_block().await?;

	let storage_at = quantus_client.client().storage().at(latest_block_hash);

	let account_info = storage_at
		.fetch(&storage_addr)
		.await
		.map_err(|e| QuantusError::NetworkError(format!("Failed to fetch account info: {e:?}")))?;

	let (nonce, exists) = crate::chain::client::QuantusClient::interpret_account_nonce(
		account_info.map(|info| info.nonce),
	);
	if exists {
		log_verbose!("✅ Account info retrieved with storage query!");
	} else {
		log_print!(
			"⚠️  Account has no on-chain System::Account entry; reporting nonce 0 (new/unused account)"
		);
	}
	log_verbose!("🔢 Nonce: {} (exists={})", nonce, exists);

	Ok(nonce)
}

/// Fetch high-security status from chain for an account (SS58). Returns None if disabled or on
/// error.
async fn fetch_high_security_status(
	quantus_client: &crate::chain::client::QuantusClient,
	account_ss58: &str,
) -> crate::error::Result<Option<(String, String)>> {
	use quantus_subxt::api::runtime_types::qp_scheduler::BlockNumberOrTimestamp;

	let (account_id_sp, _) = SpAccountId32::from_ss58check_with_version(account_ss58)
		.map_err(|e| QuantusError::Generic(format!("Invalid SS58 for HS lookup: {e:?}")))?;
	let account_bytes: [u8; 32] = *account_id_sp.as_ref();
	let account_id = subxt::ext::subxt_core::utils::AccountId32::from(account_bytes);

	let storage_addr = quantus_subxt::api::storage()
		.reversible_transfers()
		.high_security_accounts(account_id);
	let latest = quantus_client.get_latest_block().await?;
	let value = quantus_client
		.client()
		.storage()
		.at(latest)
		.fetch(&storage_addr)
		.await
		.map_err(|e| QuantusError::NetworkError(format!("Fetch HS storage: {e:?}")))?;

	let Some(data) = value else {
		return Ok(None);
	};

	let guardian_ss58 = data.guardian.to_quantus_ss58();
	let delay_str = match data.delay {
		BlockNumberOrTimestamp::BlockNumber(blocks) => format!("{} blocks", blocks),
		BlockNumberOrTimestamp::Timestamp(ms) => format!("{} seconds", ms / 1000),
	};
	Ok(Some((guardian_ss58, delay_str)))
}

/// Fetch list of accounts for which this account is guardian (guardian_index).
/// Returns an empty vec when the storage entry is absent (`None`), and an error on failure.
async fn fetch_guardian_for_list(
	quantus_client: &crate::chain::client::QuantusClient,
	account_ss58: &str,
) -> crate::error::Result<Vec<String>> {
	let account_id_sp = SpAccountId32::from_ss58check(account_ss58)
		.map_err(|e| QuantusError::Generic(format!("Invalid SS58 for guardian_index: {e:?}")))?;
	let account_bytes: [u8; 32] = *account_id_sp.as_ref();
	let account_id = subxt::ext::subxt_core::utils::AccountId32::from(account_bytes);

	let storage_addr =
		quantus_subxt::api::storage().reversible_transfers().guardian_index(account_id);
	let latest = quantus_client.get_latest_block().await?;
	let value = quantus_client
		.client()
		.storage()
		.at(latest)
		.fetch(&storage_addr)
		.await
		.map_err(|e| QuantusError::NetworkError(format!("Fetch guardian_index: {e:?}")))?;

	let list: Vec<String> = value
		.map(|bounded| {
			bounded
				.0
				.iter()
				.map(|a: &subxt::ext::subxt_core::utils::AccountId32| a.to_quantus_ss58())
				.collect()
		})
		.unwrap_or_default();
	Ok(list)
}

/// For each entrusted account (SS58), count pending reversible transfers by sender. Returns (total,
/// per-account list).
async fn fetch_pending_transfers_for_guardian(
	quantus_client: &crate::chain::client::QuantusClient,
	entrusted_ss58: &[String],
) -> crate::error::Result<(u32, Vec<(String, u32)>)> {
	let latest = quantus_client.get_latest_block().await?;
	let storage = quantus_client.client().storage().at(latest);
	let pending_iter =
		quantus_subxt::api::storage().reversible_transfers().pending_transfers_iter();

	let entrusted_ids: Vec<[u8; 32]> = entrusted_ss58
		.iter()
		.map(|s| {
			let id = SpAccountId32::from_ss58check(s).map_err(|e| {
				QuantusError::Generic(format!("Invalid SS58 for pending lookup: {e:?}"))
			})?;
			Ok::<_, crate::error::QuantusError>(*id.as_ref())
		})
		.collect::<Result<Vec<_>, _>>()?;

	let mut counts: std::collections::HashMap<[u8; 32], u32> =
		entrusted_ids.iter().map(|id| (*id, 0u32)).collect();

	let mut iter = storage
		.iter(pending_iter)
		.await
		.map_err(|e| QuantusError::NetworkError(format!("Pending transfers iter: {e:?}")))?;

	while let Some(result) = iter.next().await {
		if let Ok(entry) = result {
			let from_bytes: [u8; 32] = *entry.value.from.as_ref();
			if let Some(c) = counts.get_mut(&from_bytes) {
				*c += 1;
			}
		}
	}

	let mut total = 0u32;
	let mut per_account = Vec::with_capacity(entrusted_ss58.len());
	for (ss58, id) in entrusted_ss58.iter().zip(entrusted_ids.iter()) {
		let count = *counts.get(id).unwrap_or(&0);
		total += count;
		per_account.push((ss58.clone(), count));
	}
	Ok((total, per_account))
}

fn write_mnemonic_to_protected_file(
	path: &std::path::Path,
	mnemonic: &str,
) -> crate::error::Result<()> {
	let mut options = std::fs::OpenOptions::new();
	options.write(true).create_new(true);
	#[cfg(unix)]
	options.mode(0o600);

	let mut file = options.open(path).map_err(|e| {
		QuantusError::Generic(format!("Failed to create mnemonic export file: {e}"))
	})?;
	file.write_all(mnemonic.as_bytes())
		.map_err(|e| QuantusError::Generic(format!("Failed to write mnemonic export file: {e}")))?;
	file.write_all(b"\n")
		.map_err(|e| QuantusError::Generic(format!("Failed to write mnemonic export file: {e}")))?;
	file.sync_all()
		.map_err(|e| QuantusError::Generic(format!("Failed to sync mnemonic export file: {e}")))?;
	Ok(())
}

/// Colored checkphrase for a real address; None for placeholders like "[Wrong password]"
fn checkphrase_line(address: &str) -> Option<String> {
	(!address.starts_with('['))
		.then(|| crate::wallet::checkphrase::checkphrase(address).bright_blue().to_string())
}

/// Handle wallet commands
pub async fn handle_wallet_command(
	command: WalletCommands,
	node_url: &str,
) -> crate::error::Result<()> {
	match command {
		WalletCommands::Create {
			name,
			password,
			password_file,
			allow_empty_password,
			derivation_path,
			no_derivation,
			scheme,
		} => {
			log_print!("🔐 Creating new quantum wallet...");

			let final_password =
				get_new_wallet_password(&name, password, password_file, allow_empty_password)?;

			let wallet_manager = WalletManager::new()?;

			let result = if no_derivation {
				wallet_manager
					.create_wallet_no_derivation_with_scheme(&name, Some(&final_password), scheme)
					.await
			} else {
				let path =
					derivation_path.as_deref().unwrap_or_else(|| default_derivation_path(scheme));
				wallet_manager
					.create_wallet_with_scheme(&name, Some(&final_password), path, scheme)
					.await
			};

			match result {
				Ok(wallet_info) => {
					log_success!("Wallet name: {}", name.bright_green());
					log_success!("Address: {}", wallet_info.address.bright_cyan());
					if let Some(checkphrase) = checkphrase_line(&wallet_info.address) {
						log_success!("Checkphrase: {}", checkphrase);
					}
					log_success!("Key type: {}", wallet_info.key_type.bright_yellow());
					log_success!(
						"Derivation path: {}",
						wallet_info.derivation_path.bright_magenta()
					);
					log_success!(
						"Created: {}",
						wallet_info.created_at.format("%Y-%m-%d %H:%M:%S UTC").to_string().dimmed()
					);
					log_success!("✅ Wallet created successfully!");
				},
				Err(e) => {
					log_error!("{}", format!("❌ Failed to create wallet: {e}").red());
					return Err(e);
				},
			}

			Ok(())
		},

		WalletCommands::View { name, all } => {
			log_print!("👁️  Viewing wallet information...");

			let wallet_manager = WalletManager::new()?;

			if all {
				// Show all wallets (same as list command but with different header)
				match wallet_manager.list_wallets() {
					Ok(wallets) =>
						if wallets.is_empty() {
							log_print!("{}", "No wallets found.".dimmed());
						} else {
							log_print!("All wallets ({}):\n", wallets.len());

							for (i, wallet) in wallets.iter().enumerate() {
								log_print!(
									"{}. {}",
									(i + 1).to_string().bright_yellow(),
									wallet.name.bright_green()
								);
								log_print!("   Address: {}", wallet.address.bright_cyan());
								if let Some(checkphrase) = checkphrase_line(&wallet.address) {
									log_print!("   Checkphrase: {}", checkphrase);
								}
								log_print!("   Type: {}", wallet.key_type.bright_yellow());
								log_print!(
									"   Derivation Path: {}",
									wallet.derivation_path.bright_magenta()
								);
								log_print!(
									"   Created: {}",
									wallet
										.created_at
										.format("%Y-%m-%d %H:%M:%S UTC")
										.to_string()
										.dimmed()
								);
								if i < wallets.len() - 1 {
									log_print!();
								}
							}
						},
					Err(e) => {
						log_error!("{}", format!("❌ Failed to view wallets: {e}").red());
						return Err(e);
					},
				}
			} else if let Some(wallet_name) = name {
				// Show specific wallet details
				match wallet_manager.get_wallet(&wallet_name, None) {
					Ok(Some(wallet_info)) => {
						log_print!("Wallet Details:\n");
						log_print!("Name: {}", wallet_info.name.bright_green());
						log_print!("Address: {}", wallet_info.address.bright_cyan());
						if let Some(checkphrase) = checkphrase_line(&wallet_info.address) {
							log_print!("Checkphrase: {}", checkphrase);
						}
						log_print!("Key Type: {}", wallet_info.key_type.bright_yellow());
						log_print!(
							"Derivation Path: {}",
							wallet_info.derivation_path.bright_magenta()
						);
						log_print!(
							"Created: {}",
							wallet_info
								.created_at
								.format("%Y-%m-%d %H:%M:%S UTC")
								.to_string()
								.dimmed()
						);

						if wallet_info.address.contains("[") {
							log_print!(
								"\n{}",
								"💡 To see the full address, use the export command with password"
									.dimmed()
							);
						}

						// High-Security status and Guardian-for list from chain (optional; don't
						// fail view if node unavailable)
						if !wallet_info.address.contains("[") {
							if let Ok(quantus_client) =
								crate::chain::client::QuantusClient::new(node_url).await
							{
								match fetch_high_security_status(
									&quantus_client,
									&wallet_info.address,
								)
								.await
								{
									Ok(Some((interceptor_ss58, delay_str))) => {
										log_print!(
											"\n🛡️  High Security: {}",
											"ENABLED".bright_green().bold()
										);
										log_print!(
											"   Guardian/Interceptor: {}",
											interceptor_ss58.bright_cyan()
										);
										log_print!("   Delay: {}", delay_str.bright_yellow());
									},
									Ok(None) => {
										log_print!("\n🛡️  High Security: {}", "DISABLED".dimmed());
									},
									Err(e) => {
										log_verbose!("High Security status skipped: {}", e);
										log_print!(
											"\n{}",
											"💡 Run quantus high-security status --account <address> to check on-chain"
												.dimmed()
										);
									},
								}

								// Guardian for: accounts that have this wallet as their interceptor
								if let Ok(entrusted) =
									fetch_guardian_for_list(&quantus_client, &wallet_info.address)
										.await
								{
									if entrusted.is_empty() {
										log_print!("🛡️  Guardian for: {}", "none".dimmed());
									} else {
										log_print!(
											"\n🛡️  Guardian for: {} account(s)",
											entrusted.len().to_string().bright_green()
										);
										for (i, addr) in entrusted.iter().enumerate() {
											log_print!("   {}. {}", i + 1, addr.bright_cyan());
										}
										// Pending reversible transfers that this guardian can
										// intercept
										if let Ok((total, per_account)) =
											fetch_pending_transfers_for_guardian(
												&quantus_client,
												&entrusted,
											)
											.await
										{
											if total > 0 {
												log_print!(
													"\n   {} {} pending transfer(s) you can intercept",
													"⚠️".bright_yellow(),
													total.to_string().bright_yellow().bold()
												);
												for (addr, count) in per_account {
													if count > 0 {
														log_print!(
															"      from {}: {}",
															addr.bright_cyan(),
															count
														);
													}
												}
												log_print!("   {}", "Use: quantus reversible cancel --tx-id <id> --from <you>".dimmed());
											}
										}
									}
								}
							} else {
								log_verbose!(
									"Could not connect to node; High Security status skipped."
								);
							}
						}
					},
					Ok(None) => {
						log_error!("{}", format!("❌ Wallet '{wallet_name}' not found").red());
						log_print!(
							"Use {} to see available wallets",
							"quantus wallet list".bright_green()
						);
					},
					Err(e) => {
						log_error!("{}", format!("❌ Failed to view wallet: {e}").red());
						return Err(e);
					},
				}
			} else {
				log_print!(
					"{}",
					"Please specify a wallet name with --name or use --all to show all wallets"
						.yellow()
				);
				log_print!("Examples:");
				log_print!("  {}", "quantus wallet view --name my-wallet".bright_green());
				log_print!("  {}", "quantus wallet view --all".bright_green());
			}

			Ok(())
		},

		WalletCommands::Export { name, password, format, output } => {
			log_print!("📤 Exporting wallet...");

			if format.to_lowercase() != "mnemonic" {
				log_error!("Only 'mnemonic' export format is currently supported.");
				return Err(crate::error::QuantusError::Generic(
					"Export format not supported".to_string(),
				));
			}

			let Some(output_path) = output else {
				log_error!(
					"Refusing to print the mnemonic to stdout. Use --output <file> to create a protected export file."
				);
				return Err(crate::error::QuantusError::Generic(
					"Mnemonic export requires --output".to_string(),
				));
			};

			let wallet_manager = WalletManager::new()?;

			match wallet_manager.export_mnemonic(&name, password.as_deref()) {
				Ok(mnemonic) => {
					write_mnemonic_to_protected_file(&output_path, &mnemonic)?;
					log_success!("✅ Wallet exported successfully!");
					log_print!(
						"Mnemonic written to: {}",
						output_path.display().to_string().bright_cyan()
					);
					log_print!(
						"{}",
						"⚠️  Keep this file safe and secret. Anyone with this phrase can access your funds."
							.bright_red()
					);
				},
				Err(e) => {
					log_error!("{}", format!("❌ Failed to export wallet: {e}").red());
					return Err(e);
				},
			}

			Ok(())
		},

		WalletCommands::Import {
			name,
			password,
			password_file,
			allow_empty_password,
			derivation_path,
			no_derivation,
			scheme,
		} => {
			log_print!("📥 Importing wallet...");

			let wallet_manager = WalletManager::new()?;

			// New-wallet password policy: confirmed prompt, no silent empty
			// default. Resolve (and reject rejected forms like a raw
			// --password) before prompting for the mnemonic, so a doomed
			// invocation doesn't collect the secret first.
			let final_password = crate::wallet::password::get_new_wallet_password(
				&name,
				password,
				password_file,
				allow_empty_password,
			)?;

			// Always read mnemonic from a hidden prompt so it never appears in process argv.
			let mut mnemonic_phrase = get_mnemonic_from_user()?;

			let result = if no_derivation {
				wallet_manager
					.import_wallet_no_derivation_with_scheme(
						&name,
						&mnemonic_phrase,
						Some(&final_password),
						scheme,
					)
					.await
			} else {
				let path =
					derivation_path.as_deref().unwrap_or_else(|| default_derivation_path(scheme));
				wallet_manager
					.import_wallet_with_scheme(
						&name,
						&mnemonic_phrase,
						Some(&final_password),
						path,
						scheme,
					)
					.await
			};
			crate::wallet::keystore::zeroize_string(&mut mnemonic_phrase);

			match result {
				Ok(wallet_info) => {
					log_success!("Wallet name: {}", name.bright_green());
					log_success!("Address: {}", wallet_info.address.bright_cyan());
					if let Some(checkphrase) = checkphrase_line(&wallet_info.address) {
						log_success!("Checkphrase: {}", checkphrase);
					}
					log_success!("Key type: {}", wallet_info.key_type.bright_yellow());
					log_success!(
						"Derivation path: {}",
						wallet_info.derivation_path.bright_magenta()
					);
					log_success!(
						"Imported: {}",
						wallet_info.created_at.format("%Y-%m-%d %H:%M:%S UTC").to_string().dimmed()
					);
					log_success!("✅ Wallet imported successfully!");
				},
				Err(e) => {
					log_error!("{}", format!("❌ Failed to import wallet: {e}").red());
					return Err(e);
				},
			}

			Ok(())
		},

		WalletCommands::FromSeed {
			name,
			password,
			password_file,
			allow_empty_password,
			scheme,
		} => {
			log_print!("🌱 Creating wallet from seed...");

			let wallet_manager = WalletManager::new()?;

			// New-wallet password policy: confirmed prompt, no silent empty
			// default. Resolve before prompting for the seed, so a doomed
			// invocation doesn't collect the secret first.
			let final_password = crate::wallet::password::get_new_wallet_password(
				&name,
				password,
				password_file,
				allow_empty_password,
			)?;

			// Always read seed from a hidden prompt so it never appears in process argv.
			log_print!("Enter 32-byte seed in hex format (64 hex characters):");
			let mut seed_raw = rpassword::read_password()
				.map_err(|e| QuantusError::Generic(format!("Failed to read seed: {e}")))?;
			let mut seed = seed_raw.trim().to_string();
			crate::wallet::keystore::zeroize_string(&mut seed_raw);

			let result = wallet_manager
				.create_wallet_from_seed_with_scheme(&name, &seed, Some(&final_password), scheme)
				.await;
			crate::wallet::keystore::zeroize_string(&mut seed);

			match result {
				Ok(wallet_info) => {
					log_success!("Wallet name: {}", name.bright_green());
					log_success!("Address: {}", wallet_info.address.bright_cyan());
					if let Some(checkphrase) = checkphrase_line(&wallet_info.address) {
						log_success!("Checkphrase: {}", checkphrase);
					}
					log_success!("Key type: {}", wallet_info.key_type.bright_yellow());
					log_success!(
						"Created: {}",
						wallet_info.created_at.format("%Y-%m-%d %H:%M:%S UTC").to_string().dimmed()
					);
					log_success!("✅ Wallet created from seed successfully!");
				},
				Err(e) => {
					log_error!("{}", format!("❌ Failed to create wallet from seed: {e}").red());
					return Err(e);
				},
			}

			Ok(())
		},

		WalletCommands::List => {
			log_print!("📋 Listing all wallets...");

			let wallet_manager = WalletManager::new()?;

			match wallet_manager.list_wallets() {
				Ok(wallets) =>
					if wallets.is_empty() {
						log_print!("{}", "No wallets found.".dimmed());
						log_print!(
							"Create a new wallet with: {}",
							"quantus wallet create --name <name>".bright_green()
						);
					} else {
						log_print!("Found {} wallet(s):\n", wallets.len());

						for (i, wallet) in wallets.iter().enumerate() {
							log_print!(
								"{}. {}",
								(i + 1).to_string().bright_yellow(),
								wallet.name.bright_green()
							);
							log_print!("   Address: {}", wallet.address.bright_cyan());
							if let Some(checkphrase) = checkphrase_line(&wallet.address) {
								log_print!("   Checkphrase: {}", checkphrase);
							}
							log_print!("   Type: {}", wallet.key_type.bright_yellow());
							log_print!(
								"   Created: {}",
								wallet
									.created_at
									.format("%Y-%m-%d %H:%M:%S UTC")
									.to_string()
									.dimmed()
							);
							if i < wallets.len() - 1 {
								log_print!();
							}
						}

						log_print!(
							"\n{}",
							"💡 Use 'quantus wallet view --name <wallet>' to see full details"
								.dimmed()
						);
					},
				Err(e) => {
					log_error!("{}", format!("❌ Failed to list wallets: {e}").red());
					return Err(e);
				},
			}

			Ok(())
		},

		WalletCommands::Delete { name, force } => {
			log_print!("🗑️  Deleting wallet...");

			let wallet_manager = WalletManager::new()?;

			// Check if wallet exists first. A parse error means the file exists
			// but is corrupt; it must still be deletable via the CLI.
			let wallet_info = match wallet_manager.get_wallet(&name, None) {
				Ok(Some(wallet_info)) => Some(wallet_info),
				Ok(None) => {
					log_error!("{}", format!("❌ Wallet '{name}' not found").red());
					log_print!(
						"Use {} to see available wallets",
						"quantus wallet list".bright_green()
					);
					return Ok(());
				},
				Err(e) => {
					log_print!(
						"{}",
						format!("⚠️  Wallet file for '{name}' exists but cannot be parsed: {e}")
							.yellow()
					);
					log_print!("   Deleting will remove the corrupt wallet file.");
					None
				},
			};

			if let Some(wallet_info) = wallet_info {
				// Show wallet info before deletion
				log_print!("Wallet to delete:");
				log_print!("  Name: {}", wallet_info.name.bright_green());
				log_print!("  Address: {}", wallet_info.address.bright_cyan());
				if let Some(checkphrase) = checkphrase_line(&wallet_info.address) {
					log_print!("  Checkphrase: {}", checkphrase);
				}
				log_print!("  Type: {}", wallet_info.key_type.bright_yellow());
				log_print!(
					"  Created: {}",
					wallet_info.created_at.format("%Y-%m-%d %H:%M:%S UTC").to_string().dimmed()
				);
			}

			// Confirmation prompt unless --force is used
			if !force {
				log_print!("\n{}", "⚠️  This action cannot be undone!".bright_red());
				log_print!("Type the wallet name to confirm deletion:");

				print!("Confirm wallet name: ");
				io::stdout().flush().unwrap();

				let mut input = String::new();
				io::stdin().read_line(&mut input).unwrap();
				let input = input.trim();

				if input != name {
					log_print!("{}", "❌ Wallet name doesn't match. Deletion cancelled.".red());
					return Ok(());
				}
			}

			// Perform deletion
			match wallet_manager.delete_wallet(&name) {
				Ok(true) => {
					log_success!("✅ Wallet '{}' deleted successfully!", name);
				},
				Ok(false) => {
					log_error!("{}", format!("❌ Wallet '{name}' was not found").red());
				},
				Err(e) => {
					log_error!("{}", format!("❌ Failed to delete wallet: {e}").red());
					return Err(e);
				},
			}

			Ok(())
		},

		WalletCommands::Nonce { address, wallet, password } => {
			log_print!("🔢 Querying account nonce...");

			let quantus_client = crate::chain::client::QuantusClient::new(node_url).await?;

			// Determine which address to query
			let target_address = match (address, wallet) {
				(Some(addr), _) => {
					// Validate the provided address
					SpAccountId32::from_ss58check(&addr)
						.map_err(|e| QuantusError::Generic(format!("Invalid address: {e:?}")))?;
					addr
				},
				(None, Some(wallet_name)) => {
					// Load wallet and get its address
					let keypair =
						crate::wallet::load_keypair_from_wallet(&wallet_name, password, None)?;
					keypair.try_to_account_id_ss58check()?
				},
				(None, None) => {
					// This case should be prevented by clap's `required_unless_present`
					unreachable!("Either --address or --wallet must be provided");
				},
			};

			log_print!("Account: {}", target_address.bright_cyan());

			match get_account_nonce(&quantus_client, &target_address).await {
				Ok(nonce) => {
					log_success!("Nonce: {}", nonce.to_string().bright_green());
				},
				Err(e) => {
					log_print!("❌ Failed to get nonce: {}", e);
					return Err(e);
				},
			}

			Ok(())
		},
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use clap::Parser;
	use serial_test::serial;
	use tempfile::TempDir;

	#[derive(Parser, Debug)]
	#[command(name = "quantus")]
	struct TestCli {
		#[command(subcommand)]
		command: crate::cli::Commands,
	}

	#[tokio::test]
	#[serial]
	async fn wallet_export_without_output_refuses_stdout_mnemonic() {
		// #159469: export must not emit the recovery secret via log_print/stdout.
		let home = TempDir::new().expect("temp HOME");
		std::env::set_var("HOME", home.path());
		std::env::set_var("QUANTUS_NO_UPDATE_CHECK", "1");

		let manager = WalletManager::new().expect("wallet manager");
		manager.create_wallet("export-leak", Some("")).await.expect("create wallet");

		let result = handle_wallet_command(
			WalletCommands::Export {
				name: "export-leak".to_string(),
				password: None,
				format: "mnemonic".to_string(),
				output: None,
			},
			"ws://127.0.0.1:9944",
		)
		.await;

		assert!(result.is_err(), "export without --output must refuse stdout mnemonic emission");
		assert!(
			result.unwrap_err().to_string().contains("requires --output"),
			"error should mention --output"
		);
	}

	#[tokio::test]
	#[serial]
	async fn wallet_export_writes_mnemonic_to_protected_file_not_stdout_path() {
		let home = TempDir::new().expect("temp HOME");
		std::env::set_var("HOME", home.path());
		std::env::set_var("QUANTUS_NO_UPDATE_CHECK", "1");
		std::env::remove_var("QUANTUS_WALLET_PASSWORD");
		std::env::remove_var("QUANTUS_WALLET_PASSWORD_EXPORT_FILE");

		let manager = WalletManager::new().expect("wallet manager");
		manager.create_wallet("export-file", Some("")).await.expect("create wallet");
		let mnemonic = manager
			.export_mnemonic("export-file", None)
			.expect("export mnemonic for fixture");

		let out = home.path().join("mnemonic.txt");
		handle_wallet_command(
			WalletCommands::Export {
				name: "export-file".to_string(),
				password: None,
				format: "mnemonic".to_string(),
				output: Some(out.clone()),
			},
			"ws://127.0.0.1:9944",
		)
		.await
		.expect("export with --output must succeed");

		let written = std::fs::read_to_string(&out).expect("export file");
		assert_eq!(written.trim(), mnemonic.trim());
		#[cfg(unix)]
		{
			use std::os::unix::fs::PermissionsExt;
			let mode = std::fs::metadata(&out).unwrap().permissions().mode() & 0o777;
			assert_eq!(mode, 0o600, "export file must be owner-read/write only");
		}
	}

	#[test]
	fn wallet_import_rejects_mnemonic_cli_argument() {
		let result = TestCli::try_parse_from([
			"quantus",
			"wallet",
			"import",
			"--name",
			"poc",
			"--mnemonic",
			"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
		]);
		assert!(result.is_err(), "wallet import must not accept --mnemonic on the command line");
	}

	#[test]
	fn wallet_from_seed_rejects_seed_cli_argument() {
		let result = TestCli::try_parse_from([
			"quantus",
			"wallet",
			"from-seed",
			"--name",
			"poc",
			"--seed",
			"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
		]);
		assert!(result.is_err(), "wallet from-seed must not accept --seed on the command line");
	}

	#[test]
	fn wallet_scheme_cli_uses_hyphen_before_security_level() {
		let parsed = TestCli::try_parse_from([
			"quantus",
			"wallet",
			"create",
			"--name",
			"poc",
			"--scheme",
			"ml-dsa-87",
			"--allow-empty-password",
		])
		.expect("ml-dsa-87 must parse");
		match parsed.command {
			crate::cli::Commands::Wallet(WalletCommands::Create { scheme, .. }) =>
				assert_eq!(scheme, DilithiumScheme::MlDsa87),
			other => panic!("expected Wallet(Create), got {other:?}"),
		}

		let legacy = TestCli::try_parse_from([
			"quantus",
			"wallet",
			"create",
			"--name",
			"poc",
			"--scheme",
			"ml-dsa87",
			"--allow-empty-password",
		]);
		assert!(legacy.is_err(), "unhyphenated ml-dsa87 must not parse");
	}
}