quantus-cli 1.3.4

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
use crate::{log_error, log_print, log_success, log_verbose};
use clap::Subcommand;
use colored::Colorize;

pub mod address_format;
pub mod batch;
pub mod block;
pub mod common;
pub mod events;
pub mod generic_call;
pub mod high_security;
pub mod metadata;
pub mod multisend;
pub mod multisig;
pub mod preimage;
pub mod recovery;
pub mod referenda;
pub mod referenda_decode;
pub mod reversible;
pub mod runtime;
pub mod scheduler;
pub mod send;
pub mod storage;
pub mod system;
pub mod tech_collective;
pub mod tech_referenda;
pub mod transfers;
pub mod treasury;
pub mod wallet;
pub mod wormhole;

/// Main CLI commands
#[derive(Subcommand, Debug)]
pub enum Commands {
	/// Wallet management commands
	#[command(subcommand)]
	Wallet(wallet::WalletCommands),

	/// Send tokens to another account
	Send {
		/// The recipient's account address
		#[arg(short, long)]
		to: String,

		/// Amount to send (e.g., "10", "10.5", "0.0001")
		#[arg(short, long)]
		amount: String,

		/// Wallet name to send from
		#[arg(short, long)]
		from: String,

		/// Password for the wallet (or use environment variables)
		#[arg(short, long)]
		password: Option<String>,

		/// Read password from file (for scripting)
		#[arg(long)]
		password_file: Option<String>,

		/// Optional tip amount to prioritize the transaction (e.g., "1", "0.5")
		#[arg(long)]
		tip: Option<String>,

		/// Manual nonce override (use with caution - must be exact next nonce for account)
		#[arg(long)]
		nonce: Option<u32>,
	},

	/// Batch transfer commands and configuration
	#[command(subcommand)]
	Batch(batch::BatchCommands),

	/// Reversible transfer commands
	#[command(subcommand)]
	Reversible(reversible::ReversibleCommands),

	/// High-Security commands (reversible account settings)
	#[command(subcommand)]
	HighSecurity(high_security::HighSecurityCommands),

	/// Recovery commands
	#[command(subcommand)]
	Recovery(recovery::RecoveryCommands),

	/// Multisig commands (multi-signature wallets)
	#[command(subcommand)]
	Multisig(multisig::MultisigCommands),

	/// Scheduler commands
	#[command(subcommand)]
	Scheduler(scheduler::SchedulerCommands),

	/// Direct interaction with chain storage (read-only)
	#[command(subcommand)]
	Storage(storage::StorageCommands),

	/// Tech Collective management commands
	#[command(subcommand)]
	TechCollective(tech_collective::TechCollectiveCommands),

	/// Preimage management commands
	#[command(subcommand)]
	Preimage(preimage::PreimageCommands),

	/// Tech Referenda management commands (for runtime upgrade proposals)
	#[command(subcommand)]
	TechReferenda(tech_referenda::TechReferendaCommands),

	/// Standard Referenda management commands (public governance)
	#[command(subcommand)]
	Referenda(referenda::ReferendaCommands),

	/// Treasury account info
	#[command(subcommand)]
	Treasury(treasury::TreasuryCommands),

	/// Privacy-preserving transfer queries via Subsquid indexer
	#[command(subcommand)]
	Transfers(transfers::TransfersCommands),

	/// Runtime management commands (via governance where required)
	#[command(subcommand)]
	Runtime(runtime::RuntimeCommands),

	/// Generic extrinsic call - call ANY pallet function!
	Call {
		/// Pallet name (e.g., "Balances")
		#[arg(long)]
		pallet: String,

		/// Call/function name (e.g., "transfer_allow_death")
		#[arg(short, long)]
		call: String,

		/// Arguments as JSON array (e.g., '["5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
		/// "1000000000000"]')
		#[arg(short, long)]
		args: Option<String>,

		/// Wallet name to sign with
		#[arg(short, long)]
		from: String,

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

		/// Read password from file
		#[arg(long)]
		password_file: Option<String>,

		/// Optional tip amount to prioritize the transaction
		#[arg(long)]
		tip: Option<String>,

		/// Create offline extrinsic without submitting
		#[arg(long)]
		offline: bool,

		/// Output the call as hex-encoded data only
		#[arg(long)]
		call_data_only: bool,
	},

	/// Query account balance
	Balance {
		/// Account address to query (SS58 format)
		#[arg(short, long)]
		address: String,
	},

	/// Developer utilities and testing tools
	#[command(subcommand)]
	Developer(DeveloperCommands),

