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
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
//! `quantus referenda` subcommand - manage standard Referenda proposals
use crate::{
	chain::quantus_subxt,
	cli::{common::submit_transaction, tech_collective::VoteChoice},
	error::QuantusError,
	log_error, log_print, log_success, log_verbose,
};
use clap::Subcommand;
use colored::Colorize;
use std::str::FromStr;

/// Standard Referenda management commands
#[derive(Subcommand, Debug)]
pub enum ReferendaCommands {
	/// Submit a simple proposal (System::remark) to test Referenda
	SubmitRemark {
		/// Message to include in the remark
		#[arg(long)]
		message: 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>,

		/// Origin type: signed (default) or root
		#[arg(long, default_value = "signed")]
		origin: String,
	},

	/// Submit a proposal using existing preimage hash
	Submit {
		/// Preimage hash (must already exist on chain)
		#[arg(long)]
		preimage_hash: 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>,

		/// Origin type: signed (default) or root
		#[arg(long, default_value = "signed")]
		origin: String,
	},

	/// List all active Referenda proposals
	List,

	/// Get details of a specific Referendum
	Get {
		/// Referendum index
		#[arg(short, long)]
		index: u32,

		/// Decode and display the proposal call in human-readable format
		#[arg(long)]
		decode: bool,
	},

	/// Check the status of a Referendum
	Status {
		/// Referendum index
		#[arg(short, long)]
		index: u32,
	},

	/// Place a decision deposit for a Referendum
	PlaceDecisionDeposit {
		/// Referendum index
		#[arg(short, long)]
		index: u32,

		/// 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>,
	},

	/// Vote on a Referendum (uses conviction voting)
	Vote {
		/// Referendum index
		#[arg(short, long)]
		index: u32,

		/// Vote: "aye" or "nay"
		#[arg(long)]
		vote: VoteChoice,

		/// Conviction (0=None, 1=Locked1x, 2=Locked2x, up to 6=Locked6x)
		#[arg(long, default_value = "0")]
		conviction: u8,

		/// Amount to vote with
		#[arg(long)]
		amount: 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>,
	},

	/// Refund submission deposit for a completed Referendum
	RefundSubmissionDeposit {
		/// Referendum index
		#[arg(short, long)]
		index: u32,

		/// Wallet name that submitted the referendum
		#[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>,
	},

	/// Refund decision deposit for a completed Referendum
	RefundDecisionDeposit {
		/// Referendum index
		#[arg(short, long)]
		index: u32,

		/// Wallet name that placed the decision deposit
		#[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>,
	},

	/// Get Referenda configuration
	Config,
}

/// Handle referenda commands
pub async fn handle_referenda_command(
	command: ReferendaCommands,
	node_url: &str,
	execution_mode: crate::cli::common::ExecutionMode,
) -> crate::error::Result<()> {
	let quantus_client = crate::chain::client::QuantusClient::new(node_url).await?;

	match command {
		ReferendaCommands::SubmitRemark { message, from, password, password_file, origin } =>
			submit_remark_proposal(
				&quantus_client,
				&message,
				&from,
				password,
				password_file,
				&origin,
				execution_mode,
			)
			.await,
		ReferendaCommands::Submit { preimage_hash, from, password, password_file, origin } =>
			submit_proposal(
				&quantus_client,
				&preimage_hash,
				&from,
				password,
				password_file,
				&origin,
				execution_mode,
			)
			.await,
		ReferendaCommands::List => list_proposals(&quantus_client).await,
		ReferendaCommands::Get { index, decode } =>
			get_proposal_details(&quantus_client, index, decode).await,
		ReferendaCommands::Status { index } => get_proposal_status(&quantus_client, index).await,
		ReferendaCommands::PlaceDecisionDeposit { index, from, password, password_file } =>
			place_decision_deposit(
				&quantus_client,
				index,
				&from,
				password,
				password_file,
				execution_mode,
			)
			.await,
		ReferendaCommands::Vote {
			index,
			vote,
			conviction,
			amount,
			from,
			password,
			password_file,
		} =>
			vote_on_referendum(
				&quantus_client,
				index,
				matches!(vote, VoteChoice::Aye),
				conviction,
				&amount,
				&from,
				password,
				password_file,
				execution_mode,
			)
			.await,
		ReferendaCommands::RefundSubmissionDeposit { index, from, password, password_file } =>
			refund_submission_deposit(
				&quantus_client,
				index,
				&from,
				password,
				password_file,
				execution_mode,
			)
			.await,
		ReferendaCommands::RefundDecisionDeposit { index, from, password, password_file } =>
			refund_decision_deposit(
				&quantus_client,
				index,
				&from,
				password,
				password_file,
				execution_mode,
			)
			.await,
		ReferendaCommands::Config => get_config(&quantus_client).await,
	}
}

