quantus-cli 1.3.3

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
use crate::{
	chain::quantus_subxt,
	cli::{address_format::QuantusSS58, common::resolve_address},
	error::Result,
	log_info, log_print, log_verbose,
};
use clap::Subcommand;
use colored::Colorize;
use sp_core::crypto::{AccountId32 as SpAccountId32, Ss58Codec};
use std::str::FromStr;

/// Reversible transfer commands
#[derive(Subcommand, Debug)]
pub enum ReversibleCommands {
	/// Schedule a transfer with default delay
	ScheduleTransfer {
		/// The recipient's account address
		#[arg(short, long)]
		to: String,

		/// Amount to transfer (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
		#[arg(short, long)]
		password: Option<String>,

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

	/// Schedule a transfer with custom delay
	ScheduleTransferWithDelay {
		/// The recipient's account address
		#[arg(short, long)]
		to: String,

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

		/// Delay in seconds (default) or blocks if --unit-blocks is specified
		#[arg(short, long)]
		delay: u64,

		/// Use blocks instead of seconds for delay
		#[arg(long)]
		unit_blocks: bool,

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

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

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

	/// Cancel a pending reversible transaction
	Cancel {
		/// Transaction ID to cancel (hex hash)
		#[arg(long)]
		tx_id: 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 (for scripting)
		#[arg(long)]
		password_file: Option<String>,
	},

	/// List all pending reversible transactions for an account
	ListPending {
		/// 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)]
		from: Option<String>,

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

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

/// Schedule a transfer with default delay
pub async fn schedule_transfer(
	quantus_client: &crate::chain::client::QuantusClient,
	from_keypair: &crate::wallet::QuantumKeyPair,
	to_address: &str,
	amount: u128,
	execution_mode: crate::cli::common::ExecutionMode,
) -> Result<subxt::utils::H256> {
	log_verbose!("🔄 Creating reversible transfer...");
	log_verbose!("   From: {}", from_keypair.to_account_id_ss58check().bright_cyan());
	log_verbose!("   To: {}", to_address.bright_green());
	log_verbose!("   Amount: {}", amount);

	// Parse the destination address
	let (to_account_id_sp, _version) = SpAccountId32::from_ss58check_with_version(to_address)
		.map_err(|e| {
			crate::error::QuantusError::NetworkError(format!("Invalid destination address: {e:?}"))
		})?;

	// Convert to subxt_core AccountId32
	let to_account_id_bytes: [u8; 32] = *to_account_id_sp.as_ref();
	let to_account_id = subxt::ext::subxt_core::utils::AccountId32::from(to_account_id_bytes);

	log_verbose!("✍️  Creating reversible transfer extrinsic...");

	// Create the reversible transfer call using static API from quantus_subxt
	let transfer_call = quantus_subxt::api::tx()
		.reversible_transfers()
		.schedule_transfer(subxt::ext::subxt_core::utils::MultiAddress::Id(to_account_id), amount);

	// Submit the transaction
	let tx_hash = crate::cli::common::submit_transaction(
		quantus_client,
		from_keypair,
		transfer_call,
		None,
		execution_mode,
	)
	.await?;

	log_verbose!("📋 Reversible transfer submitted: {:?}", tx_hash);

	Ok(tx_hash)
}

/// Cancel a pending reversible transaction
pub async fn cancel_transaction(
	quantus_client: &crate::chain::client::QuantusClient,
	from_keypair: &crate::wallet::QuantumKeyPair,
	tx_id: &str,
	execution_mode: crate::cli::common::ExecutionMode,
) -> Result<subxt::utils::H256> {
	log_verbose!("❌ Cancelling reversible transfer...");
	log_verbose!("   Transaction ID: {}", tx_id.bright_yellow());

	// Parse transaction ID using H256::from_str
	let tx_hash = subxt::utils::H256::from_str(tx_id).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Invalid transaction ID: {e:?}"))
	})?;

	log_verbose!("✍️  Creating cancel transaction extrinsic...");

	// Create the cancel transaction call using static API from quantus_subxt
	let cancel_call = quantus_subxt::api::tx().reversible_transfers().cancel(tx_hash);

	// Submit the transaction
	let tx_hash_result = crate::cli::common::submit_transaction(
		quantus_client,
		from_keypair,
		cancel_call,
		None,
		execution_mode,
	)
	.await?;

	log_verbose!("📋 Cancel transaction submitted: {:?}", tx_hash_result);

	Ok(tx_hash_result)
}

/// Schedule a transfer with custom delay
pub async fn schedule_transfer_with_delay(
	quantus_client: &crate::chain::client::QuantusClient,
	from_keypair: &crate::wallet::QuantumKeyPair,
	to_address: &str,
	amount: u128,
	delay: u64,
	unit_blocks: bool,
	execution_mode: crate::cli::common::ExecutionMode,
) -> Result<subxt::utils::H256> {
	let unit_str = if unit_blocks { "blocks" } else { "seconds" };
	log_verbose!("🔄 Creating reversible transfer with custom delay ...");
	log_verbose!("   From: {}", from_keypair.to_account_id_ss58check().bright_cyan());
	log_verbose!("   To: {}", to_address.bright_green());
	log_verbose!("   Amount: {}", amount);
	log_verbose!("   Delay: {} {}", delay, unit_str);

	// Parse the destination address
	let to_account_id_sp = SpAccountId32::from_ss58check(to_address).map_err(|e| {
		crate::error::QuantusError::NetworkError(format!("Invalid destination address: {e:?}"))
	})?;
	let to_account_id_bytes: [u8; 32] = *to_account_id_sp.as_ref();
	let to_account_id_subxt = subxt::ext::subxt_core::utils::AccountId32::from(to_account_id_bytes);

	// Convert delay to proper BlockNumberOrTimestamp
	let delay_value = if unit_blocks {
		quantus_subxt::api::reversible_transfers::calls::types::schedule_transfer_with_delay::Delay::BlockNumber(delay as u32)
	} else {
		// Convert seconds to milliseconds for the runtime
		quantus_subxt::api::reversible_transfers::calls::types::schedule_transfer_with_delay::Delay::Timestamp(delay * 1000)
	};

	log_verbose!("✍️  Creating schedule_transfer_with_delay extrinsic...");

	// Create the schedule transfer with delay call using static API from quantus_subxt
	let transfer_call =
		quantus_subxt::api::tx().reversible_transfers().schedule_transfer_with_delay(
			subxt::ext::subxt_core::utils::MultiAddress::Id(to_account_id_subxt),
			amount,
			delay_value,
		);

	// Submit the transaction
	let tx_hash = crate::cli::common::submit_transaction(
		quantus_client,
		from_keypair,
		transfer_call,
		None,
		execution_mode,
	)
	.await?;

	log_verbose!("📋 Reversible transfer with custom delay submitted: {:?}", tx_hash);

	Ok(tx_hash)
}

/// Handle reversible transfer subxt commands
pub async fn handle_reversible_command(
	command: ReversibleCommands,
	node_url: &str,
	execution_mode: crate::cli::common::ExecutionMode,
) -> Result<()> {
	log_print!("🔄 Reversible Transfers");

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

	match command {
		ReversibleCommands::ListPending { address, from, password, password_file } =>
			list_pending_transactions(&quantus_client, address, from, password, password_file).await,
		ReversibleCommands::ScheduleTransfer { to, amount, from, password, password_file } => {
			// Parse and validate the amount
			let quantus_client = crate::chain::client::QuantusClient::new(node_url).await?;
			let (raw_amount, formatted_amount) =
				crate::cli::send::validate_and_format_amount(&quantus_client, &amount).await?;

			// Resolve the destination address (could be wallet name or SS58 address)
			let resolved_address = resolve_address(&to)?;

			log_info!(
				"🔄 Scheduling reversible transfer of {} to {}",
				formatted_amount,
				resolved_address
			);
			log_verbose!(
				"🚀 {} Scheduling reversible transfer {} to {} ()",
				"REVERSIBLE".bright_cyan().bold(),
				formatted_amount.bright_yellow().bold(),
				resolved_address.bright_green()
			);

			// Get password securely for decryption
			log_verbose!("📦 Using wallet: {}", from.bright_blue().bold());
			let keypair = crate::wallet::load_keypair_from_wallet(&from, password, password_file)?;

			// Submit transaction
			let tx_hash = schedule_transfer(
				&quantus_client,
				&keypair,
				&resolved_address,
				raw_amount,
				execution_mode,
			)
			.await?;

			log_print!(
				"✅ {} Reversible transfer scheduled! Hash: {:?}",
				"SUCCESS".bright_green().bold(),
				tx_hash
			);

			Ok(())
		},
		ReversibleCommands::Cancel { tx_id, from, password, password_file } => {
			log_verbose!(
				"❌ {} Cancelling reversible transfer {} ()",
				"CANCEL".bright_red().bold(),
				tx_id.bright_yellow().bold()
			);

			// Get password securely for decryption
			log_verbose!("📦 Using wallet: {}", from.bright_blue().bold());
			let keypair = crate::wallet::load_keypair_from_wallet(&from, password, password_file)?;

			// Submit cancel transaction
			let tx_hash =
				cancel_transaction(&quantus_client, &keypair, &tx_id, execution_mode).await?;

			log_print!(
				"✅ {} Cancel transaction submitted! Hash: {:?}",
				"SUCCESS".bright_green().bold(),
				tx_hash
			);

			Ok(())
		},

		ReversibleCommands::ScheduleTransferWithDelay {
			to,
			amount,
			delay,
			unit_blocks,
			from,
			password,
			password_file,
		} => {
			// Parse and validate the amount
			let quantus_client = crate::chain::client::QuantusClient::new(node_url).await?;
			let (raw_amount, formatted_amount) =
				crate::cli::send::validate_and_format_amount(&quantus_client, &amount).await?;

			// Resolve the destination address (could be wallet name or SS58 address)
			let resolved_address = resolve_address(&to)?;

			let unit_str = if unit_blocks { "blocks" } else { "seconds" };
			log_verbose!(
				"🚀 {} Scheduling reversible transfer {} to {} with {} {} delay ()",
				"REVERSIBLE".bright_cyan().bold(),
				formatted_amount.bright_yellow().bold(),
				resolved_address.bright_green(),
				delay.to_string().bright_magenta(),
				unit_str
			);

			// Get password securely for decryption
			log_verbose!("📦 Using wallet: {}", from.bright_blue().bold());
			let keypair = crate::wallet::load_keypair_from_wallet(&from, password, password_file)?;

			// Submit transaction
			let tx_hash = schedule_transfer_with_delay(
				&quantus_client,
				&keypair,
				&resolved_address,
				raw_amount,
				delay,
				unit_blocks,
				execution_mode,
			)
			.await?;

			log_print!(
				"✅ {} Reversible transfer with custom delay scheduled! Hash: {:?}",
				"SUCCESS".bright_green().bold(),
				tx_hash
			);

			Ok(())
		},
	}
}

/// List all pending reversible transactions for an account
async fn list_pending_transactions(
	quantus_client: &crate::chain::client::QuantusClient,
	address: Option<String>,
	wallet_name: Option<String>,
	password: Option<String>,
	password_file: Option<String>,
) -> Result<()> {
	log_print!("📋 Listing pending reversible transactions");

	// Determine which address to query
	let target_address = match (address, wallet_name) {
		(Some(addr), _) => {
			// Validate the provided address
			SpAccountId32::from_ss58check(&addr).map_err(|e| {
				crate::error::QuantusError::Generic(format!("Invalid address: {e:?}"))
			})?;
			addr
		},
		(None, Some(wallet)) => {
			// Load wallet and get its address
			let keypair =
				crate::wallet::load_keypair_from_wallet(&wallet, password, password_file)?;
			keypair.to_account_id_ss58check()
		},
		(None, None) => {
			return Err(crate::error::QuantusError::Generic(
				"Either --address or --from must be provided".to_string(),
			));
		},
	};

	// Convert to AccountId32 for storage queries
	let account_id_sp = SpAccountId32::from_ss58check(&target_address)
		.map_err(|e| crate::error::QuantusError::Generic(format!("Invalid address: {e:?}")))?;
	let account_id_bytes: [u8; 32] = *account_id_sp.as_ref();
	let account_id = subxt::ext::subxt_core::utils::AccountId32::from(account_id_bytes);

	log_verbose!("🔍 Querying pending transfers for: {}", target_address);

	// Query pending transfers by sender (outgoing)
	let sender_storage_address = crate::chain::quantus_subxt::api::storage()
		.reversible_transfers()
		.pending_transfers_by_sender(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 outgoing_transfers = quantus_client
		.client()
		.storage()
		.at(latest_block_hash)
		.fetch(&sender_storage_address)
		.await
		.map_err(|e| crate::error::QuantusError::NetworkError(format!("Fetch error: {e:?}")))?;

	let mut total_transfers = 0;

	// Display outgoing transfers
	if let Some(outgoing_hashes) = outgoing_transfers {
		if !outgoing_hashes.0.is_empty() {
			log_print!("📤 Outgoing pending transfers:");
			for (i, hash) in outgoing_hashes.0.iter().enumerate() {
				total_transfers += 1;
				log_print!("   {}. 0x{}", i + 1, hex::encode(hash.as_ref()));

				// Try to get transfer details
				let transfer_storage_address = crate::chain::quantus_subxt::api::storage()
					.reversible_transfers()
					.pending_transfers(*hash);

				if let Ok(Some(transfer_details)) = quantus_client
					.client()
					.storage()
					.at(latest_block_hash)
					.fetch(&transfer_storage_address)
					.await
					.map_err(|e| {
						crate::error::QuantusError::NetworkError(format!("Fetch error: {e:?}"))
					}) {
					let formatted_amount = format_amount(transfer_details.amount);
					log_print!("      👤 To: {}", transfer_details.to.to_quantus_ss58());
					log_print!("      💰 Amount: {}", formatted_amount);
					log_print!(
						"      🔄 Interceptor: {}",
						transfer_details.interceptor.to_quantus_ss58()
					);
				}
			}
		}
	}

	if total_transfers == 0 {
		log_print!("📝 No pending transfers found for account: {}", target_address);
	} else {
		log_print!("");
		log_print!("📊 Total pending transfers: {}", total_transfers);
		log_print!("💡 Use transaction hash with 'quantus reversible cancel --tx-id <hash>' to cancel outgoing transfers");
	}

	Ok(())
}

/// Helper function to format amount with QUAN units
fn format_amount(amount: u128) -> String {
	const QUAN_DECIMALS: u128 = 1_000_000_000_000; // 10^12

	if amount >= QUAN_DECIMALS {
		let whole = amount / QUAN_DECIMALS;
		let fractional = amount % QUAN_DECIMALS;

		if fractional == 0 {
			format!("{whole} QUAN")
		} else {
			// Remove trailing zeros from fractional part
			let fractional_str = format!("{fractional:012}");
			let trimmed = fractional_str.trim_end_matches('0');
			format!("{whole}.{trimmed} QUAN")
		}
	} else {
		format!("{amount} pico-QUAN")
	}
}