	/// Query events from blocks
	Events {
		/// Block number to query events from (full support)
		#[arg(long)]
		block: Option<u32>,

		/// Block hash to query events from (full support)
		#[arg(long)]
		block_hash: Option<String>,

		/// Query events from latest block
		#[arg(long)]
		latest: bool,

		/// Query events from finalized block (full support)
		#[arg(long)]
		finalized: bool,

		/// Filter events by pallet name (e.g., "Balances")
		#[arg(long)]
		pallet: Option<String>,

		/// Show raw event data
		#[arg(long)]
		raw: bool,

		/// Disable event decoding (decoding is enabled by default)
		#[arg(long)]
		no_decode: bool,
	},

	/// Query system information
	System {
		/// Show runtime version information
		#[arg(long)]
		runtime: bool,

		/// Show metadata statistics
		#[arg(long)]
		metadata: bool,

		/// Show available JSON-RPC methods exposed by the node
		#[arg(long)]
		rpc_methods: bool,
	},

	/// Explore chain metadata and available pallets/calls
	Metadata {
		/// Skip displaying documentation for calls
		#[arg(long)]
		no_docs: bool,

		/// Show only metadata statistics
		#[arg(long)]
		stats_only: bool,

		/// Filter by specific pallet name
		#[arg(long)]
		pallet: Option<String>,
	},

	/// Show version information
	Version,

	/// Check compatibility with the connected node
	CompatibilityCheck,

	/// Block management and analysis commands
	#[command(subcommand)]
	Block(block::BlockCommands),

	/// Wormhole proof generation and verification
	#[command(subcommand)]
	Wormhole(wormhole::WormholeCommands),

	/// Send random amounts to multiple addresses (total is distributed randomly)
	Multisend {
		/// Wallet name to send from
		#[arg(short, long)]
		from: String,

		/// File containing addresses (JSON array: ["addr1", "addr2", ...])
		#[arg(long, conflicts_with = "addresses")]
		addresses_file: Option<String>,

		/// Comma-separated list of recipient addresses
		#[arg(long, value_delimiter = ',', conflicts_with = "addresses_file")]
		addresses: Option<Vec<String>>,

		/// Total amount to distribute across all recipients (e.g., "1000", "100.5")
		#[arg(long)]
		total: String,

		/// Minimum amount per recipient (e.g., "10", "1.5")
		#[arg(long)]
		min: String,

		/// Maximum amount per recipient (e.g., "100", "50.5")
		#[arg(long)]
		max: String,

		/// Password for the wallet (or use environment variables)
		#[arg(short, long)]
		password: Option<String>,

		/// Read password from file (for scripting)
		#[arg(long)]
		password_file: Option<String>,

		/// Optional tip amount to prioritize the transaction (e.g., "1", "0.5")
		#[arg(long)]
		tip: Option<String>,

		/// Skip confirmation prompt (for scripting)
		#[arg(long, short = 'y')]
		yes: bool,
	},
}

/// Developer subcommands
#[derive(Subcommand, Debug)]
pub enum DeveloperCommands {
	/// Create standard test wallets (crystal_alice, crystal_bob, crystal_charlie)
	CreateTestWallets,
}

