quantus_cli/cli/
send.rs

1use crate::{
2	chain::{client::QuantusClient, quantus_subxt},
3	cli::common::resolve_address,
4	error::Result,
5	log_info, log_print, log_success, log_verbose,
6};
7use colored::Colorize;
8use sp_core::crypto::{AccountId32 as SpAccountId32, Ss58Codec};
9
10/// Get the `free` balance for the given account using on-chain storage.
11pub async fn get_balance(quantus_client: &QuantusClient, account_address: &str) -> Result<u128> {
12	use quantus_subxt::api;
13
14	log_verbose!("💰 Querying balance for account: {}", account_address.bright_green());
15
16	// Decode the SS58 address into `AccountId32` (sp-core) first …
17	let (account_id_sp, _) =
18		SpAccountId32::from_ss58check_with_version(account_address).map_err(|e| {
19			crate::error::QuantusError::Generic(format!(
20				"Invalid account address '{account_address}': {e:?}"
21			))
22		})?;
23
24	// … then convert into the `subxt` representation expected by the generated API.
25	let bytes: [u8; 32] = *account_id_sp.as_ref();
26	let account_id = subxt::ext::subxt_core::utils::AccountId32::from(bytes);
27
28	// Build the storage key for `System::Account` and fetch (or default-init) it.
29	let storage_addr = api::storage().system().account(account_id);
30
31	// Get the latest block hash to read from the latest state (not finalized)
32	let latest_block_hash = quantus_client.get_latest_block().await?;
33
34	let storage_at = quantus_client.client().storage().at(latest_block_hash);
35
36	let account_info = storage_at.fetch_or_default(&storage_addr).await.map_err(|e| {
37		crate::error::QuantusError::NetworkError(format!("Failed to fetch account info: {e:?}"))
38	})?;
39
40	Ok(account_info.data.free)
41}
42
43/// Get chain properties for formatting (uses system.rs ChainHead API)
44pub async fn get_chain_properties(quantus_client: &QuantusClient) -> Result<(String, u8)> {
45	// Use the shared ChainHead API from system.rs to avoid duplication
46	match crate::cli::system::get_complete_chain_info(quantus_client.node_url()).await {
47		Ok(chain_info) => {
48			log_verbose!(
49				"💰 Token: {} with {} decimals",
50				chain_info.token.symbol,
51				chain_info.token.decimals
52			);
53
54			Ok((chain_info.token.symbol, chain_info.token.decimals))
55		},
56		Err(e) => {
57			log_verbose!("❌ ChainHead API failed: {:?}", e);
58			Err(e)
59		},
60	}
61}
62
63/// Format balance with token symbol
64pub async fn format_balance_with_symbol(
65	quantus_client: &QuantusClient,
66	amount: u128,
67) -> Result<String> {
68	let (symbol, decimals) = get_chain_properties(quantus_client).await?;
69	let formatted_amount = format_balance(amount, decimals);
70	Ok(format!("{formatted_amount} {symbol}"))
71}
72
73/// Format balance with proper decimals
74pub fn format_balance(amount: u128, decimals: u8) -> String {
75	if decimals == 0 {
76		return amount.to_string();
77	}
78
79	let divisor = 10_u128.pow(decimals as u32);
80	let whole_part = amount / divisor;
81	let fractional_part = amount % divisor;
82
83	if fractional_part == 0 {
84		whole_part.to_string()
85	} else {
86		let fractional_str = format!("{:0width$}", fractional_part, width = decimals as usize);
87		let fractional_str = fractional_str.trim_end_matches('0');
88
89		if fractional_str.is_empty() {
90			whole_part.to_string()
91		} else {
92			format!("{whole_part}.{fractional_str}")
93		}
94	}
95}
96
97/// Parse human-readable amount string to raw chain units
98pub async fn parse_amount(quantus_client: &QuantusClient, amount_str: &str) -> Result<u128> {
99	let (_, decimals) = get_chain_properties(quantus_client).await?;
100	parse_amount_with_decimals(amount_str, decimals)
101}
102
103/// Parse amount string with specific decimals
104pub fn parse_amount_with_decimals(amount_str: &str, decimals: u8) -> Result<u128> {
105	let amount_part = amount_str.split_whitespace().next().unwrap_or("");
106
107	if amount_part.is_empty() {
108		return Err(crate::error::QuantusError::Generic("Amount cannot be empty".to_string()));
109	}
110
111	let parsed_amount: f64 = amount_part.parse().map_err(|_| {
112		crate::error::QuantusError::Generic(format!(
113			"Invalid amount format: '{amount_part}'. Use formats like '10', '10.5', '0.0001'"
114		))
115	})?;
116
117	if parsed_amount < 0.0 {
118		return Err(crate::error::QuantusError::Generic("Amount cannot be negative".to_string()));
119	}
120
121	if let Some(decimal_part) = amount_part.split('.').nth(1) {
122		if decimal_part.len() > decimals as usize {
123			return Err(crate::error::QuantusError::Generic(format!(
124				"Too many decimal places. Maximum {decimals} decimal places allowed for this chain"
125			)));
126		}
127	}
128
129	let multiplier = 10_f64.powi(decimals as i32);
130	let raw_amount = (parsed_amount * multiplier).round() as u128;
131
132	if raw_amount == 0 {
133		return Err(crate::error::QuantusError::Generic(
134			"Amount too small to represent in chain units".to_string(),
135		));
136	}
137
138	Ok(raw_amount)
139}
140
141/// Validate and format amount for display before sending
142pub async fn validate_and_format_amount(
143	quantus_client: &QuantusClient,
144	amount_str: &str,
145) -> Result<(u128, String)> {
146	let raw_amount = parse_amount(quantus_client, amount_str).await?;
147	let formatted = format_balance_with_symbol(quantus_client, raw_amount).await?;
148	Ok((raw_amount, formatted))
149}
150
151/// Transfer tokens with automatic nonce
152#[allow(dead_code)] // Used by external libraries via lib.rs export
153pub async fn transfer(
154	quantus_client: &QuantusClient,
155	from_keypair: &crate::wallet::QuantumKeyPair,
156	to_address: &str,
157	amount: u128,
158	tip: Option<u128>,
159	finalized: bool,
160) -> Result<subxt::utils::H256> {
161	transfer_with_nonce(quantus_client, from_keypair, to_address, amount, tip, None, finalized)
162		.await
163}
164
165/// Transfer tokens with manual nonce override
166pub async fn transfer_with_nonce(
167	quantus_client: &QuantusClient,
168	from_keypair: &crate::wallet::QuantumKeyPair,
169	to_address: &str,
170	amount: u128,
171	tip: Option<u128>,
172	nonce: Option<u32>,
173	finalized: bool,
174) -> Result<subxt::utils::H256> {
175	log_verbose!("🚀 Creating transfer transaction...");
176	log_verbose!("   From: {}", from_keypair.to_account_id_ss58check().bright_cyan());
177	log_verbose!("   To: {}", to_address.bright_green());
178	log_verbose!("   Amount: {}", amount);
179
180	// Resolve the destination address (could be wallet name or SS58 address)
181	let resolved_address = resolve_address(to_address)?;
182	log_verbose!("   Resolved to: {}", resolved_address.bright_green());
183
184	// Parse the destination address
185	let (to_account_id_sp, _) = SpAccountId32::from_ss58check_with_version(&resolved_address)
186		.map_err(|e| {
187			crate::error::QuantusError::NetworkError(format!("Invalid destination address: {e:?}"))
188		})?;
189
190	// Convert to subxt_core AccountId32
191	let to_account_id_bytes: [u8; 32] = *to_account_id_sp.as_ref();
192	let to_account_id = subxt::ext::subxt_core::utils::AccountId32::from(to_account_id_bytes);
193
194	log_verbose!("✍️  Creating balance transfer extrinsic...");
195
196	// Create the transfer call using static API from quantus_subxt
197	let transfer_call = quantus_subxt::api::tx().balances().transfer_allow_death(
198		subxt::ext::subxt_core::utils::MultiAddress::Id(to_account_id.clone()),
199		amount,
200	);
201
202	// Use provided tip or default tip of 10 DEV to increase priority and avoid temporarily
203	// banned errors
204	let tip_to_use = tip.unwrap_or(10_000_000_000); // Use provided tip or default 10 DEV
205
206	// Submit the transaction with optional manual nonce
207	let tx_hash = if let Some(manual_nonce) = nonce {
208		log_verbose!("🔢 Using manual nonce: {}", manual_nonce);
209		crate::cli::common::submit_transaction_with_nonce(
210			quantus_client,
211			from_keypair,
212			transfer_call,
213			Some(tip_to_use),
214			manual_nonce,
215			finalized,
216		)
217		.await?
218	} else {
219		crate::cli::common::submit_transaction(
220			quantus_client,
221			from_keypair,
222			transfer_call,
223			Some(tip_to_use),
224			finalized,
225		)
226		.await?
227	};
228
229	log_verbose!("📋 Transaction submitted: {:?}", tx_hash);
230
231	Ok(tx_hash)
232}
233
234/// Batch transfer tokens to multiple recipients in a single transaction
235pub async fn batch_transfer(
236	quantus_client: &QuantusClient,
237	from_keypair: &crate::wallet::QuantumKeyPair,
238	transfers: Vec<(String, u128)>, // (to_address, amount) pairs
239	tip: Option<u128>,
240	finalized: bool,
241) -> Result<subxt::utils::H256> {
242	log_verbose!("🚀 Creating batch transfer transaction with {} transfers...", transfers.len());
243	log_verbose!("   From: {}", from_keypair.to_account_id_ss58check().bright_cyan());
244
245	if transfers.is_empty() {
246		return Err(crate::error::QuantusError::Generic(
247			"No transfers provided for batch".to_string(),
248		));
249	}
250
251	// Get dynamic limits from chain
252	let (safe_limit, recommended_limit) =
253		get_batch_limits(quantus_client).await.unwrap_or((500, 1000));
254
255	if transfers.len() as u32 > recommended_limit {
256		return Err(crate::error::QuantusError::Generic(format!(
257			"Too many transfers in batch ({}) - chain limit is ~{} (safe: {})",
258			transfers.len(),
259			recommended_limit,
260			safe_limit
261		)));
262	}
263
264	// Warn about large batches
265	if transfers.len() as u32 > safe_limit {
266		log_verbose!(
267			"⚠️  Large batch ({} transfers) - approaching chain limits (safe: {}, max: {})",
268			transfers.len(),
269			safe_limit,
270			recommended_limit
271		);
272	}
273
274	// Prepare all transfer calls as RuntimeCall
275	let mut calls = Vec::new();
276	for (to_address, amount) in transfers {
277		log_verbose!("   To: {} Amount: {}", to_address.bright_green(), amount);
278
279		// Resolve the destination address
280		let resolved_address = crate::cli::common::resolve_address(&to_address)?;
281
282		// Parse the destination address
283		let to_account_id_sp = SpAccountId32::from_ss58check(&resolved_address).map_err(|e| {
284			crate::error::QuantusError::NetworkError(format!(
285				"Invalid destination address {resolved_address}: {e:?}"
286			))
287		})?;
288
289		// Convert to subxt_core AccountId32
290		let to_account_id_bytes: [u8; 32] = *to_account_id_sp.as_ref();
291		let to_account_id = subxt::ext::subxt_core::utils::AccountId32::from(to_account_id_bytes);
292
293		// Create the transfer call as RuntimeCall
294		use quantus_subxt::api::runtime_types::{
295			pallet_balances::pallet::Call as BalancesCall, quantus_runtime::RuntimeCall,
296		};
297
298		let transfer_call = RuntimeCall::Balances(BalancesCall::transfer_allow_death {
299			dest: subxt::ext::subxt_core::utils::MultiAddress::Id(to_account_id),
300			value: amount,
301		});
302
303		calls.push(transfer_call);
304	}
305
306	log_verbose!("✍️  Creating batch extrinsic with {} calls...", calls.len());
307
308	// Create the batch call using utility pallet
309	let batch_call = quantus_subxt::api::tx().utility().batch(calls);
310
311	// Use provided tip or default tip
312	let tip_to_use = tip.unwrap_or(10_000_000_000);
313
314	// Submit the batch transaction
315	let tx_hash = crate::cli::common::submit_transaction(
316		quantus_client,
317		from_keypair,
318		batch_call,
319		Some(tip_to_use),
320		finalized,
321	)
322	.await?;
323
324	log_verbose!("📋 Batch transaction submitted: {:?}", tx_hash);
325
326	Ok(tx_hash)
327}
328
329// (Removed custom `AccountData` struct – we now use the runtime-generated type)
330
331/// Handle the send command
332pub async fn handle_send_command(
333	from_wallet: String,
334	to_address: String,
335	amount_str: &str,
336	node_url: &str,
337	password: Option<String>,
338	password_file: Option<String>,
339	tip: Option<String>,
340	nonce: Option<u32>,
341	finalized: bool,
342) -> Result<()> {
343	// Create quantus chain client
344	let quantus_client = QuantusClient::new(node_url).await?;
345
346	// Parse and validate the amount
347	let (amount, formatted_amount) =
348		validate_and_format_amount(&quantus_client, amount_str).await?;
349
350	// Resolve the destination address (could be wallet name or SS58 address)
351	let resolved_address = resolve_address(&to_address)?;
352
353	log_info!("🚀 Initiating transfer of {} to {}", formatted_amount, resolved_address);
354	log_verbose!(
355		"🚀 {} Sending {} to {}",
356		"SEND".bright_cyan().bold(),
357		formatted_amount.bright_yellow().bold(),
358		resolved_address.bright_green()
359	);
360
361	// Get password securely for decryption
362	log_verbose!("📦 Using wallet: {}", from_wallet.bright_blue().bold());
363	let keypair = crate::wallet::load_keypair_from_wallet(&from_wallet, password, password_file)?;
364
365	// Get account information
366	let from_account_id = keypair.to_account_id_ss58check();
367	let balance = get_balance(&quantus_client, &from_account_id).await?;
368
369	// Get formatted balance with proper decimals
370	let formatted_balance = format_balance_with_symbol(&quantus_client, balance).await?;
371	log_verbose!("💰 Current balance: {}", formatted_balance.bright_yellow());
372
373	if balance < amount {
374		return Err(crate::error::QuantusError::InsufficientBalance {
375			available: balance,
376			required: amount,
377		});
378	}
379
380	// Create and submit transaction
381	log_verbose!("✍️  {} Signing transaction...", "SIGN".bright_magenta().bold());
382
383	// Parse tip amount if provided
384	let tip_amount = if let Some(tip_str) = &tip {
385		// Get chain properties for proper decimal parsing
386		let (_, decimals) = get_chain_properties(&quantus_client).await?;
387		parse_amount_with_decimals(tip_str, decimals).ok()
388	} else {
389		None
390	};
391
392	// Submit transaction
393	let tx_hash = transfer_with_nonce(
394		&quantus_client,
395		&keypair,
396		&resolved_address,
397		amount,
398		tip_amount,
399		nonce,
400		finalized,
401	)
402	.await?;
403
404	log_print!("✅ {} Transaction submitted! Hash: {:?}", "SUCCESS".bright_green().bold(), tx_hash);
405	log_success!("🎉 {} Transaction confirmed!", "FINISHED".bright_green().bold());
406
407	// Show updated balance with proper formatting
408	let new_balance = get_balance(&quantus_client, &from_account_id).await?;
409	let formatted_new_balance = format_balance_with_symbol(&quantus_client, new_balance).await?;
410
411	// Calculate and display transaction fee in verbose mode
412	let fee_paid = balance.saturating_sub(new_balance).saturating_sub(amount);
413	if fee_paid > 0 {
414		let formatted_fee = format_balance_with_symbol(&quantus_client, fee_paid).await?;
415		log_verbose!("💸 Transaction fee: {}", formatted_fee.bright_cyan());
416	}
417
418	log_print!("💰 New balance: {}", formatted_new_balance.bright_yellow());
419
420	Ok(())
421}
422
423/// Load transfers from JSON file
424pub async fn load_transfers_from_file(file_path: &str) -> Result<Vec<(String, u128)>> {
425	use serde_json;
426	use std::fs;
427
428	#[derive(serde::Deserialize)]
429	struct TransferEntry {
430		to: String,
431		amount: String,
432	}
433
434	let content = fs::read_to_string(file_path).map_err(|e| {
435		crate::error::QuantusError::Generic(format!("Failed to read batch file: {e:?}"))
436	})?;
437
438	let entries: Vec<TransferEntry> = serde_json::from_str(&content).map_err(|e| {
439		crate::error::QuantusError::Generic(format!("Failed to parse batch file JSON: {e:?}"))
440	})?;
441
442	let mut transfers = Vec::new();
443	for entry in entries {
444		// Parse amount as raw units (no decimals conversion here)
445		let amount = entry.amount.parse::<u128>().map_err(|e| {
446			crate::error::QuantusError::Generic(format!("Invalid amount '{}': {e:?}", entry.amount))
447		})?;
448		transfers.push((entry.to, amount));
449	}
450
451	Ok(transfers)
452}
453
454/// Get chain constants for batch limits
455pub async fn get_batch_limits(quantus_client: &QuantusClient) -> Result<(u32, u32)> {
456	// Try to get actual chain constants
457	let constants = quantus_client.client().constants();
458
459	// Get block weight limit
460	let block_weight_limit = constants
461		.at(&quantus_subxt::api::constants().system().block_weights())
462		.map(|weights| weights.max_block.ref_time)
463		.unwrap_or(2_000_000_000_000); // Default 2 trillion weight units
464
465	// Estimate transfers per block (rough calculation)
466	let transfer_weight = 1_500_000_000u64; // Rough estimate per transfer
467	let max_transfers_by_weight = (block_weight_limit / transfer_weight) as u32;
468
469	// Get max extrinsic length
470	let max_extrinsic_length = constants
471		.at(&quantus_subxt::api::constants().system().block_length())
472		.map(|length| length.max.normal)
473		.unwrap_or(5_242_880); // Default 5MB
474
475	// Estimate transfers per extrinsic size (very rough)
476	let transfer_size = 100u32; // Rough estimate per transfer in bytes
477	let max_transfers_by_size = max_extrinsic_length / transfer_size;
478
479	let recommended_limit = std::cmp::min(max_transfers_by_weight, max_transfers_by_size);
480	let safe_limit = recommended_limit / 2; // Be conservative
481
482	log_verbose!(
483		"📊 Chain limits: weight allows ~{}, size allows ~{}",
484		max_transfers_by_weight,
485		max_transfers_by_size
486	);
487	log_verbose!("📊 Recommended batch size: {} (safe: {})", recommended_limit, safe_limit);
488
489	Ok((safe_limit, recommended_limit))
490}