/// Submit a simple System::remark proposal
async fn submit_remark_proposal(
	quantus_client: &crate::chain::client::QuantusClient,
	message: &str,
	from: &str,
	password: Option<String>,
	password_file: Option<String>,
	origin_type: &str,
	execution_mode: crate::cli::common::ExecutionMode,
) -> crate::error::Result<()> {
	use sp_runtime::traits::{BlakeTwo256, Hash};

	log_print!("📝 Submitting System::remark Proposal to Referenda");
	log_print!("   💬 Message: {}", message.bright_cyan());
	log_print!("   🔑 Submitted by: {}", from.bright_yellow());
	log_print!("   🎯 Origin type: {}", origin_type.bright_magenta());

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

	// Build System::remark call and encode it
	let remark_bytes = message.as_bytes().to_vec();
	let remark_payload = quantus_subxt::api::tx().system().remark(remark_bytes.clone());
	let metadata = quantus_client.client().metadata();
	let encoded_call = <_ as subxt::tx::Payload>::encode_call_data(&remark_payload, &metadata)
		.map_err(|e| QuantusError::Generic(format!("Failed to encode call data: {:?}", e)))?;

	log_verbose!("📝 Encoded call size: {} bytes", encoded_call.len());

	// Must match `frame_system::Config::Hashing` (BlakeTwo256) — same key as `pallet_preimage`.
	let preimage_hash: sp_core::H256 = BlakeTwo256::hash(&encoded_call);

	log_print!("🔗 Preimage hash: {:?}", preimage_hash);

	let call_len = encoded_call.len() as u32;
	crate::cli::common::submit_preimage(quantus_client, &keypair, encoded_call, execution_mode)
		.await?;

	// Build Referenda::submit call using Lookup preimage reference
	type ProposalBounded =
		quantus_subxt::api::runtime_types::frame_support::traits::preimages::Bounded<
			quantus_subxt::api::runtime_types::quantus_runtime::RuntimeCall,
			quantus_subxt::api::runtime_types::sp_runtime::traits::BlakeTwo256,
		>;

	let preimage_hash_subxt: subxt::utils::H256 = preimage_hash;
	let proposal: ProposalBounded =
		ProposalBounded::Lookup { hash: preimage_hash_subxt, len: call_len };

	// Create origin based on origin_type parameter
	let account_id_sp = keypair.to_account_id_32();
	let account_id_subxt: subxt::ext::subxt_core::utils::AccountId32 =
		subxt::ext::subxt_core::utils::AccountId32(*account_id_sp.as_ref());

	let origin_caller = match origin_type.to_lowercase().as_str() {
		"signed" => {
			let raw_origin =
				quantus_subxt::api::runtime_types::frame_support::dispatch::RawOrigin::Signed(
					account_id_subxt,
				);
			quantus_subxt::api::runtime_types::quantus_runtime::OriginCaller::system(raw_origin)
		},
		"root" => {
			let raw_origin =
				quantus_subxt::api::runtime_types::frame_support::dispatch::RawOrigin::Root;
			quantus_subxt::api::runtime_types::quantus_runtime::OriginCaller::system(raw_origin)
		},
		"none" =>
			return Err(QuantusError::Generic(
				"Invalid origin type: none. Use 'signed' or 'root'.".to_string(),
			)),
		_ =>
			return Err(QuantusError::Generic(format!(
				"Invalid origin type: {}. Must be 'signed' or 'root'",
				origin_type
			))),
	};

	let enactment =
		quantus_subxt::api::runtime_types::frame_support::traits::schedule::DispatchTime::After(
			10u32, // Execute 10 blocks after approval
		);

	log_print!("🔧 Creating Referenda::submit call...");
	let submit_call =
		quantus_subxt::api::tx().referenda().submit(origin_caller, proposal, enactment);

	let tx_hash =
		submit_transaction(quantus_client, &keypair, submit_call, None, execution_mode).await?;
	log_print!(
		"✅ {} Referendum proposal submitted! Hash: {:?}",
		"SUCCESS".bright_green().bold(),
		tx_hash
	);

	log_print!("💡 Use 'quantus referenda list' to see active proposals");
	Ok(())
}

