1#![cfg_attr(not(feature = "std"), no_std)]
43
44extern crate alloc;
45
46use alloc::{boxed::Box, vec, vec::Vec};
47use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
48use core::{marker::PhantomData, result};
49use scale_info::TypeInfo;
50use sp_io::storage;
51use sp_runtime::{
52 traits::{Dispatchable, Hash},
53 Debug, DispatchError,
54};
55
56use frame_support::{
57 dispatch::{
58 DispatchResult, DispatchResultWithPostInfo, GetDispatchInfo, Pays, PostDispatchInfo,
59 },
60 ensure,
61 traits::{
62 Backing, ChangeMembers, Consideration, EnsureOrigin, EnsureOriginWithArg, Get, GetBacking,
63 InitializeMembers, MaybeConsideration, OriginTrait, StorageVersion,
64 },
65 weights::Weight,
66};
67
68#[cfg(any(feature = "try-runtime", test))]
69use sp_runtime::TryRuntimeError;
70
71#[cfg(test)]
72mod tests;
73
74#[cfg(feature = "runtime-benchmarks")]
75mod benchmarking;
76pub mod migrations;
77pub mod weights;
78
79pub use pallet::*;
80pub use weights::WeightInfo;
81
82const LOG_TARGET: &str = "runtime::collective";
83
84pub type ProposalIndex = u32;
86
87pub type MemberCount = u32;
92
93pub trait DefaultVote {
95 fn default_vote(
102 prime_vote: Option<bool>,
103 yes_votes: MemberCount,
104 no_votes: MemberCount,
105 len: MemberCount,
106 ) -> bool;
107}
108
109pub struct PrimeDefaultVote;
111
112impl DefaultVote for PrimeDefaultVote {
113 fn default_vote(
114 prime_vote: Option<bool>,
115 _yes_votes: MemberCount,
116 _no_votes: MemberCount,
117 _len: MemberCount,
118 ) -> bool {
119 prime_vote.unwrap_or(false)
120 }
121}
122
123pub struct MoreThanMajorityThenPrimeDefaultVote;
126
127impl DefaultVote for MoreThanMajorityThenPrimeDefaultVote {
128 fn default_vote(
129 prime_vote: Option<bool>,
130 yes_votes: MemberCount,
131 _no_votes: MemberCount,
132 len: MemberCount,
133 ) -> bool {
134 let more_than_majority = yes_votes * 2 > len;
135 more_than_majority || prime_vote.unwrap_or(false)
136 }
137}
138
139#[derive(
141 PartialEq, Eq, Clone, Debug, Encode, Decode, DecodeWithMemTracking, TypeInfo, MaxEncodedLen,
142)]
143#[scale_info(skip_type_params(I))]
144#[codec(mel_bound(AccountId: MaxEncodedLen))]
145pub enum RawOrigin<AccountId, I> {
146 Members(MemberCount, MemberCount),
148 Member(AccountId),
150 _Phantom(PhantomData<I>),
152}
153
154impl<AccountId, I> GetBacking for RawOrigin<AccountId, I> {
155 fn get_backing(&self) -> Option<Backing> {
156 match self {
157 RawOrigin::Members(n, d) => Some(Backing { approvals: *n, eligible: *d }),
158 _ => None,
159 }
160 }
161}
162
163#[derive(PartialEq, Eq, Clone, Encode, Decode, Debug, TypeInfo)]
165pub struct Votes<AccountId, BlockNumber> {
166 index: ProposalIndex,
168 threshold: MemberCount,
170 ayes: Vec<AccountId>,
172 nays: Vec<AccountId>,
174 end: BlockNumber,
176}
177
178#[doc = docify::embed!("src/tests.rs", deposit_types_with_linear_work)]
188#[doc = docify::embed!("src/tests.rs", deposit_types_with_geometric_work)]
190#[doc = docify::embed!("src/tests.rs", deposit_round_with_geometric_work)]
192pub mod deposit {
193 use core::marker::PhantomData;
194 use sp_core::Get;
195 use sp_runtime::{traits::Convert, FixedPointNumber, FixedU128, Saturating};
196
197 pub struct Constant<Deposit>(PhantomData<Deposit>);
200 impl<Deposit, Balance> Convert<u32, Balance> for Constant<Deposit>
201 where
202 Deposit: Get<Balance>,
203 Balance: frame_support::traits::tokens::Balance,
204 {
205 fn convert(_: u32) -> Balance {
206 Deposit::get()
207 }
208 }
209
210 pub struct Linear<Slope, Offset>(PhantomData<(Slope, Offset)>);
213 impl<Slope, Offset, Balance> Convert<u32, Balance> for Linear<Slope, Offset>
214 where
215 Slope: Get<u32>,
216 Offset: Get<Balance>,
217 Balance: frame_support::traits::tokens::Balance,
218 {
219 fn convert(proposal_count: u32) -> Balance {
220 let base: Balance = Slope::get().saturating_mul(proposal_count).into();
221 Offset::get().saturating_add(base)
222 }
223 }
224
225 pub struct Geometric<Ratio, Base>(PhantomData<(Ratio, Base)>);
228 impl<Ratio, Base, Balance> Convert<u32, Balance> for Geometric<Ratio, Base>
229 where
230 Ratio: Get<FixedU128>,
231 Base: Get<Balance>,
232 Balance: frame_support::traits::tokens::Balance,
233 {
234 fn convert(proposal_count: u32) -> Balance {
235 Ratio::get()
236 .saturating_pow(proposal_count as usize)
237 .saturating_mul_int(Base::get())
238 }
239 }
240
241 pub struct Round<Precision, Deposit>(PhantomData<(Precision, Deposit)>);
245 impl<Precision, Deposit, Balance> Convert<u32, Balance> for Round<Precision, Deposit>
246 where
247 Precision: Get<u32>,
248 Deposit: Convert<u32, Balance>,
249 Balance: frame_support::traits::tokens::Balance,
250 {
251 fn convert(proposal_count: u32) -> Balance {
252 let deposit = Deposit::convert(proposal_count);
253 if !deposit.is_zero() {
254 let factor: Balance =
255 Balance::from(10u32).saturating_pow(Precision::get() as usize);
256 if factor > deposit {
257 deposit
258 } else {
259 (deposit / factor) * factor
260 }
261 } else {
262 deposit
263 }
264 }
265 }
266
267 pub struct Stepped<Period, Step>(PhantomData<(Period, Step)>);
269 impl<Period, Step, Balance> Convert<u32, Balance> for Stepped<Period, Step>
270 where
271 Period: Get<u32>,
272 Step: Convert<u32, Balance>,
273 Balance: frame_support::traits::tokens::Balance,
274 {
275 fn convert(proposal_count: u32) -> Balance {
276 let step_num = proposal_count / Period::get();
277 Step::convert(step_num)
278 }
279 }
280
281 pub struct Delayed<Delay, Deposit>(PhantomData<(Delay, Deposit)>);
283 impl<Delay, Deposit, Balance> Convert<u32, Balance> for Delayed<Delay, Deposit>
284 where
285 Delay: Get<u32>,
286 Deposit: Convert<u32, Balance>,
287 Balance: frame_support::traits::tokens::Balance,
288 {
289 fn convert(proposal_count: u32) -> Balance {
290 let delay = Delay::get();
291 if delay > proposal_count {
292 return Balance::zero();
293 }
294 let pos = proposal_count.saturating_sub(delay);
295 Deposit::convert(pos)
296 }
297 }
298
299 pub struct WithCeil<Ceil, Deposit>(PhantomData<(Ceil, Deposit)>);
301 impl<Ceil, Deposit, Balance> Convert<u32, Balance> for WithCeil<Ceil, Deposit>
302 where
303 Ceil: Get<Balance>,
304 Deposit: Convert<u32, Balance>,
305 Balance: frame_support::traits::tokens::Balance,
306 {
307 fn convert(proposal_count: u32) -> Balance {
308 Deposit::convert(proposal_count).min(Ceil::get())
309 }
310 }
311}
312
313#[frame_support::pallet]
314pub mod pallet {
315 use super::*;
316 use frame_support::pallet_prelude::*;
317 use frame_system::pallet_prelude::*;
318
319 const STORAGE_VERSION: StorageVersion = StorageVersion::new(5);
321
322 #[pallet::pallet]
323 #[pallet::storage_version(STORAGE_VERSION)]
324 #[pallet::without_storage_info]
325 pub struct Pallet<T, I = ()>(PhantomData<(T, I)>);
326
327 #[pallet::config]
328 pub trait Config<I: 'static = ()>: frame_system::Config {
329 type RuntimeOrigin: From<RawOrigin<Self::AccountId, I>>;
331
332 type Proposal: Parameter
334 + Dispatchable<
335 RuntimeOrigin = <Self as Config<I>>::RuntimeOrigin,
336 PostInfo = PostDispatchInfo,
337 > + From<frame_system::Call<Self>>
338 + GetDispatchInfo;
339
340 #[allow(deprecated)]
342 type RuntimeEvent: From<Event<Self, I>>
343 + IsType<<Self as frame_system::Config>::RuntimeEvent>;
344
345 type MotionDuration: Get<BlockNumberFor<Self>>;
347
348 type MaxProposals: Get<ProposalIndex>;
350
351 type MaxMembers: Get<MemberCount>;
357
358 type DefaultVote: DefaultVote;
360
361 type WeightInfo: WeightInfo;
363
364 type SetMembersOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin>;
366
367 #[pallet::constant]
369 type MaxProposalWeight: Get<Weight>;
370
371 type DisapproveOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin>;
374
375 type KillOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin>;
380
381 type Consideration: MaybeConsideration<Self::AccountId, u32>;
391 }
392
393 #[pallet::genesis_config]
394 #[derive(frame_support::DefaultNoBound)]
395 pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
396 #[serde(skip)]
397 pub phantom: PhantomData<I>,
398 pub members: Vec<T::AccountId>,
399 }
400
401 #[pallet::genesis_build]
402 impl<T: Config<I>, I: 'static> BuildGenesisConfig for GenesisConfig<T, I> {
403 fn build(&self) {
404 use alloc::collections::btree_set::BTreeSet;
405 let members_set: BTreeSet<_> = self.members.iter().collect();
406 assert_eq!(
407 members_set.len(),
408 self.members.len(),
409 "Members cannot contain duplicate accounts."
410 );
411 assert!(
412 self.members.len() <= T::MaxMembers::get() as usize,
413 "Members length cannot exceed MaxMembers.",
414 );
415
416 Pallet::<T, I>::initialize_members(&self.members)
417 }
418 }
419
420 #[pallet::origin]
422 pub type Origin<T, I = ()> = RawOrigin<<T as frame_system::Config>::AccountId, I>;
423
424 #[pallet::storage]
426 pub type Proposals<T: Config<I>, I: 'static = ()> =
427 StorageValue<_, BoundedVec<T::Hash, T::MaxProposals>, ValueQuery>;
428
429 #[pallet::storage]
431 pub type ProposalOf<T: Config<I>, I: 'static = ()> =
432 StorageMap<_, Identity, T::Hash, <T as Config<I>>::Proposal, OptionQuery>;
433
434 #[pallet::storage]
439 pub type CostOf<T: Config<I>, I: 'static = ()> =
440 StorageMap<_, Identity, T::Hash, (T::AccountId, T::Consideration), OptionQuery>;
441
442 #[pallet::storage]
444 pub type Voting<T: Config<I>, I: 'static = ()> =
445 StorageMap<_, Identity, T::Hash, Votes<T::AccountId, BlockNumberFor<T>>, OptionQuery>;
446
447 #[pallet::storage]
449 pub type ProposalCount<T: Config<I>, I: 'static = ()> = StorageValue<_, u32, ValueQuery>;
450
451 #[pallet::storage]
453 pub type Members<T: Config<I>, I: 'static = ()> =
454 StorageValue<_, Vec<T::AccountId>, ValueQuery>;
455
456 #[pallet::storage]
458 pub type Prime<T: Config<I>, I: 'static = ()> = StorageValue<_, T::AccountId, OptionQuery>;
459
460 #[pallet::event]
461 #[pallet::generate_deposit(pub(super) fn deposit_event)]
462 pub enum Event<T: Config<I>, I: 'static = ()> {
463 Proposed {
466 account: T::AccountId,
467 proposal_index: ProposalIndex,
468 proposal_hash: T::Hash,
469 threshold: MemberCount,
470 },
471 Voted {
474 account: T::AccountId,
475 proposal_hash: T::Hash,
476 voted: bool,
477 yes: MemberCount,
478 no: MemberCount,
479 },
480 Approved { proposal_hash: T::Hash },
482 Disapproved { proposal_hash: T::Hash },
484 Executed { proposal_hash: T::Hash, result: DispatchResult },
486 MemberExecuted { proposal_hash: T::Hash, result: DispatchResult },
488 Closed { proposal_hash: T::Hash, yes: MemberCount, no: MemberCount },
490 Killed { proposal_hash: T::Hash },
492 ProposalCostBurned { proposal_hash: T::Hash, who: T::AccountId },
494 ProposalCostReleased { proposal_hash: T::Hash, who: T::AccountId },
496 }
497
498 #[pallet::error]
499 pub enum Error<T, I = ()> {
500 NotMember,
502 DuplicateProposal,
504 ProposalMissing,
506 WrongIndex,
508 DuplicateVote,
510 AlreadyInitialized,
512 TooEarly,
514 TooManyProposals,
516 WrongProposalWeight,
518 WrongProposalLength,
520 PrimeAccountNotMember,
522 ProposalActive,
524 }
525
526 #[pallet::hooks]
527 impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
528 #[cfg(feature = "try-runtime")]
529 fn try_state(_n: BlockNumberFor<T>) -> Result<(), TryRuntimeError> {
530 Self::do_try_state()
531 }
532 }
533
534 #[pallet::composite_enum]
536 pub enum HoldReason<I: 'static = ()> {
537 #[codec(index = 0)]
539 ProposalSubmission,
540 }
541
542 #[pallet::call]
544 impl<T: Config<I>, I: 'static> Pallet<T, I> {
545 #[pallet::call_index(0)]
570 #[pallet::weight((
571 T::WeightInfo::set_members(
572 *old_count, new_members.len() as u32, T::MaxProposals::get() ),
576 DispatchClass::Operational
577 ))]
578 pub fn set_members(
579 origin: OriginFor<T>,
580 new_members: Vec<T::AccountId>,
581 prime: Option<T::AccountId>,
582 old_count: MemberCount,
583 ) -> DispatchResultWithPostInfo {
584 T::SetMembersOrigin::ensure_origin(origin)?;
585 if new_members.len() > T::MaxMembers::get() as usize {
586 log::error!(
587 target: LOG_TARGET,
588 "New members count ({}) exceeds maximum amount of members expected ({}).",
589 new_members.len(),
590 T::MaxMembers::get(),
591 );
592 }
593
594 let old = Members::<T, I>::get();
595 if old.len() > old_count as usize {
596 log::warn!(
597 target: LOG_TARGET,
598 "Wrong count used to estimate set_members weight. expected ({}) vs actual ({})",
599 old_count,
600 old.len(),
601 );
602 }
603 if let Some(p) = &prime {
604 ensure!(new_members.contains(p), Error::<T, I>::PrimeAccountNotMember);
605 }
606 let mut new_members = new_members;
607 new_members.sort();
608 <Self as ChangeMembers<T::AccountId>>::set_members_sorted(&new_members, &old);
609 Prime::<T, I>::set(prime);
610
611 Ok(Some(T::WeightInfo::set_members(
612 old.len() as u32, new_members.len() as u32, T::MaxProposals::get(), ))
616 .into())
617 }
618
619 #[pallet::call_index(1)]
629 #[pallet::weight((
630 T::WeightInfo::execute(
631 *length_bound, T::MaxMembers::get(), ).saturating_add(proposal.get_dispatch_info().call_weight), DispatchClass::Operational
635 ))]
636 pub fn execute(
637 origin: OriginFor<T>,
638 proposal: Box<<T as Config<I>>::Proposal>,
639 #[pallet::compact] length_bound: u32,
640 ) -> DispatchResultWithPostInfo {
641 let who = ensure_signed(origin)?;
642 let members = Members::<T, I>::get();
643 ensure!(members.contains(&who), Error::<T, I>::NotMember);
644 let proposal_len = proposal.encoded_size();
645 ensure!(proposal_len <= length_bound as usize, Error::<T, I>::WrongProposalLength);
646
647 let proposal_hash = T::Hashing::hash_of(&proposal);
648 let result = proposal.dispatch(RawOrigin::Member(who).into());
649 Self::deposit_event(Event::MemberExecuted {
650 proposal_hash,
651 result: result.map(|_| ()).map_err(|e| e.error),
652 });
653
654 Ok(get_result_weight(result)
655 .map(|w| {
656 T::WeightInfo::execute(
657 proposal_len as u32, members.len() as u32, )
660 .saturating_add(w) })
662 .into())
663 }
664
665 #[pallet::call_index(2)]
687 #[pallet::weight((
688 if *threshold < 2 {
689 T::WeightInfo::propose_execute(
690 *length_bound, T::MaxMembers::get(), ).saturating_add(proposal.get_dispatch_info().call_weight) } else {
694 T::WeightInfo::propose_proposed(
695 *length_bound, T::MaxMembers::get(), T::MaxProposals::get(), )
699 },
700 DispatchClass::Operational
701 ))]
702 pub fn propose(
703 origin: OriginFor<T>,
704 #[pallet::compact] threshold: MemberCount,
705 proposal: Box<<T as Config<I>>::Proposal>,
706 #[pallet::compact] length_bound: u32,
707 ) -> DispatchResultWithPostInfo {
708 let who = ensure_signed(origin)?;
709 let members = Members::<T, I>::get();
710 ensure!(members.contains(&who), Error::<T, I>::NotMember);
711
712 if threshold < 2 {
713 let (proposal_len, result) =
714 Self::do_propose_execute(threshold, proposal, length_bound)?;
715
716 Ok(get_result_weight(result)
717 .map(|w| {
718 T::WeightInfo::propose_execute(
719 proposal_len as u32, members.len() as u32, )
722 .saturating_add(w) })
724 .into())
725 } else {
726 let (proposal_len, active_proposals) =
727 Self::do_propose_proposed(who, threshold, proposal, length_bound)?;
728
729 Ok(Some(T::WeightInfo::propose_proposed(
730 proposal_len as u32, members.len() as u32, active_proposals, ))
734 .into())
735 }
736 }
737
738 #[pallet::call_index(3)]
748 #[pallet::weight((T::WeightInfo::vote(T::MaxMembers::get()), DispatchClass::Operational))]
749 pub fn vote(
750 origin: OriginFor<T>,
751 proposal: T::Hash,
752 #[pallet::compact] index: ProposalIndex,
753 approve: bool,
754 ) -> DispatchResultWithPostInfo {
755 let who = ensure_signed(origin)?;
756 let members = Members::<T, I>::get();
757 ensure!(members.contains(&who), Error::<T, I>::NotMember);
758
759 let is_account_voting_first_time = Self::do_vote(who, proposal, index, approve)?;
761
762 if is_account_voting_first_time {
763 Ok((Some(T::WeightInfo::vote(members.len() as u32)), Pays::No).into())
764 } else {
765 Ok((Some(T::WeightInfo::vote(members.len() as u32)), Pays::Yes).into())
766 }
767 }
768
769 #[pallet::call_index(5)]
782 #[pallet::weight(T::WeightInfo::disapprove_proposal(T::MaxProposals::get()))]
783 pub fn disapprove_proposal(
784 origin: OriginFor<T>,
785 proposal_hash: T::Hash,
786 ) -> DispatchResultWithPostInfo {
787 T::DisapproveOrigin::ensure_origin(origin)?;
788 let proposal_count = Self::do_disapprove_proposal(proposal_hash);
789 Ok(Some(T::WeightInfo::disapprove_proposal(proposal_count)).into())
790 }
791
792 #[pallet::call_index(6)]
817 #[pallet::weight((
818 {
819 let b = *length_bound;
820 let m = T::MaxMembers::get();
821 let p1 = *proposal_weight_bound;
822 let p2 = T::MaxProposals::get();
823 T::WeightInfo::close_early_approved(b, m, p2)
824 .max(T::WeightInfo::close_early_disapproved(m, p2))
825 .max(T::WeightInfo::close_approved(b, m, p2))
826 .max(T::WeightInfo::close_disapproved(m, p2))
827 .saturating_add(p1)
828 },
829 DispatchClass::Operational
830 ))]
831 pub fn close(
832 origin: OriginFor<T>,
833 proposal_hash: T::Hash,
834 #[pallet::compact] index: ProposalIndex,
835 proposal_weight_bound: Weight,
836 #[pallet::compact] length_bound: u32,
837 ) -> DispatchResultWithPostInfo {
838 ensure_signed(origin)?;
839
840 Self::do_close(proposal_hash, index, proposal_weight_bound, length_bound)
841 }
842
843 #[pallet::call_index(7)]
851 #[pallet::weight(T::WeightInfo::kill(1, T::MaxProposals::get()))]
852 pub fn kill(origin: OriginFor<T>, proposal_hash: T::Hash) -> DispatchResultWithPostInfo {
853 T::KillOrigin::ensure_origin(origin)?;
854 ensure!(
855 ProposalOf::<T, I>::get(&proposal_hash).is_some(),
856 Error::<T, I>::ProposalMissing
857 );
858 let burned = if let Some((who, cost)) = <CostOf<T, I>>::take(proposal_hash) {
859 cost.burn(&who);
860 Self::deposit_event(Event::ProposalCostBurned { proposal_hash, who });
861 true
862 } else {
863 false
864 };
865 let proposal_count = Self::remove_proposal(proposal_hash);
866
867 Self::deposit_event(Event::Killed { proposal_hash });
868
869 Ok(Some(T::WeightInfo::kill(burned as u32, proposal_count)).into())
870 }
871
872 #[pallet::call_index(8)]
882 #[pallet::weight(T::WeightInfo::release_proposal_cost())]
883 pub fn release_proposal_cost(
884 origin: OriginFor<T>,
885 proposal_hash: T::Hash,
886 ) -> DispatchResult {
887 ensure_signed_or_root(origin)?;
888 ensure!(
889 ProposalOf::<T, I>::get(&proposal_hash).is_none(),
890 Error::<T, I>::ProposalActive
891 );
892 if let Some((who, cost)) = <CostOf<T, I>>::take(proposal_hash) {
893 cost.drop(&who)?;
894 Self::deposit_event(Event::ProposalCostReleased { proposal_hash, who });
895 }
896
897 Ok(())
898 }
899 }
900}
901
902fn get_result_weight(result: DispatchResultWithPostInfo) -> Option<Weight> {
906 match result {
907 Ok(post_info) => post_info.actual_weight,
908 Err(err) => err.post_info.actual_weight,
909 }
910}
911
912impl<T: Config<I>, I: 'static> Pallet<T, I> {
913 pub fn is_member(who: &T::AccountId) -> bool {
915 Members::<T, I>::get().contains(who)
918 }
919
920 pub fn proposal_hash(proposal: &<T as Config<I>>::Proposal, threshold: MemberCount) -> T::Hash {
923 T::Hashing::hash_of(&(proposal, threshold))
924 }
925
926 pub fn do_propose_execute(
928 threshold: MemberCount,
929 proposal: Box<<T as Config<I>>::Proposal>,
930 length_bound: MemberCount,
931 ) -> Result<(u32, DispatchResultWithPostInfo), DispatchError> {
932 let proposal_len = proposal.encoded_size();
933 ensure!(proposal_len <= length_bound as usize, Error::<T, I>::WrongProposalLength);
934 let proposal_weight = proposal.get_dispatch_info().call_weight;
935 ensure!(
936 proposal_weight.all_lte(T::MaxProposalWeight::get()),
937 Error::<T, I>::WrongProposalWeight
938 );
939
940 let proposal_hash = Self::proposal_hash(&proposal, threshold);
941 ensure!(!<ProposalOf<T, I>>::contains_key(proposal_hash), Error::<T, I>::DuplicateProposal);
944
945 let seats = Members::<T, I>::get().len() as MemberCount;
946 let result = proposal.dispatch(RawOrigin::Members(1, seats).into());
947 Self::deposit_event(Event::Executed {
948 proposal_hash,
949 result: result.map(|_| ()).map_err(|e| e.error),
950 });
951 Ok((proposal_len as u32, result))
952 }
953
954 pub fn do_propose_proposed(
956 who: T::AccountId,
957 threshold: MemberCount,
958 proposal: Box<<T as Config<I>>::Proposal>,
959 length_bound: MemberCount,
960 ) -> Result<(u32, u32), DispatchError> {
961 let proposal_len = proposal.encoded_size();
962 ensure!(proposal_len <= length_bound as usize, Error::<T, I>::WrongProposalLength);
963 let proposal_weight = proposal.get_dispatch_info().call_weight;
964 ensure!(
965 proposal_weight.all_lte(T::MaxProposalWeight::get()),
966 Error::<T, I>::WrongProposalWeight
967 );
968
969 let proposal_hash = Self::proposal_hash(&proposal, threshold);
970 ensure!(!<ProposalOf<T, I>>::contains_key(proposal_hash), Error::<T, I>::DuplicateProposal);
971
972 let active_proposals =
973 <Proposals<T, I>>::try_mutate(|proposals| -> Result<usize, DispatchError> {
974 proposals.try_push(proposal_hash).map_err(|_| Error::<T, I>::TooManyProposals)?;
975 Ok(proposals.len())
976 })?;
977
978 let cost = T::Consideration::new(&who, active_proposals as u32 - 1)?;
979 if !cost.is_none() {
980 <CostOf<T, I>>::insert(proposal_hash, (who.clone(), cost));
981 }
982
983 let index = ProposalCount::<T, I>::get();
984
985 <ProposalCount<T, I>>::mutate(|i| *i += 1);
986 <ProposalOf<T, I>>::insert(proposal_hash, proposal);
987 let votes = {
988 let end = frame_system::Pallet::<T>::block_number() + T::MotionDuration::get();
989 Votes { index, threshold, ayes: vec![], nays: vec![], end }
990 };
991 <Voting<T, I>>::insert(proposal_hash, votes);
992
993 Self::deposit_event(Event::Proposed {
994 account: who,
995 proposal_index: index,
996 proposal_hash,
997 threshold,
998 });
999 Ok((proposal_len as u32, active_proposals as u32))
1000 }
1001
1002 pub fn do_vote(
1005 who: T::AccountId,
1006 proposal: T::Hash,
1007 index: ProposalIndex,
1008 approve: bool,
1009 ) -> Result<bool, DispatchError> {
1010 let mut voting = Voting::<T, I>::get(&proposal).ok_or(Error::<T, I>::ProposalMissing)?;
1011 ensure!(voting.index == index, Error::<T, I>::WrongIndex);
1012
1013 let position_yes = voting.ayes.iter().position(|a| a == &who);
1014 let position_no = voting.nays.iter().position(|a| a == &who);
1015
1016 let is_account_voting_first_time = position_yes.is_none() && position_no.is_none();
1018
1019 if approve {
1020 if position_yes.is_none() {
1021 voting.ayes.push(who.clone());
1022 } else {
1023 return Err(Error::<T, I>::DuplicateVote.into());
1024 }
1025 if let Some(pos) = position_no {
1026 voting.nays.swap_remove(pos);
1027 }
1028 } else {
1029 if position_no.is_none() {
1030 voting.nays.push(who.clone());
1031 } else {
1032 return Err(Error::<T, I>::DuplicateVote.into());
1033 }
1034 if let Some(pos) = position_yes {
1035 voting.ayes.swap_remove(pos);
1036 }
1037 }
1038
1039 let yes_votes = voting.ayes.len() as MemberCount;
1040 let no_votes = voting.nays.len() as MemberCount;
1041 Self::deposit_event(Event::Voted {
1042 account: who,
1043 proposal_hash: proposal,
1044 voted: approve,
1045 yes: yes_votes,
1046 no: no_votes,
1047 });
1048
1049 Voting::<T, I>::insert(&proposal, voting);
1050
1051 Ok(is_account_voting_first_time)
1052 }
1053
1054 pub fn do_close(
1056 proposal_hash: T::Hash,
1057 index: ProposalIndex,
1058 proposal_weight_bound: Weight,
1059 length_bound: u32,
1060 ) -> DispatchResultWithPostInfo {
1061 let voting = Voting::<T, I>::get(&proposal_hash).ok_or(Error::<T, I>::ProposalMissing)?;
1062 ensure!(voting.index == index, Error::<T, I>::WrongIndex);
1063
1064 let mut no_votes = voting.nays.len() as MemberCount;
1065 let mut yes_votes = voting.ayes.len() as MemberCount;
1066 let seats = Members::<T, I>::get().len() as MemberCount;
1067 let approved = yes_votes >= voting.threshold;
1068 let disapproved = seats.saturating_sub(no_votes) < voting.threshold;
1069 if approved {
1071 let (proposal, len) = Self::validate_and_get_proposal(
1072 &proposal_hash,
1073 length_bound,
1074 proposal_weight_bound,
1075 )?;
1076 Self::deposit_event(Event::Closed { proposal_hash, yes: yes_votes, no: no_votes });
1077 let (proposal_weight, proposal_count) =
1078 Self::do_approve_proposal(seats, yes_votes, proposal_hash, proposal);
1079 return Ok((
1080 Some(
1081 T::WeightInfo::close_early_approved(len as u32, seats, proposal_count)
1082 .saturating_add(proposal_weight),
1083 ),
1084 Pays::Yes,
1085 )
1086 .into());
1087 } else if disapproved {
1088 Self::deposit_event(Event::Closed { proposal_hash, yes: yes_votes, no: no_votes });
1089 let proposal_count = Self::do_disapprove_proposal(proposal_hash);
1090 return Ok((
1091 Some(T::WeightInfo::close_early_disapproved(seats, proposal_count)),
1092 Pays::No,
1093 )
1094 .into());
1095 }
1096
1097 ensure!(frame_system::Pallet::<T>::block_number() >= voting.end, Error::<T, I>::TooEarly);
1099
1100 let prime_vote = Prime::<T, I>::get().map(|who| voting.ayes.iter().any(|a| a == &who));
1101
1102 let default = T::DefaultVote::default_vote(prime_vote, yes_votes, no_votes, seats);
1104
1105 let abstentions = seats - (yes_votes + no_votes);
1106 match default {
1107 true => yes_votes += abstentions,
1108 false => no_votes += abstentions,
1109 }
1110 let approved = yes_votes >= voting.threshold;
1111
1112 if approved {
1113 let (proposal, len) = Self::validate_and_get_proposal(
1114 &proposal_hash,
1115 length_bound,
1116 proposal_weight_bound,
1117 )?;
1118 Self::deposit_event(Event::Closed { proposal_hash, yes: yes_votes, no: no_votes });
1119 let (proposal_weight, proposal_count) =
1120 Self::do_approve_proposal(seats, yes_votes, proposal_hash, proposal);
1121 Ok((
1122 Some(
1123 T::WeightInfo::close_approved(len as u32, seats, proposal_count)
1124 .saturating_add(proposal_weight),
1125 ),
1126 Pays::Yes,
1127 )
1128 .into())
1129 } else {
1130 Self::deposit_event(Event::Closed { proposal_hash, yes: yes_votes, no: no_votes });
1131 let proposal_count = Self::do_disapprove_proposal(proposal_hash);
1132 Ok((Some(T::WeightInfo::close_disapproved(seats, proposal_count)), Pays::No).into())
1133 }
1134 }
1135
1136 fn validate_and_get_proposal(
1141 hash: &T::Hash,
1142 length_bound: u32,
1143 weight_bound: Weight,
1144 ) -> Result<(<T as Config<I>>::Proposal, usize), DispatchError> {
1145 let key = ProposalOf::<T, I>::hashed_key_for(hash);
1146 let proposal_len =
1148 storage::read(&key, &mut [0; 0], 0).ok_or(Error::<T, I>::ProposalMissing)?;
1149 ensure!(proposal_len <= length_bound, Error::<T, I>::WrongProposalLength);
1150 let proposal = ProposalOf::<T, I>::get(hash).ok_or(Error::<T, I>::ProposalMissing)?;
1151 let proposal_weight = proposal.get_dispatch_info().call_weight;
1152 ensure!(proposal_weight.all_lte(weight_bound), Error::<T, I>::WrongProposalWeight);
1153 Ok((proposal, proposal_len as usize))
1154 }
1155
1156 fn do_approve_proposal(
1171 seats: MemberCount,
1172 yes_votes: MemberCount,
1173 proposal_hash: T::Hash,
1174 proposal: <T as Config<I>>::Proposal,
1175 ) -> (Weight, u32) {
1176 Self::deposit_event(Event::Approved { proposal_hash });
1177
1178 let dispatch_weight = proposal.get_dispatch_info().call_weight;
1179 let origin = RawOrigin::Members(yes_votes, seats).into();
1180 let result = proposal.dispatch(origin);
1181 Self::deposit_event(Event::Executed {
1182 proposal_hash,
1183 result: result.map(|_| ()).map_err(|e| e.error),
1184 });
1185 let proposal_weight = get_result_weight(result).unwrap_or(dispatch_weight); let proposal_count = Self::remove_proposal(proposal_hash);
1189 (proposal_weight, proposal_count)
1190 }
1191
1192 pub fn do_disapprove_proposal(proposal_hash: T::Hash) -> u32 {
1194 Self::deposit_event(Event::Disapproved { proposal_hash });
1196 Self::remove_proposal(proposal_hash)
1197 }
1198
1199 fn remove_proposal(proposal_hash: T::Hash) -> u32 {
1201 ProposalOf::<T, I>::remove(&proposal_hash);
1203 Voting::<T, I>::remove(&proposal_hash);
1204 let num_proposals = Proposals::<T, I>::mutate(|proposals| {
1205 proposals.retain(|h| h != &proposal_hash);
1206 proposals.len() + 1 });
1208 num_proposals as u32
1209 }
1210
1211 #[cfg(any(feature = "try-runtime", test))]
1241 fn do_try_state() -> Result<(), TryRuntimeError> {
1242 Proposals::<T, I>::get().into_iter().try_for_each(
1243 |proposal| -> Result<(), TryRuntimeError> {
1244 let call = ProposalOf::<T, I>::get(proposal).ok_or(
1245 "Proposal hash from `Proposals` is not found inside the `ProposalOf` mapping.",
1246 )?;
1247 if let Some(votes) = Voting::<T, I>::get(proposal) {
1248 ensure!(
1249 proposal == Self::proposal_hash(&call, votes.threshold),
1250 "Proposal hash is not derived from the proposal's call and threshold."
1251 );
1252 }
1253 Ok(())
1254 },
1255 )?;
1256
1257 ensure!(
1258 Proposals::<T, I>::get().into_iter().count() <= ProposalCount::<T, I>::get() as usize,
1259 "The actual number of proposals is greater than `ProposalCount`"
1260 );
1261 ensure!(
1262 Proposals::<T, I>::get().into_iter().count() == <ProposalOf<T, I>>::iter_keys().count(),
1263 "Proposal count inside `Proposals` is not equal to the proposal count in `ProposalOf`"
1264 );
1265
1266 Proposals::<T, I>::get().into_iter().try_for_each(
1267 |proposal| -> Result<(), TryRuntimeError> {
1268 if let Some(votes) = Voting::<T, I>::get(proposal) {
1269 let ayes = votes.ayes.len();
1270 let nays = votes.nays.len();
1271
1272 ensure!(
1273 ayes.saturating_add(nays) <= T::MaxMembers::get() as usize,
1274 "The sum of ayes and nays is greater than `MaxMembers`"
1275 );
1276 }
1277 Ok(())
1278 },
1279 )?;
1280
1281 let mut proposal_indices = vec![];
1282 Proposals::<T, I>::get().into_iter().try_for_each(
1283 |proposal| -> Result<(), TryRuntimeError> {
1284 if let Some(votes) = Voting::<T, I>::get(proposal) {
1285 let proposal_index = votes.index;
1286 ensure!(
1287 !proposal_indices.contains(&proposal_index),
1288 "The proposal index is not unique."
1289 );
1290 proposal_indices.push(proposal_index);
1291 }
1292 Ok(())
1293 },
1294 )?;
1295
1296 <Voting<T, I>>::iter_keys().try_for_each(
1297 |proposal_hash| -> Result<(), TryRuntimeError> {
1298 ensure!(
1299 Proposals::<T, I>::get().contains(&proposal_hash),
1300 "`Proposals` doesn't contain the proposal hash from the `Voting` storage map."
1301 );
1302 Ok(())
1303 },
1304 )?;
1305
1306 ensure!(
1307 Members::<T, I>::get().len() <= T::MaxMembers::get() as usize,
1308 "The member count is greater than `MaxMembers`."
1309 );
1310
1311 ensure!(
1312 Members::<T, I>::get().windows(2).all(|members| members[0] <= members[1]),
1313 "The members are not sorted by value."
1314 );
1315
1316 if let Some(prime) = Prime::<T, I>::get() {
1317 ensure!(Members::<T, I>::get().contains(&prime), "Prime account is not a member.");
1318 }
1319
1320 Ok(())
1321 }
1322}
1323
1324impl<T: Config<I>, I: 'static> ChangeMembers<T::AccountId> for Pallet<T, I> {
1325 fn change_members_sorted(
1336 _incoming: &[T::AccountId],
1337 outgoing: &[T::AccountId],
1338 new: &[T::AccountId],
1339 ) {
1340 if new.len() > T::MaxMembers::get() as usize {
1341 log::error!(
1342 target: LOG_TARGET,
1343 "New members count ({}) exceeds maximum amount of members expected ({}).",
1344 new.len(),
1345 T::MaxMembers::get(),
1346 );
1347 }
1348 let mut outgoing = outgoing.to_vec();
1350 outgoing.sort();
1351 for h in Proposals::<T, I>::get().into_iter() {
1352 <Voting<T, I>>::mutate(h, |v| {
1353 if let Some(mut votes) = v.take() {
1354 votes.ayes = votes
1355 .ayes
1356 .into_iter()
1357 .filter(|i| outgoing.binary_search(i).is_err())
1358 .collect();
1359 votes.nays = votes
1360 .nays
1361 .into_iter()
1362 .filter(|i| outgoing.binary_search(i).is_err())
1363 .collect();
1364 *v = Some(votes);
1365 }
1366 });
1367 }
1368 Members::<T, I>::put(new);
1369 Prime::<T, I>::kill();
1370 }
1371
1372 fn set_prime(prime: Option<T::AccountId>) {
1373 Prime::<T, I>::set(prime);
1374 }
1375
1376 fn get_prime() -> Option<T::AccountId> {
1377 Prime::<T, I>::get()
1378 }
1379}
1380
1381impl<T: Config<I>, I: 'static> InitializeMembers<T::AccountId> for Pallet<T, I> {
1382 fn initialize_members(members: &[T::AccountId]) {
1383 if !members.is_empty() {
1384 assert!(<Members<T, I>>::get().is_empty(), "Members are already initialized!");
1385 let mut members = members.to_vec();
1386 members.sort();
1387 <Members<T, I>>::put(members);
1388 }
1389 }
1390}
1391
1392pub fn ensure_members<OuterOrigin, AccountId, I>(
1395 o: OuterOrigin,
1396 n: MemberCount,
1397) -> result::Result<MemberCount, &'static str>
1398where
1399 OuterOrigin: Into<result::Result<RawOrigin<AccountId, I>, OuterOrigin>>,
1400{
1401 match o.into() {
1402 Ok(RawOrigin::Members(x, _)) if x >= n => Ok(n),
1403 _ => Err("bad origin: expected to be a threshold number of members"),
1404 }
1405}
1406
1407pub struct EnsureMember<AccountId, I: 'static>(PhantomData<(AccountId, I)>);
1408impl<O: OriginTrait + From<RawOrigin<AccountId, I>>, I, AccountId: Decode + Clone> EnsureOrigin<O>
1409 for EnsureMember<AccountId, I>
1410where
1411 for<'a> &'a O::PalletsOrigin: TryInto<&'a RawOrigin<AccountId, I>>,
1412{
1413 type Success = AccountId;
1414 fn try_origin(o: O) -> Result<Self::Success, O> {
1415 match o.caller().try_into() {
1416 Ok(RawOrigin::Member(id)) => return Ok(id.clone()),
1417 _ => (),
1418 }
1419
1420 Err(o)
1421 }
1422
1423 #[cfg(feature = "runtime-benchmarks")]
1424 fn try_successful_origin() -> Result<O, ()> {
1425 let zero_account_id =
1426 AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes())
1427 .expect("infinite length input; no invalid inputs for type; qed");
1428 Ok(O::from(RawOrigin::Member(zero_account_id)))
1429 }
1430}
1431
1432impl<O: OriginTrait + From<RawOrigin<AccountId, I>>, I, AccountId: Decode + Clone, T>
1433 EnsureOriginWithArg<O, T> for EnsureMember<AccountId, I>
1434where
1435 for<'a> &'a O::PalletsOrigin: TryInto<&'a RawOrigin<AccountId, I>>,
1436{
1437 type Success = <Self as EnsureOrigin<O>>::Success;
1438 fn try_origin(o: O, _: &T) -> Result<Self::Success, O> {
1439 <Self as EnsureOrigin<O>>::try_origin(o)
1440 }
1441 #[cfg(feature = "runtime-benchmarks")]
1442 fn try_successful_origin(_: &T) -> Result<O, ()> {
1443 <Self as EnsureOrigin<O>>::try_successful_origin()
1444 }
1445}
1446
1447pub struct EnsureMembers<AccountId, I: 'static, const N: u32>(PhantomData<(AccountId, I)>);
1448impl<O: OriginTrait + From<RawOrigin<AccountId, I>>, AccountId, I, const N: u32> EnsureOrigin<O>
1449 for EnsureMembers<AccountId, I, N>
1450where
1451 for<'a> &'a O::PalletsOrigin: TryInto<&'a RawOrigin<AccountId, I>>,
1452{
1453 type Success = (MemberCount, MemberCount);
1454 fn try_origin(o: O) -> Result<Self::Success, O> {
1455 match o.caller().try_into() {
1456 Ok(RawOrigin::Members(n, m)) if *n >= N => return Ok((*n, *m)),
1457 _ => (),
1458 }
1459
1460 Err(o)
1461 }
1462
1463 #[cfg(feature = "runtime-benchmarks")]
1464 fn try_successful_origin() -> Result<O, ()> {
1465 Ok(O::from(RawOrigin::Members(N, N)))
1466 }
1467}
1468
1469impl<O: OriginTrait + From<RawOrigin<AccountId, I>>, AccountId, I, const N: u32, T>
1470 EnsureOriginWithArg<O, T> for EnsureMembers<AccountId, I, N>
1471where
1472 for<'a> &'a O::PalletsOrigin: TryInto<&'a RawOrigin<AccountId, I>>,
1473{
1474 type Success = <Self as EnsureOrigin<O>>::Success;
1475 fn try_origin(o: O, _: &T) -> Result<Self::Success, O> {
1476 <Self as EnsureOrigin<O>>::try_origin(o)
1477 }
1478 #[cfg(feature = "runtime-benchmarks")]
1479 fn try_successful_origin(_: &T) -> Result<O, ()> {
1480 <Self as EnsureOrigin<O>>::try_successful_origin()
1481 }
1482}
1483
1484pub struct EnsureProportionMoreThan<AccountId, I: 'static, const N: u32, const D: u32>(
1485 PhantomData<(AccountId, I)>,
1486);
1487impl<O: OriginTrait + From<RawOrigin<AccountId, I>>, AccountId, I, const N: u32, const D: u32>
1488 EnsureOrigin<O> for EnsureProportionMoreThan<AccountId, I, N, D>
1489where
1490 for<'a> &'a O::PalletsOrigin: TryInto<&'a RawOrigin<AccountId, I>>,
1491{
1492 type Success = ();
1493 fn try_origin(o: O) -> Result<Self::Success, O> {
1494 match o.caller().try_into() {
1495 Ok(RawOrigin::Members(n, m)) if n * D > N * m => return Ok(()),
1496 _ => (),
1497 }
1498
1499 Err(o)
1500 }
1501
1502 #[cfg(feature = "runtime-benchmarks")]
1503 fn try_successful_origin() -> Result<O, ()> {
1504 Ok(O::from(RawOrigin::Members(1u32, 0u32)))
1505 }
1506}
1507
1508impl<
1509 O: OriginTrait + From<RawOrigin<AccountId, I>>,
1510 AccountId,
1511 I,
1512 const N: u32,
1513 const D: u32,
1514 T,
1515 > EnsureOriginWithArg<O, T> for EnsureProportionMoreThan<AccountId, I, N, D>
1516where
1517 for<'a> &'a O::PalletsOrigin: TryInto<&'a RawOrigin<AccountId, I>>,
1518{
1519 type Success = <Self as EnsureOrigin<O>>::Success;
1520 fn try_origin(o: O, _: &T) -> Result<Self::Success, O> {
1521 <Self as EnsureOrigin<O>>::try_origin(o)
1522 }
1523 #[cfg(feature = "runtime-benchmarks")]
1524 fn try_successful_origin(_: &T) -> Result<O, ()> {
1525 <Self as EnsureOrigin<O>>::try_successful_origin()
1526 }
1527}
1528
1529pub struct EnsureProportionAtLeast<AccountId, I: 'static, const N: u32, const D: u32>(
1530 PhantomData<(AccountId, I)>,
1531);
1532impl<O: OriginTrait + From<RawOrigin<AccountId, I>>, AccountId, I, const N: u32, const D: u32>
1533 EnsureOrigin<O> for EnsureProportionAtLeast<AccountId, I, N, D>
1534where
1535 for<'a> &'a O::PalletsOrigin: TryInto<&'a RawOrigin<AccountId, I>>,
1536{
1537 type Success = ();
1538 fn try_origin(o: O) -> Result<Self::Success, O> {
1539 match o.caller().try_into() {
1540 Ok(RawOrigin::Members(n, m)) if n * D >= N * m => return Ok(()),
1541 _ => (),
1542 };
1543
1544 Err(o)
1545 }
1546
1547 #[cfg(feature = "runtime-benchmarks")]
1548 fn try_successful_origin() -> Result<O, ()> {
1549 Ok(O::from(RawOrigin::Members(0u32, 0u32)))
1550 }
1551}
1552
1553impl<
1554 O: OriginTrait + From<RawOrigin<AccountId, I>>,
1555 AccountId,
1556 I,
1557 const N: u32,
1558 const D: u32,
1559 T,
1560 > EnsureOriginWithArg<O, T> for EnsureProportionAtLeast<AccountId, I, N, D>
1561where
1562 for<'a> &'a O::PalletsOrigin: TryInto<&'a RawOrigin<AccountId, I>>,
1563{
1564 type Success = <Self as EnsureOrigin<O>>::Success;
1565 fn try_origin(o: O, _: &T) -> Result<Self::Success, O> {
1566 <Self as EnsureOrigin<O>>::try_origin(o)
1567 }
1568 #[cfg(feature = "runtime-benchmarks")]
1569 fn try_successful_origin(_: &T) -> Result<O, ()> {
1570 <Self as EnsureOrigin<O>>::try_successful_origin()
1571 }
1572}