From 666f39b8a22108f57732215de006518738034ba2 Mon Sep 17 00:00:00 2001 From: Qinxuan Chen Date: Fri, 25 Mar 2022 00:36:58 +0800 Subject: [PATCH] pallet-referenda: make the pallet instanceable (#11089) Signed-off-by: koushiro --- frame/referenda/src/branch.rs | 14 +- frame/referenda/src/lib.rs | 244 ++++++++++++++++++---------------- frame/referenda/src/types.rs | 43 +++--- 3 files changed, 160 insertions(+), 141 deletions(-) diff --git a/frame/referenda/src/branch.rs b/frame/referenda/src/branch.rs index 6a4efa31e15e2..f381f5fe5b709 100644 --- a/frame/referenda/src/branch.rs +++ b/frame/referenda/src/branch.rs @@ -59,7 +59,7 @@ impl From for ServiceBranch { impl ServiceBranch { /// Return the weight of the `nudge` function when it takes the branch denoted by `self`. - pub fn weight_of_nudge(self) -> frame_support::weights::Weight { + pub fn weight_of_nudge, I: 'static>(self) -> frame_support::weights::Weight { use ServiceBranch::*; match self { NoDeposit => T::WeightInfo::nudge_referendum_no_deposit(), @@ -81,7 +81,7 @@ impl ServiceBranch { } /// Return the maximum possible weight of the `nudge` function. - pub fn max_weight_of_nudge() -> frame_support::weights::Weight { + pub fn max_weight_of_nudge, I: 'static>() -> frame_support::weights::Weight { 0.max(T::WeightInfo::nudge_referendum_no_deposit()) .max(T::WeightInfo::nudge_referendum_preparing()) .max(T::WeightInfo::nudge_referendum_queued()) @@ -101,7 +101,9 @@ impl ServiceBranch { /// Return the weight of the `place_decision_deposit` function when it takes the branch denoted /// by `self`. - pub fn weight_of_deposit(self) -> Option { + pub fn weight_of_deposit, I: 'static>( + self, + ) -> Option { use ServiceBranch::*; Some(match self { Preparing => T::WeightInfo::place_decision_deposit_preparing(), @@ -124,7 +126,7 @@ impl ServiceBranch { } /// Return the maximum possible weight of the `place_decision_deposit` function. - pub fn max_weight_of_deposit() -> frame_support::weights::Weight { + pub fn max_weight_of_deposit, I: 'static>() -> frame_support::weights::Weight { 0.max(T::WeightInfo::place_decision_deposit_preparing()) .max(T::WeightInfo::place_decision_deposit_queued()) .max(T::WeightInfo::place_decision_deposit_not_queued()) @@ -154,7 +156,7 @@ impl From for OneFewerDecidingBranch { impl OneFewerDecidingBranch { /// Return the weight of the `one_fewer_deciding` function when it takes the branch denoted /// by `self`. - pub fn weight(self) -> frame_support::weights::Weight { + pub fn weight, I: 'static>(self) -> frame_support::weights::Weight { use OneFewerDecidingBranch::*; match self { QueueEmpty => T::WeightInfo::one_fewer_deciding_queue_empty(), @@ -164,7 +166,7 @@ impl OneFewerDecidingBranch { } /// Return the maximum possible weight of the `one_fewer_deciding` function. - pub fn max_weight() -> frame_support::weights::Weight { + pub fn max_weight, I: 'static>() -> frame_support::weights::Weight { 0.max(T::WeightInfo::one_fewer_deciding_queue_empty()) .max(T::WeightInfo::one_fewer_deciding_passing()) .max(T::WeightInfo::one_fewer_deciding_failing()) diff --git a/frame/referenda/src/lib.rs b/frame/referenda/src/lib.rs index fb19d2b9ed248..067775fd336d0 100644 --- a/frame/referenda/src/lib.rs +++ b/frame/referenda/src/lib.rs @@ -83,15 +83,18 @@ use sp_std::{fmt::Debug, prelude::*}; mod branch; mod types; pub mod weights; -use branch::{BeginDecidingBranch, OneFewerDecidingBranch, ServiceBranch}; -pub use pallet::*; -pub use types::{ - BalanceOf, CallOf, Curve, DecidingStatus, DecidingStatusOf, Deposit, InsertSorted, - NegativeImbalanceOf, PalletsOriginOf, ReferendumIndex, ReferendumInfo, ReferendumInfoOf, - ReferendumStatus, ReferendumStatusOf, ScheduleAddressOf, TallyOf, TrackIdOf, TrackInfo, - TrackInfoOf, TracksInfo, VotesOf, + +use self::branch::{BeginDecidingBranch, OneFewerDecidingBranch, ServiceBranch}; +pub use self::{ + pallet::*, + types::{ + BalanceOf, CallOf, Curve, DecidingStatus, DecidingStatusOf, Deposit, InsertSorted, + NegativeImbalanceOf, PalletsOriginOf, ReferendumIndex, ReferendumInfo, ReferendumInfoOf, + ReferendumStatus, ReferendumStatusOf, ScheduleAddressOf, TallyOf, TrackIdOf, TrackInfo, + TrackInfoOf, TracksInfo, VotesOf, + }, + weights::WeightInfo, }; -pub use weights::WeightInfo; #[cfg(test)] mod mock; @@ -106,25 +109,33 @@ const ASSEMBLY_ID: LockIdentifier = *b"assembly"; #[frame_support::pallet] pub mod pallet { use super::*; - use frame_support::{pallet_prelude::*, traits::EnsureOrigin, Parameter}; + use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; - use sp_runtime::DispatchResult; #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] #[pallet::without_storage_info] - pub struct Pallet(_); + pub struct Pallet(_); #[pallet::config] - pub trait Config: frame_system::Config + Sized { + pub trait Config: frame_system::Config + Sized { // System level stuff. - type Call: Parameter + Dispatchable + From>; - type Event: From> + IsType<::Event>; + type Call: Parameter + Dispatchable + From>; + type Event: From> + IsType<::Event>; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; /// The Scheduler. - type Scheduler: ScheduleAnon, PalletsOriginOf, Hash = Self::Hash> - + ScheduleNamed, PalletsOriginOf, Hash = Self::Hash>; + type Scheduler: ScheduleAnon< + Self::BlockNumber, + CallOf, + PalletsOriginOf, + Hash = Self::Hash, + > + ScheduleNamed< + Self::BlockNumber, + CallOf, + PalletsOriginOf, + Hash = Self::Hash, + >; /// Currency type for this pallet. type Currency: ReservableCurrency; // Origins and unbalances. @@ -133,7 +144,7 @@ pub mod pallet { /// Origin from which any vote may be killed. type KillOrigin: EnsureOrigin; /// Handler for the unbalanced reduction when slashing a preimage deposit. - type Slash: OnUnbalanced>; + type Slash: OnUnbalanced>; /// The counting type for votes. Usually just balance. type Votes: AtLeast32BitUnsigned + Copy + Parameter + Member; /// The tallying type. @@ -142,7 +153,7 @@ pub mod pallet { // Constants /// The minimum amount to be used as a deposit for a public referendum proposal. #[pallet::constant] - type SubmissionDeposit: Get>; + type SubmissionDeposit: Get>; /// Maximum size of the referendum queue for a single track. #[pallet::constant] @@ -162,7 +173,7 @@ pub mod pallet { // The other stuff. /// Information concerning the different referendum tracks. type Tracks: TracksInfo< - BalanceOf, + BalanceOf, Self::BlockNumber, Origin = ::PalletsOrigin, >; @@ -170,39 +181,40 @@ pub mod pallet { /// The next free referendum index, aka the number of referenda started so far. #[pallet::storage] - pub type ReferendumCount = StorageValue<_, ReferendumIndex, ValueQuery>; + pub type ReferendumCount = StorageValue<_, ReferendumIndex, ValueQuery>; /// Information concerning any given referendum. #[pallet::storage] - pub type ReferendumInfoFor = - StorageMap<_, Blake2_128Concat, ReferendumIndex, ReferendumInfoOf>; + pub type ReferendumInfoFor, I: 'static = ()> = + StorageMap<_, Blake2_128Concat, ReferendumIndex, ReferendumInfoOf>; /// The sorted list of referenda ready to be decided but not yet being decided, ordered by /// conviction-weighted approvals. /// /// This should be empty if `DecidingCount` is less than `TrackInfo::max_deciding`. #[pallet::storage] - pub type TrackQueue = StorageMap< + pub type TrackQueue, I: 'static = ()> = StorageMap< _, Twox64Concat, - TrackIdOf, + TrackIdOf, BoundedVec<(ReferendumIndex, T::Votes), T::MaxQueued>, ValueQuery, >; /// The number of referenda being decided currently. #[pallet::storage] - pub type DecidingCount = StorageMap<_, Twox64Concat, TrackIdOf, u32, ValueQuery>; + pub type DecidingCount, I: 'static = ()> = + StorageMap<_, Twox64Concat, TrackIdOf, u32, ValueQuery>; #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event { + pub enum Event, I: 'static = ()> { /// A referendum has being submitted. Submitted { /// Index of the referendum. index: ReferendumIndex, /// The track (and by extension proposal dispatch origin) of this referendum. - track: TrackIdOf, + track: TrackIdOf, /// The hash of the proposal up for referendum. proposal_hash: T::Hash, }, @@ -213,7 +225,7 @@ pub mod pallet { /// The account who placed the deposit. who: T::AccountId, /// The amount placed by the account. - amount: BalanceOf, + amount: BalanceOf, }, /// The decision deposit has been refunded. DecisionDepositRefunded { @@ -222,21 +234,21 @@ pub mod pallet { /// The account who placed the deposit. who: T::AccountId, /// The amount placed by the account. - amount: BalanceOf, + amount: BalanceOf, }, /// A deposit has been slashaed. DepositSlashed { /// The account who placed the deposit. who: T::AccountId, /// The amount placed by the account. - amount: BalanceOf, + amount: BalanceOf, }, /// A referendum has moved into the deciding phase. DecisionStarted { /// Index of the referendum. index: ReferendumIndex, /// The track (and by extension proposal dispatch origin) of this referendum. - track: TrackIdOf, + track: TrackIdOf, /// The hash of the proposal up for referendum. proposal_hash: T::Hash, /// The current tally of votes in this referendum. @@ -293,7 +305,7 @@ pub mod pallet { } #[pallet::error] - pub enum Error { + pub enum Error { /// Referendum is not ongoing. NotOngoing, /// Referendum's decision deposit is already paid. @@ -319,7 +331,7 @@ pub mod pallet { } #[pallet::call] - impl Pallet { + impl, I: 'static> Pallet { /// Propose a referendum on a privileged action. /// /// - `origin`: must be `Signed` and the account must have `SubmissionDeposit` funds @@ -338,9 +350,10 @@ pub mod pallet { ) -> DispatchResult { let who = ensure_signed(origin)?; - let track = T::Tracks::track_for(&proposal_origin).map_err(|_| Error::::NoTrack)?; + let track = + T::Tracks::track_for(&proposal_origin).map_err(|_| Error::::NoTrack)?; let submission_deposit = Self::take_deposit(who, T::SubmissionDeposit::get())?; - let index = ReferendumCount::::mutate(|x| { + let index = ReferendumCount::::mutate(|x| { let r = *x; *x += 1; r @@ -360,9 +373,9 @@ pub mod pallet { in_queue: false, alarm: Self::set_alarm(nudge_call, now.saturating_add(T::UndecidingTimeout::get())), }; - ReferendumInfoFor::::insert(index, ReferendumInfo::Ongoing(status)); + ReferendumInfoFor::::insert(index, ReferendumInfo::Ongoing(status)); - Self::deposit_event(Event::::Submitted { index, track, proposal_hash }); + Self::deposit_event(Event::::Submitted { index, track, proposal_hash }); Ok(()) } @@ -374,24 +387,24 @@ pub mod pallet { /// posted. /// /// Emits `DecisionDepositPlaced`. - #[pallet::weight(ServiceBranch::max_weight_of_deposit::())] + #[pallet::weight(ServiceBranch::max_weight_of_deposit::())] pub fn place_decision_deposit( origin: OriginFor, index: ReferendumIndex, ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; let mut status = Self::ensure_ongoing(index)?; - ensure!(status.decision_deposit.is_none(), Error::::HasDeposit); - let track = Self::track(status.track).ok_or(Error::::NoTrack)?; + ensure!(status.decision_deposit.is_none(), Error::::HasDeposit); + let track = Self::track(status.track).ok_or(Error::::NoTrack)?; status.decision_deposit = Some(Self::take_deposit(who.clone(), track.decision_deposit)?); let now = frame_system::Pallet::::block_number(); let (info, _, branch) = Self::service_referendum(now, index, status); - ReferendumInfoFor::::insert(index, info); + ReferendumInfoFor::::insert(index, info); let e = - Event::::DecisionDepositPlaced { index, who, amount: track.decision_deposit }; + Event::::DecisionDepositPlaced { index, who, amount: track.decision_deposit }; Self::deposit_event(e); - Ok(branch.weight_of_deposit::().into()) + Ok(branch.weight_of_deposit::().into()) } /// Refund the Decision Deposit for a closed referendum back to the depositor. @@ -407,14 +420,15 @@ pub mod pallet { index: ReferendumIndex, ) -> DispatchResult { ensure_signed_or_root(origin)?; - let mut info = ReferendumInfoFor::::get(index).ok_or(Error::::BadReferendum)?; + let mut info = + ReferendumInfoFor::::get(index).ok_or(Error::::BadReferendum)?; let deposit = info .take_decision_deposit() - .map_err(|_| Error::::Unfinished)? - .ok_or(Error::::NoDeposit)?; + .map_err(|_| Error::::Unfinished)? + .ok_or(Error::::NoDeposit)?; Self::refund_deposit(Some(deposit.clone())); - ReferendumInfoFor::::insert(index, info); - let e = Event::::DecisionDepositRefunded { + ReferendumInfoFor::::insert(index, info); + let e = Event::::DecisionDepositRefunded { index, who: deposit.who, amount: deposit.amount, @@ -437,13 +451,13 @@ pub mod pallet { let _ = T::Scheduler::cancel(last_alarm); } Self::note_one_fewer_deciding(status.track); - Self::deposit_event(Event::::Cancelled { index, tally: status.tally }); + Self::deposit_event(Event::::Cancelled { index, tally: status.tally }); let info = ReferendumInfo::Cancelled( frame_system::Pallet::::block_number(), status.submission_deposit, status.decision_deposit, ); - ReferendumInfoFor::::insert(index, info); + ReferendumInfoFor::::insert(index, info); Ok(()) } @@ -461,11 +475,11 @@ pub mod pallet { let _ = T::Scheduler::cancel(last_alarm); } Self::note_one_fewer_deciding(status.track); - Self::deposit_event(Event::::Killed { index, tally: status.tally }); + Self::deposit_event(Event::::Killed { index, tally: status.tally }); Self::slash_deposit(Some(status.submission_deposit.clone())); Self::slash_deposit(status.decision_deposit.clone()); let info = ReferendumInfo::Killed(frame_system::Pallet::::block_number()); - ReferendumInfoFor::::insert(index, info); + ReferendumInfoFor::::insert(index, info); Ok(()) } @@ -473,7 +487,7 @@ pub mod pallet { /// /// - `origin`: must be `Root`. /// - `index`: the referendum to be advanced. - #[pallet::weight(ServiceBranch::max_weight_of_nudge::())] + #[pallet::weight(ServiceBranch::max_weight_of_nudge::())] pub fn nudge_referendum( origin: OriginFor, index: ReferendumIndex, @@ -485,9 +499,9 @@ pub mod pallet { status.alarm = None; let (info, dirty, branch) = Self::service_referendum(now, index, status); if dirty { - ReferendumInfoFor::::insert(index, info); + ReferendumInfoFor::::insert(index, info); } - Ok(Some(branch.weight_of_nudge::()).into()) + Ok(Some(branch.weight_of_nudge::()).into()) } /// Advance a track onto its next logical state. Only used internally. @@ -499,14 +513,14 @@ pub mod pallet { /// `DecidingCount` is not yet updated. This means that we should either: /// - begin deciding another referendum (and leave `DecidingCount` alone); or /// - decrement `DecidingCount`. - #[pallet::weight(OneFewerDecidingBranch::max_weight::())] + #[pallet::weight(OneFewerDecidingBranch::max_weight::())] pub fn one_fewer_deciding( origin: OriginFor, - track: TrackIdOf, + track: TrackIdOf, ) -> DispatchResultWithPostInfo { ensure_root(origin)?; - let track_info = T::Tracks::info(track).ok_or(Error::::BadTrack)?; - let mut track_queue = TrackQueue::::get(track); + let track_info = T::Tracks::info(track).ok_or(Error::::BadTrack)?; + let mut track_queue = TrackQueue::::get(track); let branch = if let Some((index, mut status)) = Self::next_for_deciding(&mut track_queue) { let now = frame_system::Pallet::::block_number(); @@ -515,23 +529,23 @@ pub mod pallet { if let Some(set_alarm) = maybe_alarm { Self::ensure_alarm_at(&mut status, index, set_alarm); } - ReferendumInfoFor::::insert(index, ReferendumInfo::Ongoing(status)); - TrackQueue::::insert(track, track_queue); + ReferendumInfoFor::::insert(index, ReferendumInfo::Ongoing(status)); + TrackQueue::::insert(track, track_queue); branch.into() } else { - DecidingCount::::mutate(track, |x| x.saturating_dec()); + DecidingCount::::mutate(track, |x| x.saturating_dec()); OneFewerDecidingBranch::QueueEmpty }; - Ok(Some(branch.weight::()).into()) + Ok(Some(branch.weight::()).into()) } } } -impl Polling for Pallet { +impl, I: 'static> Polling for Pallet { type Index = ReferendumIndex; - type Votes = VotesOf; + type Votes = VotesOf; type Moment = T::BlockNumber; - type Class = TrackIdOf; + type Class = TrackIdOf; fn classes() -> Vec { T::Tracks::tracks().iter().map(|x| x.0).collect() @@ -539,14 +553,14 @@ impl Polling for Pallet { fn access_poll( index: Self::Index, - f: impl FnOnce(PollStatus<&mut T::Tally, T::BlockNumber, TrackIdOf>) -> R, + f: impl FnOnce(PollStatus<&mut T::Tally, T::BlockNumber, TrackIdOf>) -> R, ) -> R { - match ReferendumInfoFor::::get(index) { + match ReferendumInfoFor::::get(index) { Some(ReferendumInfo::Ongoing(mut status)) => { let result = f(PollStatus::Ongoing(&mut status.tally, status.track)); let now = frame_system::Pallet::::block_number(); Self::ensure_alarm_at(&mut status, index, now + One::one()); - ReferendumInfoFor::::insert(index, ReferendumInfo::Ongoing(status)); + ReferendumInfoFor::::insert(index, ReferendumInfo::Ongoing(status)); result }, Some(ReferendumInfo::Approved(end, ..)) => f(PollStatus::Completed(end, true)), @@ -558,15 +572,15 @@ impl Polling for Pallet { fn try_access_poll( index: Self::Index, f: impl FnOnce( - PollStatus<&mut T::Tally, T::BlockNumber, TrackIdOf>, + PollStatus<&mut T::Tally, T::BlockNumber, TrackIdOf>, ) -> Result, ) -> Result { - match ReferendumInfoFor::::get(index) { + match ReferendumInfoFor::::get(index) { Some(ReferendumInfo::Ongoing(mut status)) => { let result = f(PollStatus::Ongoing(&mut status.tally, status.track))?; let now = frame_system::Pallet::::block_number(); Self::ensure_alarm_at(&mut status, index, now + One::one()); - ReferendumInfoFor::::insert(index, ReferendumInfo::Ongoing(status)); + ReferendumInfoFor::::insert(index, ReferendumInfo::Ongoing(status)); Ok(result) }, Some(ReferendumInfo::Approved(end, ..)) => f(PollStatus::Completed(end, true)), @@ -575,13 +589,13 @@ impl Polling for Pallet { } } - fn as_ongoing(index: Self::Index) -> Option<(T::Tally, TrackIdOf)> { + fn as_ongoing(index: Self::Index) -> Option<(T::Tally, TrackIdOf)> { Self::ensure_ongoing(index).ok().map(|x| (x.tally, x.track)) } #[cfg(feature = "runtime-benchmarks")] fn create_ongoing(class: Self::Class) -> Result { - let index = ReferendumCount::::mutate(|x| { + let index = ReferendumCount::::mutate(|x| { let r = *x; *x += 1; r @@ -590,7 +604,7 @@ impl Polling for Pallet { let dummy_account_id = codec::Decode::decode(&mut sp_runtime::traits::TrailingZeroInput::new(&b"dummy"[..])) .expect("infinite length input; no invalid inputs for type; qed"); - let mut status = ReferendumStatusOf:: { + let mut status = ReferendumStatusOf:: { track: class, origin: frame_support::dispatch::RawOrigin::Root.into(), proposal_hash: ::hash_of(&index), @@ -604,7 +618,7 @@ impl Polling for Pallet { alarm: None, }; Self::ensure_alarm_at(&mut status, index, sp_runtime::traits::Bounded::max_value()); - ReferendumInfoFor::::insert(index, ReferendumInfo::Ongoing(status)); + ReferendumInfoFor::::insert(index, ReferendumInfo::Ongoing(status)); Ok(index) } @@ -619,7 +633,7 @@ impl Polling for Pallet { } else { ReferendumInfo::Rejected(now, status.submission_deposit, status.decision_deposit) }; - ReferendumInfoFor::::insert(index, info); + ReferendumInfoFor::::insert(index, info); Ok(()) } @@ -633,20 +647,22 @@ impl Polling for Pallet { } } -impl Pallet { +impl, I: 'static> Pallet { /// Check that referendum `index` is in the `Ongoing` state and return the `ReferendumStatus` /// value, or `Err` otherwise. - pub fn ensure_ongoing(index: ReferendumIndex) -> Result, DispatchError> { - match ReferendumInfoFor::::get(index) { + pub fn ensure_ongoing( + index: ReferendumIndex, + ) -> Result, DispatchError> { + match ReferendumInfoFor::::get(index) { Some(ReferendumInfo::Ongoing(status)) => Ok(status), - _ => Err(Error::::NotOngoing.into()), + _ => Err(Error::::NotOngoing.into()), } } // Enqueue a proposal from a referendum which has presumably passed. fn schedule_enactment( index: ReferendumIndex, - track: &TrackInfoOf, + track: &TrackInfoOf, desired: DispatchTime, origin: PalletsOriginOf, call_hash: T::Hash, @@ -668,9 +684,9 @@ impl Pallet { /// Set an alarm to dispatch `call` at block number `when`. fn set_alarm( - call: impl Into>, + call: impl Into>, when: T::BlockNumber, - ) -> Option<(T::BlockNumber, ScheduleAddressOf)> { + ) -> Option<(T::BlockNumber, ScheduleAddressOf)> { let alarm_interval = T::AlarmInterval::get().max(One::one()); let when = (when + alarm_interval - One::one()) / alarm_interval * alarm_interval; let maybe_result = T::Scheduler::schedule( @@ -698,10 +714,10 @@ impl Pallet { /// /// This will properly set up the `confirming` item. fn begin_deciding( - status: &mut ReferendumStatusOf, + status: &mut ReferendumStatusOf, index: ReferendumIndex, now: T::BlockNumber, - track: &TrackInfoOf, + track: &TrackInfoOf, ) -> (Option, BeginDecidingBranch) { let is_passing = Self::is_passing( &status.tally, @@ -711,14 +727,14 @@ impl Pallet { &track.min_approval, ); status.in_queue = false; - Self::deposit_event(Event::::DecisionStarted { + Self::deposit_event(Event::::DecisionStarted { index, tally: status.tally.clone(), proposal_hash: status.proposal_hash.clone(), track: status.track.clone(), }); let confirming = if is_passing { - Self::deposit_event(Event::::ConfirmStarted { index }); + Self::deposit_event(Event::::ConfirmStarted { index }); Some(now.saturating_add(track.confirm_period)) } else { None @@ -737,21 +753,21 @@ impl Pallet { /// If `None`, then it is queued and should be nudged automatically as the queue gets drained. fn ready_for_deciding( now: T::BlockNumber, - track: &TrackInfoOf, + track: &TrackInfoOf, index: ReferendumIndex, - status: &mut ReferendumStatusOf, + status: &mut ReferendumStatusOf, ) -> (Option, ServiceBranch) { - let deciding_count = DecidingCount::::get(status.track); + let deciding_count = DecidingCount::::get(status.track); if deciding_count < track.max_deciding { // Begin deciding. - DecidingCount::::insert(status.track, deciding_count.saturating_add(1)); + DecidingCount::::insert(status.track, deciding_count.saturating_add(1)); let r = Self::begin_deciding(status, index, now, track); (r.0, r.1.into()) } else { // Add to queue. let item = (index, status.tally.ayes()); status.in_queue = true; - TrackQueue::::mutate(status.track, |q| q.insert_sorted_by_key(item, |x| x.1)); + TrackQueue::::mutate(status.track, |q| q.insert_sorted_by_key(item, |x| x.1)); (None, ServiceBranch::Queued) } } @@ -759,8 +775,8 @@ impl Pallet { /// Grab the index and status for the referendum which is the highest priority of those for the /// given track which are ready for being decided. fn next_for_deciding( - track_queue: &mut BoundedVec<(u32, VotesOf), T::MaxQueued>, - ) -> Option<(ReferendumIndex, ReferendumStatusOf)> { + track_queue: &mut BoundedVec<(u32, VotesOf), T::MaxQueued>, + ) -> Option<(ReferendumIndex, ReferendumStatusOf)> { loop { let (index, _) = track_queue.pop()?; match Self::ensure_ongoing(index) { @@ -773,7 +789,7 @@ impl Pallet { /// Schedule a call to `one_fewer_deciding` function via the dispatchable /// `defer_one_fewer_deciding`. We could theoretically call it immediately (and it would be /// overall more efficient), however the weights become rather less easy to measure. - fn note_one_fewer_deciding(track: TrackIdOf) { + fn note_one_fewer_deciding(track: TrackIdOf) { // Set an alarm call for the next block to nudge the track along. let now = frame_system::Pallet::::block_number(); let next_block = now + One::one(); @@ -801,7 +817,7 @@ impl Pallet { /// /// Returns `false` if nothing changed. fn ensure_alarm_at( - status: &mut ReferendumStatusOf, + status: &mut ReferendumStatusOf, index: ReferendumIndex, alarm: T::BlockNumber, ) -> bool { @@ -839,8 +855,8 @@ impl Pallet { fn service_referendum( now: T::BlockNumber, index: ReferendumIndex, - mut status: ReferendumStatusOf, - ) -> (ReferendumInfoOf, bool, ServiceBranch) { + mut status: ReferendumStatusOf, + ) -> (ReferendumInfoOf, bool, ServiceBranch) { let mut dirty = false; // Should it begin being decided? let track = match Self::track(status.track) { @@ -857,7 +873,7 @@ impl Pallet { if status.in_queue { // Does our position in the queue need updating? let ayes = status.tally.ayes(); - let mut queue = TrackQueue::::get(status.track); + let mut queue = TrackQueue::::get(status.track); let maybe_old_pos = queue.iter().position(|(x, _)| *x == index); let new_pos = queue.binary_search_by_key(&ayes, |x| x.1).unwrap_or_else(|x| x); branch = if maybe_old_pos.is_none() && new_pos > 0 { @@ -872,7 +888,7 @@ impl Pallet { } else { ServiceBranch::NotQueued }; - TrackQueue::::insert(status.track, queue); + TrackQueue::::insert(status.track, queue); } else { // Are we ready for deciding? branch = if status.decision_deposit.is_some() { @@ -897,7 +913,7 @@ impl Pallet { if status.deciding.is_none() && now >= timeout { // Too long without being decided - end it. Self::ensure_no_alarm(&mut status); - Self::deposit_event(Event::::TimedOut { index, tally: status.tally }); + Self::deposit_event(Event::::TimedOut { index, tally: status.tally }); return ( ReferendumInfo::TimedOut( now, @@ -931,7 +947,7 @@ impl Pallet { status.origin, call_hash, ); - Self::deposit_event(Event::::Confirmed { + Self::deposit_event(Event::::Confirmed { index, tally: status.tally, }); @@ -950,7 +966,7 @@ impl Pallet { // Start confirming dirty = true; deciding.confirming = Some(now.saturating_add(track.confirm_period)); - Self::deposit_event(Event::::ConfirmStarted { index }); + Self::deposit_event(Event::::ConfirmStarted { index }); ServiceBranch::BeginConfirming }, } @@ -959,7 +975,7 @@ impl Pallet { // Failed! Self::ensure_no_alarm(&mut status); Self::note_one_fewer_deciding(status.track); - Self::deposit_event(Event::::Rejected { index, tally: status.tally }); + Self::deposit_event(Event::::Rejected { index, tally: status.tally }); return ( ReferendumInfo::Rejected( now, @@ -974,7 +990,7 @@ impl Pallet { // Stop confirming dirty = true; deciding.confirming = None; - Self::deposit_event(Event::::ConfirmAborted { index }); + Self::deposit_event(Event::::ConfirmAborted { index }); ServiceBranch::EndConfirming } else { ServiceBranch::ContinueNotConfirming @@ -993,7 +1009,7 @@ impl Pallet { fn decision_time( deciding: &DecidingStatusOf, tally: &T::Tally, - track: &TrackInfoOf, + track: &TrackInfoOf, ) -> T::BlockNumber { deciding.confirming.unwrap_or_else(|| { // Set alarm to the point where the current voting would make it pass. @@ -1007,7 +1023,7 @@ impl Pallet { } /// Cancel the alarm in `status`, if one exists. - fn ensure_no_alarm(status: &mut ReferendumStatusOf) { + fn ensure_no_alarm(status: &mut ReferendumStatusOf) { if let Some((_, last_alarm)) = status.alarm.take() { // Incorrect alarm - cancel it. let _ = T::Scheduler::cancel(last_alarm); @@ -1017,29 +1033,29 @@ impl Pallet { /// Reserve a deposit and return the `Deposit` instance. fn take_deposit( who: T::AccountId, - amount: BalanceOf, - ) -> Result>, DispatchError> { + amount: BalanceOf, + ) -> Result>, DispatchError> { T::Currency::reserve(&who, amount)?; Ok(Deposit { who, amount }) } /// Return a deposit, if `Some`. - fn refund_deposit(deposit: Option>>) { + fn refund_deposit(deposit: Option>>) { if let Some(Deposit { who, amount }) = deposit { T::Currency::unreserve(&who, amount); } } /// Slash a deposit, if `Some`. - fn slash_deposit(deposit: Option>>) { + fn slash_deposit(deposit: Option>>) { if let Some(Deposit { who, amount }) = deposit { T::Slash::on_unbalanced(T::Currency::slash_reserved(&who, amount).0); - Self::deposit_event(Event::::DepositSlashed { who, amount }); + Self::deposit_event(Event::::DepositSlashed { who, amount }); } } /// Get the track info value for the track `id`. - fn track(id: TrackIdOf) -> Option<&'static TrackInfoOf> { + fn track(id: TrackIdOf) -> Option<&'static TrackInfoOf> { let tracks = T::Tracks::tracks(); let index = tracks.binary_search_by_key(&id, |x| x.0).unwrap_or_else(|x| x); Some(&tracks[index].1) diff --git a/frame/referenda/src/types.rs b/frame/referenda/src/types.rs index 8ea9fc3faf3d0..622075100631b 100644 --- a/frame/referenda/src/types.rs +++ b/frame/referenda/src/types.rs @@ -24,44 +24,45 @@ use scale_info::TypeInfo; use sp_runtime::RuntimeDebug; use sp_std::fmt::Debug; -pub type BalanceOf = - <::Currency as Currency<::AccountId>>::Balance; -pub type NegativeImbalanceOf = <::Currency as Currency< +pub type BalanceOf = + <>::Currency as Currency<::AccountId>>::Balance; +pub type NegativeImbalanceOf = <>::Currency as Currency< ::AccountId, >>::NegativeImbalance; -pub type CallOf = ::Call; -pub type VotesOf = ::Votes; -pub type TallyOf = ::Tally; +pub type CallOf = >::Call; +pub type VotesOf = >::Votes; +pub type TallyOf = >::Tally; pub type PalletsOriginOf = <::Origin as OriginTrait>::PalletsOrigin; -pub type ReferendumInfoOf = ReferendumInfo< - TrackIdOf, +pub type ReferendumInfoOf = ReferendumInfo< + TrackIdOf, PalletsOriginOf, ::BlockNumber, ::Hash, - BalanceOf, - TallyOf, + BalanceOf, + TallyOf, ::AccountId, - ScheduleAddressOf, + ScheduleAddressOf, >; -pub type ReferendumStatusOf = ReferendumStatus< - TrackIdOf, +pub type ReferendumStatusOf = ReferendumStatus< + TrackIdOf, PalletsOriginOf, ::BlockNumber, ::Hash, - BalanceOf, - TallyOf, + BalanceOf, + TallyOf, ::AccountId, - ScheduleAddressOf, + ScheduleAddressOf, >; pub type DecidingStatusOf = DecidingStatus<::BlockNumber>; -pub type TrackInfoOf = TrackInfo, ::BlockNumber>; -pub type TrackIdOf = <::Tracks as TracksInfo< - BalanceOf, +pub type TrackInfoOf = + TrackInfo, ::BlockNumber>; +pub type TrackIdOf = <>::Tracks as TracksInfo< + BalanceOf, ::BlockNumber, >>::Id; -pub type ScheduleAddressOf = <::Scheduler as Anon< +pub type ScheduleAddressOf = <>::Scheduler as Anon< ::BlockNumber, - CallOf, + CallOf, PalletsOriginOf, >>::Address;