/// Submit a proposal using existing preimage hash
async fn submit_proposal(
	quantus_client: &crate::chain::client::QuantusClient,
	preimage_hash: &str,
	from: &str,
	password: Option<String>,
	password_file: Option<String>,
	origin_type: &str,
	execution_mode: crate::cli::common::ExecutionMode,
) -> crate::error::Result<()> {
	log_print!("📝 Submitting Proposal to Referenda");
	log_print!("   🔗 Preimage hash: {}", preimage_hash.bright_cyan());
	log_print!("   🔑 Submitted by: {}", from.bright_yellow());
	log_print!("   🎯 Origin type: {}", origin_type.bright_magenta());

	// Parse preimage hash
	let hash_str = preimage_hash.trim_start_matches("0x");
	let preimage_hash_parsed: sp_core::H256 = sp_core::H256::from_str(hash_str)
		.map_err(|_| QuantusError::Generic("Invalid preimage hash format".to_string()))?;

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

	// Check if preimage exists and get its length
	log_print!("🔍 Checking preimage status...");
	let latest_block_hash = quantus_client.get_latest_block().await?;
	let storage_at = quantus_client.client().storage().at(latest_block_hash);

	let preimage_status = storage_at
		.fetch(
			&quantus_subxt::api::storage()
				.preimage()
				.request_status_for(preimage_hash_parsed),
		)
		.await
		.map_err(|e| QuantusError::Generic(format!("Failed to fetch preimage status: {:?}", e)))?
		.ok_or_else(|| QuantusError::Generic("Preimage not found on chain".to_string()))?;

	let preimage_len = match preimage_status {
		quantus_subxt::api::runtime_types::pallet_preimage::RequestStatus::Unrequested {
			ticket: _,
			len,
		} => len,
		quantus_subxt::api::runtime_types::pallet_preimage::RequestStatus::Requested {
			maybe_ticket: _,
			count: _,
			maybe_len,
		} => match maybe_len {
			Some(len) => len,
			None => return Err(QuantusError::Generic("Preimage length not available".to_string())),
		},
	};

	log_print!("✅ Preimage found! Length: {} bytes", preimage_len);

	// Build Referenda::submit call
	type ProposalBounded =
		quantus_subxt::api::runtime_types::frame_support::traits::preimages::Bounded<
			quantus_subxt::api::runtime_types::quantus_runtime::RuntimeCall,
			quantus_subxt::api::runtime_types::sp_runtime::traits::BlakeTwo256,
		>;

	let preimage_hash_subxt: subxt::utils::H256 = preimage_hash_parsed;
	let proposal: ProposalBounded =
		ProposalBounded::Lookup { hash: preimage_hash_subxt, len: preimage_len };

	// Create origin based on origin_type parameter
	let account_id_sp = keypair.to_account_id_32();
	let account_id_subxt: subxt::ext::subxt_core::utils::AccountId32 =
		subxt::ext::subxt_core::utils::AccountId32(*account_id_sp.as_ref());

	let origin_caller = match origin_type.to_lowercase().as_str() {
		"signed" => {
			let raw_origin =
				quantus_subxt::api::runtime_types::frame_support::dispatch::RawOrigin::Signed(
					account_id_subxt,
				);
			quantus_subxt::api::runtime_types::quantus_runtime::OriginCaller::system(raw_origin)
		},
		"root" => {
			let raw_origin =
				quantus_subxt::api::runtime_types::frame_support::dispatch::RawOrigin::Root;
			quantus_subxt::api::runtime_types::quantus_runtime::OriginCaller::system(raw_origin)
		},
		"none" =>
			return Err(QuantusError::Generic(
				"Invalid origin type: none. Use 'signed' or 'root'.".to_string(),
			)),
		_ =>
			return Err(QuantusError::Generic(format!(
				"Invalid origin type: {}. Must be 'signed' or 'root'",
				origin_type
			))),
	};

	let enactment =
		quantus_subxt::api::runtime_types::frame_support::traits::schedule::DispatchTime::After(
			10u32,
		);

	log_print!("🔧 Creating Referenda::submit call...");
	let submit_call =
		quantus_subxt::api::tx().referenda().submit(origin_caller, proposal, enactment);

	let tx_hash =
		submit_transaction(quantus_client, &keypair, submit_call, None, execution_mode).await?;
	log_print!(
		"✅ {} Referendum proposal submitted! Hash: {:?}",
		"SUCCESS".bright_green().bold(),
		tx_hash
	);

	log_print!("💡 Use 'quantus referenda list' to see active proposals");
	Ok(())
}

