-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmultisig.rs
More file actions
3226 lines (2808 loc) · 100 KB
/
multisig.rs
File metadata and controls
3226 lines (2808 loc) · 100 KB
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::{
chain::quantus_subxt::{self},
cli::common::ExecutionMode,
log_error, log_print, log_success, log_verbose,
};
use clap::Subcommand;
use colored::Colorize;
use hex;
use sp_core::crypto::{AccountId32 as SpAccountId32, Ss58Codec};
// Base unit (QUAN) decimals for amount conversions
const QUAN_DECIMALS: u128 = 1_000_000_000_000; // 10^12
const DEFAULT_TRANSFER_EXPIRY_BLOCKS: u32 = (2 * 60 * 60) / 10; // ~2h at 10s/block
// ============================================================================
// PUBLIC LIBRARY API - Data Structures
// ============================================================================
/// Multisig account information
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct MultisigInfo {
/// Multisig address (SS58 format)
pub address: String,
/// Creator address (SS58 format) - receives deposit back on dissolve
pub creator: String,
/// Current balance (spendable)
pub balance: u128,
/// Approval threshold
pub threshold: u32,
/// List of signer addresses (SS58 format)
pub signers: Vec<String>,
/// Next proposal ID
pub proposal_nonce: u32,
/// Locked deposit amount (returned to creator on dissolve)
pub deposit: u128,
/// Number of active proposals
pub active_proposals: u32,
}
/// Proposal status
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq)]
pub enum ProposalStatus {
Active,
/// Threshold reached; any signer can call execute to dispatch
Approved,
Executed,
Cancelled,
}
/// Proposal information
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct ProposalInfo {
/// Proposal ID
pub id: u32,
/// Proposer address (SS58 format)
pub proposer: String,
/// Encoded call data
pub call_data: Vec<u8>,
/// Expiry block number
pub expiry: u32,
/// List of approver addresses (SS58 format)
pub approvals: Vec<String>,
/// Locked deposit amount
pub deposit: u128,
/// Proposal status
pub status: ProposalStatus,
}
// ============================================================================
// PUBLIC LIBRARY API - Helper Functions
// ============================================================================
/// Parse amount from human-readable format (e.g., "10", "10.5", "0.001")
/// or raw format (e.g., "10000000000000")
pub fn parse_amount(amount: &str) -> crate::error::Result<u128> {
// If contains decimal point, parse as float and multiply by QUAN_DECIMALS
if amount.contains('.') {
let amount_f64: f64 = amount
.parse()
.map_err(|e| crate::error::QuantusError::Generic(format!("Invalid amount: {}", e)))?;
if amount_f64 < 0.0 {
return Err(crate::error::QuantusError::Generic(
"Amount cannot be negative".to_string(),
));
}
// Multiply by decimals and convert to u128
let base_amount = (amount_f64 * QUAN_DECIMALS as f64) as u128;
Ok(base_amount)
} else {
// Try parsing as u128 first (raw format)
if let Ok(raw) = amount.parse::<u128>() {
// If the number is very large (>= 10^10), assume it's already in base units
if raw >= 10_000_000_000 {
Ok(raw)
} else {
// Otherwise assume it's in QUAN and convert
Ok(raw * QUAN_DECIMALS)
}
} else {
Err(crate::error::QuantusError::Generic(format!("Invalid amount: {}", amount)))
}
}
}
/// Subcommands for proposing transactions
#[derive(Subcommand, Debug)]
pub enum ProposeSubcommand {
/// Propose a simple transfer (most common case)
#[command(arg_required_else_help = true)]
Transfer {
/// The multisig account address (SS58 format)
#[arg(long, value_name = "MULTISIG_ADDRESS")]
address: String,
/// The recipient address (SS58 format or wallet name)
#[arg(long, value_name = "RECIPIENT")]
to: String,
/// The amount to transfer (e.g. "10", "10.5", or raw base units)
#[arg(long, value_name = "AMOUNT")]
amount: String,
/// Expiry block number for this proposal. If omitted, defaults to head + ~2h
#[arg(long, value_name = "EXPIRY_BLOCK")]
expiry: Option<u32>,
/// The proposer wallet name (must be a signer in this multisig)
#[arg(long, value_name = "PROPOSER_WALLET")]
from: String,
/// Password for the wallet
#[arg(short, long)]
password: Option<String>,
/// Read password from file
#[arg(long)]
password_file: Option<String>,
},
/// Propose a custom transaction (full flexibility)
Custom {
/// Multisig account address (SS58 format)
#[arg(long)]
address: String,
/// Pallet name for the call (e.g., "Balances")
#[arg(long)]
pallet: String,
/// Call/function name (e.g., "transfer_allow_death")
#[arg(long)]
call: String,
/// Arguments as JSON array (e.g., '["5GrwvaEF...", "1000000000000"]')
#[arg(long)]
args: Option<String>,
/// Expiry block number (when this proposal expires)
#[arg(long)]
expiry: u32,
/// Proposer wallet name (must be a signer)
#[arg(long)]
from: String,
/// Password for the wallet
#[arg(short, long)]
password: Option<String>,
/// Read password from file
#[arg(long)]
password_file: Option<String>,
},
/// Propose to enable high-security for this multisig
HighSecurity {
/// Multisig account address (SS58 format)
#[arg(long)]
address: String,
/// Guardian/Interceptor account (SS58 or wallet name)
#[arg(long)]
interceptor: String,
/// Delay in blocks (mutually exclusive with --delay-seconds)
#[arg(long, conflicts_with = "delay_seconds")]
delay_blocks: Option<u32>,
/// Delay in seconds (mutually exclusive with --delay-blocks)
#[arg(long, conflicts_with = "delay_blocks")]
delay_seconds: Option<u64>,
/// Expiry block number (when this proposal expires)
#[arg(long)]
expiry: u32,
/// Proposer wallet name (must be a signer)
#[arg(long)]
from: String,
/// Password for the wallet
#[arg(short, long)]
password: Option<String>,
/// Read password from file
#[arg(long)]
password_file: Option<String>,
},
}
/// Multisig-related commands
#[derive(Subcommand, Debug)]
pub enum MultisigCommands {
/// Create a new multisig account
#[command(
arg_required_else_help = true,
after_help = "Examples:\n quantus multisig create --signers \"5F3sa2TJ...abc,5DAAnrj7...xyz,5HGjWAeF...123\" --threshold 2 --from alice\n quantus multisig create --signers \"alice,bob,charlie\" --threshold 2 --from alice"
)]
Create {
/// List of signer addresses (SS58 or wallet names), comma-separated
#[arg(long, value_name = "SIGNERS_CSV")]
signers: String,
/// Number of approvals required to execute transactions
#[arg(long)]
threshold: u32,
/// Nonce for deterministic address generation (allows creating multiple multisigs with
/// same signers)
#[arg(long, default_value = "0")]
nonce: u64,
/// Wallet name to pay for multisig creation
#[arg(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>,
},
/// Predict multisig address without creating it (deterministic calculation)
PredictAddress {
/// List of signer addresses (SS58 or wallet names), comma-separated
#[arg(long)]
signers: String,
/// Number of approvals required to execute transactions
#[arg(long)]
threshold: u32,
/// Nonce for deterministic address generation
#[arg(long, default_value = "0")]
nonce: u64,
},
/// Propose a transaction to be executed by the multisig
#[command(subcommand)]
Propose(ProposeSubcommand),
/// Approve a proposed transaction
Approve {
/// Multisig account address
#[arg(long)]
address: String,
/// Proposal ID (u32 nonce)
#[arg(long)]
proposal_id: u32,
/// Approver wallet name (must be a signer)
#[arg(long)]
from: String,
/// Password for the wallet
#[arg(short, long)]
password: Option<String>,
/// Read password from file
#[arg(long)]
password_file: Option<String>,
},
/// Execute an approved proposal (any signer; proposal must have reached threshold)
Execute {
/// Multisig account address
#[arg(long)]
address: String,
/// Proposal ID (u32 nonce) to execute
#[arg(long)]
proposal_id: u32,
/// Wallet name (must be a signer)
#[arg(long)]
from: String,
/// Password for the wallet
#[arg(short, long)]
password: Option<String>,
/// Read password from file
#[arg(long)]
password_file: Option<String>,
},
/// Cancel a proposed transaction (only by proposer)
Cancel {
/// Multisig account address
#[arg(long)]
address: String,
/// Proposal ID (u32 nonce) to cancel
#[arg(long)]
proposal_id: u32,
/// Wallet name (must be the proposer)
#[arg(long)]
from: String,
/// Password for the wallet
#[arg(short, long)]
password: Option<String>,
/// Read password from file
#[arg(long)]
password_file: Option<String>,
},
/// Remove an expired proposal
RemoveExpired {
/// Multisig account address
#[arg(long)]
address: String,
/// Proposal ID (u32 nonce) to remove
#[arg(long)]
proposal_id: u32,
/// Wallet name (must be a signer)
#[arg(long)]
from: String,
/// Password for the wallet
#[arg(short, long)]
password: Option<String>,
/// Read password from file
#[arg(long)]
password_file: Option<String>,
},
/// Claim all deposits from removable proposals (batch operation)
ClaimDeposits {
/// Multisig account address
#[arg(long)]
address: String,
/// Wallet name (must be the proposer)
#[arg(long)]
from: String,
/// Password for the wallet
#[arg(short, long)]
password: Option<String>,
/// Read password from file
#[arg(long)]
password_file: Option<String>,
},
/// Dissolve a multisig and recover the creation deposit
Dissolve {
/// Multisig account address
#[arg(long)]
address: String,
/// Wallet name (must be creator or a signer)
#[arg(long)]
from: String,
/// Password for the wallet
#[arg(short, long)]
password: Option<String>,
/// Read password from file
#[arg(long)]
password_file: Option<String>,
},
/// Query multisig information (or specific proposal if --proposal-id provided)
Info {
/// Multisig account address
#[arg(long)]
address: String,
/// Optional: Query specific proposal by ID
#[arg(long)]
proposal_id: Option<u32>,
},
/// List all proposals for a multisig
ListProposals {
/// Multisig account address
#[arg(long)]
address: String,
},
/// High-Security operations for multisig accounts
#[command(subcommand)]
HighSecurity(HighSecuritySubcommands),
}
/// High-Security subcommands for multisig (query only)
#[derive(Subcommand, Debug)]
pub enum HighSecuritySubcommands {
/// Check if multisig has high-security enabled
Status {
/// Multisig account address
#[arg(long)]
address: String,
},
}
// ============================================================================
// PUBLIC LIBRARY API - Core Functions
// ============================================================================
// Note: These functions are public library API and may not be used by the CLI binary
/// Predict multisig address deterministically
///
/// This function calculates what the multisig address will be BEFORE creating it.
/// The address is computed as: hash(pallet_id || sorted_signers || threshold || nonce)
///
/// # Arguments
/// * `signers` - List of signer AccountId32 (order doesn't matter - will be sorted)
/// * `threshold` - Number of approvals required
/// * `nonce` - Nonce for uniqueness (allows multiple multisigs with same signers)
///
/// # Returns
/// Predicted multisig address in SS58 format
#[allow(dead_code)]
pub fn predict_multisig_address(
signers: Vec<subxt::ext::subxt_core::utils::AccountId32>,
threshold: u32,
nonce: u64,
) -> String {
use codec::Encode;
// Pallet ID from runtime: py/mltsg
const PALLET_ID: [u8; 8] = *b"py/mltsg";
// Convert subxt AccountId32 to sp_core AccountId32 for consistent encoding
use sp_core::crypto::AccountId32 as SpAccountId32;
let sp_signers: Vec<SpAccountId32> = signers
.iter()
.map(|s| {
let bytes: [u8; 32] = *s.as_ref();
SpAccountId32::from(bytes)
})
.collect();
// Sort signers for deterministic address (same as runtime does)
let mut sorted_signers = sp_signers;
sorted_signers.sort();
// Build data to hash: pallet_id || sorted_signers || threshold || nonce
// IMPORTANT: Must match runtime encoding exactly
let mut data = Vec::new();
data.extend_from_slice(&PALLET_ID);
// Encode Vec<sp_core::AccountId32> - same as runtime!
data.extend_from_slice(&sorted_signers.encode());
data.extend_from_slice(&threshold.encode());
data.extend_from_slice(&nonce.encode());
use codec::Decode;
use sp_core::crypto::AccountId32;
use sp_runtime::traits::{BlakeTwo256, Hash as HashT, TrailingZeroInput};
let hash = BlakeTwo256::hash(&data);
let account_id = AccountId32::decode(&mut TrailingZeroInput::new(hash.as_ref()))
.expect("TrailingZeroInput provides sufficient bytes; qed");
// Convert to SS58 format (network 189 for Quantus)
account_id.to_ss58check_with_version(sp_core::crypto::Ss58AddressFormat::custom(189))
}
/// Create a multisig account
///
/// # Arguments
/// * `quantus_client` - Connected Quantus client
/// * `creator_keypair` - Keypair of the account creating the multisig
/// * `signers` - List of signer addresses (AccountId32)
/// * `threshold` - Number of approvals required
/// * `nonce` - Nonce for deterministic address (allows multiple multisigs with same signers)
/// * `wait_for_inclusion` - Whether to wait for transaction inclusion
///
/// # Returns
/// Transaction hash and optionally the multisig address (if wait_for_inclusion=true)
#[allow(dead_code)]
pub async fn create_multisig(
quantus_client: &crate::chain::client::QuantusClient,
creator_keypair: &crate::wallet::QuantumKeyPair,
signers: Vec<subxt::ext::subxt_core::utils::AccountId32>,
threshold: u32,
nonce: u64,
wait_for_inclusion: bool,
) -> crate::error::Result<(subxt::utils::H256, Option<String>)> {
// Build transaction with nonce
let create_tx =
quantus_subxt::api::tx()
.multisig()
.create_multisig(signers.clone(), threshold, nonce);
// Submit transaction
let execution_mode =
ExecutionMode { finalized: false, wait_for_transaction: wait_for_inclusion };
let tx_hash = crate::cli::common::submit_transaction(
quantus_client,
creator_keypair,
create_tx,
None,
execution_mode,
)
.await?;
// If waiting, extract address from events
let multisig_address = if wait_for_inclusion {
let latest_block_hash = quantus_client.get_latest_block().await?;
let events = quantus_client.client().events().at(latest_block_hash).await?;
let mut multisig_events =
events.find::<quantus_subxt::api::multisig::events::MultisigCreated>();
let address: Option<String> = if let Some(Ok(ev)) = multisig_events.next() {
let addr_bytes: &[u8; 32] = ev.multisig_address.as_ref();
let addr = SpAccountId32::from(*addr_bytes);
Some(addr.to_ss58check_with_version(sp_core::crypto::Ss58AddressFormat::custom(189)))
} else {
None
};
address
} else {
None
};
Ok((tx_hash, multisig_address))
}
/// Propose a transfer from multisig
///
/// # Returns
/// Transaction hash
#[allow(dead_code)]
pub async fn propose_transfer(
quantus_client: &crate::chain::client::QuantusClient,
proposer_keypair: &crate::wallet::QuantumKeyPair,
multisig_address: subxt::ext::subxt_core::utils::AccountId32,
to_address: subxt::ext::subxt_core::utils::AccountId32,
amount: u128,
expiry: u32,
) -> crate::error::Result<subxt::utils::H256> {
use codec::{Compact, Encode};
// Build Balances::transfer_allow_death call
let pallet_index = 5u8; // Balances pallet
let call_index = 0u8; // transfer_allow_death
let mut call_data = Vec::new();
call_data.push(pallet_index);
call_data.push(call_index);
// Encode destination (MultiAddress::Id)
call_data.push(0u8); // MultiAddress::Id variant
call_data.extend_from_slice(to_address.as_ref());
// Encode amount (Compact<u128>)
Compact(amount).encode_to(&mut call_data);
// Build propose transaction
let propose_tx =
quantus_subxt::api::tx().multisig().propose(multisig_address, call_data, expiry);
// Submit transaction
let execution_mode = ExecutionMode { finalized: false, wait_for_transaction: false };
let tx_hash = crate::cli::common::submit_transaction(
quantus_client,
proposer_keypair,
propose_tx,
None,
execution_mode,
)
.await?;
Ok(tx_hash)
}
/// Propose a custom call from multisig
///
/// # Returns
/// Transaction hash
#[allow(dead_code)]
pub async fn propose_custom(
quantus_client: &crate::chain::client::QuantusClient,
proposer_keypair: &crate::wallet::QuantumKeyPair,
multisig_address: subxt::ext::subxt_core::utils::AccountId32,
call_data: Vec<u8>,
expiry: u32,
) -> crate::error::Result<subxt::utils::H256> {
// Build propose transaction
let propose_tx =
quantus_subxt::api::tx().multisig().propose(multisig_address, call_data, expiry);
// Submit transaction
let execution_mode = ExecutionMode { finalized: false, wait_for_transaction: false };
let tx_hash = crate::cli::common::submit_transaction(
quantus_client,
proposer_keypair,
propose_tx,
None,
execution_mode,
)
.await?;
Ok(tx_hash)
}
/// Approve a proposal
///
/// # Returns
/// Transaction hash
#[allow(dead_code)]
pub async fn approve_proposal(
quantus_client: &crate::chain::client::QuantusClient,
approver_keypair: &crate::wallet::QuantumKeyPair,
multisig_address: subxt::ext::subxt_core::utils::AccountId32,
proposal_id: u32,
) -> crate::error::Result<subxt::utils::H256> {
let approve_tx = quantus_subxt::api::tx().multisig().approve(multisig_address, proposal_id);
let execution_mode = ExecutionMode { finalized: false, wait_for_transaction: false };
let tx_hash = crate::cli::common::submit_transaction(
quantus_client,
approver_keypair,
approve_tx,
None,
execution_mode,
)
.await?;
Ok(tx_hash)
}
/// Cancel a proposal (only by proposer)
///
/// # Returns
/// Transaction hash
#[allow(dead_code)]
pub async fn cancel_proposal(
quantus_client: &crate::chain::client::QuantusClient,
proposer_keypair: &crate::wallet::QuantumKeyPair,
multisig_address: subxt::ext::subxt_core::utils::AccountId32,
proposal_id: u32,
) -> crate::error::Result<subxt::utils::H256> {
let cancel_tx = quantus_subxt::api::tx().multisig().cancel(multisig_address, proposal_id);
let execution_mode = ExecutionMode { finalized: false, wait_for_transaction: false };
let tx_hash = crate::cli::common::submit_transaction(
quantus_client,
proposer_keypair,
cancel_tx,
None,
execution_mode,
)
.await?;
Ok(tx_hash)
}
/// Get multisig information
///
/// # Returns
/// Multisig information or None if not found
#[allow(dead_code)]
pub async fn get_multisig_info(
quantus_client: &crate::chain::client::QuantusClient,
multisig_address: subxt::ext::subxt_core::utils::AccountId32,
) -> crate::error::Result<Option<MultisigInfo>> {
let latest_block_hash = quantus_client.get_latest_block().await?;
let storage_at = quantus_client.client().storage().at(latest_block_hash);
// Query multisig data
let storage_query =
quantus_subxt::api::storage().multisig().multisigs(multisig_address.clone());
let multisig_data = storage_at.fetch(&storage_query).await?;
if let Some(data) = multisig_data {
// Query balance
let balance_query =
quantus_subxt::api::storage().system().account(multisig_address.clone());
let account_info = storage_at.fetch(&balance_query).await?;
let balance = account_info.map(|info| info.data.free).unwrap_or(0);
// Convert to SS58
let multisig_bytes: &[u8; 32] = multisig_address.as_ref();
let multisig_sp = SpAccountId32::from(*multisig_bytes);
let address =
multisig_sp.to_ss58check_with_version(sp_core::crypto::Ss58AddressFormat::custom(189));
// Convert creator to SS58
let creator_bytes: &[u8; 32] = data.creator.as_ref();
let creator_sp = SpAccountId32::from(*creator_bytes);
let creator =
creator_sp.to_ss58check_with_version(sp_core::crypto::Ss58AddressFormat::custom(189));
let signers: Vec<String> = data
.signers
.0
.iter()
.map(|signer| {
let signer_bytes: &[u8; 32] = signer.as_ref();
let signer_sp = SpAccountId32::from(*signer_bytes);
signer_sp.to_ss58check_with_version(sp_core::crypto::Ss58AddressFormat::custom(189))
})
.collect();
Ok(Some(MultisigInfo {
address,
creator,
balance,
threshold: data.threshold,
signers,
proposal_nonce: data.proposal_nonce,
deposit: data.deposit,
active_proposals: data.active_proposals,
}))
} else {
Ok(None)
}
}
/// Get proposal information
///
/// # Returns
/// Proposal information or None if not found
#[allow(dead_code)]
pub async fn get_proposal_info(
quantus_client: &crate::chain::client::QuantusClient,
multisig_address: subxt::ext::subxt_core::utils::AccountId32,
proposal_id: u32,
) -> crate::error::Result<Option<ProposalInfo>> {
let latest_block_hash = quantus_client.get_latest_block().await?;
let storage_at = quantus_client.client().storage().at(latest_block_hash);
let storage_query = quantus_subxt::api::storage()
.multisig()
.proposals(multisig_address, proposal_id);
let proposal_data = storage_at.fetch(&storage_query).await?;
if let Some(data) = proposal_data {
let proposer_bytes: &[u8; 32] = data.proposer.as_ref();
let proposer_sp = SpAccountId32::from(*proposer_bytes);
let proposer =
proposer_sp.to_ss58check_with_version(sp_core::crypto::Ss58AddressFormat::custom(189));
let approvals: Vec<String> = data
.approvals
.0
.iter()
.map(|approver| {
let approver_bytes: &[u8; 32] = approver.as_ref();
let approver_sp = SpAccountId32::from(*approver_bytes);
approver_sp
.to_ss58check_with_version(sp_core::crypto::Ss58AddressFormat::custom(189))
})
.collect();
let status = match data.status {
quantus_subxt::api::runtime_types::pallet_multisig::ProposalStatus::Active =>
ProposalStatus::Active,
quantus_subxt::api::runtime_types::pallet_multisig::ProposalStatus::Approved =>
ProposalStatus::Approved,
quantus_subxt::api::runtime_types::pallet_multisig::ProposalStatus::Executed =>
ProposalStatus::Executed,
quantus_subxt::api::runtime_types::pallet_multisig::ProposalStatus::Cancelled =>
ProposalStatus::Cancelled,
};
Ok(Some(ProposalInfo {
id: proposal_id,
proposer,
call_data: data.call.0,
expiry: data.expiry,
approvals,
deposit: data.deposit,
status,
}))
} else {
Ok(None)
}
}
/// List all proposals for a multisig
///
/// # Returns
/// List of proposals
#[allow(dead_code)]
pub async fn list_proposals(
quantus_client: &crate::chain::client::QuantusClient,
multisig_address: subxt::ext::subxt_core::utils::AccountId32,
) -> crate::error::Result<Vec<ProposalInfo>> {
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()
.multisig()
.proposals_iter1(multisig_address.clone());
let mut proposals_iter = storage.iter(address).await?;
let mut proposals = Vec::new();
while let Some(result) = proposals_iter.next().await {
if let Ok(kv) = result {
// Extract proposal_id from key
let key_bytes = kv.key_bytes;
if key_bytes.len() >= 4 {
let id_bytes = &key_bytes[key_bytes.len() - 4..];
let proposal_id =
u32::from_le_bytes([id_bytes[0], id_bytes[1], id_bytes[2], id_bytes[3]]);
// Use value directly from iterator (more efficient)
let data = kv.value;
let proposer_bytes: &[u8; 32] = data.proposer.as_ref();
let proposer_sp = SpAccountId32::from(*proposer_bytes);
let proposer = proposer_sp
.to_ss58check_with_version(sp_core::crypto::Ss58AddressFormat::custom(189));
let approvals: Vec<String> = data
.approvals
.0
.iter()
.map(|approver| {
let approver_bytes: &[u8; 32] = approver.as_ref();
let approver_sp = SpAccountId32::from(*approver_bytes);
approver_sp.to_ss58check_with_version(
sp_core::crypto::Ss58AddressFormat::custom(189),
)
})
.collect();
let status = match data.status {
quantus_subxt::api::runtime_types::pallet_multisig::ProposalStatus::Active =>
ProposalStatus::Active,
quantus_subxt::api::runtime_types::pallet_multisig::ProposalStatus::Approved =>
ProposalStatus::Approved,
quantus_subxt::api::runtime_types::pallet_multisig::ProposalStatus::Executed =>
ProposalStatus::Executed,
quantus_subxt::api::runtime_types::pallet_multisig::ProposalStatus::Cancelled =>
ProposalStatus::Cancelled,
};
proposals.push(ProposalInfo {
id: proposal_id,
proposer,
call_data: data.call.0,
expiry: data.expiry,
approvals,
deposit: data.deposit,
status,
});
}
}
}
Ok(proposals)
}
/// Approve dissolving a multisig
///
/// Requires threshold approvals. When threshold is reached, multisig is dissolved.
/// Requirements:
/// - No proposals exist (active, executed, or cancelled)
/// - Multisig account balance must be zero
/// - Deposit is returned to creator
///
/// # Returns
/// Transaction hash
#[allow(dead_code)]
pub async fn approve_dissolve_multisig(
quantus_client: &crate::chain::client::QuantusClient,
caller_keypair: &crate::wallet::QuantumKeyPair,
multisig_address: subxt::ext::subxt_core::utils::AccountId32,
) -> crate::error::Result<subxt::utils::H256> {
let approve_tx = quantus_subxt::api::tx().multisig().approve_dissolve(multisig_address);
let execution_mode = ExecutionMode { finalized: false, wait_for_transaction: false };
let tx_hash = crate::cli::common::submit_transaction(
quantus_client,
caller_keypair,
approve_tx,
None,
execution_mode,
)
.await?;
Ok(tx_hash)
}
// ============================================================================
// CLI HANDLERS (Internal)
// ============================================================================
/// Handle multisig command
pub async fn handle_multisig_command(
command: MultisigCommands,
node_url: &str,
execution_mode: ExecutionMode,
) -> crate::error::Result<()> {
match command {
MultisigCommands::Create { signers, threshold, nonce, from, password, password_file } =>
handle_create_multisig(
signers,
threshold,
nonce,
from,
password,
password_file,
node_url,
execution_mode,
)
.await,
MultisigCommands::PredictAddress { signers, threshold, nonce } =>
handle_predict_address(signers, threshold, nonce).await,
MultisigCommands::Propose(subcommand) => match subcommand {
ProposeSubcommand::Transfer {
address,
to,
amount,
expiry,
from,
password,
password_file,
} =>
handle_propose_transfer(
address,
to,
amount,
expiry,
from,
password,
password_file,
node_url,
execution_mode,
)
.await,
ProposeSubcommand::Custom {
address,
pallet,
call,
args,
expiry,
from,
password,
password_file,
} =>
handle_propose(
address,
pallet,
call,
args,
expiry,
from,
password,
password_file,
node_url,
execution_mode,
)
.await,
ProposeSubcommand::HighSecurity {
address,
interceptor,
delay_blocks,
delay_seconds,
expiry,
from,
password,
password_file,
} =>
handle_high_security_set(