/// Execute a CLI command
pub async fn execute_command(
	command: Commands,
	node_url: &str,
	verbose: bool,
	execution_mode: common::ExecutionMode,
) -> crate::error::Result<()> {
	match command {
		Commands::Wallet(wallet_cmd) => wallet::handle_wallet_command(wallet_cmd, node_url).await,
		Commands::Send { from, to, amount, password, password_file, tip, nonce } =>
			send::handle_send_command(
				from,
				to,
				&amount,
				node_url,
				password,
				password_file,
				tip,
				nonce,
				execution_mode,
			)
			.await,
		Commands::Batch(batch_cmd) =>
			batch::handle_batch_command(batch_cmd, node_url, execution_mode).await,
		Commands::Reversible(reversible_cmd) =>
			reversible::handle_reversible_command(reversible_cmd, node_url, execution_mode).await,
		Commands::HighSecurity(hs_cmd) =>
			high_security::handle_high_security_command(hs_cmd, node_url, execution_mode).await,
		Commands::Recovery(recovery_cmd) =>
			recovery::handle_recovery_command(recovery_cmd, node_url, execution_mode).await,
		Commands::Multisig(multisig_cmd) =>
			multisig::handle_multisig_command(multisig_cmd, node_url, execution_mode).await,
		Commands::Scheduler(scheduler_cmd) =>
			scheduler::handle_scheduler_command(scheduler_cmd, node_url, execution_mode).await,
		Commands::Storage(storage_cmd) =>
			storage::handle_storage_command(storage_cmd, node_url, execution_mode).await,
		Commands::TechCollective(tech_collective_cmd) =>
			tech_collective::handle_tech_collective_command(
				tech_collective_cmd,
				node_url,
				execution_mode,
			)
			.await,
		Commands::Preimage(preimage_cmd) =>
			preimage::handle_preimage_command(preimage_cmd, node_url, execution_mode).await,
		Commands::TechReferenda(tech_referenda_cmd) =>
			tech_referenda::handle_tech_referenda_command(
				tech_referenda_cmd,
				node_url,
				execution_mode,
			)
			.await,
		Commands::Referenda(referenda_cmd) =>
			referenda::handle_referenda_command(referenda_cmd, node_url, execution_mode).await,
		Commands::Treasury(treasury_cmd) =>
			treasury::handle_treasury_command(treasury_cmd, node_url, execution_mode).await,
		Commands::Transfers(transfers_cmd) =>
			transfers::handle_transfers_command(transfers_cmd).await,
		Commands::Runtime(runtime_cmd) =>
			runtime::handle_runtime_command(runtime_cmd, node_url, execution_mode).await,
		Commands::Call {
			pallet,
			call,
			args,
			from,
			password,
			password_file,
			tip,
			offline,
			call_data_only,
		} =>
			handle_generic_call_command(
				pallet,
				call,
				args,
				from,
				password,
				password_file,
				tip,
				offline,
				call_data_only,
				node_url,
				execution_mode,
			)
			.await,
		Commands::Balance { address } => {
			let quantus_client = crate::chain::client::QuantusClient::new(node_url).await?;

			// Resolve address (could be wallet name or SS58 address)
			let resolved_address = common::resolve_address(&address)?;

			let account_data = send::get_account_data(&quantus_client, &resolved_address).await?;
			let (symbol, decimals) = send::get_chain_properties(&quantus_client).await?;

			let free_fmt = send::format_balance(account_data.free, decimals);
			let reserved_fmt = send::format_balance(account_data.reserved, decimals);
			let frozen_fmt = send::format_balance(account_data.frozen, decimals);

			log_print!("๐Ÿ’ฐ {} {}", "Balance".bright_green().bold(), resolved_address.bright_cyan());
			log_print!("   Free:     {} {}", free_fmt.bright_green(), symbol);
			log_print!("   Reserved: {} {}", reserved_fmt.bright_yellow(), symbol);
			log_print!("   Frozen:   {} {}", frozen_fmt.bright_red(), symbol);
			Ok(())
		},
		Commands::Developer(dev_cmd) => handle_developer_command(dev_cmd).await,
		Commands::Events { block, block_hash, latest: _, finalized, pallet, raw, no_decode } =>
			events::handle_events_command(
				block, block_hash, finalized, pallet, raw, !no_decode, node_url,
			)
			.await,
		Commands::System { runtime, metadata, rpc_methods } => {
			if runtime || metadata || rpc_methods {
				system::handle_system_extended_command(
					node_url,
					runtime,
					metadata,
					rpc_methods,
					verbose,
				)
				.await
			} else {
				system::handle_system_command(node_url).await
			}
		},
		Commands::Metadata { no_docs, stats_only, pallet } =>
			metadata::handle_metadata_command(node_url, no_docs, stats_only, pallet).await,
		Commands::Version => {
			log_print!("CLI Version: Quantus CLI v{}", env!("CARGO_PKG_VERSION"));
			Ok(())
		},
		Commands::CompatibilityCheck => handle_compatibility_check(node_url).await,
		Commands::Block(block_cmd) => block::handle_block_command(block_cmd, node_url).await,
		Commands::Wormhole(wormhole_cmd) =>
			wormhole::handle_wormhole_command(wormhole_cmd, node_url).await,
		Commands::Multisend {
			from,
			addresses_file,
			addresses,
			total,
			min,
			max,
			password,
			password_file,
			tip,
			yes,
		} =>
			multisend::handle_multisend_command(
				from,
				node_url,
				addresses_file,
				addresses,
				total,
				min,
				max,
				password,
				password_file,
				tip,
				yes,
				execution_mode,
			)
			.await,
	}
}

/// Handle generic extrinsic call command
#[allow(clippy::too_many_arguments)]
async fn handle_generic_call_command(
	pallet: String,
	call: String,
	args: Option<String>,
	from: String,
	password: Option<String>,
	password_file: Option<String>,
	tip: Option<String>,
	offline: bool,
	call_data_only: bool,
	node_url: &str,
	execution_mode: common::ExecutionMode,
) -> crate::error::Result<()> {
	// For now, we only support live submission (not offline or call-data-only)
	if offline {
		log_error!("โŒ Offline mode is not yet implemented");
		log_print!("๐Ÿ’ก Currently only live submission is supported");
		return Ok(());
	}

	if call_data_only {
		log_error!("โŒ Call-data-only mode is not yet implemented");
		log_print!("๐Ÿ’ก Currently only live submission is supported");
		return Ok(());
	}

	let keypair = crate::wallet::load_keypair_from_wallet(&from, password, password_file)?;

	let args_vec = if let Some(args_str) = args {
		serde_json::from_str(&args_str).map_err(|e| {
			crate::error::QuantusError::Generic(format!("Invalid JSON for arguments: {e}"))
		})?
	} else {
		vec![]
	};

	generic_call::handle_generic_call(
		&pallet,
		&call,
		args_vec,
		&keypair,
		tip,
		node_url,
		execution_mode,
	)
	.await
}