/// List recent Referenda proposals
async fn list_proposals(
	quantus_client: &crate::chain::client::QuantusClient,
) -> crate::error::Result<()> {
	log_print!("📜 Active Referenda Proposals");
	log_print!("");

	let addr = quantus_subxt::api::storage().referenda().referendum_count();

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

	let count = storage_at.fetch(&addr).await?;

	if let Some(total) = count {
		log_print!("📊 Total referenda created: {}", total);
		if total == 0 {
			log_print!("📭 No active proposals found");
			return Ok(());
		}
		log_print!("🔍 Fetching recent referenda...");
		for i in (0..total).rev().take(10) {
			get_proposal_status(quantus_client, i).await?;
			log_print!("----------------------------------------");
		}
	} else {
		log_print!("📭 No referenda found - Referenda may be empty");
	}

	Ok(())
}

/// Get details of a specific Referendum
async fn get_proposal_details(
	quantus_client: &crate::chain::client::QuantusClient,
	index: u32,
	decode: bool,
) -> crate::error::Result<()> {
	use quantus_subxt::api::runtime_types::pallet_referenda::types::ReferendumInfo;

	log_print!("📄 Referendum #{} Details", index);
	log_print!("");

	let addr = quantus_subxt::api::storage().referenda().referendum_info_for(index);

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

	let info = storage_at.fetch(&addr).await?;

	if let Some(referendum_info) = info {
		if decode {
			// Try to decode the proposal
			match &referendum_info {
				ReferendumInfo::Ongoing(status) => {
					log_print!("📊 {} Referendum #{}", "Ongoing".bright_green(), index);
					log_print!("   🛤️  Track: {}", status.track);
					log_print!("   📅 Submitted: Block #{}", status.submitted);
					log_print!(
						"   🗳️  Tally: Ayes: {}, Nays: {}, Support: {}",
						status.tally.ayes,
						status.tally.nays,
						status.tally.support
					);
					log_print!("");

					// Extract preimage hash and length from proposal
					if let quantus_subxt::api::runtime_types::frame_support::traits::preimages::Bounded::Lookup {
						hash,
						len,
					} = &status.proposal
					{
						log_print!("📝 Proposal Details:");
						log_print!("   🔗 Preimage Hash: {:?}", hash);
						log_print!("   📏 Length: {} bytes", len);
						log_print!("");

						// Fetch and decode the preimage
					match crate::cli::referenda_decode::decode_preimage(quantus_client, hash, *len).await {
						Ok(decoded) => {
							log_print!("✅ Decoded Proposal:");
							log_print!("{}", decoded);
						},
						Err(e) => {
							log_print!("⚠️  Could not decode proposal: {}", e);
							log_print!("   Run 'quantus preimage get --hash {:?} --len {}' to see raw data", hash, len);
						},
					}
					} else {
						log_print!("⚠️  Proposal is inline (not a preimage lookup)");
					}
				},
				ReferendumInfo::Approved(..) => {
					log_print!("📊 {} Referendum #{}", "Approved".green(), index);
					log_print!(
						"   ℹ️  Proposal details no longer available (referendum finalized)"
					);
				},
				ReferendumInfo::Rejected(..) => {
					log_print!("📊 {} Referendum #{}", "Rejected".red(), index);
					log_print!(
						"   ℹ️  Proposal details no longer available (referendum finalized)"
					);
				},
				ReferendumInfo::Cancelled(..) => {
					log_print!("📊 {} Referendum #{}", "Cancelled".yellow(), index);
					log_print!(
						"   ℹ️  Proposal details no longer available (referendum finalized)"
					);
				},
				ReferendumInfo::TimedOut(..) => {
					log_print!("📊 {} Referendum #{}", "TimedOut".dimmed(), index);
					log_print!(
						"   ℹ️  Proposal details no longer available (referendum finalized)"
					);
				},
				ReferendumInfo::Killed(..) => {
					log_print!("📊 {} Referendum #{}", "Killed".red().bold(), index);
					log_print!("   ℹ️  Proposal details no longer available (referendum killed)");
				},
			}
		} else {
			// Raw output (original behavior)
			log_print!("📋 Referendum Information (raw):");
			log_print!("{:#?}", referendum_info);
		}
	} else {
		log_print!("📭 Referendum #{} not found", index);
	}
	Ok(())
}

