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
//! `quantus vesting` — treasury-funded vesting schedules.
//!
//! The Vesting pallet holds treasury-granted schedules in a pot account and pays
//! beneficiaries linearly between `start` and `end` (nothing before `cliff`).
//! `claim` is permissionless: anyone may trigger a payout, which always goes to
//! the stored beneficiary. The admin calls (`create-schedule`, `end-schedule`,
//! `retarget`) require the treasury origin (or Root): on real deployments the
//! treasury is a multisig, so route them through `quantus multisig propose`
//! using the call data these commands can print with `--call-data-only`.
use crate::{
	chain::quantus_subxt,
	cli::{address_format::QuantusSS58, common::ExecutionMode},
	error::{QuantusError, Result},
	log_print, log_success,
};
use clap::Subcommand;
use colored::Colorize;
use subxt::tx::Payload;

type VestingScheduleInfo =
	quantus_subxt::api::runtime_types::pallet_vesting::pallet::VestingSchedule<
		crate::cli::common::SubxtAccountId32,
		u128,
	>;

/// Vesting commands
#[derive(Subcommand, Debug)]
pub enum VestingCommands {
	/// Show vesting pallet constants and the next schedule id
	Info,

	/// List all vesting schedules (optionally filtered by beneficiary)
	List {
		/// Only show schedules for this beneficiary (address or wallet name)
		#[arg(long)]
		beneficiary: Option<String>,
	},

	/// Show a single vesting schedule
	Show {
		/// Schedule id
		#[arg(long)]
		schedule_id: u64,
	},

