1#![recursion_limit = "256"]
65#![cfg_attr(not(feature = "std"), no_std)]
66
67extern crate alloc;
68
69use alloc::boxed::Box;
70use codec::{Codec, Encode};
71use core::fmt::Debug;
72use frame_support::{
73 dispatch::DispatchResult,
74 ensure,
75 traits::{
76 schedule::{
77 v3::{Anon as ScheduleAnon, Named as ScheduleNamed},
78 DispatchTime,
79 },
80 Currency, LockIdentifier, OnUnbalanced, OriginTrait, PollStatus, Polling, QueryPreimage,
81 ReservableCurrency, StorePreimage, VoteTally,
82 },
83 BoundedVec,
84};
85use scale_info::TypeInfo;
86use sp_runtime::{
87 traits::{AtLeast32BitUnsigned, Bounded, Dispatchable, One, Saturating, Zero},
88 DispatchError, Perbill,
89};
90
91mod branch;
92pub mod migration;
93mod types;
94pub mod weights;
95
96use self::branch::{BeginDecidingBranch, OneFewerDecidingBranch, ServiceBranch};
97pub use self::{
98 pallet::*,
99 types::{
100 BalanceOf, BlockNumberFor, BoundedCallOf, CallOf, ConstTrackInfo, Curve, DecidingStatus,
101 DecidingStatusOf, Deposit, InsertSorted, NegativeImbalanceOf, PalletsOriginOf,
102 ReferendumIndex, ReferendumInfo, ReferendumInfoOf, ReferendumStatus, ReferendumStatusOf,
103 ScheduleAddressOf, StringLike, TallyOf, Track, TrackIdOf, TrackInfo, TrackInfoOf,
104 TracksInfo, VotesOf,
105 },
106 weights::WeightInfo,
107};
108pub use alloc::vec::Vec;
109use sp_runtime::traits::BlockNumberProvider;
110
111#[cfg(test)]
112mod mock;
113#[cfg(test)]
114mod tests;
115
116#[cfg(feature = "runtime-benchmarks")]
117pub mod benchmarking;
118
119pub use frame_support::traits::Get;
120
121const ASSEMBLY_ID: LockIdentifier = *b"assembly";
122
123#[frame_support::pallet]
124pub mod pallet {
125 use super::*;
126 use frame_support::{pallet_prelude::*, traits::EnsureOriginWithArg};
127 use frame_system::pallet_prelude::{
128 ensure_root, ensure_signed, ensure_signed_or_root, BlockNumberFor as SystemBlockNumberFor,
129 OriginFor,
130 };
131
132 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
134
135 #[pallet::pallet]
136 #[pallet::storage_version(STORAGE_VERSION)]
137 pub struct Pallet<T, I = ()>(_);
138
139 #[pallet::config]
140 pub trait Config<I: 'static = ()>: frame_system::Config + Sized {
141 type RuntimeCall: Parameter
143 + Dispatchable<RuntimeOrigin = Self::RuntimeOrigin>
144 + From<Call<Self, I>>
145 + IsType<<Self as frame_system::Config>::RuntimeCall>
146 + From<frame_system::Call<Self>>;
147 #[allow(deprecated)]
148 type RuntimeEvent: From<Event<Self, I>>
149 + IsType<<Self as frame_system::Config>::RuntimeEvent>;
150 type WeightInfo: WeightInfo;
152 type Scheduler: ScheduleAnon<
154 BlockNumberFor<Self, I>,
155 CallOf<Self, I>,
156 PalletsOriginOf<Self>,
157 Hasher = Self::Hashing,
158 > + ScheduleNamed<
159 BlockNumberFor<Self, I>,
160 CallOf<Self, I>,
161 PalletsOriginOf<Self>,
162 Hasher = Self::Hashing,
163 >;
164 type Currency: ReservableCurrency<Self::AccountId>;
166 type SubmitOrigin: EnsureOriginWithArg<
169 Self::RuntimeOrigin,
170 PalletsOriginOf<Self>,
171 Success = Self::AccountId,
172 >;
173 type CancelOrigin: EnsureOrigin<Self::RuntimeOrigin>;
175 type KillOrigin: EnsureOrigin<Self::RuntimeOrigin>;
177 type Slash: OnUnbalanced<NegativeImbalanceOf<Self, I>>;
179 type Votes: AtLeast32BitUnsigned + Copy + Parameter + Member + MaxEncodedLen;
181 type Tally: VoteTally<Self::Votes, TrackIdOf<Self, I>>
183 + Clone
184 + Codec
185 + Eq
186 + Debug
187 + TypeInfo
188 + MaxEncodedLen;
189
190 #[pallet::constant]
193 type SubmissionDeposit: Get<BalanceOf<Self, I>>;
194
195 #[pallet::constant]
197 type MaxQueued: Get<u32>;
198
199 #[pallet::constant]
202 type UndecidingTimeout: Get<BlockNumberFor<Self, I>>;
203
204 #[pallet::constant]
208 type AlarmInterval: Get<BlockNumberFor<Self, I>>;
209
210 type Tracks: TracksInfo<
213 BalanceOf<Self, I>,
214 BlockNumberFor<Self, I>,
215 RuntimeOrigin = <Self::RuntimeOrigin as OriginTrait>::PalletsOrigin,
216 >;
217
218 type Preimages: QueryPreimage<H = Self::Hashing> + StorePreimage;
220
221 type BlockNumberProvider: BlockNumberProvider;
225 }
226
227 #[pallet::extra_constants]
228 impl<T: Config<I>, I: 'static> Pallet<T, I> {
229 #[pallet::constant_name(Tracks)]
233 fn tracks() -> Vec<(TrackIdOf<T, I>, ConstTrackInfo<BalanceOf<T, I>, BlockNumberFor<T, I>>)>
234 {
235 T::Tracks::tracks()
236 .map(|t| t.into_owned())
237 .map(|Track { id, info }| {
238 (
239 id,
240 ConstTrackInfo {
241 name: StringLike(info.name),
242 max_deciding: info.max_deciding,
243 decision_deposit: info.decision_deposit,
244 prepare_period: info.prepare_period,
245 decision_period: info.decision_period,
246 confirm_period: info.confirm_period,
247 min_enactment_period: info.min_enactment_period,
248 min_approval: info.min_approval,
249 min_support: info.min_support,
250 },
251 )
252 })
253 .collect()
254 }
255 }
256
257 #[pallet::storage]
259 pub type ReferendumCount<T, I = ()> = StorageValue<_, ReferendumIndex, ValueQuery>;
260
261 #[pallet::storage]
263 pub type ReferendumInfoFor<T: Config<I>, I: 'static = ()> =
264 StorageMap<_, Blake2_128Concat, ReferendumIndex, ReferendumInfoOf<T, I>>;
265
266 #[pallet::storage]
271 pub type TrackQueue<T: Config<I>, I: 'static = ()> = StorageMap<
272 _,
273 Twox64Concat,
274 TrackIdOf<T, I>,
275 BoundedVec<(ReferendumIndex, T::Votes), T::MaxQueued>,
276 ValueQuery,
277 >;
278
279 #[pallet::storage]
281 pub type DecidingCount<T: Config<I>, I: 'static = ()> =
282 StorageMap<_, Twox64Concat, TrackIdOf<T, I>, u32, ValueQuery>;
283
284 #[pallet::storage]
291 pub type MetadataOf<T: Config<I>, I: 'static = ()> =
292 StorageMap<_, Blake2_128Concat, ReferendumIndex, T::Hash>;
293
294 #[pallet::event]
295 #[pallet::generate_deposit(pub(super) fn deposit_event)]
296 pub enum Event<T: Config<I>, I: 'static = ()> {
297 Submitted {
299 index: ReferendumIndex,
301 track: TrackIdOf<T, I>,
303 proposal: BoundedCallOf<T, I>,
305 },
306 DecisionDepositPlaced {
308 index: ReferendumIndex,
310 who: T::AccountId,
312 amount: BalanceOf<T, I>,
314 },
315 DecisionDepositRefunded {
317 index: ReferendumIndex,
319 who: T::AccountId,
321 amount: BalanceOf<T, I>,
323 },
324 DepositSlashed {
326 who: T::AccountId,
328 amount: BalanceOf<T, I>,
330 },
331 DecisionStarted {
333 index: ReferendumIndex,
335 track: TrackIdOf<T, I>,
337 proposal: BoundedCallOf<T, I>,
339 tally: T::Tally,
341 },
342 ConfirmStarted {
343 index: ReferendumIndex,
345 },
346 ConfirmAborted {
347 index: ReferendumIndex,
349 },
350 Confirmed {
352 index: ReferendumIndex,
354 tally: T::Tally,
356 },
357 Approved {
359 index: ReferendumIndex,
361 },
362 Rejected {
364 index: ReferendumIndex,
366 tally: T::Tally,
368 },
369 TimedOut {
371 index: ReferendumIndex,
373 tally: T::Tally,
375 },
376 Cancelled {
378 index: ReferendumIndex,
380 tally: T::Tally,
382 },
383 Killed {
385 index: ReferendumIndex,
387 tally: T::Tally,
389 },
390 SubmissionDepositRefunded {
392 index: ReferendumIndex,
394 who: T::AccountId,
396 amount: BalanceOf<T, I>,
398 },
399 MetadataSet {
401 index: ReferendumIndex,
403 hash: T::Hash,
405 },
406 MetadataCleared {
408 index: ReferendumIndex,
410 hash: T::Hash,
412 },
413 }
414
415 #[pallet::error]
416 pub enum Error<T, I = ()> {
417 NotOngoing,
419 HasDeposit,
421 BadTrack,
423 Full,
425 QueueEmpty,
427 BadReferendum,
429 NothingToDo,
431 NoTrack,
433 Unfinished,
435 NoPermission,
437 NoDeposit,
439 BadStatus,
441 PreimageNotExist,
443 PreimageStoredWithDifferentLength,
445 }
446
447 #[pallet::hooks]
448 impl<T: Config<I>, I: 'static> Hooks<SystemBlockNumberFor<T>> for Pallet<T, I> {
449 #[cfg(feature = "try-runtime")]
450 fn try_state(_n: SystemBlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
451 Self::do_try_state()?;
452 Ok(())
453 }
454
455 #[cfg(any(feature = "std", test))]
456 fn integrity_test() {
457 T::Tracks::check_integrity().expect("Static tracks configuration is valid.");
458 }
459 }
460
461 #[pallet::call]
462 impl<T: Config<I>, I: 'static> Pallet<T, I> {
463 #[pallet::call_index(0)]
473 #[pallet::weight(T::WeightInfo::submit())]
474 pub fn submit(
475 origin: OriginFor<T>,
476 proposal_origin: Box<PalletsOriginOf<T>>,
477 proposal: BoundedCallOf<T, I>,
478 enactment_moment: DispatchTime<BlockNumberFor<T, I>>,
479 ) -> DispatchResult {
480 let proposal_origin = *proposal_origin;
481 let who = T::SubmitOrigin::ensure_origin(origin, &proposal_origin)?;
482
483 if let (Some(preimage_len), Some(proposal_len)) =
486 (proposal.lookup_hash().and_then(|h| T::Preimages::len(&h)), proposal.lookup_len())
487 {
488 if preimage_len != proposal_len {
489 return Err(Error::<T, I>::PreimageStoredWithDifferentLength.into());
490 }
491 }
492
493 let track =
494 T::Tracks::track_for(&proposal_origin).map_err(|_| Error::<T, I>::NoTrack)?;
495 let submission_deposit = Self::take_deposit(who, T::SubmissionDeposit::get())?;
496 let index = ReferendumCount::<T, I>::mutate(|x| {
497 let r = *x;
498 *x += 1;
499 r
500 });
501 let now = T::BlockNumberProvider::current_block_number();
502 let nudge_call =
503 T::Preimages::bound(CallOf::<T, I>::from(Call::nudge_referendum { index }))?;
504 let status = ReferendumStatus {
505 track,
506 origin: proposal_origin,
507 proposal: proposal.clone(),
508 enactment: enactment_moment,
509 submitted: now,
510 submission_deposit,
511 decision_deposit: None,
512 deciding: None,
513 tally: TallyOf::<T, I>::new(track),
514 in_queue: false,
515 alarm: Self::set_alarm(nudge_call, now.saturating_add(T::UndecidingTimeout::get())),
516 };
517 ReferendumInfoFor::<T, I>::insert(index, ReferendumInfo::Ongoing(status));
518
519 Self::deposit_event(Event::<T, I>::Submitted { index, track, proposal });
520 Ok(())
521 }
522
523 #[pallet::call_index(1)]
532 #[pallet::weight(ServiceBranch::max_weight_of_deposit::<T, I>())]
533 pub fn place_decision_deposit(
534 origin: OriginFor<T>,
535 index: ReferendumIndex,
536 ) -> DispatchResultWithPostInfo {
537 let who = ensure_signed(origin)?;
538 let mut status = Self::ensure_ongoing(index)?;
539 ensure!(status.decision_deposit.is_none(), Error::<T, I>::HasDeposit);
540 let track = T::Tracks::info(status.track).ok_or(Error::<T, I>::NoTrack)?;
541 status.decision_deposit =
542 Some(Self::take_deposit(who.clone(), track.decision_deposit)?);
543 let now = T::BlockNumberProvider::current_block_number();
544 let (info, _, branch) = Self::service_referendum(now, index, status);
545 ReferendumInfoFor::<T, I>::insert(index, info);
546 let e =
547 Event::<T, I>::DecisionDepositPlaced { index, who, amount: track.decision_deposit };
548 Self::deposit_event(e);
549 Ok(branch.weight_of_deposit::<T, I>().into())
550 }
551
552 #[pallet::call_index(2)]
560 #[pallet::weight(T::WeightInfo::refund_decision_deposit())]
561 pub fn refund_decision_deposit(
562 origin: OriginFor<T>,
563 index: ReferendumIndex,
564 ) -> DispatchResult {
565 ensure_signed_or_root(origin)?;
566 let mut info =
567 ReferendumInfoFor::<T, I>::get(index).ok_or(Error::<T, I>::BadReferendum)?;
568 let deposit = info
569 .take_decision_deposit()
570 .map_err(|_| Error::<T, I>::Unfinished)?
571 .ok_or(Error::<T, I>::NoDeposit)?;
572 Self::refund_deposit(Some(deposit.clone()));
573 ReferendumInfoFor::<T, I>::insert(index, info);
574 let e = Event::<T, I>::DecisionDepositRefunded {
575 index,
576 who: deposit.who,
577 amount: deposit.amount,
578 };
579 Self::deposit_event(e);
580 Ok(())
581 }
582
583 #[pallet::call_index(3)]
590 #[pallet::weight(T::WeightInfo::cancel())]
591 pub fn cancel(origin: OriginFor<T>, index: ReferendumIndex) -> DispatchResult {
592 T::CancelOrigin::ensure_origin(origin)?;
593 let status = Self::ensure_ongoing(index)?;
594 if let Some((_, last_alarm)) = status.alarm {
595 let _ = T::Scheduler::cancel(last_alarm);
596 }
597 if status.deciding.is_some() {
598 Self::note_one_fewer_deciding(status.track);
599 }
600 Self::deposit_event(Event::<T, I>::Cancelled { index, tally: status.tally });
601 let info = ReferendumInfo::Cancelled(
602 T::BlockNumberProvider::current_block_number(),
603 Some(status.submission_deposit),
604 status.decision_deposit,
605 );
606 ReferendumInfoFor::<T, I>::insert(index, info);
607 Ok(())
608 }
609
610 #[pallet::call_index(4)]
617 #[pallet::weight(T::WeightInfo::kill())]
618 pub fn kill(origin: OriginFor<T>, index: ReferendumIndex) -> DispatchResult {
619 T::KillOrigin::ensure_origin(origin)?;
620 let status = Self::ensure_ongoing(index)?;
621 if let Some((_, last_alarm)) = status.alarm {
622 let _ = T::Scheduler::cancel(last_alarm);
623 }
624 if status.deciding.is_some() {
625 Self::note_one_fewer_deciding(status.track);
626 }
627 Self::deposit_event(Event::<T, I>::Killed { index, tally: status.tally });
628 Self::slash_deposit(Some(status.submission_deposit.clone()));
629 Self::slash_deposit(status.decision_deposit.clone());
630 Self::do_clear_metadata(index);
631 let info = ReferendumInfo::Killed(T::BlockNumberProvider::current_block_number());
632 ReferendumInfoFor::<T, I>::insert(index, info);
633 Ok(())
634 }
635
636 #[pallet::call_index(5)]
641 #[pallet::weight(ServiceBranch::max_weight_of_nudge::<T, I>())]
642 pub fn nudge_referendum(
643 origin: OriginFor<T>,
644 index: ReferendumIndex,
645 ) -> DispatchResultWithPostInfo {
646 ensure_root(origin)?;
647 let now = T::BlockNumberProvider::current_block_number();
648 let mut status = Self::ensure_ongoing(index)?;
649 status.alarm = None;
651 let (info, dirty, branch) = Self::service_referendum(now, index, status);
652 if dirty {
653 ReferendumInfoFor::<T, I>::insert(index, info);
654 }
655 Ok(Some(branch.weight_of_nudge::<T, I>()).into())
656 }
657
658 #[pallet::call_index(6)]
668 #[pallet::weight(OneFewerDecidingBranch::max_weight::<T, I>())]
669 pub fn one_fewer_deciding(
670 origin: OriginFor<T>,
671 track: TrackIdOf<T, I>,
672 ) -> DispatchResultWithPostInfo {
673 ensure_root(origin)?;
674 let track_info = T::Tracks::info(track).ok_or(Error::<T, I>::BadTrack)?;
675 let mut track_queue = TrackQueue::<T, I>::get(track);
676 let branch =
677 if let Some((index, mut status)) = Self::next_for_deciding(&mut track_queue) {
678 let now = T::BlockNumberProvider::current_block_number();
679 let (maybe_alarm, branch) =
680 Self::begin_deciding(&mut status, index, now, &track_info);
681 if let Some(set_alarm) = maybe_alarm {
682 Self::ensure_alarm_at(&mut status, index, set_alarm);
683 }
684 ReferendumInfoFor::<T, I>::insert(index, ReferendumInfo::Ongoing(status));
685 TrackQueue::<T, I>::insert(track, track_queue);
686 branch.into()
687 } else {
688 DecidingCount::<T, I>::mutate(track, |x| x.saturating_dec());
689 OneFewerDecidingBranch::QueueEmpty
690 };
691 Ok(Some(branch.weight::<T, I>()).into())
692 }
693
694 #[pallet::call_index(7)]
702 #[pallet::weight(T::WeightInfo::refund_submission_deposit())]
703 pub fn refund_submission_deposit(
704 origin: OriginFor<T>,
705 index: ReferendumIndex,
706 ) -> DispatchResult {
707 ensure_signed_or_root(origin)?;
708 let mut info =
709 ReferendumInfoFor::<T, I>::get(index).ok_or(Error::<T, I>::BadReferendum)?;
710 ensure!(
712 matches!(info, ReferendumInfo::Approved(..) | ReferendumInfo::Cancelled(..)),
713 Error::<T, I>::BadStatus
714 );
715 let deposit = info.take_submission_deposit().ok_or(Error::<T, I>::NoDeposit)?;
716 Self::refund_deposit(Some(deposit.clone()));
717 ReferendumInfoFor::<T, I>::insert(index, info);
718 let e = Event::<T, I>::SubmissionDepositRefunded {
719 index,
720 who: deposit.who,
721 amount: deposit.amount,
722 };
723 Self::deposit_event(e);
724 Ok(())
725 }
726
727 #[pallet::call_index(9)]
735 #[pallet::weight(T::WeightInfo::slash_submission_deposit())]
736 pub fn slash_submission_deposit(
737 origin: OriginFor<T>,
738 index: ReferendumIndex,
739 ) -> DispatchResult {
740 ensure_signed_or_root(origin)?;
741 let mut info =
742 ReferendumInfoFor::<T, I>::get(index).ok_or(Error::<T, I>::BadReferendum)?;
743 ensure!(
745 matches!(info, ReferendumInfo::Rejected(..) | ReferendumInfo::TimedOut(..)),
746 Error::<T, I>::BadStatus
747 );
748 let deposit = info.take_submission_deposit().ok_or(Error::<T, I>::NoDeposit)?;
749 Self::slash_deposit(Some(deposit));
750 ReferendumInfoFor::<T, I>::insert(index, info);
751 Ok(())
752 }
753
754 #[pallet::call_index(8)]
762 #[pallet::weight(
763 maybe_hash.map_or(
764 T::WeightInfo::clear_metadata(), |_| T::WeightInfo::set_some_metadata())
765 )]
766 pub fn set_metadata(
767 origin: OriginFor<T>,
768 index: ReferendumIndex,
769 maybe_hash: Option<T::Hash>,
770 ) -> DispatchResult {
771 let who = ensure_signed(origin)?;
772 if let Some(hash) = maybe_hash {
773 let status = Self::ensure_ongoing(index)?;
774 ensure!(status.submission_deposit.who == who, Error::<T, I>::NoPermission);
775 ensure!(T::Preimages::len(&hash).is_some(), Error::<T, I>::PreimageNotExist);
776 MetadataOf::<T, I>::insert(index, hash);
777 Self::deposit_event(Event::<T, I>::MetadataSet { index, hash });
778 Ok(())
779 } else {
780 if let Some(status) = Self::ensure_ongoing(index).ok() {
781 ensure!(status.submission_deposit.who == who, Error::<T, I>::NoPermission);
782 }
783 Self::do_clear_metadata(index);
784 Ok(())
785 }
786 }
787 }
788}
789
790impl<T: Config<I>, I: 'static> Polling<T::Tally> for Pallet<T, I> {
791 type Index = ReferendumIndex;
792 type Votes = VotesOf<T, I>;
793 type Moment = BlockNumberFor<T, I>;
794 type Class = TrackIdOf<T, I>;
795
796 fn classes() -> Vec<Self::Class> {
797 T::Tracks::track_ids().collect()
798 }
799
800 fn access_poll<R>(
801 index: Self::Index,
802 f: impl FnOnce(PollStatus<&mut T::Tally, BlockNumberFor<T, I>, TrackIdOf<T, I>>) -> R,
803 ) -> R {
804 match ReferendumInfoFor::<T, I>::get(index) {
805 Some(ReferendumInfo::Ongoing(mut status)) => {
806 let result = f(PollStatus::Ongoing(&mut status.tally, status.track));
807 let now = T::BlockNumberProvider::current_block_number();
808 Self::ensure_alarm_at(&mut status, index, now + One::one());
809 ReferendumInfoFor::<T, I>::insert(index, ReferendumInfo::Ongoing(status));
810 result
811 },
812 Some(ReferendumInfo::Approved(end, ..)) => f(PollStatus::Completed(end, true)),
813 Some(ReferendumInfo::Rejected(end, ..)) => f(PollStatus::Completed(end, false)),
814 _ => f(PollStatus::None),
815 }
816 }
817
818 fn try_access_poll<R>(
819 index: Self::Index,
820 f: impl FnOnce(
821 PollStatus<&mut T::Tally, BlockNumberFor<T, I>, TrackIdOf<T, I>>,
822 ) -> Result<R, DispatchError>,
823 ) -> Result<R, DispatchError> {
824 match ReferendumInfoFor::<T, I>::get(index) {
825 Some(ReferendumInfo::Ongoing(mut status)) => {
826 let result = f(PollStatus::Ongoing(&mut status.tally, status.track))?;
827 let now = T::BlockNumberProvider::current_block_number();
828 Self::ensure_alarm_at(&mut status, index, now + One::one());
829 ReferendumInfoFor::<T, I>::insert(index, ReferendumInfo::Ongoing(status));
830 Ok(result)
831 },
832 Some(ReferendumInfo::Approved(end, ..)) => f(PollStatus::Completed(end, true)),
833 Some(ReferendumInfo::Rejected(end, ..)) => f(PollStatus::Completed(end, false)),
834 _ => f(PollStatus::None),
835 }
836 }
837
838 fn as_ongoing(index: Self::Index) -> Option<(T::Tally, TrackIdOf<T, I>)> {
839 Self::ensure_ongoing(index).ok().map(|x| (x.tally, x.track))
840 }
841
842 #[cfg(feature = "runtime-benchmarks")]
843 fn create_ongoing(class: Self::Class) -> Result<Self::Index, ()> {
844 let index = ReferendumCount::<T, I>::mutate(|x| {
845 let r = *x;
846 *x += 1;
847 r
848 });
849 let now = T::BlockNumberProvider::current_block_number();
850 let dummy_account_id =
851 codec::Decode::decode(&mut sp_runtime::traits::TrailingZeroInput::new(&b"dummy"[..]))
852 .expect("infinite length input; no invalid inputs for type; qed");
853 let mut status = ReferendumStatusOf::<T, I> {
854 track: class,
855 origin: frame_support::dispatch::RawOrigin::Root.into(),
856 proposal: T::Preimages::bound(CallOf::<T, I>::from(Call::nudge_referendum { index }))
857 .map_err(|_| ())?,
858 enactment: DispatchTime::After(Zero::zero()),
859 submitted: now,
860 submission_deposit: Deposit { who: dummy_account_id, amount: Zero::zero() },
861 decision_deposit: None,
862 deciding: None,
863 tally: TallyOf::<T, I>::new(class),
864 in_queue: false,
865 alarm: None,
866 };
867
868 Self::ensure_alarm_at(&mut status, index, sp_runtime::traits::Bounded::max_value());
869 ReferendumInfoFor::<T, I>::insert(index, ReferendumInfo::Ongoing(status));
870 Ok(index)
871 }
872
873 #[cfg(feature = "runtime-benchmarks")]
874 fn end_ongoing(index: Self::Index, approved: bool) -> Result<(), ()> {
875 let mut status = Self::ensure_ongoing(index).map_err(|_| ())?;
876 Self::ensure_no_alarm(&mut status);
877 Self::note_one_fewer_deciding(status.track);
878 let now = T::BlockNumberProvider::current_block_number();
879 let info = if approved {
880 ReferendumInfo::Approved(now, Some(status.submission_deposit), status.decision_deposit)
881 } else {
882 ReferendumInfo::Rejected(now, Some(status.submission_deposit), status.decision_deposit)
883 };
884 ReferendumInfoFor::<T, I>::insert(index, info);
885 Ok(())
886 }
887
888 #[cfg(feature = "runtime-benchmarks")]
889 fn max_ongoing() -> (Self::Class, u32) {
890 let r = T::Tracks::tracks()
891 .max_by_key(|t| t.info.max_deciding)
892 .expect("Always one class");
893 (r.id, r.info.max_deciding)
894 }
895}
896
897impl<T: Config<I>, I: 'static> Pallet<T, I> {
898 pub fn ensure_ongoing(
901 index: ReferendumIndex,
902 ) -> Result<ReferendumStatusOf<T, I>, DispatchError> {
903 match ReferendumInfoFor::<T, I>::get(index) {
904 Some(ReferendumInfo::Ongoing(status)) => Ok(status),
905 _ => Err(Error::<T, I>::NotOngoing.into()),
906 }
907 }
908
909 pub fn is_referendum_passing(ref_index: ReferendumIndex) -> Result<bool, DispatchError> {
912 let info = ReferendumInfoFor::<T, I>::get(ref_index).ok_or(Error::<T, I>::BadReferendum)?;
913 match info {
914 ReferendumInfo::Ongoing(status) => {
915 let track = T::Tracks::info(status.track).ok_or(Error::<T, I>::NoTrack)?;
916 let elapsed = if let Some(deciding) = status.deciding {
917 T::BlockNumberProvider::current_block_number().saturating_sub(deciding.since)
918 } else {
919 Zero::zero()
920 };
921 Ok(Self::is_passing(
922 &status.tally,
923 elapsed,
924 track.decision_period,
925 &track.min_support,
926 &track.min_approval,
927 status.track,
928 ))
929 },
930 _ => Err(Error::<T, I>::NotOngoing.into()),
931 }
932 }
933
934 fn schedule_enactment(
936 index: ReferendumIndex,
937 track: &TrackInfoOf<T, I>,
938 desired: DispatchTime<BlockNumberFor<T, I>>,
939 origin: PalletsOriginOf<T>,
940 call: BoundedCallOf<T, I>,
941 ) {
942 let now = T::BlockNumberProvider::current_block_number();
943 let earliest_allowed = now.saturating_add(track.min_enactment_period.max(One::one()));
945 let desired = desired.evaluate(now);
946 let ok = T::Scheduler::schedule_named(
947 (ASSEMBLY_ID, "enactment", index).using_encoded(sp_io::hashing::blake2_256),
948 DispatchTime::At(desired.max(earliest_allowed)),
949 None,
950 63,
951 origin,
952 call,
953 )
954 .is_ok();
955 debug_assert!(ok, "LOGIC ERROR: bake_referendum/schedule_named failed");
956 }
957
958 fn set_alarm(
960 call: BoundedCallOf<T, I>,
961 when: BlockNumberFor<T, I>,
962 ) -> Option<(BlockNumberFor<T, I>, ScheduleAddressOf<T, I>)> {
963 let alarm_interval = T::AlarmInterval::get().max(One::one());
964 let when = (when.saturating_add(alarm_interval.saturating_sub(One::one())) /
967 alarm_interval)
968 .saturating_mul(alarm_interval);
969 let result = T::Scheduler::schedule(
970 DispatchTime::At(when),
971 None,
972 128u8,
973 frame_system::RawOrigin::Root.into(),
974 call,
975 );
976 debug_assert!(
977 result.is_ok(),
978 "Unable to schedule a new alarm at #{:?} (now: #{:?}), scheduler error: `{:?}`",
979 when,
980 T::BlockNumberProvider::current_block_number(),
981 result.unwrap_err(),
982 );
983 result.ok().map(|x| (when, x))
984 }
985
986 fn begin_deciding(
993 status: &mut ReferendumStatusOf<T, I>,
994 index: ReferendumIndex,
995 now: BlockNumberFor<T, I>,
996 track: &TrackInfoOf<T, I>,
997 ) -> (Option<BlockNumberFor<T, I>>, BeginDecidingBranch) {
998 let is_passing = Self::is_passing(
999 &status.tally,
1000 Zero::zero(),
1001 track.decision_period,
1002 &track.min_support,
1003 &track.min_approval,
1004 status.track,
1005 );
1006 status.in_queue = false;
1007 Self::deposit_event(Event::<T, I>::DecisionStarted {
1008 index,
1009 tally: status.tally.clone(),
1010 proposal: status.proposal.clone(),
1011 track: status.track,
1012 });
1013 let confirming = if is_passing {
1014 Self::deposit_event(Event::<T, I>::ConfirmStarted { index });
1015 Some(now.saturating_add(track.confirm_period))
1016 } else {
1017 None
1018 };
1019 let deciding_status = DecidingStatus { since: now, confirming };
1020 let alarm = Self::decision_time(&deciding_status, &status.tally, status.track, track)
1021 .max(now.saturating_add(One::one()));
1022 status.deciding = Some(deciding_status);
1023 let branch =
1024 if is_passing { BeginDecidingBranch::Passing } else { BeginDecidingBranch::Failing };
1025 (Some(alarm), branch)
1026 }
1027
1028 fn ready_for_deciding(
1033 now: BlockNumberFor<T, I>,
1034 track: &TrackInfoOf<T, I>,
1035 index: ReferendumIndex,
1036 status: &mut ReferendumStatusOf<T, I>,
1037 ) -> (Option<BlockNumberFor<T, I>>, ServiceBranch) {
1038 let deciding_count = DecidingCount::<T, I>::get(status.track);
1039 if deciding_count < track.max_deciding {
1040 DecidingCount::<T, I>::insert(status.track, deciding_count.saturating_add(1));
1042 let r = Self::begin_deciding(status, index, now, track);
1043 (r.0, r.1.into())
1044 } else {
1045 let item = (index, status.tally.ayes(status.track));
1047 status.in_queue = true;
1048 TrackQueue::<T, I>::mutate(status.track, |q| q.insert_sorted_by_key(item, |x| x.1));
1049 (None, ServiceBranch::Queued)
1050 }
1051 }
1052
1053 fn next_for_deciding(
1056 track_queue: &mut BoundedVec<(u32, VotesOf<T, I>), T::MaxQueued>,
1057 ) -> Option<(ReferendumIndex, ReferendumStatusOf<T, I>)> {
1058 loop {
1059 let (index, _) = track_queue.pop()?;
1060 match Self::ensure_ongoing(index) {
1061 Ok(s) => return Some((index, s)),
1062 Err(_) => {}, }
1064 }
1065 }
1066
1067 fn note_one_fewer_deciding(track: TrackIdOf<T, I>) {
1071 let now = T::BlockNumberProvider::current_block_number();
1073 let next_block = now + One::one();
1074 let call = match T::Preimages::bound(CallOf::<T, I>::from(Call::one_fewer_deciding {
1075 track,
1076 })) {
1077 Ok(c) => c,
1078 Err(_) => {
1079 debug_assert!(false, "Unable to create a bounded call from `one_fewer_deciding`??",);
1080 return;
1081 },
1082 };
1083 Self::set_alarm(call, next_block);
1084 }
1085
1086 fn ensure_alarm_at(
1092 status: &mut ReferendumStatusOf<T, I>,
1093 index: ReferendumIndex,
1094 alarm: BlockNumberFor<T, I>,
1095 ) -> bool {
1096 if status.alarm.as_ref().map_or(true, |&(when, _)| when != alarm) {
1097 Self::ensure_no_alarm(status);
1099 let call =
1100 match T::Preimages::bound(CallOf::<T, I>::from(Call::nudge_referendum { index })) {
1101 Ok(c) => c,
1102 Err(_) => {
1103 debug_assert!(
1104 false,
1105 "Unable to create a bounded call from `nudge_referendum`??",
1106 );
1107 return false;
1108 },
1109 };
1110 status.alarm = Self::set_alarm(call, alarm);
1111 true
1112 } else {
1113 false
1114 }
1115 }
1116
1117 fn service_referendum(
1139 now: BlockNumberFor<T, I>,
1140 index: ReferendumIndex,
1141 mut status: ReferendumStatusOf<T, I>,
1142 ) -> (ReferendumInfoOf<T, I>, bool, ServiceBranch) {
1143 let mut dirty = false;
1144 let track = match T::Tracks::info(status.track) {
1146 Some(x) => x,
1147 None => return (ReferendumInfo::Ongoing(status), false, ServiceBranch::Fail),
1148 };
1149 let timeout = status.submitted + T::UndecidingTimeout::get();
1151 let mut alarm = BlockNumberFor::<T, I>::max_value();
1152 let branch;
1153 match &mut status.deciding {
1154 None => {
1155 if status.in_queue {
1157 let ayes = status.tally.ayes(status.track);
1159 let mut queue = TrackQueue::<T, I>::get(status.track);
1160 let maybe_old_pos = queue.iter().position(|(x, _)| *x == index);
1161 let new_pos = queue.binary_search_by_key(&ayes, |x| x.1).unwrap_or_else(|x| x);
1162 branch = if maybe_old_pos.is_none() && new_pos > 0 {
1163 let _ = queue.force_insert_keep_right(new_pos, (index, ayes));
1165 ServiceBranch::RequeuedInsertion
1166 } else if let Some(old_pos) = maybe_old_pos {
1167 queue[old_pos].1 = ayes;
1169 queue.slide(old_pos, new_pos);
1170 ServiceBranch::RequeuedSlide
1171 } else {
1172 ServiceBranch::NotQueued
1173 };
1174 TrackQueue::<T, I>::insert(status.track, queue);
1175 } else {
1176 branch = if status.decision_deposit.is_some() {
1178 let prepare_end = status.submitted.saturating_add(track.prepare_period);
1179 if now >= prepare_end {
1180 let (maybe_alarm, branch) =
1181 Self::ready_for_deciding(now, &track, index, &mut status);
1182 if let Some(set_alarm) = maybe_alarm {
1183 alarm = alarm.min(set_alarm);
1184 }
1185 dirty = true;
1186 branch
1187 } else {
1188 alarm = alarm.min(prepare_end);
1189 ServiceBranch::Preparing
1190 }
1191 } else {
1192 alarm = timeout;
1193 ServiceBranch::NoDeposit
1194 }
1195 }
1196 if status.deciding.is_none() && now >= timeout && !status.in_queue {
1198 Self::ensure_no_alarm(&mut status);
1200 Self::deposit_event(Event::<T, I>::TimedOut { index, tally: status.tally });
1201 return (
1202 ReferendumInfo::TimedOut(
1203 now,
1204 Some(status.submission_deposit),
1205 status.decision_deposit,
1206 ),
1207 true,
1208 ServiceBranch::TimedOut,
1209 );
1210 }
1211 },
1212 Some(deciding) => {
1213 let is_passing = Self::is_passing(
1214 &status.tally,
1215 now.saturating_sub(deciding.since),
1216 track.decision_period,
1217 &track.min_support,
1218 &track.min_approval,
1219 status.track,
1220 );
1221 branch = if is_passing {
1222 match deciding.confirming {
1223 Some(t) if now >= t => {
1224 Self::ensure_no_alarm(&mut status);
1226 Self::note_one_fewer_deciding(status.track);
1227 let (desired, call) = (status.enactment, status.proposal);
1228 Self::schedule_enactment(index, &track, desired, status.origin, call);
1229 Self::deposit_event(Event::<T, I>::Confirmed {
1230 index,
1231 tally: status.tally,
1232 });
1233 return (
1234 ReferendumInfo::Approved(
1235 now,
1236 Some(status.submission_deposit),
1237 status.decision_deposit,
1238 ),
1239 true,
1240 ServiceBranch::Approved,
1241 );
1242 },
1243 Some(_) => ServiceBranch::ContinueConfirming,
1244 None => {
1245 dirty = true;
1247 deciding.confirming = Some(now.saturating_add(track.confirm_period));
1248 Self::deposit_event(Event::<T, I>::ConfirmStarted { index });
1249 ServiceBranch::BeginConfirming
1250 },
1251 }
1252 } else {
1253 if now >= deciding.since.saturating_add(track.decision_period) {
1254 Self::ensure_no_alarm(&mut status);
1256 Self::note_one_fewer_deciding(status.track);
1257 Self::deposit_event(Event::<T, I>::Rejected { index, tally: status.tally });
1258 return (
1259 ReferendumInfo::Rejected(
1260 now,
1261 Some(status.submission_deposit),
1262 status.decision_deposit,
1263 ),
1264 true,
1265 ServiceBranch::Rejected,
1266 );
1267 }
1268 if deciding.confirming.is_some() {
1269 dirty = true;
1271 deciding.confirming = None;
1272 Self::deposit_event(Event::<T, I>::ConfirmAborted { index });
1273 ServiceBranch::EndConfirming
1274 } else {
1275 ServiceBranch::ContinueNotConfirming
1276 }
1277 };
1278 alarm = Self::decision_time(deciding, &status.tally, status.track, &track);
1279 },
1280 }
1281
1282 let dirty_alarm = if alarm < BlockNumberFor::<T, I>::max_value() {
1283 Self::ensure_alarm_at(&mut status, index, alarm)
1284 } else {
1285 Self::ensure_no_alarm(&mut status)
1286 };
1287 (ReferendumInfo::Ongoing(status), dirty_alarm || dirty, branch)
1288 }
1289
1290 fn decision_time(
1293 deciding: &DecidingStatusOf<T, I>,
1294 tally: &T::Tally,
1295 track_id: TrackIdOf<T, I>,
1296 track: &TrackInfoOf<T, I>,
1297 ) -> BlockNumberFor<T, I> {
1298 deciding.confirming.unwrap_or_else(|| {
1299 let approval = tally.approval(track_id);
1301 let support = tally.support(track_id);
1302 let until_approval = track.min_approval.delay(approval);
1303 let until_support = track.min_support.delay(support);
1304 let offset = until_support.max(until_approval);
1305 deciding.since.saturating_add(offset.mul_ceil(track.decision_period))
1306 })
1307 }
1308
1309 fn ensure_no_alarm(status: &mut ReferendumStatusOf<T, I>) -> bool {
1311 if let Some((_, last_alarm)) = status.alarm.take() {
1312 let _ = T::Scheduler::cancel(last_alarm);
1314 true
1315 } else {
1316 false
1317 }
1318 }
1319
1320 fn take_deposit(
1322 who: T::AccountId,
1323 amount: BalanceOf<T, I>,
1324 ) -> Result<Deposit<T::AccountId, BalanceOf<T, I>>, DispatchError> {
1325 T::Currency::reserve(&who, amount)?;
1326 Ok(Deposit { who, amount })
1327 }
1328
1329 fn refund_deposit(deposit: Option<Deposit<T::AccountId, BalanceOf<T, I>>>) {
1331 if let Some(Deposit { who, amount }) = deposit {
1332 T::Currency::unreserve(&who, amount);
1333 }
1334 }
1335
1336 fn slash_deposit(deposit: Option<Deposit<T::AccountId, BalanceOf<T, I>>>) {
1338 if let Some(Deposit { who, amount }) = deposit {
1339 T::Slash::on_unbalanced(T::Currency::slash_reserved(&who, amount).0);
1340 Self::deposit_event(Event::<T, I>::DepositSlashed { who, amount });
1341 }
1342 }
1343
1344 fn is_passing(
1348 tally: &T::Tally,
1349 elapsed: BlockNumberFor<T, I>,
1350 period: BlockNumberFor<T, I>,
1351 support_needed: &Curve,
1352 approval_needed: &Curve,
1353 id: TrackIdOf<T, I>,
1354 ) -> bool {
1355 let x = Perbill::from_rational(elapsed.min(period), period);
1356 support_needed.passing(x, tally.support(id)) &&
1357 approval_needed.passing(x, tally.approval(id))
1358 }
1359
1360 fn do_clear_metadata(index: ReferendumIndex) {
1362 if let Some(hash) = MetadataOf::<T, I>::take(index) {
1363 Self::deposit_event(Event::<T, I>::MetadataCleared { index, hash });
1364 }
1365 }
1366
1367 #[cfg(any(feature = "try-runtime", test))]
1377 fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
1378 ensure!(
1379 ReferendumCount::<T, I>::get() as usize ==
1380 ReferendumInfoFor::<T, I>::iter_keys().count(),
1381 "Number of referenda in `ReferendumInfoFor` is different than `ReferendumCount`"
1382 );
1383
1384 MetadataOf::<T, I>::iter_keys().try_for_each(|referendum_index| -> DispatchResult {
1385 ensure!(
1386 ReferendumInfoFor::<T, I>::contains_key(referendum_index),
1387 "Referendum indices in `MetadataOf` must also be stored in `ReferendumInfoOf`"
1388 );
1389 Ok(())
1390 })?;
1391
1392 Self::try_state_referenda_info()?;
1393 Self::try_state_tracks()?;
1394
1395 Ok(())
1396 }
1397
1398 #[cfg(any(feature = "try-runtime", test))]
1407 fn try_state_referenda_info() -> Result<(), sp_runtime::TryRuntimeError> {
1408 ReferendumInfoFor::<T, I>::iter().try_for_each(|(_, referendum)| {
1409 match referendum {
1410 ReferendumInfo::Ongoing(status) => {
1411 ensure!(
1412 T::Tracks::info(status.track).is_some(),
1413 "No track info for the track of the referendum."
1414 );
1415
1416 if let Some(deciding) = status.deciding {
1417 ensure!(
1418 deciding.since <
1419 deciding
1420 .confirming
1421 .unwrap_or(BlockNumberFor::<T, I>::max_value()),
1422 "Deciding status cannot begin before confirming stage."
1423 )
1424 }
1425 },
1426 _ => {},
1427 }
1428 Ok(())
1429 })
1430 }
1431
1432 #[cfg(any(feature = "try-runtime", test))]
1437 fn try_state_tracks() -> Result<(), sp_runtime::TryRuntimeError> {
1438 T::Tracks::tracks().try_for_each(|track| {
1439 TrackQueue::<T, I>::get(track.id).iter().try_for_each(
1440 |(referendum_index, _)| -> Result<(), sp_runtime::TryRuntimeError> {
1441 ensure!(
1442 ReferendumInfoFor::<T, I>::contains_key(referendum_index),
1443 "`ReferendumIndex` inside the `TrackQueue` should be a key in `ReferendumInfoFor`"
1444 );
1445 Ok(())
1446 },
1447 )?;
1448 Ok(())
1449 })
1450 }
1451}