referrerpolicy=no-referrer-when-downgrade

pallet_collective/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Collective system: Members of a set of account IDs can make their collective feelings known
19//! through dispatched calls from one of two specialized origins.
20//!
21//! The membership can be provided in one of two ways: either directly, using the Root-dispatchable
22//! function `set_members`, or indirectly, through implementing the `ChangeMembers`.
23//! The pallet assumes that the amount of members stays at or below `MaxMembers` for its weight
24//! calculations, but enforces this neither in `set_members` nor in `change_members_sorted`.
25//!
26//! A "prime" member may be set to help determine the default vote behavior based on chain
27//! config. If `PrimeDefaultVote` is used, the prime vote acts as the default vote in case of any
28//! abstentions after the voting period. If `MoreThanMajorityThenPrimeDefaultVote` is used, then
29//! abstentions will first follow the majority of the collective voting, and then the prime
30//! member.
31//!
32//! Voting happens through motions comprising a proposal (i.e. a curried dispatchable) plus a
33//! number of approvals required for it to pass and be called. Motions are open for members to
34//! vote on for a minimum period given by `MotionDuration`. As soon as the needed number of
35//! approvals is given, the motion is closed and executed. If the number of approvals is not reached
36//! during the voting period, then `close` may be called by any account in order to force the end
37//! the motion explicitly. If a prime member is defined then their vote is used in place of any
38//! abstentions and the proposal is executed if there are enough approvals counting the new votes.
39//!
40//! If there are not, or if no prime is set, then the motion is dropped without being executed.
41
42#![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
84/// Simple index type for proposal counting.
85pub type ProposalIndex = u32;
86
87/// A number of members.
88///
89/// This also serves as a number of voting members, and since for motions, each member may
90/// vote exactly once, therefore also the number of votes for any given motion.
91pub type MemberCount = u32;
92
93/// Default voting strategy when a member is inactive.
94pub trait DefaultVote {
95	/// Get the default voting strategy, given:
96	///
97	/// - Whether the prime member voted Aye.
98	/// - Raw number of yes votes.
99	/// - Raw number of no votes.
100	/// - Total number of member count.
101	fn default_vote(
102		prime_vote: Option<bool>,
103		yes_votes: MemberCount,
104		no_votes: MemberCount,
105		len: MemberCount,
106	) -> bool;
107}
108
109/// Set the prime member's vote as the default vote.
110pub 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
123/// First see if yes vote are over majority of the whole collective. If so, set the default vote
124/// as yes. Otherwise, use the prime member's vote as the default vote.
125pub 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/// Origin for the collective module.
140#[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	/// It has been condoned by a given number of members of the collective from a given total.
147	Members(MemberCount, MemberCount),
148	/// It has been condoned by a single member of the collective.
149	Member(AccountId),
150	/// Dummy to manage the fact we have instancing.
151	_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/// Info for keeping track of a motion being voted on.
164#[derive(PartialEq, Eq, Clone, Encode, Decode, Debug, TypeInfo)]
165pub struct Votes<AccountId, BlockNumber> {
166	/// The proposal's unique index.
167	index: ProposalIndex,
168	/// The number of approval votes that are needed to pass the motion.
169	threshold: MemberCount,
170	/// The current set of voters that approved it.
171	ayes: Vec<AccountId>,
172	/// The current set of voters that rejected it.
173	nays: Vec<AccountId>,
174	/// The hard end time of this vote.
175	end: BlockNumber,
176}
177
178/// Types implementing various cost strategies for a given proposal count.
179///
180/// These types implement [Convert](sp_runtime::traits::Convert) trait and can be used with types
181/// like [HoldConsideration](`frame_support::traits::fungible::HoldConsideration`) implementing
182/// [Consideration](`frame_support::traits::Consideration`) trait.
183///
184/// ### Example:
185///
186/// 1. Linear increasing with helper types.
187#[doc = docify::embed!("src/tests.rs", deposit_types_with_linear_work)]
188/// 2. Geometrically increasing with helper types.
189#[doc = docify::embed!("src/tests.rs", deposit_types_with_geometric_work)]
190/// 3. Geometrically increasing with rounding.
191#[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	/// Constant deposit amount regardless of current proposal count.
198	/// Returns `None` if configured with zero deposit.
199	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	/// Linear increasing with some offset.
211	/// f(x) = ax + b, a = `Slope`, x = `proposal_count`, b = `Offset`.
212	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	/// Geometrically increasing.
226	/// f(x) = a * r^x, a = `Base`, x = `proposal_count`, r = `Ratio`.
227	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	/// Rounds a `Deposit` result with `Precision`.
242	/// Particularly useful for types like [`Geometric`] that might produce deposits with high
243	/// precision.
244	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	/// Defines `Period` for supplied `Step` implementing [`Convert`] trait.
268	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	/// Defines `Delay` for supplied `Step` implementing [`Convert`] trait.
282	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	/// Defines `Ceil` for supplied `Step` implementing [`Convert`] trait.
300	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	/// The in-code storage version.
320	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		/// The runtime origin type.
330		type RuntimeOrigin: From<RawOrigin<Self::AccountId, I>>;
331
332		/// The runtime call dispatch type.
333		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		/// The runtime event type.
341		#[allow(deprecated)]
342		type RuntimeEvent: From<Event<Self, I>>
343			+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
344
345		/// The time-out for council motions.
346		type MotionDuration: Get<BlockNumberFor<Self>>;
347
348		/// Maximum number of proposals allowed to be active in parallel.
349		type MaxProposals: Get<ProposalIndex>;
350
351		/// The maximum number of members supported by the pallet. Used for weight estimation.
352		///
353		/// NOTE:
354		/// + Benchmarks will need to be re-run and weights adjusted if this changes.
355		/// + This pallet assumes that dependents keep to the limit without enforcing it.
356		type MaxMembers: Get<MemberCount>;
357
358		/// Default vote strategy of this collective.
359		type DefaultVote: DefaultVote;
360
361		/// Weight information for extrinsics in this pallet.
362		type WeightInfo: WeightInfo;
363
364		/// Origin allowed to set collective members
365		type SetMembersOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin>;
366
367		/// The maximum weight of a dispatch call that can be proposed and executed.
368		#[pallet::constant]
369		type MaxProposalWeight: Get<Weight>;
370
371		/// Origin from which a proposal in any status may be disapproved without associated cost
372		/// for a proposer.
373		type DisapproveOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin>;
374
375		/// Origin from which any malicious proposal may be killed with associated cost for a
376		/// proposer.
377		///
378		/// The associated cost is set by [`Config::Consideration`] and can be none.
379		type KillOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin>;
380
381		/// Mechanism to assess the necessity of some cost for publishing and storing a proposal.
382		///
383		/// The footprint is defined as `proposal_count`, which reflects the total number of active
384		/// proposals in the system, excluding the one currently being proposed. The cost may vary
385		/// based on this count.
386		///
387		/// Note: If the resulting deposits are excessively high and cause benchmark failures,
388		/// consider using a constant cost (e.g., [`crate::deposit::Constant`]) equal to the minimum
389		/// balance under the `runtime-benchmarks` feature.
390		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	/// Origin for the collective pallet.
421	#[pallet::origin]
422	pub type Origin<T, I = ()> = RawOrigin<<T as frame_system::Config>::AccountId, I>;
423
424	/// The hashes of the active proposals.
425	#[pallet::storage]
426	pub type Proposals<T: Config<I>, I: 'static = ()> =
427		StorageValue<_, BoundedVec<T::Hash, T::MaxProposals>, ValueQuery>;
428
429	/// Actual proposal for a given hash, if it's current.
430	#[pallet::storage]
431	pub type ProposalOf<T: Config<I>, I: 'static = ()> =
432		StorageMap<_, Identity, T::Hash, <T as Config<I>>::Proposal, OptionQuery>;
433
434	/// Consideration cost created for publishing and storing a proposal.
435	///
436	/// Determined by [Config::Consideration] and may be not present for certain proposals (e.g. if
437	/// the proposal count at the time of creation was below threshold N).
438	#[pallet::storage]
439	pub type CostOf<T: Config<I>, I: 'static = ()> =
440		StorageMap<_, Identity, T::Hash, (T::AccountId, T::Consideration), OptionQuery>;
441
442	/// Votes on a given proposal, if it is ongoing.
443	#[pallet::storage]
444	pub type Voting<T: Config<I>, I: 'static = ()> =
445		StorageMap<_, Identity, T::Hash, Votes<T::AccountId, BlockNumberFor<T>>, OptionQuery>;
446
447	/// Proposals so far.
448	#[pallet::storage]
449	pub type ProposalCount<T: Config<I>, I: 'static = ()> = StorageValue<_, u32, ValueQuery>;
450
451	/// The current members of the collective. This is stored sorted (just by value).
452	#[pallet::storage]
453	pub type Members<T: Config<I>, I: 'static = ()> =
454		StorageValue<_, Vec<T::AccountId>, ValueQuery>;
455
456	/// The prime member that helps determine the default vote behavior in case of abstentions.
457	#[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		/// A motion (given hash) has been proposed (by given account) with a threshold (given
464		/// `MemberCount`).
465		Proposed {
466			account: T::AccountId,
467			proposal_index: ProposalIndex,
468			proposal_hash: T::Hash,
469			threshold: MemberCount,
470		},
471		/// A motion (given hash) has been voted on by given account, leaving
472		/// a tally (yes votes and no votes given respectively as `MemberCount`).
473		Voted {
474			account: T::AccountId,
475			proposal_hash: T::Hash,
476			voted: bool,
477			yes: MemberCount,
478			no: MemberCount,
479		},
480		/// A motion was approved by the required threshold.
481		Approved { proposal_hash: T::Hash },
482		/// A motion was not approved by the required threshold.
483		Disapproved { proposal_hash: T::Hash },
484		/// A motion was executed; result will be `Ok` if it returned without error.
485		Executed { proposal_hash: T::Hash, result: DispatchResult },
486		/// A single member did some action; result will be `Ok` if it returned without error.
487		MemberExecuted { proposal_hash: T::Hash, result: DispatchResult },
488		/// A proposal was closed because its threshold was reached or after its duration was up.
489		Closed { proposal_hash: T::Hash, yes: MemberCount, no: MemberCount },
490		/// A proposal was killed.
491		Killed { proposal_hash: T::Hash },
492		/// Some cost for storing a proposal was burned.
493		ProposalCostBurned { proposal_hash: T::Hash, who: T::AccountId },
494		/// Some cost for storing a proposal was released.
495		ProposalCostReleased { proposal_hash: T::Hash, who: T::AccountId },
496	}
497
498	#[pallet::error]
499	pub enum Error<T, I = ()> {
500		/// Account is not a member
501		NotMember,
502		/// A proposal with the same call and threshold is already active.
503		DuplicateProposal,
504		/// Proposal must exist
505		ProposalMissing,
506		/// Mismatched index
507		WrongIndex,
508		/// Duplicate vote ignored
509		DuplicateVote,
510		/// Members are already initialized!
511		AlreadyInitialized,
512		/// The close call was made too early, before the end of the voting.
513		TooEarly,
514		/// There can only be a maximum of `MaxProposals` active proposals.
515		TooManyProposals,
516		/// The given weight bound for the proposal was too low.
517		WrongProposalWeight,
518		/// The given length bound for the proposal was too low.
519		WrongProposalLength,
520		/// Prime account is not a member
521		PrimeAccountNotMember,
522		/// Proposal is still active.
523		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	/// A reason for the pallet placing a hold on funds.
535	#[pallet::composite_enum]
536	pub enum HoldReason<I: 'static = ()> {
537		/// Funds are held for submitting and storing a proposal.
538		#[codec(index = 0)]
539		ProposalSubmission,
540	}
541
542	// Note that councillor operations are assigned to the operational class.
543	#[pallet::call]
544	impl<T: Config<I>, I: 'static> Pallet<T, I> {
545		/// Set the collective's membership.
546		///
547		/// - `new_members`: The new member list. Be nice to the chain and provide it sorted.
548		/// - `prime`: The prime member whose vote sets the default.
549		/// - `old_count`: The upper bound for the previous number of members in storage. Used for
550		///   weight estimation.
551		///
552		/// The dispatch of this call must be `SetMembersOrigin`.
553		///
554		/// NOTE: Does not enforce the expected `MaxMembers` limit on the amount of members, but
555		///       the weight estimations rely on it to estimate dispatchable weight.
556		///
557		/// # WARNING:
558		///
559		/// The `pallet-collective` can also be managed by logic outside of the pallet through the
560		/// implementation of the trait [`ChangeMembers`].
561		/// Any call to `set_members` must be careful that the member set doesn't get out of sync
562		/// with other logic managing the member set.
563		///
564		/// ## Complexity:
565		/// - `O(MP + N)` where:
566		///   - `M` old-members-count (code- and governance-bounded)
567		///   - `N` new-members-count (code- and governance-bounded)
568		///   - `P` proposals-count (code-bounded)
569		#[pallet::call_index(0)]
570		#[pallet::weight((
571			T::WeightInfo::set_members(
572				*old_count, // M
573				new_members.len() as u32, // N
574				T::MaxProposals::get() // P
575			),
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,         // M
613				new_members.len() as u32, // N
614				T::MaxProposals::get(),   // P
615			))
616			.into())
617		}
618
619		/// Dispatch a proposal from a member using the `Member` origin.
620		///
621		/// Origin must be a member of the collective.
622		///
623		/// ## Complexity:
624		/// - `O(B + M + P)` where:
625		/// - `B` is `proposal` size in bytes (length-fee-bounded)
626		/// - `M` members-count (code-bounded)
627		/// - `P` complexity of dispatching `proposal`
628		#[pallet::call_index(1)]
629		#[pallet::weight((
630			T::WeightInfo::execute(
631				*length_bound, // B
632				T::MaxMembers::get(), // M
633			).saturating_add(proposal.get_dispatch_info().call_weight), // P
634			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,  // B
658						members.len() as u32, // M
659					)
660					.saturating_add(w) // P
661				})
662				.into())
663		}
664
665		/// Add a new proposal to either be voted on or executed directly.
666		///
667		/// Requires the sender to be member.
668		///
669		/// `threshold` determines whether `proposal` is executed directly (`threshold < 2`)
670		/// or put up for voting.
671		///
672		/// The proposal is identified by [`Pallet::proposal_hash`], which covers both the call
673		/// and the `threshold`. The threshold is fixed at submission time and is therefore part
674		/// of the proposal's identity: the same call may be under consideration with different
675		/// thresholds without colliding. With `threshold < 2` the call still fails with
676		/// `DuplicateProposal` while a motion with the same call and threshold is active; such a
677		/// motion can be opened through [`Pallet::do_propose_proposed`], e.g. by pallet-alliance.
678		///
679		/// ## Complexity
680		/// - `O(B + M + P1)` or `O(B + M + P2)` where:
681		///   - `B` is `proposal` size in bytes (length-fee-bounded)
682		///   - `M` is members-count (code- and governance-bounded)
683		///   - branching is influenced by `threshold` where:
684		///     - `P1` is proposal execution complexity (`threshold < 2`)
685		///     - `P2` is proposals-count (code-bounded) (`threshold >= 2`)
686		#[pallet::call_index(2)]
687		#[pallet::weight((
688			if *threshold < 2 {
689				T::WeightInfo::propose_execute(
690					*length_bound, // B
691					T::MaxMembers::get(), // M
692				).saturating_add(proposal.get_dispatch_info().call_weight) // P1
693			} else {
694				T::WeightInfo::propose_proposed(
695					*length_bound, // B
696					T::MaxMembers::get(), // M
697					T::MaxProposals::get(), // P2
698				)
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,  // B
720							members.len() as u32, // M
721						)
722						.saturating_add(w) // P1
723					})
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,  // B
731					members.len() as u32, // M
732					active_proposals,     // P2
733				))
734				.into())
735			}
736		}
737
738		/// Add an aye or nay vote for the sender to the given proposal.
739		///
740		/// Requires the sender to be a member.
741		///
742		/// Transaction fees will be waived if the member is voting on any particular proposal
743		/// for the first time and the call is successful. Subsequent vote changes will charge a
744		/// fee.
745		/// ## Complexity
746		/// - `O(M)` where `M` is members-count (code- and governance-bounded)
747		#[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			// Detects first vote of the member in the motion
760			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		// Index 4 was `close_old_weight`; it was removed due to weights v1 deprecation.
770
771		/// Disapprove a proposal, close, and remove it from the system, regardless of its current
772		/// state.
773		///
774		/// Must be called by the Root origin.
775		///
776		/// Parameters:
777		/// * `proposal_hash`: The hash of the proposal that should be disapproved.
778		///
779		/// ## Complexity
780		/// O(P) where P is the number of max proposals
781		#[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		/// Close a vote that is either approved, disapproved or whose voting period has ended.
793		///
794		/// May be called by any signed account in order to finish voting and close the proposal.
795		///
796		/// If called before the end of the voting period it will only close the vote if it is
797		/// has enough votes to be approved or disapproved.
798		///
799		/// If called after the end of the voting period abstentions are counted as rejections
800		/// unless there is a prime member set and the prime member cast an approval.
801		///
802		/// If the close operation completes successfully with disapproval, the transaction fee will
803		/// be waived. Otherwise execution of the approved operation will be charged to the caller.
804		///
805		/// + `proposal_weight_bound`: The maximum amount of weight consumed by executing the closed
806		/// proposal.
807		/// + `length_bound`: The upper bound for the length of the proposal in storage. Checked via
808		/// `storage::read` so it is `size_of::<u32>() == 4` larger than the pure length.
809		///
810		/// ## Complexity
811		/// - `O(B + M + P1 + P2)` where:
812		///   - `B` is `proposal` size in bytes (length-fee-bounded)
813		///   - `M` is members-count (code- and governance-bounded)
814		///   - `P1` is the complexity of `proposal` preimage.
815		///   - `P2` is proposal-count (code-bounded)
816		#[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		/// Disapprove the proposal and burn the cost held for storing this proposal.
844		///
845		/// Parameters:
846		/// - `origin`: must be the `KillOrigin`.
847		/// - `proposal_hash`: The hash of the proposal that should be killed.
848		///
849		/// Emits `Killed` and `ProposalCostBurned` if any cost was held for a given proposal.
850		#[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		/// Release the cost held for storing a proposal once the given proposal is completed.
873		///
874		/// If there is no associated cost for the given proposal, this call will have no effect.
875		///
876		/// Parameters:
877		/// - `origin`: must be `Signed` or `Root`.
878		/// - `proposal_hash`: The hash of the proposal.
879		///
880		/// Emits `ProposalCostReleased` if any cost held for a given proposal.
881		#[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
902/// Return the weight of a dispatch call result as an `Option`.
903///
904/// Will return the weight regardless of what the state of the result is.
905fn 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	/// Check whether `who` is a member of the collective.
914	pub fn is_member(who: &T::AccountId) -> bool {
915		// Note: The dispatchables *do not* use this to check membership so make sure
916		// to update those if this is changed.
917		Members::<T, I>::get().contains(who)
918	}
919
920	/// Hash identifying a proposal submitted via [`Pallet::propose`]: the hash of the SCALE
921	/// encoding of `(proposal, threshold)`.
922	pub fn proposal_hash(proposal: &<T as Config<I>>::Proposal, threshold: MemberCount) -> T::Hash {
923		T::Hashing::hash_of(&(proposal, threshold))
924	}
925
926	/// Execute immediately when adding a new proposal.
927	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		// A `ProposalProvider` (e.g. pallet-alliance) can store a motion with `threshold < 2`
942		// through `do_propose_proposed`, so the same identity may still be live here.
943		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	/// Add a new proposal to be voted.
955	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	/// Add an aye or nay vote for the member to the given proposal, returns true if it's the first
1003	/// vote of the member in the motion
1004	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		// Detects first vote of the member in the motion
1017		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	/// Close a vote that is either approved, disapproved or whose voting period has ended.
1055	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		// Allow (dis-)approving the proposal as soon as there are enough votes.
1070		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		// Only allow actual closing of the proposal after the voting period has ended.
1098		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		// default voting strategy.
1103		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	/// Ensure that the right proposal bounds were passed and get the proposal from storage.
1137	///
1138	/// Checks the length in storage via `storage::read` which adds an extra `size_of::<u32>() == 4`
1139	/// to the length.
1140	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		// read the length of the proposal storage entry directly
1147		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	/// Weight:
1157	/// If `approved`:
1158	/// - the weight of `proposal` preimage.
1159	/// - two events deposited.
1160	/// - two removals, one mutation.
1161	/// - computation and i/o `O(P + L)` where:
1162	///   - `P` is number of active proposals,
1163	///   - `L` is the encoded length of `proposal` preimage.
1164	///
1165	/// If not `approved`:
1166	/// - one event deposited.
1167	/// Two removals, one mutation.
1168	/// Computation and i/o `O(P)` where:
1169	/// - `P` is number of active proposals
1170	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		// default to the dispatch info weight for safety
1186		let proposal_weight = get_result_weight(result).unwrap_or(dispatch_weight); // P1
1187
1188		let proposal_count = Self::remove_proposal(proposal_hash);
1189		(proposal_weight, proposal_count)
1190	}
1191
1192	/// Removes a proposal from the pallet, and deposit the `Disapproved` event.
1193	pub fn do_disapprove_proposal(proposal_hash: T::Hash) -> u32 {
1194		// disapproved
1195		Self::deposit_event(Event::Disapproved { proposal_hash });
1196		Self::remove_proposal(proposal_hash)
1197	}
1198
1199	// Removes a proposal from the pallet, cleaning up votes and the vector of proposals.
1200	fn remove_proposal(proposal_hash: T::Hash) -> u32 {
1201		// remove proposal and vote
1202		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 // calculate weight based on original length
1207		});
1208		num_proposals as u32
1209	}
1210
1211	/// Ensure the correctness of the state of this pallet.
1212	///
1213	/// The following expectation must always apply.
1214	///
1215	/// ## Expectations:
1216	///
1217	/// Looking at proposals:
1218	///
1219	/// * Each hash of a proposal that is stored inside `Proposals` must have a
1220	/// call mapped to it inside the `ProposalOf` storage map.
1221	/// * `ProposalCount` must always be more or equal to the number of
1222	/// proposals inside the `Proposals` storage value. The reason why
1223	/// `ProposalCount` can be more is because when a proposal is removed the
1224	/// count is not deducted.
1225	/// * Count of `ProposalOf` should match the count of `Proposals`
1226	/// * Every proposal hash must equal `proposal_hash(call, threshold)` of its stored entries.
1227	///
1228	/// Looking at votes:
1229	/// * The sum of aye and nay votes for a proposal can never exceed
1230	///  `MaxMembers`.
1231	/// * The proposal index inside the `Voting` storage map must be unique.
1232	/// * All proposal hashes inside `Voting` must exist in `Proposals`.
1233	///
1234	/// Looking at members:
1235	/// * The members count must never exceed `MaxMembers`.
1236	/// * All the members must be sorted by value.
1237	///
1238	/// Looking at prime account:
1239	/// * The prime account must be a member of the collective.
1240	#[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	/// Update the members of the collective. Votes are updated and the prime is reset.
1326	///
1327	/// NOTE: Does not enforce the expected `MaxMembers` limit on the amount of members, but
1328	///       the weight estimations rely on it to estimate dispatchable weight.
1329	///
1330	/// ## Complexity
1331	/// - `O(MP + N)`
1332	///   - where `M` old-members-count (governance-bounded)
1333	///   - where `N` new-members-count (governance-bounded)
1334	///   - where `P` proposals-count
1335	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		// remove accounts from all current voting in motions.
1349		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
1392/// Ensure that the origin `o` represents at least `n` members. Returns `Ok` or an `Err`
1393/// otherwise.
1394pub 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}