-
Notifications
You must be signed in to change notification settings - Fork 5
/
lib.rs
765 lines (661 loc) 路 25 KB
/
lib.rs
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
//! # Supersig Pallet
//!
//! The supersig pallet extends the capabilities of a multisig so it can be fit for governance of
//! larger funds. It is a superset of the multisig pallet, adding multiple functionalities and
//! options to the original multi-signature dispatch allowing multiple signed origins (accounts) to
//! coordinate and dispatch a call from the supersig account
//!
//! Note: the multisig addresses won鈥檛 change even though the members can be added, removed, or can
//! leave themselves
//!
//! ## Overview
//!
//! The Supersig pallet provide function for:
//!
//! - Creating a supersig
//! - Adding and removing members
//! - Leaving the supersig
//! - Submit transaction to a supersig
//! - Vote for the transaction
//! - Remove a pending transaction
//! - Delete a supersig
//!
//!
//! ### Dispatchable Functions
//!
//! - `create_supersig` - create a supersig, with specified members. The creator will have to
//! deposit an existencial balance and a deposit that depend on the number of members, in the
//! supersig account. This last amount will be reserved on the supersig
//!
//! /!!\ note of caution /!!\ the creator of the supersig will NOT be added by default, he will
//! have to pass his adress into the list of added users.
//!
//! - `submit_call` - make a proposal on the specified supersig. an amount corresponding to the
//! length of the encoded call will be reserved. You need to wrap this around another call such as
//! sending balance. Anything that requires a vote needs to be wrapped in a submitCall.
//!
//! - `approve_call` - give a positive vote to a call. if the number of vote >= SimpleMajority, the
//! call is executed. An user can only approve a call once.
//!
//! - `remove_call` - remove a call from the poll. The reserved amount of the proposer will be
//! unreserved
//!
//! - `add_members` - add new members to the supersig. In case some user are already in the
//! supersig, they will be ignored.
//!
//! - `remove_members` - remove members from the supersig. In case some user are not in the
//! supersig, they will be ignored.
//!
//! - `delete_supersig` - remove the supersig and all the associated data. Funds will be unreserved
//! and transfered to specified beneficiary.
//!
//! - `leave_supersig` - remove the caller from the supersig.
#![cfg_attr(not(feature = "std"), no_std)]
// use frame_system::Config;
pub use pallet::*;
#[cfg(test)]
mod tests;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
pub use frame_support::{
dispatch::{
DispatchError, DispatchErrorWithPostInfo, DispatchResult, GetDispatchInfo, PostDispatchInfo,
},
traits::{tokens::ExistenceRequirement, Currency, ReservableCurrency},
transactional, PalletId,
};
pub use sp_core::Hasher;
pub use sp_runtime::traits::{
AccountIdConversion, CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, Dispatchable, Hash,
Saturating,
};
pub use sp_std::{boxed::Box, cmp::max, mem::size_of, prelude::Vec};
pub mod rpc;
pub mod types;
pub mod weights;
pub use types::*;
pub use weights::*;
#[frame_support::pallet]
pub mod pallet {
pub use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::config]
pub trait Config: frame_system::Config {
/// the obiquitous event type
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// The trait to manage funds
type Currency: Currency<Self::AccountId> + ReservableCurrency<Self::AccountId>;
/// The base id used for accountId calculation
#[pallet::constant]
type PalletId: Get<PalletId>;
/// The call type
type Call: Parameter
+ Dispatchable<RuntimeOrigin = Self::RuntimeOrigin, PostInfo = PostDispatchInfo>
+ GetDispatchInfo
+ From<frame_system::Call<Self>>;
/// The amount of balance that must be deposited per bytes stored
#[pallet::constant]
type DepositPerByte: Get<BalanceOf<Self>>;
/// The maximum number of account that can added or removed in a single call
#[pallet::constant]
type MaxAccountsPerTransaction: Get<u32>;
/// Weigths module
type WeightInfo: WeightInfo;
}
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
#[pallet::storage]
#[pallet::getter(fn nonce_supersig)]
pub type NonceSupersig<T: Config> = StorageValue<_, SupersigId, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn members)]
pub type Members<T: Config> =
StorageDoubleMap<_, Twox64Concat, SupersigId, Twox64Concat, T::AccountId, Role, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn total_members)]
pub type TotalMembers<T: Config> = StorageMap<_, Twox64Concat, SupersigId, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn total_deposit)]
pub type TotalDeposit<T: Config> =
StorageMap<_, Twox64Concat, SupersigId, BalanceOf<T>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn nonce_call)]
pub type NonceCall<T: Config> = StorageMap<_, Twox64Concat, SupersigId, CallId, ValueQuery>;
#[pallet::storage]
#[pallet::unbounded]
#[pallet::getter(fn calls)]
pub type Calls<T: Config> = StorageDoubleMap<
_,
Twox64Concat,
SupersigId,
Twox64Concat,
CallId,
PreimageCall<T::AccountId, BalanceOf<T>>,
OptionQuery,
>;
#[pallet::storage]
#[pallet::getter(fn votes)]
pub type Votes<T: Config> =
StorageDoubleMap<_, Twox64Concat, SupersigId, Twox64Concat, CallId, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn members_votes)]
pub type MembersVotes<T: Config> = StorageNMap<
_,
(
NMapKey<Twox64Concat, SupersigId>,
NMapKey<Twox64Concat, CallId>,
NMapKey<Twox64Concat, T::AccountId>,
),
bool,
ValueQuery,
>;
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// Supersig has been created [supersig]
SupersigCreated(T::AccountId),
/// a supersig have been removed [supersig]
SupersigRemoved(T::AccountId),
/// a Call has been submited [supersig, call_nonce, submiter]
CallSubmitted(T::AccountId, CallId, T::AccountId),
/// a Call has been voted [supersig, call_nonce, voter]
CallVoted(T::AccountId, CallId, T::AccountId),
/// a Call execution has been attempted [supersig, call_nonce, call_result]
CallExecutionAttempted(T::AccountId, CallId, DispatchResultWithPostInfo),
/// a Call has been removed [supersig, call_nonce]
CallRemoved(T::AccountId, CallId),
/// the list of users added to the supersig [supersig, [(user, role)]]
/// Users that were already in the supersig wont appear
MembersAdded(T::AccountId, Vec<(T::AccountId, Role)>),
/// the list of users removed from the supersig [supersig, removed_users]
MembersRemoved(T::AccountId, Vec<T::AccountId>),
/// a member leaved the supersig [supersig, member]
SupersigLeaved(T::AccountId, T::AccountId),
}
#[pallet::error]
pub enum Error<T> {
/// supersig must have at least one member
MustHaveAtLeastOneMember,
/// the call origin is not an existing supersig
NotSupersig,
/// the call doesn't exist
CallNotFound,
/// the user is not a member of the supersig
NotMember,
/// the member already voted for the call
AlreadyVoted,
/// the signatory is not allowed to perform this call
NotAllowed,
/// the supersig couldn't be deleted. This is due to the supersig having locked tokens
SupersigHaveLockedFunds,
/// conversion
Conversion,
/// overflow
Overflow,
/// could not execute the call because it was incorrectly encoded
BadEncodedCall,
/// no more valid supersig nonce
InvalidNonce,
/// the tx failed after execution attempt
TxFailed,
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// create a supersig.
///
/// `create_supersig` will create a supersig with specified parameters, and transfer
/// currencies from the creator to the generated supersig:
/// - the existencial deposit (minimum amount to make an account alive)
/// - the price corresponding to the size (in bytes) of the members times the
/// DepositPerByte
///
/// The dispatch origin for this call must be `Signed`.
///
/// # <weight>
///
/// Related functions:
/// - `Currency::transfer` will be called once to deposit an existencial amount on supersig
/// - `frame_system::inc_consumers` will be called once to protect the supersig from
/// deletion
#[pallet::call_index(0)]
#[transactional]
#[pallet::weight(T::WeightInfo::create_supersig(members.len() as u32))]
pub fn create_supersig(
origin: OriginFor<T>,
members: BoundedVec<(T::AccountId, Role), T::MaxAccountsPerTransaction>,
) -> DispatchResult {
let who = ensure_signed(origin)?;
// A supersig should at least have one member
let member_length = members.len();
if member_length < 1 {
return Err(Error::<T>::MustHaveAtLeastOneMember.into())
}
// Get id and associated account
let supersig_id = Self::nonce_supersig();
let supersig_account: T::AccountId = T::PalletId::get()
.try_into_sub_account(supersig_id)
.ok_or(Error::<T>::InvalidNonce)?;
// Update Members and TotalMembers storages
let added_members = Self::internal_add_members(supersig_id, members)?;
// Bring account to existence
let deposit = Self::compute_deposit(size_of::<T::AccountId>() * added_members.len())?;
let amount_to_transfer = max(T::Currency::minimum_balance(), deposit);
T::Currency::transfer(
&who,
&supersig_account,
amount_to_transfer,
ExistenceRequirement::AllowDeath,
)?;
// Prevent the supersig account to sign transaction that would kill it
frame_system::Pallet::<T>::inc_consumers(&supersig_account)?;
// Incentive to delete supersigs that are no longer used
Self::reserve_and_record_deposit(supersig_id, &supersig_account, deposit)?;
NonceSupersig::<T>::put(supersig_id + 1);
Self::deposit_event(Event::<T>::SupersigCreated(supersig_account.clone()));
Self::deposit_event(Event::<T>::MembersAdded(supersig_account, added_members));
Ok(())
}
/// To create a proposal use submitCall. You need to wrap a submit call around all calls
/// that require a vote.
///
/// `submit_call` will create a proposal on the supersig, that members can approve.
/// this will lock an amount that depend on the lenght of the encoded call, to prevent spam
///
/// The dispatch origin for this call must be `Signed`, and the origin must be a
/// supersig's member
///
/// # <weight>
///
/// Related functions:
/// - `Currency::reserve` will be called once to lock the deposit amount
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::submit_call(call.encode().len() as u32))]
pub fn submit_call(
origin: OriginFor<T>,
supersig_account: T::AccountId,
call: Box<<T as pallet::Config>::Call>,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let supersig_id = Self::get_supersig_id_from_account(&supersig_account)?;
let data = call.encode();
// Incentive to remove proposal that won't be accepted
let deposit = Self::compute_deposit(data.len())?;
T::Currency::reserve(&who, deposit)?;
// The encoded call is stored, along with the infos needed to unreserve the funds
// associated with it
let call_id = Self::nonce_call(supersig_id);
NonceCall::<T>::insert(supersig_id, call_id + 1);
let preimage = PreimageCall::<T::AccountId, BalanceOf<T>> {
data,
provider: who.clone(),
deposit,
};
Calls::<T>::insert(supersig_id, call_id, preimage);
Self::deposit_event(Event::<T>::CallSubmitted(supersig_account, call_id, who));
Ok(())
}
/// vote for a call in the supersig. You do not need to wrap this call in a submit call.
///
/// `approve_call` will add a positive, unique vote to the specified call proposal.
/// if the numbers of votes on this proposal = SimpleMajority (51%), then the call is
/// executed
///
/// The dispatch origin for this call must be `Signed`, and the origin must be a
/// supersig's member
///
/// # <weight>
///
/// Related functions:
/// - `Currency::unreserve` will be called once IF SimpleMajority is reached
#[pallet::call_index(2)]
#[pallet::weight(T::WeightInfo::approve_call())]
pub fn approve_call(
origin: OriginFor<T>,
supersig_account: T::AccountId,
call_id: CallId,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let supersig_id = Self::get_supersig_id_from_account(&supersig_account)?;
if Self::calls(supersig_id, call_id).is_none() {
return Err(Error::<T>::CallNotFound.into())
}
if Self::members_votes((supersig_id, call_id, who.clone())) {
return Err(Error::<T>::AlreadyVoted.into())
}
// Different roles have different voting weight
let vote_weight = Self::compute_vote_weight(supersig_id, &who)?;
// Update storages with the user vote
MembersVotes::<T>::insert((supersig_id, call_id, who.clone()), true);
Votes::<T>::mutate(supersig_id, call_id, |val| {
*val = val.saturating_add(vote_weight)
});
Self::deposit_event(Event::<T>::CallVoted(
supersig_account.clone(),
call_id,
who,
));
let total_votes = Self::votes(supersig_id, call_id);
if total_votes >= (Self::total_members(supersig_id) / 2 + 1) {
if let Some(preimage) = Self::calls(supersig_id, call_id) {
// free storage and unreserve deposit
Self::unchecked_remove_call_from_storages(supersig_id, call_id);
T::Currency::unreserve(&preimage.provider, preimage.deposit);
// Try to decode and execute the call
let res = if let Ok(call) = <T as Config>::Call::decode(&mut &preimage.data[..])
{
call.dispatch(
frame_system::RawOrigin::Signed(supersig_account.clone()).into(),
)
} else {
Err(Error::<T>::BadEncodedCall.into())
};
Self::deposit_event(Event::<T>::CallExecutionAttempted(
supersig_account,
call_id,
res,
));
}
}
Ok(())
}
/// remove a call from the supersig.
///
/// `remove_call` will remove a call from the poll.
///
/// The dispatch origin for this call must be `Signed` by either the supersig or the
/// account who submited the call
///
/// # <weight>
///
/// Related functions:
/// - `Currency::unreserve` will be called once
#[pallet::call_index(3)]
#[pallet::weight(T::WeightInfo::remove_call())]
pub fn remove_call(
origin: OriginFor<T>,
supersig_account: T::AccountId,
call_id: CallId,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let supersig_id = Self::get_supersig_id_from_account(&supersig_account)?;
let preimage = Self::calls(supersig_id, call_id).ok_or(Error::<T>::CallNotFound)?;
// Either the supersig or the user that created the vote can remove a call
if who != supersig_account && who != preimage.provider {
return Err(Error::<T>::NotAllowed.into())
}
// Clean up storage and release reserved funds
Self::unchecked_remove_call_from_storages(supersig_id, call_id);
T::Currency::unreserve(&preimage.provider, preimage.deposit);
Self::deposit_event(Event::<T>::CallRemoved(supersig_account, call_id));
Ok(())
}
/// add members the supersig. You need to wrap this in a submitCall function.
///
/// `add members` will add a list of addesses to the members list of the supersig.
/// if an address is already present, it will be ignored.
///
/// The dispatch origin for this call must be `Signed` by the supersig
///
/// # <weight>
#[pallet::call_index(4)]
#[transactional]
#[pallet::weight(T::WeightInfo::add_members(new_members.len() as u32))]
pub fn add_members(
origin: OriginFor<T>,
new_members: BoundedVec<(T::AccountId, Role), T::MaxAccountsPerTransaction>,
) -> DispatchResult {
let supersig_account = ensure_signed(origin)?;
let supersig_id = Self::get_supersig_id_from_account(&supersig_account)?;
// Update Members and TotalMembers storages
let added_members = Self::internal_add_members(supersig_id, new_members)?;
// Incentive to delete supersigs that are no longer used
let deposit = Self::compute_deposit(size_of::<T::AccountId>() * added_members.len())?;
Self::reserve_and_record_deposit(supersig_id, &supersig_account, deposit)?;
Self::deposit_event(Event::<T>::MembersAdded(supersig_account, added_members));
Ok(())
}
/// remove members from the supersig
///
/// `remove_members` will remove a list of addesses from the members list of the supersig.
/// if an address is not present, it will be ignored.
///
/// The dispatch origin for this call must be `Signed` by the supersig
///
/// # <weight>
#[pallet::call_index(5)]
#[transactional]
#[pallet::weight(T::WeightInfo::remove_members(members_to_remove.len() as u32))]
pub fn remove_members(
origin: OriginFor<T>,
members_to_remove: BoundedVec<T::AccountId, T::MaxAccountsPerTransaction>,
) -> DispatchResult {
let supersig_account = ensure_signed(origin)?;
let supersig_id = Self::get_supersig_id_from_account(&supersig_account)?;
// Remeber the storage state before we remove the members from it
let total_deposit = Self::total_deposit(supersig_id);
let initial_total_members = Self::total_members(supersig_id);
let removed_members = Self::internal_remove_members(supersig_id, members_to_remove)?;
// amount = total_deposit / initial_n_members * n_removed_members
let amount_to_unreserve = Self::compute_proportional_amount_to_unreserve(
total_deposit,
initial_total_members,
removed_members.len(),
)?;
// Release a proportional amount of deposit
Self::unreserve_and_record_deposit(supersig_id, &supersig_account, amount_to_unreserve);
Self::deposit_event(Event::<T>::MembersRemoved(
supersig_account,
removed_members,
));
Ok(())
}
/// remove the supersig
///
/// `delete_supersig` will remove every members, transfer every remanent funds to the
/// target account, remove the supersig from storage, and set the consumers and providers
/// to 0
///
/// The dispatch origin for this call must be `Signed` by the supersig
///
/// # <weight>
#[pallet::call_index(6)]
#[transactional]
#[pallet::weight(T::WeightInfo::delete_supersig())]
pub fn delete_supersig(origin: OriginFor<T>, beneficiary: T::AccountId) -> DispatchResult {
let supersig_account = ensure_signed(origin)?;
let supersig_id = Self::get_supersig_id_from_account(&supersig_account)?;
// Release all member related deposits
let total_deposit = TotalDeposit::<T>::take(supersig_id);
T::Currency::unreserve(&supersig_account, total_deposit);
// Release all call related deposits
Calls::<T>::iter_prefix_values(supersig_id).for_each(|preimage| {
T::Currency::unreserve(&preimage.provider, preimage.deposit);
});
// Erase trace of this supersis in storage and decrement the account reference counter
Self::unchecked_remove_supersig_from_storages(supersig_id, &supersig_account);
// Empty the supersig account balance
// Will cause death of the account
// Will fail and revert the transaction if this account is not allowed to die
// due to an other pallet reference counter, reserved or frozen funds
T::Currency::transfer(
&supersig_account,
&beneficiary,
T::Currency::total_balance(&supersig_account),
ExistenceRequirement::AllowDeath,
)
.map_err(|_| Error::<T>::SupersigHaveLockedFunds)?;
Self::deposit_event(Event::<T>::SupersigRemoved(supersig_account));
Ok(())
}
/// leave a supersig, unless you are the only member, in which case you need to
/// deleteSupersig.
///
/// `leave_supersig` will remove caller from selected supersig
///
/// The dispatch origin for this call must be `Signed` by the user.
///
/// # <weight>
#[pallet::call_index(7)]
#[pallet::weight(T::WeightInfo::leave_supersig())]
pub fn leave_supersig(
origin: OriginFor<T>,
supersig_account: T::AccountId,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let supersig_id = Self::get_supersig_id_from_account(&supersig_account)?;
if Self::members(supersig_id, &who) == Role::NotMember {
return Err(Error::<T>::NotMember.into())
}
// Remeber the storage state before we remove the members from it
let total_deposit = Self::total_deposit(supersig_id);
let initial_total_members = Self::total_members(supersig_id);
// amount = total_deposit / initial_n_members * n_removed_members
let amount_to_unreserve = Self::compute_proportional_amount_to_unreserve(
total_deposit,
initial_total_members,
1,
)?;
// A supersig should at least have one member
TotalMembers::<T>::try_mutate(supersig_id, |nb| {
if *nb == 1 {
return Err(Error::<T>::MustHaveAtLeastOneMember)
};
*nb -= 1;
Ok(())
})?;
// Note that the votes the user made stays in storage
Members::<T>::remove(supersig_id, &who);
// Release a proportional amount of deposit
Self::unreserve_and_record_deposit(supersig_id, &supersig_account, amount_to_unreserve);
Self::deposit_event(Event::<T>::SupersigLeaved(supersig_account, who));
Ok(())
}
}
impl<T: Config> Pallet<T> {
pub fn get_supersig_id_from_account(
supersig_account: &T::AccountId,
) -> Result<SupersigId, pallet::Error<T>> {
if let Some((account, supersig_id)) = PalletId::try_from_sub_account(supersig_account) {
if account != T::PalletId::get() || Self::total_members(supersig_id) == 0 {
return Err(Error::<T>::NotSupersig)
}
Ok(supersig_id)
} else {
Err(Error::<T>::NotSupersig)
}
}
fn unchecked_remove_call_from_storages(supersig_id: SupersigId, call_id: CallId) {
Calls::<T>::remove(supersig_id, call_id);
Votes::<T>::remove(supersig_id, call_id);
let _ = MembersVotes::<T>::clear_prefix((supersig_id, call_id), u32::MAX, None);
}
fn unchecked_remove_supersig_from_storages(
supersig_id: SupersigId,
supersig_account: &T::AccountId,
) {
NonceCall::<T>::remove(supersig_id);
let _ = Members::<T>::clear_prefix(supersig_id, u32::MAX, None);
TotalMembers::<T>::remove(supersig_id);
let _ = Calls::<T>::clear_prefix(supersig_id, u32::MAX, None);
let _ = Votes::<T>::clear_prefix(supersig_id, u32::MAX, None);
let _ = MembersVotes::<T>::clear_prefix((supersig_id,), u32::MAX, None);
frame_system::Pallet::<T>::dec_consumers(supersig_account);
}
fn internal_add_members(
supersig_id: SupersigId,
members: BoundedVec<(T::AccountId, Role), T::MaxAccountsPerTransaction>,
) -> Result<Vec<(T::AccountId, Role)>, Error<T>> {
let mut added = Vec::new();
for (member, role) in members {
if Self::members(supersig_id, &member) == Role::NotMember {
added.push((member.clone(), role.clone()));
}
Members::<T>::insert(supersig_id, member, role);
}
TotalMembers::<T>::try_mutate(supersig_id, |n| {
*n = n
.checked_add(added.len().try_into().map_err(|_| Error::<T>::Conversion)?)
.ok_or(Error::<T>::Overflow)?;
Ok(())
})?;
Ok(added)
}
fn internal_remove_members(
supersig_id: SupersigId,
members: BoundedVec<T::AccountId, T::MaxAccountsPerTransaction>,
) -> Result<Vec<T::AccountId>, pallet::Error<T>> {
let mut removed = Vec::new();
for member in members {
if Self::members(supersig_id, &member) != Role::NotMember {
Members::<T>::remove(supersig_id, member.clone());
removed.push(member);
}
}
TotalMembers::<T>::try_mutate(supersig_id, |n| {
let new_total_members =
n.saturating_sub(removed.len().try_into().map_err(|_| Error::<T>::Conversion)?);
if new_total_members < 1 {
return Err(Error::<T>::MustHaveAtLeastOneMember)
}
*n = new_total_members;
Ok(())
})?;
Ok(removed)
}
fn compute_deposit(data_size: usize) -> Result<BalanceOf<T>, Error<T>> {
let bytes_stored: u32 = data_size.try_into().map_err(|_| Error::<T>::Conversion)?;
Ok(<BalanceOf<T>>::from(bytes_stored).saturating_mul(T::DepositPerByte::get()))
}
// this function can fail after a storage mutation.
// extrinsics that use it should have the #[transactional] annotation.
fn reserve_and_record_deposit(
supersig_id: SupersigId,
supersig_account: &T::AccountId,
deposit: BalanceOf<T>,
) -> DispatchResult {
T::Currency::reserve(supersig_account, deposit)?;
TotalDeposit::<T>::try_mutate(supersig_id, |val| {
*val = val.checked_add(&deposit).ok_or(Error::<T>::Overflow)?;
Ok(())
})
}
fn unreserve_and_record_deposit(
supersig_id: SupersigId,
supersig_account: &T::AccountId,
amount: BalanceOf<T>,
) {
T::Currency::unreserve(supersig_account, amount);
TotalDeposit::<T>::mutate(supersig_id, |val| *val = val.saturating_sub(amount));
}
fn compute_vote_weight(
supersig_id: SupersigId,
who: &T::AccountId,
) -> Result<u32, Error<T>> {
match Self::members(supersig_id, who) {
Role::Standard => Ok(1),
Role::Master => Ok(max(Self::total_members(supersig_id) / 2, 1)),
Role::NotMember => Err(Error::<T>::NotMember),
}
}
pub fn compute_proportional_amount_to_unreserve(
total_deposit: BalanceOf<T>,
initial_total_members: u32,
removed_members: usize,
) -> Result<BalanceOf<T>, Error<T>> {
let amount_to_unreserve = total_deposit
.checked_div(
&<BalanceOf<T>>::try_from(initial_total_members)
.map_err(|_| Error::<T>::Conversion)?,
)
.ok_or(Error::<T>::Overflow)?
.checked_mul(
&<BalanceOf<T>>::try_from(removed_members)
.map_err(|_| Error::<T>::Conversion)?,
)
.ok_or(Error::<T>::Overflow)?;
Ok(amount_to_unreserve)
}
}
}