/// Get the status of a Referendum
async fn get_proposal_status(
	quantus_client: &crate::chain::client::QuantusClient,
	index: u32,
) -> crate::error::Result<()> {
	use quantus_subxt::api::runtime_types::pallet_referenda::types::ReferendumInfo;

	log_verbose!("📊 Fetching status for Referendum #{}...", index);

	let addr = quantus_subxt::api::storage().referenda().referendum_info_for(index);

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

	let info_res = storage_at.fetch(&addr).await;

	match info_res {
		Ok(Some(info)) => {
			log_print!("📊 Status for Referendum #{}", index.to_string().bright_yellow());
			match info {
				ReferendumInfo::Ongoing(status) => {
					log_print!("   - Status: {}", "Ongoing".bright_green());
					log_print!("   - Track: {}", status.track);
					log_print!("   - Submitted at: block {}", status.submitted);
					log_print!(
						"   - Tally: Ayes: {}, Nays: {}",
						status.tally.ayes,
						status.tally.nays
					);
					log_verbose!("   - Full status: {:#?}", status);
				},
				ReferendumInfo::Approved(submitted, ..) => {
					log_print!("   - Status: {}", "Approved".green());
					log_print!("   - Submitted at block: {}", submitted);
				},
				ReferendumInfo::Rejected(submitted, ..) => {
					log_print!("   - Status: {}", "Rejected".red());
					log_print!("   - Submitted at block: {}", submitted);
				},
				ReferendumInfo::Cancelled(submitted, ..) => {
					log_print!("   - Status: {}", "Cancelled".yellow());
					log_print!("   - Submitted at block: {}", submitted);
				},
				ReferendumInfo::TimedOut(submitted, ..) => {
					log_print!("   - Status: {}", "TimedOut".dimmed());
					log_print!("   - Submitted at block: {}", submitted);
				},
				ReferendumInfo::Killed(submitted) => {
					log_print!("   - Status: {}", "Killed".red().bold());
					log_print!("   - Killed at block: {}", submitted);
				},
			}
		},
		Ok(None) => log_print!("📭 Referendum #{} not found", index),
		Err(e) => log_error!("❌ Failed to fetch referendum #{}: {:?}", index, e),
	}

	Ok(())
}

/// Place a decision deposit for a Referendum
async fn place_decision_deposit(
	quantus_client: &crate::chain::client::QuantusClient,
	index: u32,
	from: &str,
	password: Option<String>,
	password_file: Option<String>,
	execution_mode: crate::cli::common::ExecutionMode,
) -> crate::error::Result<()> {
	log_print!("📋 Placing decision deposit for Referendum #{}", index);
	log_print!("   🔑 Placed by: {}", from.bright_yellow());

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

	let deposit_call = quantus_subxt::api::tx().referenda().place_decision_deposit(index);
	let tx_hash =
		submit_transaction(quantus_client, &keypair, deposit_call, None, execution_mode).await?;
	log_success!("✅ Decision deposit placed! Hash: {:?}", tx_hash.to_string().bright_yellow());
	Ok(())
}