/// Handle developer subcommands
pub async fn handle_developer_command(command: DeveloperCommands) -> crate::error::Result<()> {
	match command {
		DeveloperCommands::CreateTestWallets => {
			use crate::wallet::WalletManager;

			log_print!(
				"๐Ÿงช {} Creating standard test wallets...",
				"DEVELOPER".bright_magenta().bold()
			);
			log_print!("");

			let wallet_manager = WalletManager::new()?;

			// Standard test wallets with well-known names
			let test_wallets = vec![
				("crystal_alice", "Alice's test wallet for development"),
				("crystal_bob", "Bob's test wallet for development"),
				("crystal_charlie", "Charlie's test wallet for development"),
			];

			let mut created_count = 0;

			for (name, description) in test_wallets {
				log_verbose!("Creating wallet: {}", name.bright_green());

				// Create wallet with a default password for testing
				match wallet_manager.create_developer_wallet(name).await {
					Ok(wallet_info) => {
						log_success!("โœ… Created {}", name.bright_green());
						log_success!("   Address: {}", wallet_info.address.bright_cyan());
						log_success!("   Description: {}", description.dimmed());
						created_count += 1;
					},
					Err(e) => {
						log_error!("โŒ Failed to create {}: {}", name.bright_red(), e);
					},
				}
			}

			log_print!("");
			log_success!("๐ŸŽ‰ Test wallet creation complete!");
			log_success!("   Created: {} wallets", created_count.to_string().bright_green());
			log_print!("");
			log_print!("๐Ÿ’ก {} You can now use these wallets:", "TIP".bright_blue().bold());
			log_print!("   quantus send --from crystal_alice --to <address> --amount 1000");
			log_print!("   quantus send --from crystal_bob --to <address> --amount 1000");
			log_print!("   quantus send --from crystal_charlie --to <address> --amount 1000");
			log_print!("");

			Ok(())
		},
	}
}

/// Handle compatibility check command
async fn handle_compatibility_check(node_url: &str) -> crate::error::Result<()> {
	log_print!("๐Ÿ” Compatibility Check");
	log_print!("๐Ÿ”— Connecting to: {}", node_url.bright_cyan());
	log_print!("");

	// Connect to the node
	let quantus_client = crate::chain::client::QuantusClient::new(node_url).await?;

	// Get runtime version
	let runtime_version = runtime::get_runtime_version(quantus_client.client()).await?;

	// Get system info for additional details
	let chain_info = system::get_complete_chain_info(node_url).await?;

	log_print!("๐Ÿ“‹ Version Information:");
	log_print!("   โ€ข CLI Version: {}", env!("CARGO_PKG_VERSION").bright_green());
	log_print!(
		"   โ€ข Runtime Spec Version: {}",
		runtime_version.spec_version.to_string().bright_yellow()
	);
	log_print!(
		"   โ€ข Runtime Impl Version: {}",
		runtime_version.impl_version.to_string().bright_blue()
	);
	log_print!(
		"   โ€ข Transaction Version: {}",
		runtime_version.transaction_version.to_string().bright_magenta()
	);

	if let Some(name) = &chain_info.chain_name {
		log_print!("   โ€ข Chain Name: {}", name.bright_cyan());
	}

	log_print!("");

	// Check compatibility
	let is_compatible = crate::config::is_runtime_compatible(runtime_version.spec_version);

	log_print!("๐Ÿ” Compatibility Analysis:");
	log_print!("   โ€ข Supported Runtime Versions: {:?}", crate::config::COMPATIBLE_RUNTIME_VERSIONS);
	log_print!("   โ€ข Current Runtime Version: {}", runtime_version.spec_version);

	if is_compatible {
		log_success!("โœ… COMPATIBLE - This CLI version supports the connected node");
		log_print!("   โ€ข All features should work correctly");
		log_print!("   โ€ข You can safely use all CLI commands");
	} else {
		log_error!("โŒ INCOMPATIBLE - This CLI version may not work with the connected node");
		log_print!("   โ€ข Some features may not work correctly");
		log_print!("   โ€ข Consider updating the CLI or connecting to a compatible node");
		log_print!("   โ€ข Supported versions: {:?}", crate::config::COMPATIBLE_RUNTIME_VERSIONS);
	}

	log_print!("");
	log_print!("๐Ÿ’ก Tip: Use 'quantus version' for quick version check");
	log_print!("๐Ÿ’ก Tip: Use 'quantus system --runtime' for detailed system info");

	Ok(())
}