	/// Claim the currently vested payout of a schedule (permissionless; pays the beneficiary)
	Claim {
		/// Schedule id
		#[arg(long)]
		schedule_id: u64,

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

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

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

	/// Create a schedule, moving `total` from the treasury into the vesting pot
	/// (requires the treasury origin; use --call-data-only to route via multisig)
	CreateSchedule {
		/// Beneficiary address or wallet name
		#[arg(long)]
		beneficiary: String,

		/// Vesting start: unix ms, or "now", or "+<seconds>" relative to now
		#[arg(long)]
		start: String,

		/// Cliff: unix ms, "now", or "+<seconds>" (defaults to the start moment)
		#[arg(long)]
		cliff: Option<String>,

		/// Vesting end: unix ms, "now", or "+<seconds>"
		#[arg(long)]
		end: String,

		/// Total amount to vest (e.g., "1000", "10.5")
		#[arg(long)]
		total: String,

		/// Wallet name to sign with (must be the treasury account unless printing call data)
		#[arg(short, long, required_unless_present = "call_data_only")]
		from: Option<String>,

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

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

		/// Print the hex call data instead of submitting (for multisig proposals)
		#[arg(long)]
		call_data_only: bool,
	},

	/// End a schedule early: unpaid vested part to the beneficiary, the rest back to
	/// the treasury (requires the treasury origin)
	EndSchedule {
		/// Schedule id
		#[arg(long)]
		schedule_id: u64,

		/// Wallet name to sign with (must be the treasury account unless printing call data)
		#[arg(short, long, required_unless_present = "call_data_only")]
		from: Option<String>,

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

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

		/// Print the hex call data instead of submitting (for multisig proposals)
		#[arg(long)]
		call_data_only: bool,
	},

	/// Change a schedule's beneficiary after settling any currently claimable payout
	/// (requires the treasury origin)
	Retarget {
		/// Schedule id
		#[arg(long)]
		schedule_id: u64,

		/// New beneficiary address or wallet name
		#[arg(long)]
		new_beneficiary: String,

		/// Wallet name to sign with (must be the treasury account unless printing call data)
		#[arg(short, long, required_unless_present = "call_data_only")]
		from: Option<String>,

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

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

		/// Print the hex call data instead of submitting (for multisig proposals)
		#[arg(long)]
		call_data_only: bool,
	},
}

/// Handle vesting commands
pub async fn handle_vesting_command(
	command: VestingCommands,
	node_url: &str,
	execution_mode: ExecutionMode,
) -> Result<()> {
	let quantus_client = crate::chain::client::QuantusClient::new(node_url).await?;

	match command {
		VestingCommands::Info => show_info(&quantus_client).await,
		VestingCommands::List { beneficiary } => list_schedules(&quantus_client, beneficiary).await,
		VestingCommands::Show { schedule_id } => show_schedule(&quantus_client, schedule_id).await,
		VestingCommands::Claim { schedule_id, from, password, password_file } => {
			let keypair = crate::wallet::load_keypair_from_wallet(&from, password, password_file)?;
			claim(&quantus_client, &keypair, schedule_id, execution_mode).await
		},
		VestingCommands::CreateSchedule {
			beneficiary,
			start,
			cliff,
			end,
			total,
			from,
			password,
			password_file,
			call_data_only,
		} => {
			let beneficiary_id = crate::cli::common::resolve_to_subxt_account_id(&beneficiary)?;
			let start_ms = parse_moment(&start)?;
			let cliff_ms = match &cliff {
				Some(value) => parse_moment(value)?,
				None => start_ms,
			};
			let end_ms = parse_moment(&end)?;
			let total_amount = crate::cli::send::parse_amount(&quantus_client, &total).await?;
			let call = quantus_subxt::api::tx().vesting().create_schedule(
				beneficiary_id,
				start_ms,
				cliff_ms,
				end_ms,
				total_amount,
			);
			if call_data_only {
				return print_call_data(&quantus_client, &call);
			}
			let keypair = load_admin_keypair(from, password, password_file)?;
			log_print!("🪙 Creating vesting schedule...");
			log_print!("   Beneficiary: {}", beneficiary.bright_cyan());
			log_print!("   Start: {}   Cliff: {}   End: {}", start_ms, cliff_ms, end_ms);
			let tx_hash = crate::cli::common::submit_transaction(
				&quantus_client,
				&keypair,
				call,
				None,
				execution_mode,
			)
			.await?;
			log_success!("✅ Schedule created. Tx: {:?}", tx_hash);
			Ok(())
		},
		VestingCommands::EndSchedule {
			schedule_id,
			from,
			password,
			password_file,
			call_data_only,
		} => {
			let call = quantus_subxt::api::tx().vesting().end_schedule(schedule_id);
			if call_data_only {
				return print_call_data(&quantus_client, &call);
			}
			let keypair = load_admin_keypair(from, password, password_file)?;
			log_print!("🪙 Ending vesting schedule #{schedule_id}...");
			let tx_hash = crate::cli::common::submit_transaction(
				&quantus_client,
				&keypair,
				call,
				None,
				execution_mode,
			)
			.await?;
			log_success!("✅ Schedule ended. Tx: {:?}", tx_hash);
			Ok(())
		},
		VestingCommands::Retarget {
			schedule_id,
			new_beneficiary,
			from,
			password,
			password_file,
			call_data_only,
		} => {
			let new_beneficiary_id =
				crate::cli::common::resolve_to_subxt_account_id(&new_beneficiary)?;
			let call = quantus_subxt::api::tx()
				.vesting()
				.retarget_schedule(schedule_id, new_beneficiary_id);
			if call_data_only {
				return print_call_data(&quantus_client, &call);
			}
			let keypair = load_admin_keypair(from, password, password_file)?;
			log_print!(
				"🪙 Retargeting schedule #{schedule_id} to {}...",
				new_beneficiary.bright_cyan()
			);
			let tx_hash = crate::cli::common::submit_transaction(
				&quantus_client,
				&keypair,
				call,
				None,
				execution_mode,
			)
			.await?;
			log_success!("✅ Schedule retargeted. Tx: {:?}", tx_hash);
			Ok(())
		},
	}
}

fn load_admin_keypair(
	from: Option<String>,
	password: Option<String>,
	password_file: Option<String>,
) -> Result<crate::wallet::QuantumKeyPair> {
	let from = from.ok_or_else(|| {
		QuantusError::Generic(
			"--from is required when submitting (or pass --call-data-only)".into(),
		)
	})?;
	crate::wallet::load_keypair_from_wallet(&from, password, password_file)
}

fn print_call_data<Call: Payload>(
	quantus_client: &crate::chain::client::QuantusClient,
	call: &Call,
) -> Result<()> {
	let call_data = call
		.encode_call_data(&quantus_client.client().metadata())
		.map_err(|e| QuantusError::Generic(format!("Failed to encode call: {e:?}")))?;
	log_print!("0x{}", hex::encode(&call_data));
	log_print!(
		"💡 Propose it from the treasury multisig: quantus multisig propose --multisig <treasury> --call-data <hex> ..."
	);
	Ok(())
}

/// Parse a vesting moment: unix milliseconds, "now", or "+<seconds>" relative to now.
fn parse_moment(value: &str) -> Result<u64> {
	let now_ms = || -> Result<u64> {
		std::time::SystemTime::now()
			.duration_since(std::time::UNIX_EPOCH)
			.map(|d| d.as_millis() as u64)
			.map_err(|e| QuantusError::Generic(format!("System clock error: {e}")))
	};
	if value == "now" {
		return now_ms();
	}
	if let Some(offset) = value.strip_prefix('+') {
		let seconds: u64 = offset.parse().map_err(|_| {
			QuantusError::Generic(format!("Invalid relative moment '+{offset}': expected seconds"))
		})?;
		let offset_ms = seconds.checked_mul(1_000).ok_or_else(|| {
			QuantusError::Generic(format!(
				"Invalid relative moment '+{offset}': seconds overflow when converting to milliseconds"
			))
		})?;
		return now_ms()?.checked_add(offset_ms).ok_or_else(|| {
			QuantusError::Generic(format!(
				"Invalid relative moment '+{offset}': timestamp overflow when adding to now"
			))
		});
	}
	value.parse().map_err(|_| {
		QuantusError::Generic(format!(
			"Invalid moment '{value}': expected unix milliseconds, \"now\", or \"+<seconds>\""
		))
	})
}

async fn show_info(quantus_client: &crate::chain::client::QuantusClient) -> Result<()> {
	let constants = quantus_client.client().constants();
	let payout_quantum =
		constants.at(&quantus_subxt::api::constants().vesting().payout_quantum())?;
	let minimum_payout =
		constants.at(&quantus_subxt::api::constants().vesting().minimum_payout())?;
	let min_claim_interval =
		constants.at(&quantus_subxt::api::constants().vesting().min_claim_interval())?;

	let latest_block_hash = quantus_client.get_latest_block().await?;
	let storage_at = quantus_client.client().storage().at(latest_block_hash);
	let next_id_addr = quantus_subxt::api::storage().vesting().next_schedule_id();
	let next_id = storage_at.fetch_or_default(&next_id_addr).await?;

	let quantum_fmt =
		crate::cli::send::format_balance_with_symbol(quantus_client, payout_quantum).await?;
	let minimum_fmt =
		crate::cli::send::format_balance_with_symbol(quantus_client, minimum_payout).await?;

	log_print!("🪙 {}", "Vesting".bright_green().bold());
	log_print!("   Payout quantum:     {}", quantum_fmt);
	log_print!("   Minimum payout:     {}", minimum_fmt);
	log_print!("   Min claim interval: {} ms", min_claim_interval);
	log_print!("   Next schedule id:   {}", next_id.to_string().bright_yellow());
	Ok(())
}

/// Fetch all schedules as (id, schedule) pairs, sorted by id.
pub async fn fetch_all_schedules(
	quantus_client: &crate::chain::client::QuantusClient,
) -> Result<Vec<(u64, VestingScheduleInfo)>> {
	let latest_block_hash = quantus_client.get_latest_block().await?;
	let storage = quantus_client.client().storage().at(latest_block_hash);
	let address = quantus_subxt::api::storage().vesting().schedules_iter();
	let mut iter = storage.iter(address).await?;

	let mut schedules = Vec::new();
	while let Some(result) = iter.next().await {
		let kv = result?;
		// Twox64Concat key: the raw u64 id is the last 8 bytes of the storage key.
		if kv.key_bytes.len() >= 8 {
			let id_bytes: [u8; 8] = kv.key_bytes[kv.key_bytes.len() - 8..]
				.try_into()
				.expect("slice is 8 bytes; qed");
			schedules.push((u64::from_le_bytes(id_bytes), kv.value));
		}
	}
	schedules.sort_by_key(|(id, _)| *id);
	Ok(schedules)
}

/// Fetch a single schedule by id.
pub async fn fetch_schedule(
	quantus_client: &crate::chain::client::QuantusClient,
	schedule_id: u64,
) -> Result<Option<VestingScheduleInfo>> {
	let latest_block_hash = quantus_client.get_latest_block().await?;
	let storage = quantus_client.client().storage().at(latest_block_hash);
	let address = quantus_subxt::api::storage().vesting().schedules(schedule_id);
	Ok(storage.fetch(&address).await?)
}

async fn list_schedules(
	quantus_client: &crate::chain::client::QuantusClient,
	beneficiary: Option<String>,
) -> Result<()> {
	let filter = match &beneficiary {
		Some(value) => Some(crate::cli::common::resolve_to_subxt_account_id(value)?),
		None => None,
	};

	let mut schedules = fetch_all_schedules(quantus_client).await?;
	if let Some(filter_id) = &filter {
		schedules.retain(|(_, s)| &s.beneficiary == filter_id);
	}

	if schedules.is_empty() {
		log_print!("🪙 No vesting schedules found");
		return Ok(());
	}

	log_print!("🪙 {} vesting schedule(s):", schedules.len().to_string().bright_yellow());
	for (id, schedule) in &schedules {
		log_print!("");
		print_schedule(quantus_client, *id, schedule).await?;
	}
	Ok(())
}

async fn show_schedule(
	quantus_client: &crate::chain::client::QuantusClient,
	schedule_id: u64,
) -> Result<()> {
	match fetch_schedule(quantus_client, schedule_id).await? {
		Some(schedule) => print_schedule(quantus_client, schedule_id, &schedule).await,
		None => Err(QuantusError::Generic(format!("No vesting schedule with id {schedule_id}"))),
	}
}

fn format_moment(ms: u64) -> String {
	use chrono::TimeZone;
	match chrono::Utc.timestamp_millis_opt(ms as i64) {
		chrono::LocalResult::Single(dt) => format!("{ms} ({})", dt.format("%Y-%m-%d %H:%M:%S UTC")),
		_ => format!("{ms}"),
	}
}

async fn print_schedule(
	quantus_client: &crate::chain::client::QuantusClient,
	id: u64,
	schedule: &VestingScheduleInfo,
) -> Result<()> {
	let total_fmt =
		crate::cli::send::format_balance_with_symbol(quantus_client, schedule.total).await?;
	let claimed_fmt =
		crate::cli::send::format_balance_with_symbol(quantus_client, schedule.claimed).await?;

	log_print!("📋 Schedule #{}", id.to_string().bright_yellow());
	log_print!("   Beneficiary: {}", schedule.beneficiary.to_quantus_ss58().bright_cyan());
	log_print!("   Start: {}", format_moment(schedule.start));
	log_print!("   Cliff: {}", format_moment(schedule.cliff));
	log_print!("   End:   {}", format_moment(schedule.end));
	log_print!("   Total:   {}", total_fmt);
	log_print!("   Claimed: {}", claimed_fmt);
	match schedule.last_claim_at {
		Some(at) => log_print!("   Last claim: {}", format_moment(at)),
		None => log_print!("   Last claim: never"),
	}
	Ok(())
}

async fn claim(
	quantus_client: &crate::chain::client::QuantusClient,
	keypair: &crate::wallet::QuantumKeyPair,
	schedule_id: u64,
	execution_mode: ExecutionMode,
) -> Result<()> {
	log_print!("🪙 Claiming vesting schedule #{schedule_id}...");

	let call = quantus_subxt::api::tx().vesting().claim(schedule_id);
	let wait_mode = ExecutionMode { wait_for_transaction: true, ..execution_mode };
	let (tx_hash, included_in) = crate::cli::common::submit_transaction_with_inclusion_block(
		quantus_client,
		keypair,
		call,
		None,
		wait_mode,
	)
	.await?;

	// Report the actual payout from the Claimed event in the inclusion block.
	if let Some(block_hash) = included_in {
		let events = quantus_client.client().events().at(block_hash).await?;
		for event in events.find::<quantus_subxt::api::vesting::events::Claimed>().flatten() {
			if event.schedule_id == schedule_id {
				let amount_fmt =
					crate::cli::send::format_balance_with_symbol(quantus_client, event.amount)
						.await?;
				log_success!(
					"✅ Paid {} to {}",
					amount_fmt,
					event.beneficiary.to_quantus_ss58().bright_cyan()
				);
			}
		}
	}
	log_success!("✅ Claim submitted. Tx: {:?}", tx_hash);
	Ok(())
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn parse_moment_rejects_relative_seconds_overflow() {
		let err = parse_moment(&format!("+{}", u64::MAX)).unwrap_err();
		let msg = err.to_string();
		assert!(
			msg.contains("overflow") && msg.contains("milliseconds"),
			"expected checked_mul error, got: {msg}"
		);
	}

	#[test]
	fn parse_moment_accepts_small_relative_offset() {
		let now = parse_moment("now").expect("now");
		let later = parse_moment("+1").expect("+1s");
		assert!(later >= now + 1_000, "expected +1s to add 1000ms");
	}
}