/// Vote on a Referendum
async fn vote_on_referendum(
	quantus_client: &crate::chain::client::QuantusClient,
	index: u32,
	aye: bool,
	conviction: u8,
	amount: &str,
	from: &str,
	password: Option<String>,
	password_file: Option<String>,
	execution_mode: crate::cli::common::ExecutionMode,
) -> crate::error::Result<()> {
	log_print!("🗳️  Voting on Referendum #{}", index);
	log_print!("   📊 Vote: {}", if aye { "AYE ✅".bright_green() } else { "NAY ❌".bright_red() });
	log_print!("   💰 Amount: {}", amount.bright_cyan());
	log_print!("   🔒 Conviction: {}", conviction);
	log_print!("   🔑 Signed by: {}", from.bright_yellow());

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

	// Parse amount using chain decimals (12 for DEV)
	let amount_value: u128 = crate::cli::send::parse_amount(quantus_client, amount).await?;

	// Validate conviction
	if conviction > 6 {
		return Err(QuantusError::Generic("Invalid conviction (must be 0-6)".to_string()));
	}

	// Build vote
	let vote =
		quantus_subxt::api::runtime_types::pallet_conviction_voting::vote::AccountVote::Standard {
			vote: quantus_subxt::api::runtime_types::pallet_conviction_voting::vote::Vote(
				if aye { 128 } else { 0 } | conviction,
			),
			balance: amount_value,
		};

	let vote_call = quantus_subxt::api::tx().conviction_voting().vote(index, vote);
	let tx_hash =
		submit_transaction(quantus_client, &keypair, vote_call, None, execution_mode).await?;

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

	log_success!("🎉 {} Vote submitted!", "FINISHED".bright_green().bold());
	Ok(())
}

/// Get Referenda configuration
async fn get_config(
	quantus_client: &crate::chain::client::QuantusClient,
) -> crate::error::Result<()> {
	log_print!("⚙️  Referenda Configuration");
	log_print!("");

	let constants = quantus_client.client().constants();
	let tracks_addr = quantus_subxt::api::constants().referenda().tracks();

	match constants.at(&tracks_addr) {
		Ok(tracks) => {
			log_print!("{}", "📊 Track Configuration:".bold());
			for (id, info) in tracks.iter() {
				log_print!("   ------------------------------------");
				log_print!(
					"   • {} #{}: {}",
					"Track".bold(),
					id,
					info.name.to_string().bright_cyan()
				);
				log_print!("   • Max Deciding: {}", info.max_deciding);
				log_print!("   • Decision Deposit: {}", info.decision_deposit);
				log_print!("   • Prepare Period: {} blocks", info.prepare_period);
				log_print!("   • Decision Period: {} blocks", info.decision_period);
				log_print!("   • Confirm Period: {} blocks", info.confirm_period);
				log_print!("   • Min Enactment Period: {} blocks", info.min_enactment_period);
			}
			log_print!("   ------------------------------------");
		},
		Err(e) => {
			log_error!("❌ Failed to decode Tracks constant: {:?}", e);
			log_print!("💡 It's possible the Tracks constant is not in the expected format.");
		},
	}

	Ok(())
}

/// Refund submission deposit for a completed Referendum
async fn refund_submission_deposit(
	quantus_client: &crate::chain::client::QuantusClient,
	index: u32,
	from: &str,
	password: Option<String>,
	password_file: Option<String>,
	execution_mode: crate::cli::common::ExecutionMode,
) -> crate::error::Result<()> {
	log_print!("💰 Refunding submission deposit for Referendum #{}", index);
	log_print!("   🔑 Refund to: {}", from.bright_yellow());

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

	// Create refund_submission_deposit call
	let refund_call = quantus_subxt::api::tx().referenda().refund_submission_deposit(index);

	let tx_hash =
		submit_transaction(quantus_client, &keypair, refund_call, None, execution_mode).await?;
	log_print!(
		"✅ {} Refund transaction submitted! Hash: {:?}",
		"SUCCESS".bright_green().bold(),
		tx_hash
	);

	log_print!("💡 Check your balance to confirm the refund");
	Ok(())
}

/// Refund decision deposit for a completed Referendum
async fn refund_decision_deposit(
	quantus_client: &crate::chain::client::QuantusClient,
	index: u32,
	from: &str,
	password: Option<String>,
	password_file: Option<String>,
	execution_mode: crate::cli::common::ExecutionMode,
) -> crate::error::Result<()> {
	log_print!("💰 Refunding decision deposit for Referendum #{}", index);
	log_print!("   🔑 Refund to: {}", from.bright_yellow());

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

	// Create refund_decision_deposit call
	let refund_call = quantus_subxt::api::tx().referenda().refund_decision_deposit(index);

	let tx_hash =
		submit_transaction(quantus_client, &keypair, refund_call, None, execution_mode).await?;
	log_print!(
		"✅ {} Refund transaction submitted! Hash: {:?}",
		"SUCCESS".bright_green().bold(),
		tx_hash
	);

	log_print!("💡 Check your balance to confirm the refund");
	Ok(())
}