From 871859c2a6812c0008fca51e6cd0590c8a54942e Mon Sep 17 00:00:00 2001 From: "polka.dom" Date: Mon, 29 Jul 2024 15:05:29 -0700 Subject: [PATCH] Remove pallet::getter macro usage from pallet-election-provider-multi-phase (#4487) As per #3326, removes pallet::getter macro usage from the election-provider-multi-phase pallet. The syntax `StorageItem::::get()` should be used instead. cc @muraca --------- Co-authored-by: Oliver Tale-Yazdi --- prdoc/pr_4487.prdoc | 16 + .../src/benchmarking.rs | 108 +++--- .../src/helpers.rs | 2 +- .../election-provider-multi-phase/src/lib.rs | 355 ++++++++++-------- .../election-provider-multi-phase/src/mock.rs | 22 +- .../src/signed.rs | 71 ++-- .../src/unsigned.rs | 96 ++--- .../test-staking-e2e/src/lib.rs | 18 +- .../test-staking-e2e/src/mock.rs | 12 +- 9 files changed, 385 insertions(+), 315 deletions(-) create mode 100644 prdoc/pr_4487.prdoc diff --git a/prdoc/pr_4487.prdoc b/prdoc/pr_4487.prdoc new file mode 100644 index 0000000000000..fb2bab2a57a89 --- /dev/null +++ b/prdoc/pr_4487.prdoc @@ -0,0 +1,16 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Remove `pallet::getter` usage from pallet-election-provider-multi-phase + +doc: + - audience: Runtime Dev + description: | + This PR removes the `pallet::getter`s from `pallet-election-provider-multi-phase`. + The syntax `StorageItem::::get()` should be used instead. + +crates: + - name: pallet-election-provider-multi-phase + bump: minor + - name: pallet-election-provider-e2e-test + bump: minor diff --git a/substrate/frame/election-provider-multi-phase/src/benchmarking.rs b/substrate/frame/election-provider-multi-phase/src/benchmarking.rs index 957ae51b8f1da..2a3994ff2aa65 100644 --- a/substrate/frame/election-provider-multi-phase/src/benchmarking.rs +++ b/substrate/frame/election-provider-multi-phase/src/benchmarking.rs @@ -110,12 +110,12 @@ fn solution_with_size( assert_eq!(all_voters.len() as u32, size.voters); assert_eq!(winners.len() as u32, desired_targets); - >::put(SolutionOrSnapshotSize { + SnapshotMetadata::::put(SolutionOrSnapshotSize { voters: all_voters.len() as u32, targets: targets.len() as u32, }); - >::put(desired_targets); - >::put(RoundSnapshot { voters: all_voters.clone(), targets: targets.clone() }); + DesiredTargets::::put(desired_targets); + Snapshot::::put(RoundSnapshot { voters: all_voters.clone(), targets: targets.clone() }); // write the snapshot to staking or whoever is the data provider, in case it is needed further // down the road. @@ -137,7 +137,7 @@ fn solution_with_size( who: voter.clone(), distribution: votes .iter() - .map(|t| (t.clone(), >::from_percent(percent_per_edge))) + .map(|t| (t.clone(), SolutionAccuracyOf::::from_percent(percent_per_edge))) .collect::>(), } }) @@ -147,7 +147,7 @@ fn solution_with_size( >::from_assignment(&assignments, &voter_index, &target_index) .unwrap(); let score = solution.clone().score(stake_of, voter_at, target_at).unwrap(); - let round = >::round(); + let round = Round::::get(); assert!( score.minimal_stake > 0, @@ -192,32 +192,32 @@ fn set_up_data_provider(v: u32, t: u32) { frame_benchmarking::benchmarks! { on_initialize_nothing { - assert!(>::current_phase().is_off()); + assert!(CurrentPhase::::get().is_off()); }: { - >::on_initialize(1u32.into()); + MultiPhase::::on_initialize(1u32.into()); } verify { - assert!(>::current_phase().is_off()); + assert!(CurrentPhase::::get().is_off()); } on_initialize_open_signed { - assert!(>::snapshot().is_none()); - assert!(>::current_phase().is_off()); + assert!(Snapshot::::get().is_none()); + assert!(CurrentPhase::::get().is_off()); }: { - >::phase_transition(Phase::Signed); + MultiPhase::::phase_transition(Phase::Signed); } verify { - assert!(>::snapshot().is_none()); - assert!(>::current_phase().is_signed()); + assert!(Snapshot::::get().is_none()); + assert!(CurrentPhase::::get().is_signed()); } on_initialize_open_unsigned { - assert!(>::snapshot().is_none()); - assert!(>::current_phase().is_off()); + assert!(Snapshot::::get().is_none()); + assert!(CurrentPhase::::get().is_off()); }: { let now = frame_system::Pallet::::block_number(); - >::phase_transition(Phase::Unsigned((true, now))); + MultiPhase::::phase_transition(Phase::Unsigned((true, now))); } verify { - assert!(>::snapshot().is_none()); - assert!(>::current_phase().is_unsigned()); + assert!(Snapshot::::get().is_none()); + assert!(CurrentPhase::::get().is_unsigned()); } finalize_signed_phase_accept_solution { @@ -233,7 +233,7 @@ frame_benchmarking::benchmarks! { assert_ok!(T::Currency::reserve(&receiver, deposit)); assert_eq!(T::Currency::free_balance(&receiver), T::Currency::minimum_balance()); }: { - >::finalize_signed_phase_accept_solution( + MultiPhase::::finalize_signed_phase_accept_solution( ready, &receiver, deposit, @@ -257,7 +257,7 @@ frame_benchmarking::benchmarks! { assert_eq!(T::Currency::free_balance(&receiver), T::Currency::minimum_balance()); assert_eq!(T::Currency::reserved_balance(&receiver), 10u32.into()); }: { - >::finalize_signed_phase_reject_solution(&receiver, deposit) + MultiPhase::::finalize_signed_phase_reject_solution(&receiver, deposit) } verify { assert_eq!(T::Currency::free_balance(&receiver), T::Currency::minimum_balance()); assert_eq!(T::Currency::reserved_balance(&receiver), 0u32.into()); @@ -275,13 +275,13 @@ frame_benchmarking::benchmarks! { let targets = T::DataProvider::electable_targets(DataProviderBounds::default())?; let voters = T::DataProvider::electing_voters(DataProviderBounds::default())?; let desired_targets = T::DataProvider::desired_targets()?; - assert!(>::snapshot().is_none()); + assert!(Snapshot::::get().is_none()); }: { - >::create_snapshot_internal(targets, voters, desired_targets) + MultiPhase::::create_snapshot_internal(targets, voters, desired_targets) } verify { - assert!(>::snapshot().is_some()); - assert_eq!(>::snapshot_metadata().ok_or("metadata missing")?.voters, v); - assert_eq!(>::snapshot_metadata().ok_or("metadata missing")?.targets, t); + assert!(Snapshot::::get().is_some()); + assert_eq!(SnapshotMetadata::::get().ok_or("metadata missing")?.voters, v); + assert_eq!(SnapshotMetadata::::get().ok_or("metadata missing")?.targets, t); } // a call to `::elect` where we only return the queued solution. @@ -300,31 +300,31 @@ frame_benchmarking::benchmarks! { let witness = SolutionOrSnapshotSize { voters: v, targets: t }; let raw_solution = solution_with_size::(witness, a, d)?; let ready_solution = - >::feasibility_check(raw_solution, ElectionCompute::Signed) + MultiPhase::::feasibility_check(raw_solution, ElectionCompute::Signed) .map_err(<&str>::from)?; - >::put(Phase::Signed); + CurrentPhase::::put(Phase::Signed); // assume a queued solution is stored, regardless of where it comes from. - >::put(ready_solution); + QueuedSolution::::put(ready_solution); // these are set by the `solution_with_size` function. - assert!(>::get().is_some()); - assert!(>::get().is_some()); - assert!(>::get().is_some()); + assert!(DesiredTargets::::get().is_some()); + assert!(Snapshot::::get().is_some()); + assert!(SnapshotMetadata::::get().is_some()); }: { assert_ok!( as ElectionProvider>::elect()); } verify { - assert!(>::queued_solution().is_none()); - assert!(>::get().is_none()); - assert!(>::get().is_none()); - assert!(>::get().is_none()); - assert_eq!(>::get(), >>::Off); + assert!(QueuedSolution::::get().is_none()); + assert!(DesiredTargets::::get().is_none()); + assert!(Snapshot::::get().is_none()); + assert!(SnapshotMetadata::::get().is_none()); + assert_eq!(CurrentPhase::::get(), >>::Off); } submit { // the queue is full and the solution is only better than the worse. - >::create_snapshot().map_err(<&str>::from)?; - >::phase_transition(Phase::Signed); - >::put(1); + MultiPhase::::create_snapshot().map_err(<&str>::from)?; + MultiPhase::::phase_transition(Phase::Signed); + Round::::put(1); let mut signed_submissions = SignedSubmissions::::get(); @@ -353,13 +353,13 @@ frame_benchmarking::benchmarks! { let caller = frame_benchmarking::whitelisted_caller(); let deposit = MultiPhase::::deposit_for( &solution, - MultiPhase::::snapshot_metadata().unwrap_or_default(), + SnapshotMetadata::::get().unwrap_or_default(), ); T::Currency::make_free_balance_be(&caller, T::Currency::minimum_balance() * 1000u32.into() + deposit); }: _(RawOrigin::Signed(caller), Box::new(solution)) verify { - assert!(>::signed_submissions().len() as u32 == T::SignedMaxSubmissions::get()); + assert!(MultiPhase::::signed_submissions().len() as u32 == T::SignedMaxSubmissions::get()); } submit_unsigned { @@ -379,11 +379,11 @@ frame_benchmarking::benchmarks! { let witness = SolutionOrSnapshotSize { voters: v, targets: t }; let raw_solution = solution_with_size::(witness, a, d)?; - assert!(>::queued_solution().is_none()); - >::put(Phase::Unsigned((true, 1u32.into()))); + assert!(QueuedSolution::::get().is_none()); + CurrentPhase::::put(Phase::Unsigned((true, 1u32.into()))); }: _(RawOrigin::None, Box::new(raw_solution), witness) verify { - assert!(>::queued_solution().is_some()); + assert!(QueuedSolution::::get().is_some()); } // This is checking a valid solution. The worse case is indeed a valid solution. @@ -404,7 +404,7 @@ frame_benchmarking::benchmarks! { assert_eq!(raw_solution.solution.voter_count() as u32, a); assert_eq!(raw_solution.solution.unique_targets().len() as u32, d); }: { - assert!(>::feasibility_check(raw_solution, ElectionCompute::Unsigned).is_ok()); + assert!(MultiPhase::::feasibility_check(raw_solution, ElectionCompute::Unsigned).is_ok()); } // NOTE: this weight is not used anywhere, but the fact that it should succeed when execution in @@ -428,11 +428,11 @@ frame_benchmarking::benchmarks! { set_up_data_provider::(v, t); let now = frame_system::Pallet::::block_number(); - >::put(Phase::Unsigned((true, now))); - >::create_snapshot().unwrap(); + CurrentPhase::::put(Phase::Unsigned((true, now))); + MultiPhase::::create_snapshot().unwrap(); }: { // we can't really verify this as it won't write anything to state, check logs. - >::offchain_worker(now) + MultiPhase::::offchain_worker(now) } // NOTE: this weight is not used anywhere, but the fact that it should succeed when execution in @@ -449,13 +449,13 @@ frame_benchmarking::benchmarks! { let t = T::BenchmarkingConfig::MAXIMUM_TARGETS; set_up_data_provider::(v, t); - assert!(>::snapshot().is_none()); + assert!(Snapshot::::get().is_none()); }: { - >::create_snapshot().map_err(|_| "could not create snapshot")?; + MultiPhase::::create_snapshot().map_err(|_| "could not create snapshot")?; } verify { - assert!(>::snapshot().is_some()); - assert_eq!(>::snapshot_metadata().ok_or("snapshot missing")?.voters, v); - assert_eq!(>::snapshot_metadata().ok_or("snapshot missing")?.targets, t); + assert!(Snapshot::::get().is_some()); + assert_eq!(SnapshotMetadata::::get().ok_or("snapshot missing")?.voters, v); + assert_eq!(SnapshotMetadata::::get().ok_or("snapshot missing")?.targets, t); } #[extra] @@ -480,7 +480,7 @@ frame_benchmarking::benchmarks! { // assignments let witness = SolutionOrSnapshotSize { voters: v, targets: t }; let RawSolution { solution, .. } = solution_with_size::(witness, a, d)?; - let RoundSnapshot { voters, targets } = MultiPhase::::snapshot().ok_or("snapshot missing")?; + let RoundSnapshot { voters, targets } = Snapshot::::get().ok_or("snapshot missing")?; let voter_at = helpers::voter_at_fn::(&voters); let target_at = helpers::target_at_fn::(&targets); let mut assignments = solution.into_assignment(voter_at, target_at).expect("solution generated by `solution_with_size` must be valid."); diff --git a/substrate/frame/election-provider-multi-phase/src/helpers.rs b/substrate/frame/election-provider-multi-phase/src/helpers.rs index 8269b2cb73be2..68facd098e65f 100644 --- a/substrate/frame/election-provider-multi-phase/src/helpers.rs +++ b/substrate/frame/election-provider-multi-phase/src/helpers.rs @@ -28,7 +28,7 @@ macro_rules! log { ($level:tt, $pattern:expr $(, $values:expr)* $(,)?) => { log::$level!( target: $crate::LOG_TARGET, - concat!("[#{:?}] 🗳 ", $pattern), >::block_number() $(, $values)* + concat!("[#{:?}] 🗳 ", $pattern), frame_system::Pallet::::block_number() $(, $values)* ) }; } diff --git a/substrate/frame/election-provider-multi-phase/src/lib.rs b/substrate/frame/election-provider-multi-phase/src/lib.rs index 9ce8b3890a624..09248e77848b6 100644 --- a/substrate/frame/election-provider-multi-phase/src/lib.rs +++ b/substrate/frame/election-provider-multi-phase/src/lib.rs @@ -746,14 +746,14 @@ pub mod pallet { let unsigned_deadline = T::UnsignedPhase::get(); let remaining = next_election - now; - let current_phase = Self::current_phase(); + let current_phase = CurrentPhase::::get(); log!( trace, "current phase {:?}, next election {:?}, metadata: {:?}", current_phase, next_election, - Self::snapshot_metadata() + SnapshotMetadata::::get() ); match current_phase { Phase::Off if remaining <= signed_deadline && remaining > unsigned_deadline => { @@ -853,7 +853,7 @@ pub mod pallet { let maximum_chain_accuracy: Vec>> = (0..max_vote) .map(|_| { >>::from( - >::one().deconstruct(), + SolutionAccuracyOf::::one().deconstruct(), ) }) .collect(); @@ -923,7 +923,7 @@ pub mod pallet { // Ensure witness was correct. let SolutionOrSnapshotSize { voters, targets } = - Self::snapshot_metadata().expect(error_message); + SnapshotMetadata::::get().expect(error_message); // NOTE: we are asserting, not `ensure`ing -- we want to panic here. assert!(voters as u32 == witness.voters, "{}", error_message); @@ -934,8 +934,8 @@ pub mod pallet { // Store the newly received solution. log!(debug, "queued unsigned solution with score {:?}", ready.score); - let ejected_a_solution = >::exists(); - >::put(ready); + let ejected_a_solution = QueuedSolution::::exists(); + QueuedSolution::::put(ready); Self::deposit_event(Event::SolutionStored { compute: ElectionCompute::Unsigned, origin: None, @@ -957,7 +957,7 @@ pub mod pallet { maybe_next_score: Option, ) -> DispatchResult { T::ForceOrigin::ensure_origin(origin)?; - >::set(maybe_next_score); + MinimumUntrustedScore::::set(maybe_next_score); Ok(()) } @@ -976,7 +976,7 @@ pub mod pallet { supports: Supports, ) -> DispatchResult { T::ForceOrigin::ensure_origin(origin)?; - ensure!(Self::current_phase().is_emergency(), >::CallNotAllowed); + ensure!(CurrentPhase::::get().is_emergency(), Error::::CallNotAllowed); // bound supports with T::MaxWinners let supports = supports.try_into().map_err(|_| Error::::TooManyWinners)?; @@ -995,7 +995,7 @@ pub mod pallet { prev_ejected: QueuedSolution::::exists(), }); - >::put(solution); + QueuedSolution::::put(solution); Ok(()) } @@ -1017,15 +1017,15 @@ pub mod pallet { let who = ensure_signed(origin)?; // ensure solution is timely. - ensure!(Self::current_phase().is_signed(), Error::::PreDispatchEarlySubmission); - ensure!(raw_solution.round == Self::round(), Error::::PreDispatchDifferentRound); + ensure!(CurrentPhase::::get().is_signed(), Error::::PreDispatchEarlySubmission); + ensure!(raw_solution.round == Round::::get(), Error::::PreDispatchDifferentRound); // NOTE: this is the only case where having separate snapshot would have been better // because could do just decode_len. But we can create abstractions to do this. // build size. Note: this is not needed for weight calc, thus not input. // unlikely to ever return an error: if phase is signed, snapshot will exist. - let size = Self::snapshot_metadata().ok_or(Error::::MissingSnapshotMetadata)?; + let size = SnapshotMetadata::::get().ok_or(Error::::MissingSnapshotMetadata)?; ensure!( Self::solution_weight_of(&raw_solution, size).all_lt(T::SignedMaxWeight::get()), @@ -1088,7 +1088,7 @@ pub mod pallet { maybe_max_targets: Option, ) -> DispatchResult { T::ForceOrigin::ensure_origin(origin)?; - ensure!(Self::current_phase().is_emergency(), >::CallNotAllowed); + ensure!(CurrentPhase::::get().is_emergency(), Error::::CallNotAllowed); let election_bounds = ElectionBoundsBuilder::default() .voters_count(maybe_max_voters.unwrap_or(u32::MAX).into()) @@ -1123,7 +1123,7 @@ pub mod pallet { prev_ejected: QueuedSolution::::exists(), }); - >::put(solution); + QueuedSolution::::put(solution); Ok(()) } } @@ -1256,19 +1256,16 @@ pub mod pallet { /// /// This is merely incremented once per every time that an upstream `elect` is called. #[pallet::storage] - #[pallet::getter(fn round)] pub type Round = StorageValue<_, u32, ValueQuery, DefaultForRound>; /// Current phase. #[pallet::storage] - #[pallet::getter(fn current_phase)] pub type CurrentPhase = StorageValue<_, Phase>, ValueQuery>; /// Current best solution, signed or unsigned, queued to be returned upon `elect`. /// /// Always sorted by score. #[pallet::storage] - #[pallet::getter(fn queued_solution)] pub type QueuedSolution = StorageValue<_, ReadySolution>; @@ -1277,7 +1274,6 @@ pub mod pallet { /// This is created at the beginning of the signed phase and cleared upon calling `elect`. /// Note: This storage type must only be mutated through [`SnapshotWrapper`]. #[pallet::storage] - #[pallet::getter(fn snapshot)] pub type Snapshot = StorageValue<_, RoundSnapshot>>; /// Desired number of targets to elect for this round. @@ -1285,7 +1281,6 @@ pub mod pallet { /// Only exists when [`Snapshot`] is present. /// Note: This storage type must only be mutated through [`SnapshotWrapper`]. #[pallet::storage] - #[pallet::getter(fn desired_targets)] pub type DesiredTargets = StorageValue<_, u32>; /// The metadata of the [`RoundSnapshot`] @@ -1293,7 +1288,6 @@ pub mod pallet { /// Only exists when [`Snapshot`] is present. /// Note: This storage type must only be mutated through [`SnapshotWrapper`]. #[pallet::storage] - #[pallet::getter(fn snapshot_metadata)] pub type SnapshotMetadata = StorageValue<_, SolutionOrSnapshotSize>; // The following storage items collectively comprise `SignedSubmissions`, and should never be @@ -1340,7 +1334,6 @@ pub mod pallet { /// /// Can be set via `set_minimum_untrusted_score`. #[pallet::storage] - #[pallet::getter(fn minimum_untrusted_score)] pub type MinimumUntrustedScore = StorageValue<_, ElectionScore>; /// The in-code storage version. @@ -1361,15 +1354,15 @@ pub struct SnapshotWrapper(core::marker::PhantomData); impl SnapshotWrapper { /// Kill all snapshot related storage items at the same time. pub fn kill() { - >::kill(); - >::kill(); - >::kill(); + Snapshot::::kill(); + SnapshotMetadata::::kill(); + DesiredTargets::::kill(); } /// Set all snapshot related storage items at the same time. pub fn set(metadata: SolutionOrSnapshotSize, desired_targets: u32, buffer: &[u8]) { - >::put(metadata); - >::put(desired_targets); - sp_io::storage::set(&>::hashed_key(), &buffer); + SnapshotMetadata::::put(metadata); + DesiredTargets::::put(desired_targets); + sp_io::storage::set(&Snapshot::::hashed_key(), &buffer); } /// Check if all of the storage items exist at the same time or all of the storage items do not @@ -1377,9 +1370,9 @@ impl SnapshotWrapper { #[cfg(feature = "try-runtime")] pub fn is_consistent() -> bool { let snapshots = [ - >::exists(), - >::exists(), - >::exists(), + Snapshot::::exists(), + SnapshotMetadata::::exists(), + DesiredTargets::::exists(), ]; // All should either exist or not exist @@ -1388,10 +1381,64 @@ impl SnapshotWrapper { } impl Pallet { + /// Internal counter for the number of rounds. + /// + /// This is useful for de-duplication of transactions submitted to the pool, and general + /// diagnostics of the pallet. + /// + /// This is merely incremented once per every time that an upstream `elect` is called. + pub fn round() -> u32 { + Round::::get() + } + + /// Current phase. + pub fn current_phase() -> Phase> { + CurrentPhase::::get() + } + + /// Current best solution, signed or unsigned, queued to be returned upon `elect`. + /// + /// Always sorted by score. + pub fn queued_solution() -> Option> { + QueuedSolution::::get() + } + + /// Snapshot data of the round. + /// + /// This is created at the beginning of the signed phase and cleared upon calling `elect`. + /// Note: This storage type must only be mutated through [`SnapshotWrapper`]. + pub fn snapshot() -> Option>> { + Snapshot::::get() + } + + /// Desired number of targets to elect for this round. + /// + /// Only exists when [`Snapshot`] is present. + /// Note: This storage type must only be mutated through [`SnapshotWrapper`]. + pub fn desired_targets() -> Option { + DesiredTargets::::get() + } + + /// The metadata of the [`RoundSnapshot`] + /// + /// Only exists when [`Snapshot`] is present. + /// Note: This storage type must only be mutated through [`SnapshotWrapper`]. + pub fn snapshot_metadata() -> Option { + SnapshotMetadata::::get() + } + + /// The minimum score that each 'untrusted' solution must attain in order to be considered + /// feasible. + /// + /// Can be set via `set_minimum_untrusted_score`. + pub fn minimum_untrusted_score() -> Option { + MinimumUntrustedScore::::get() + } + /// Internal logic of the offchain worker, to be executed only when the offchain lock is /// acquired with success. fn do_synchronized_offchain_worker(now: BlockNumberFor) { - let current_phase = Self::current_phase(); + let current_phase = CurrentPhase::::get(); log!(trace, "lock for offchain worker acquired. Phase = {:?}", current_phase); match current_phase { Phase::Unsigned((true, opened)) if opened == now => { @@ -1417,13 +1464,13 @@ impl Pallet { /// Phase transition helper. pub(crate) fn phase_transition(to: Phase>) { - log!(info, "Starting phase {:?}, round {}.", to, Self::round()); + log!(info, "Starting phase {:?}, round {}.", to, Round::::get()); Self::deposit_event(Event::PhaseTransitioned { - from: >::get(), + from: CurrentPhase::::get(), to, - round: Self::round(), + round: Round::::get(), }); - >::put(to); + CurrentPhase::::put(to); } /// Parts of [`create_snapshot`] that happen inside of this pallet. @@ -1527,7 +1574,7 @@ impl Pallet { /// /// This is always mandatory weight. fn register_weight(weight: Weight) { - >::register_extra_weight_unchecked( + frame_system::Pallet::::register_extra_weight_unchecked( weight, DispatchClass::Mandatory, ); @@ -1539,11 +1586,11 @@ impl Pallet { compute: ElectionCompute, ) -> Result, FeasibilityError> { let desired_targets = - Self::desired_targets().ok_or(FeasibilityError::SnapshotUnavailable)?; + DesiredTargets::::get().ok_or(FeasibilityError::SnapshotUnavailable)?; - let snapshot = Self::snapshot().ok_or(FeasibilityError::SnapshotUnavailable)?; - let round = Self::round(); - let minimum_untrusted_score = Self::minimum_untrusted_score(); + let snapshot = Snapshot::::get().ok_or(FeasibilityError::SnapshotUnavailable)?; + let round = Round::::get(); + let minimum_untrusted_score = MinimumUntrustedScore::::get(); Miner::::feasibility_check( raw_solution, @@ -1562,7 +1609,7 @@ impl Pallet { /// 3. Clear all snapshot data. fn rotate_round() { // Inc round. - >::mutate(|r| *r += 1); + Round::::mutate(|r| *r += 1); // Phase is off now. Self::phase_transition(Phase::Off); @@ -1581,7 +1628,7 @@ impl Pallet { // inexpensive (1 read of an empty vector). let _ = Self::finalize_signed_phase(); - >::take() + QueuedSolution::::take() .ok_or(ElectionError::::NothingQueued) .or_else(|_| { // default data provider bounds are unbounded. calling `instant_elect` with @@ -1602,14 +1649,14 @@ impl Pallet { }) .map(|ReadySolution { compute, score, supports }| { Self::deposit_event(Event::ElectionFinalized { compute, score }); - if Self::round() != 1 { + if Round::::get() != 1 { log!(info, "Finalized election round with compute {:?}.", compute); } supports }) .map_err(|err| { Self::deposit_event(Event::ElectionFailed); - if Self::round() != 1 { + if Round::::get() != 1 { log!(warn, "Failed to finalize election round. reason {:?}", err); } err @@ -1652,10 +1699,10 @@ impl Pallet { // - [`SignedSubmissionIndices`] is sorted by election score. fn try_state_signed_submissions_map() -> Result<(), TryRuntimeError> { let mut last_score: ElectionScore = Default::default(); - let indices = >::get(); + let indices = SignedSubmissionIndices::::get(); for (i, indice) in indices.iter().enumerate() { - let submission = >::get(indice.2); + let submission = SignedSubmissionsMap::::get(indice.2); if submission.is_none() { return Err( "All signed submissions indices must be part of the submissions map".into() @@ -1674,16 +1721,16 @@ impl Pallet { } } - if >::iter().nth(indices.len()).is_some() { + if SignedSubmissionsMap::::iter().nth(indices.len()).is_some() { return Err( "Signed submissions map length should be the same as the indices vec length".into() ) } - match >::get() { + match SignedSubmissionNextIndex::::get() { 0 => Ok(()), next => - if >::get(next).is_some() { + if SignedSubmissionsMap::::get(next).is_some() { return Err( "The next submissions index should not be in the submissions maps already" .into(), @@ -1697,10 +1744,10 @@ impl Pallet { // [`Phase::Off`] state check. Invariants: // - If phase is `Phase::Off`, [`Snapshot`] must be none. fn try_state_phase_off() -> Result<(), TryRuntimeError> { - match Self::current_phase().is_off() { + match CurrentPhase::::get().is_off() { false => Ok(()), true => - if >::get().is_some() { + if Snapshot::::get().is_some() { Err("Snapshot must be none when in Phase::Off".into()) } else { Ok(()) @@ -1719,7 +1766,7 @@ impl ElectionProviderBase for Pallet { impl ElectionProvider for Pallet { fn ongoing() -> bool { - match Self::current_phase() { + match CurrentPhase::::get() { Phase::Off => false, _ => true, } @@ -1771,12 +1818,12 @@ mod feasibility_check { fn snapshot_is_there() { ExtBuilder::default().build_and_execute(|| { roll_to(::get() - ::get() - ::get()); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let solution = raw_solution(); // kill `Snapshot`, `SnapshotMetadata` and `DesiredTargets` for the storage state to // be consistent, by using the `SnapshotWrapper` for the try_state checks to pass. - >::kill(); + SnapshotWrapper::::kill(); assert_noop!( MultiPhase::feasibility_check(solution, COMPUTE), @@ -1789,7 +1836,7 @@ mod feasibility_check { fn round() { ExtBuilder::default().build_and_execute(|| { roll_to(::get() - ::get() - ::get()); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let mut solution = raw_solution(); solution.round += 1; @@ -1804,13 +1851,13 @@ mod feasibility_check { fn desired_targets_gets_capped() { ExtBuilder::default().desired_targets(8).build_and_execute(|| { roll_to(::get() - ::get() - ::get()); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let raw = raw_solution(); assert_eq!(raw.solution.unique_targets().len(), 4); // desired_targets is capped to the number of targets which is 4 - assert_eq!(MultiPhase::desired_targets().unwrap(), 4); + assert_eq!(DesiredTargets::::get().unwrap(), 4); // It should succeed assert_ok!(MultiPhase::feasibility_check(raw, COMPUTE)); @@ -1821,13 +1868,13 @@ mod feasibility_check { fn less_than_desired_targets_fails() { ExtBuilder::default().desired_targets(8).build_and_execute(|| { roll_to(::get() - ::get() - ::get()); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let mut raw = raw_solution(); assert_eq!(raw.solution.unique_targets().len(), 4); // desired_targets is capped to the number of targets which is 4 - assert_eq!(MultiPhase::desired_targets().unwrap(), 4); + assert_eq!(DesiredTargets::::get().unwrap(), 4); // Force the number of winners to be bigger to fail raw.solution.votes1[0].1 = 4; @@ -1844,10 +1891,10 @@ mod feasibility_check { fn winner_indices() { ExtBuilder::default().desired_targets(2).build_and_execute(|| { roll_to(::get() - ::get() - ::get()); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let mut raw = raw_solution(); - assert_eq!(MultiPhase::snapshot().unwrap().targets.len(), 4); + assert_eq!(Snapshot::::get().unwrap().targets.len(), 4); // ----------------------------------------------------^^ valid range is [0..3]. // Swap all votes from 3 to 4. This will ensure that the number of unique winners will @@ -1878,10 +1925,10 @@ mod feasibility_check { // Should be caught in `solution.into_assignment`. ExtBuilder::default().desired_targets(2).build_and_execute(|| { roll_to(::get() - ::get() - ::get()); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let mut solution = raw_solution(); - assert_eq!(MultiPhase::snapshot().unwrap().voters.len(), 8); + assert_eq!(Snapshot::::get().unwrap().voters.len(), 8); // ----------------------------------------------------^^ valid range is [0..7]. // Check that there is an index 7 in votes1, and flip to 8. @@ -1905,10 +1952,10 @@ mod feasibility_check { fn voter_votes() { ExtBuilder::default().desired_targets(2).build_and_execute(|| { roll_to(::get() - ::get() - ::get()); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let mut solution = raw_solution(); - assert_eq!(MultiPhase::snapshot().unwrap().voters.len(), 8); + assert_eq!(Snapshot::::get().unwrap().voters.len(), 8); // ----------------------------------------------------^^ valid range is [0..7]. // First, check that voter at index 7 (40) actually voted for 3 (40) -- this is self @@ -1934,10 +1981,10 @@ mod feasibility_check { fn score() { ExtBuilder::default().desired_targets(2).build_and_execute(|| { roll_to(::get() - ::get() - ::get()); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let mut solution = raw_solution(); - assert_eq!(MultiPhase::snapshot().unwrap().voters.len(), 8); + assert_eq!(Snapshot::::get().unwrap().voters.len(), 8); // Simply faff with the score. solution.score.minimal_stake += 1; @@ -1972,30 +2019,30 @@ mod tests { // Signed Unsigned Elect Signed Unsigned Elect assert_eq!(System::block_number(), 0); - assert_eq!(MultiPhase::current_phase(), Phase::Off); - assert_eq!(MultiPhase::round(), 1); + assert_eq!(CurrentPhase::::get(), Phase::Off); + assert_eq!(Round::::get(), 1); roll_to(4); - assert_eq!(MultiPhase::current_phase(), Phase::Off); - assert!(MultiPhase::snapshot().is_none()); - assert_eq!(MultiPhase::round(), 1); + assert_eq!(CurrentPhase::::get(), Phase::Off); + assert!(Snapshot::::get().is_none()); + assert_eq!(Round::::get(), 1); roll_to_signed(); - assert_eq!(MultiPhase::current_phase(), Phase::Signed); + assert_eq!(CurrentPhase::::get(), Phase::Signed); assert_eq!( multi_phase_events(), vec![Event::PhaseTransitioned { from: Phase::Off, to: Phase::Signed, round: 1 }] ); - assert!(MultiPhase::snapshot().is_some()); - assert_eq!(MultiPhase::round(), 1); + assert!(Snapshot::::get().is_some()); + assert_eq!(Round::::get(), 1); roll_to(24); - assert_eq!(MultiPhase::current_phase(), Phase::Signed); - assert!(MultiPhase::snapshot().is_some()); - assert_eq!(MultiPhase::round(), 1); + assert_eq!(CurrentPhase::::get(), Phase::Signed); + assert!(Snapshot::::get().is_some()); + assert_eq!(Round::::get(), 1); roll_to_unsigned(); - assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, 25))); + assert_eq!(CurrentPhase::::get(), Phase::Unsigned((true, 25))); assert_eq!( multi_phase_events(), vec![ @@ -2007,35 +2054,35 @@ mod tests { }, ], ); - assert!(MultiPhase::snapshot().is_some()); + assert!(Snapshot::::get().is_some()); roll_to(29); - assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, 25))); - assert!(MultiPhase::snapshot().is_some()); + assert_eq!(CurrentPhase::::get(), Phase::Unsigned((true, 25))); + assert!(Snapshot::::get().is_some()); roll_to(30); - assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, 25))); - assert!(MultiPhase::snapshot().is_some()); + assert_eq!(CurrentPhase::::get(), Phase::Unsigned((true, 25))); + assert!(Snapshot::::get().is_some()); // We close when upstream tells us to elect. roll_to(32); - assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, 25))); - assert!(MultiPhase::snapshot().is_some()); + assert_eq!(CurrentPhase::::get(), Phase::Unsigned((true, 25))); + assert!(Snapshot::::get().is_some()); assert_ok!(MultiPhase::elect()); - assert!(MultiPhase::current_phase().is_off()); - assert!(MultiPhase::snapshot().is_none()); - assert_eq!(MultiPhase::round(), 2); + assert!(CurrentPhase::::get().is_off()); + assert!(Snapshot::::get().is_none()); + assert_eq!(Round::::get(), 2); roll_to(44); - assert!(MultiPhase::current_phase().is_off()); + assert!(CurrentPhase::::get().is_off()); roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); roll_to(55); - assert!(MultiPhase::current_phase().is_unsigned_open_at(55)); + assert!(CurrentPhase::::get().is_unsigned_open_at(55)); assert_eq!( multi_phase_events(), @@ -2074,22 +2121,22 @@ mod tests { fn signed_phase_void() { ExtBuilder::default().phases(0, 10).build_and_execute(|| { roll_to(15); - assert!(MultiPhase::current_phase().is_off()); + assert!(CurrentPhase::::get().is_off()); roll_to(19); - assert!(MultiPhase::current_phase().is_off()); + assert!(CurrentPhase::::get().is_off()); roll_to(20); - assert!(MultiPhase::current_phase().is_unsigned_open_at(20)); - assert!(MultiPhase::snapshot().is_some()); + assert!(CurrentPhase::::get().is_unsigned_open_at(20)); + assert!(Snapshot::::get().is_some()); roll_to(30); - assert!(MultiPhase::current_phase().is_unsigned_open_at(20)); + assert!(CurrentPhase::::get().is_unsigned_open_at(20)); assert_ok!(MultiPhase::elect()); - assert!(MultiPhase::current_phase().is_off()); - assert!(MultiPhase::snapshot().is_none()); + assert!(CurrentPhase::::get().is_off()); + assert!(Snapshot::::get().is_none()); assert_eq!( multi_phase_events(), @@ -2121,22 +2168,22 @@ mod tests { fn unsigned_phase_void() { ExtBuilder::default().phases(10, 0).build_and_execute(|| { roll_to(15); - assert!(MultiPhase::current_phase().is_off()); + assert!(CurrentPhase::::get().is_off()); roll_to(19); - assert!(MultiPhase::current_phase().is_off()); + assert!(CurrentPhase::::get().is_off()); roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); - assert!(MultiPhase::snapshot().is_some()); + assert!(CurrentPhase::::get().is_signed()); + assert!(Snapshot::::get().is_some()); roll_to(30); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); assert_ok!(MultiPhase::elect()); - assert!(MultiPhase::current_phase().is_off()); - assert!(MultiPhase::snapshot().is_none()); + assert!(CurrentPhase::::get().is_off()); + assert!(Snapshot::::get().is_none()); assert_eq!( multi_phase_events(), @@ -2160,21 +2207,21 @@ mod tests { fn both_phases_void() { ExtBuilder::default().phases(0, 0).build_and_execute(|| { roll_to(15); - assert!(MultiPhase::current_phase().is_off()); + assert!(CurrentPhase::::get().is_off()); roll_to(19); - assert!(MultiPhase::current_phase().is_off()); + assert!(CurrentPhase::::get().is_off()); roll_to(20); - assert!(MultiPhase::current_phase().is_off()); + assert!(CurrentPhase::::get().is_off()); roll_to(30); - assert!(MultiPhase::current_phase().is_off()); + assert!(CurrentPhase::::get().is_off()); // This module is now only capable of doing on-chain backup. assert_ok!(MultiPhase::elect()); - assert!(MultiPhase::current_phase().is_off()); + assert!(CurrentPhase::::get().is_off()); assert_eq!( multi_phase_events(), @@ -2204,8 +2251,8 @@ mod tests { multi_phase_events(), vec![Event::PhaseTransitioned { from: Phase::Off, to: Phase::Signed, round: 1 }] ); - assert_eq!(MultiPhase::current_phase(), Phase::Signed); - assert_eq!(MultiPhase::round(), 1); + assert_eq!(CurrentPhase::::get(), Phase::Signed); + assert_eq!(Round::::get(), 1); // An unexpected call to elect. assert_ok!(MultiPhase::elect()); @@ -2223,11 +2270,11 @@ mod tests { ], ); // All storage items must be cleared. - assert_eq!(MultiPhase::round(), 2); - assert!(MultiPhase::snapshot().is_none()); - assert!(MultiPhase::snapshot_metadata().is_none()); - assert!(MultiPhase::desired_targets().is_none()); - assert!(MultiPhase::queued_solution().is_none()); + assert_eq!(Round::::get(), 2); + assert!(Snapshot::::get().is_none()); + assert!(SnapshotMetadata::::get().is_none()); + assert!(DesiredTargets::::get().is_none()); + assert!(QueuedSolution::::get().is_none()); assert!(MultiPhase::signed_submissions().is_empty()); }) } @@ -2243,8 +2290,8 @@ mod tests { multi_phase_events(), vec![Event::PhaseTransitioned { from: Phase::Off, to: Phase::Signed, round: 1 }] ); - assert_eq!(MultiPhase::current_phase(), Phase::Signed); - assert_eq!(MultiPhase::round(), 1); + assert_eq!(CurrentPhase::::get(), Phase::Signed); + assert_eq!(Round::::get(), 1); // fill the queue with signed submissions for s in 0..SignedMaxSubmissions::get() { @@ -2262,11 +2309,11 @@ mod tests { assert_ok!(MultiPhase::elect()); // all storage items must be cleared. - assert_eq!(MultiPhase::round(), 2); - assert!(MultiPhase::snapshot().is_none()); - assert!(MultiPhase::snapshot_metadata().is_none()); - assert!(MultiPhase::desired_targets().is_none()); - assert!(MultiPhase::queued_solution().is_none()); + assert_eq!(Round::::get(), 2); + assert!(Snapshot::::get().is_none()); + assert!(SnapshotMetadata::::get().is_none()); + assert!(DesiredTargets::::get().is_none()); + assert!(QueuedSolution::::get().is_none()); assert!(MultiPhase::signed_submissions().is_empty()); assert_eq!( @@ -2321,7 +2368,7 @@ mod tests { fn check_events_with_compute_signed() { ExtBuilder::default().build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let solution = raw_solution(); assert_ok!(MultiPhase::submit( @@ -2369,23 +2416,23 @@ mod tests { fn check_events_with_compute_unsigned() { ExtBuilder::default().build_and_execute(|| { roll_to_unsigned(); - assert!(MultiPhase::current_phase().is_unsigned()); + assert!(CurrentPhase::::get().is_unsigned()); // ensure we have snapshots in place. - assert!(MultiPhase::snapshot().is_some()); - assert_eq!(MultiPhase::desired_targets().unwrap(), 2); + assert!(Snapshot::::get().is_some()); + assert_eq!(DesiredTargets::::get().unwrap(), 2); // mine seq_phragmen solution with 2 iters. let (solution, witness, _) = MultiPhase::mine_solution().unwrap(); // ensure this solution is valid. - assert!(MultiPhase::queued_solution().is_none()); + assert!(QueuedSolution::::get().is_none()); assert_ok!(MultiPhase::submit_unsigned( crate::mock::RuntimeOrigin::none(), Box::new(solution), witness )); - assert!(MultiPhase::queued_solution().is_some()); + assert!(QueuedSolution::::get().is_some()); assert_ok!(MultiPhase::elect()); @@ -2425,10 +2472,10 @@ mod tests { fn fallback_strategy_works() { ExtBuilder::default().onchain_fallback(true).build_and_execute(|| { roll_to_unsigned(); - assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, 25))); + assert_eq!(CurrentPhase::::get(), Phase::Unsigned((true, 25))); // Zilch solutions thus far, but we get a result. - assert!(MultiPhase::queued_solution().is_none()); + assert!(QueuedSolution::::get().is_none()); let supports = MultiPhase::elect().unwrap(); assert_eq!( @@ -2467,15 +2514,15 @@ mod tests { ExtBuilder::default().onchain_fallback(false).build_and_execute(|| { roll_to_unsigned(); - assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, 25))); + assert_eq!(CurrentPhase::::get(), Phase::Unsigned((true, 25))); // Zilch solutions thus far. - assert!(MultiPhase::queued_solution().is_none()); + assert!(QueuedSolution::::get().is_none()); assert_eq!(MultiPhase::elect().unwrap_err(), ElectionError::Fallback("NoFallback.")); // phase is now emergency. - assert_eq!(MultiPhase::current_phase(), Phase::Emergency); + assert_eq!(CurrentPhase::::get(), Phase::Emergency); // snapshot is still there until election finalizes. - assert!(MultiPhase::snapshot().is_some()); + assert!(Snapshot::::get().is_some()); assert_eq!( multi_phase_events(), @@ -2501,16 +2548,16 @@ mod tests { fn governance_fallback_works() { ExtBuilder::default().onchain_fallback(false).build_and_execute(|| { roll_to_unsigned(); - assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, 25))); + assert_eq!(CurrentPhase::::get(), Phase::Unsigned((true, 25))); // Zilch solutions thus far. - assert!(MultiPhase::queued_solution().is_none()); + assert!(QueuedSolution::::get().is_none()); assert_eq!(MultiPhase::elect().unwrap_err(), ElectionError::Fallback("NoFallback.")); // phase is now emergency. - assert_eq!(MultiPhase::current_phase(), Phase::Emergency); - assert!(MultiPhase::queued_solution().is_none()); - assert!(MultiPhase::snapshot().is_some()); + assert_eq!(CurrentPhase::::get(), Phase::Emergency); + assert!(QueuedSolution::::get().is_none()); + assert!(Snapshot::::get().is_some()); // no single account can trigger this assert_noop!( @@ -2521,10 +2568,10 @@ mod tests { // only root can assert_ok!(MultiPhase::governance_fallback(RuntimeOrigin::root(), None, None)); // something is queued now - assert!(MultiPhase::queued_solution().is_some()); + assert!(QueuedSolution::::get().is_some()); // next election call with fix everything.; assert!(MultiPhase::elect().is_ok()); - assert_eq!(MultiPhase::current_phase(), Phase::Off); + assert_eq!(CurrentPhase::::get(), Phase::Off); assert_eq!( multi_phase_events(), @@ -2568,11 +2615,11 @@ mod tests { // Signed phase failed to open. roll_to(15); - assert_eq!(MultiPhase::current_phase(), Phase::Off); + assert_eq!(CurrentPhase::::get(), Phase::Off); // Unsigned phase failed to open. roll_to(25); - assert_eq!(MultiPhase::current_phase(), Phase::Off); + assert_eq!(CurrentPhase::::get(), Phase::Off); // On-chain backup works though. let supports = MultiPhase::elect().unwrap(); @@ -2607,16 +2654,16 @@ mod tests { // Signed phase failed to open. roll_to(15); - assert_eq!(MultiPhase::current_phase(), Phase::Off); + assert_eq!(CurrentPhase::::get(), Phase::Off); // Unsigned phase failed to open. roll_to(25); - assert_eq!(MultiPhase::current_phase(), Phase::Off); + assert_eq!(CurrentPhase::::get(), Phase::Off); roll_to(29); let err = MultiPhase::elect().unwrap_err(); assert_eq!(err, ElectionError::Fallback("NoFallback.")); - assert_eq!(MultiPhase::current_phase(), Phase::Emergency); + assert_eq!(CurrentPhase::::get(), Phase::Emergency); assert_eq!( multi_phase_events(), @@ -2640,10 +2687,10 @@ mod tests { // Signed phase opens just fine. roll_to_signed(); - assert_eq!(MultiPhase::current_phase(), Phase::Signed); + assert_eq!(CurrentPhase::::get(), Phase::Signed); assert_eq!( - MultiPhase::snapshot_metadata().unwrap(), + SnapshotMetadata::::get().unwrap(), SolutionOrSnapshotSize { voters: 2, targets: 4 } ); }) @@ -2653,7 +2700,7 @@ mod tests { fn untrusted_score_verification_is_respected() { ExtBuilder::default().build_and_execute(|| { roll_to_signed(); - assert_eq!(MultiPhase::current_phase(), Phase::Signed); + assert_eq!(CurrentPhase::::get(), Phase::Signed); // set the solution balancing to get the desired score. crate::mock::Balancing::set(Some(BalancingConfig { iterations: 2, tolerance: 0 })); @@ -2662,13 +2709,13 @@ mod tests { // Default solution's score. assert!(matches!(solution.score, ElectionScore { minimal_stake: 50, .. })); - >::put(ElectionScore { + MinimumUntrustedScore::::put(ElectionScore { minimal_stake: 49, ..Default::default() }); assert_ok!(MultiPhase::feasibility_check(solution.clone(), ElectionCompute::Signed)); - >::put(ElectionScore { + MinimumUntrustedScore::::put(ElectionScore { minimal_stake: 51, ..Default::default() }); diff --git a/substrate/frame/election-provider-multi-phase/src/mock.rs b/substrate/frame/election-provider-multi-phase/src/mock.rs index 4532185b959c0..32a099e1a26f4 100644 --- a/substrate/frame/election-provider-multi-phase/src/mock.rs +++ b/substrate/frame/election-provider-multi-phase/src/mock.rs @@ -92,12 +92,12 @@ pub fn roll_to(n: BlockNumber) { } pub fn roll_to_unsigned() { - while !matches!(MultiPhase::current_phase(), Phase::Unsigned(_)) { + while !matches!(CurrentPhase::::get(), Phase::Unsigned(_)) { roll_to(System::block_number() + 1); } } pub fn roll_to_signed() { - while !matches!(MultiPhase::current_phase(), Phase::Signed) { + while !matches!(CurrentPhase::::get(), Phase::Signed) { roll_to(System::block_number() + 1); } } @@ -112,9 +112,9 @@ pub fn roll_to_with_ocw(n: BlockNumber) { } pub fn roll_to_round(n: u32) { - assert!(MultiPhase::round() <= n); + assert!(Round::::get() <= n); - while MultiPhase::round() != n { + while Round::::get() != n { roll_to_signed(); frame_support::assert_ok!(MultiPhase::elect()); } @@ -136,7 +136,7 @@ pub struct TrimHelpers { /// /// Assignments are pre-sorted in reverse order of stake. pub fn trim_helpers() -> TrimHelpers { - let RoundSnapshot { voters, targets } = MultiPhase::snapshot().unwrap(); + let RoundSnapshot { voters, targets } = Snapshot::::get().unwrap(); let stakes: std::collections::HashMap<_, _> = voters.iter().map(|(id, stake, _)| (*id, *stake)).collect(); @@ -150,7 +150,7 @@ pub fn trim_helpers() -> TrimHelpers { let voter_index = helpers::voter_index_fn_owned::(cache); let target_index = helpers::target_index_fn::(&targets); - let desired_targets = MultiPhase::desired_targets().unwrap(); + let desired_targets = crate::DesiredTargets::::get().unwrap(); let ElectionResult::<_, SolutionAccuracyOf> { mut assignments, .. } = seq_phragmen(desired_targets as usize, targets.clone(), voters.clone(), None).unwrap(); @@ -176,8 +176,8 @@ pub fn trim_helpers() -> TrimHelpers { /// /// This is a good example of what an offchain miner would do. pub fn raw_solution() -> RawSolution> { - let RoundSnapshot { voters, targets } = MultiPhase::snapshot().unwrap(); - let desired_targets = MultiPhase::desired_targets().unwrap(); + let RoundSnapshot { voters, targets } = Snapshot::::get().unwrap(); + let desired_targets = crate::DesiredTargets::::get().unwrap(); let ElectionResult::<_, SolutionAccuracyOf> { winners: _, assignments } = seq_phragmen(desired_targets as usize, targets.clone(), voters.clone(), None).unwrap(); @@ -193,14 +193,14 @@ pub fn raw_solution() -> RawSolution> { to_supports(&staked).evaluate() }; let solution = - >::from_assignment(&assignments, &voter_index, &target_index).unwrap(); + SolutionOf::::from_assignment(&assignments, &voter_index, &target_index).unwrap(); - let round = MultiPhase::round(); + let round = Round::::get(); RawSolution { solution, score, round } } pub fn witness() -> SolutionOrSnapshotSize { - MultiPhase::snapshot() + Snapshot::::get() .map(|snap| SolutionOrSnapshotSize { voters: snap.voters.len() as u32, targets: snap.targets.len() as u32, diff --git a/substrate/frame/election-provider-multi-phase/src/signed.rs b/substrate/frame/election-provider-multi-phase/src/signed.rs index fe07e477e1d5d..c685791bbdd9d 100644 --- a/substrate/frame/election-provider-multi-phase/src/signed.rs +++ b/substrate/frame/election-provider-multi-phase/src/signed.rs @@ -22,7 +22,7 @@ use core::marker::PhantomData; use crate::{ unsigned::MinerConfig, Config, ElectionCompute, Pallet, QueuedSolution, RawSolution, ReadySolution, SignedSubmissionIndices, SignedSubmissionNextIndex, SignedSubmissionsMap, - SolutionOf, SolutionOrSnapshotSize, Weight, WeightInfo, + SnapshotMetadata, SolutionOf, SolutionOrSnapshotSize, Weight, WeightInfo, }; use alloc::{ collections::{btree_map::BTreeMap, btree_set::BTreeSet}, @@ -405,7 +405,7 @@ impl Pallet { let mut weight = T::DbWeight::get().reads(1); let SolutionOrSnapshotSize { voters, targets } = - Self::snapshot_metadata().unwrap_or_default(); + SnapshotMetadata::::get().unwrap_or_default(); while let Some(best) = all_submissions.pop_last() { log!( @@ -418,7 +418,8 @@ impl Pallet { let active_voters = raw_solution.solution.voter_count() as u32; let feasibility_weight = { // defensive only: at the end of signed phase, snapshot will exits. - let desired_targets = Self::desired_targets().defensive_unwrap_or_default(); + let desired_targets = + crate::DesiredTargets::::get().defensive_unwrap_or_default(); T::WeightInfo::feasibility_check(voters, targets, active_voters, desired_targets) }; @@ -495,7 +496,7 @@ impl Pallet { call_fee: BalanceOf, ) { // write this ready solution. - >::put(ready_solution); + QueuedSolution::::put(ready_solution); let reward = T::SignedRewardBase::get(); // emit reward event @@ -565,8 +566,8 @@ impl Pallet { mod tests { use super::*; use crate::{ - mock::*, ElectionBoundsBuilder, ElectionCompute, ElectionError, Error, Event, Perbill, - Phase, + mock::*, CurrentPhase, ElectionBoundsBuilder, ElectionCompute, ElectionError, Error, Event, + Perbill, Phase, Round, }; use frame_support::{assert_noop, assert_ok, assert_storage_noop}; use sp_runtime::Percent; @@ -576,17 +577,17 @@ mod tests { ExtBuilder::default().build_and_execute(|| { // roll to a few rounds ahead. roll_to_round(5); - assert_eq!(MultiPhase::round(), 5); + assert_eq!(Round::::get(), 5); roll_to_signed(); - assert_eq!(MultiPhase::current_phase(), Phase::Signed); + assert_eq!(CurrentPhase::::get(), Phase::Signed); // create a temp snapshot only for this test. MultiPhase::create_snapshot().unwrap(); let mut solution = raw_solution(); // try a solution prepared in a previous round. - solution.round = MultiPhase::round() - 1; + solution.round = Round::::get() - 1; assert_noop!( MultiPhase::submit(RuntimeOrigin::signed(10), Box::new(solution)), @@ -596,7 +597,7 @@ mod tests { // try a solution prepared in a later round (not expected to happen, but in any case). MultiPhase::create_snapshot().unwrap(); let mut solution = raw_solution(); - solution.round = MultiPhase::round() + 1; + solution.round = Round::::get() + 1; assert_noop!( MultiPhase::submit(RuntimeOrigin::signed(10), Box::new(solution)), @@ -609,7 +610,7 @@ mod tests { fn cannot_submit_too_early() { ExtBuilder::default().build_and_execute(|| { roll_to(2); - assert_eq!(MultiPhase::current_phase(), Phase::Off); + assert_eq!(CurrentPhase::::get(), Phase::Off); // create a temp snapshot only for this test. MultiPhase::create_snapshot().unwrap(); @@ -621,9 +622,9 @@ mod tests { ); // make sure invariants hold true and post-test try state checks to pass. - >::kill(); - >::kill(); - >::kill(); + crate::Snapshot::::kill(); + crate::SnapshotMetadata::::kill(); + crate::DesiredTargets::::kill(); }) } @@ -679,7 +680,7 @@ mod tests { fn should_pay_deposit() { ExtBuilder::default().build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let solution = raw_solution(); assert_eq!(balances(&99), (100, 0)); @@ -707,7 +708,7 @@ mod tests { fn good_solution_is_rewarded() { ExtBuilder::default().build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let solution = raw_solution(); assert_eq!(balances(&99), (100, 0)); @@ -737,7 +738,7 @@ mod tests { fn bad_solution_is_slashed() { ExtBuilder::default().build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let mut solution = raw_solution(); assert_eq!(balances(&99), (100, 0)); @@ -772,7 +773,7 @@ mod tests { fn suppressed_solution_gets_bond_back() { ExtBuilder::default().build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let mut solution = raw_solution(); assert_eq!(balances(&99), (100, 0)); @@ -818,7 +819,7 @@ mod tests { fn cannot_submit_worse_with_full_queue() { ExtBuilder::default().build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); for s in 0..SignedMaxSubmissions::get() { // score is always getting better @@ -866,7 +867,7 @@ mod tests { .signed_base_deposit(1000, true, Percent::from_percent(0)) .build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); check_progressive_base_fee(&constant); }); @@ -876,7 +877,7 @@ mod tests { .signed_base_deposit(1000, true, Percent::from_percent(10)) .build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); check_progressive_base_fee(&progression_10); }); @@ -886,7 +887,7 @@ mod tests { .signed_base_deposit(1000, true, Percent::from_percent(40)) .build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); check_progressive_base_fee(&progression_40); }); @@ -896,7 +897,7 @@ mod tests { fn call_fee_refund_is_limited_by_signed_max_refunds() { ExtBuilder::default().build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); assert_eq!(SignedMaxRefunds::get(), 1); assert!(SignedMaxSubmissions::get() > 2); @@ -977,7 +978,7 @@ mod tests { .better_signed_threshold(Perbill::from_percent(20)) .build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let mut solution = RawSolution { score: ElectionScore { @@ -1038,7 +1039,7 @@ mod tests { fn weakest_is_removed_if_better_provided() { ExtBuilder::default().build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); for s in 0..SignedMaxSubmissions::get() { let account = 99 + s as u64; @@ -1085,7 +1086,7 @@ mod tests { fn replace_weakest_by_score_works() { ExtBuilder::default().signed_max_submission(3).build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); for s in 1..SignedMaxSubmissions::get() { // score is always getting better @@ -1132,7 +1133,7 @@ mod tests { fn early_ejected_solution_gets_bond_back() { ExtBuilder::default().signed_deposit(2, 0, 0).build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); for s in 0..SignedMaxSubmissions::get() { // score is always getting better @@ -1164,7 +1165,7 @@ mod tests { // because in ordering of solutions, an older solution has higher priority and should stay. ExtBuilder::default().signed_max_submission(3).build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); for i in 0..SignedMaxSubmissions::get() { let solution = RawSolution { @@ -1199,7 +1200,7 @@ mod tests { // because in ordering of solutions, an older solution has higher priority and should stay. ExtBuilder::default().signed_max_submission(3).build_and_execute(|| { roll_to(15); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let solution = RawSolution { score: ElectionScore { minimal_stake: 5, ..Default::default() }, @@ -1251,7 +1252,7 @@ mod tests { // because in ordering of solutions, an older solution has higher priority and should stay. ExtBuilder::default().signed_max_submission(3).build_and_execute(|| { roll_to(15); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); for i in 0..SignedMaxSubmissions::get() { roll_to((15 + i).into()); @@ -1311,7 +1312,7 @@ mod tests { // - suppressed_solution_gets_bond_back ExtBuilder::default().build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); assert_eq!(balances(&99), (100, 0)); assert_eq!(balances(&999), (100, 0)); @@ -1380,7 +1381,7 @@ mod tests { .mock_weight_info(MockedWeightInfo::Basic) .build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let (raw, witness, _) = MultiPhase::mine_solution().unwrap(); let solution_weight = ::solution_weight( @@ -1414,7 +1415,7 @@ mod tests { fn insufficient_deposit_does_not_store_submission() { ExtBuilder::default().build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let solution = raw_solution(); @@ -1434,7 +1435,7 @@ mod tests { fn insufficient_deposit_with_full_queue_works_properly() { ExtBuilder::default().build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); for s in 0..SignedMaxSubmissions::get() { // score is always getting better @@ -1480,7 +1481,7 @@ mod tests { fn finalize_signed_phase_is_idempotent_given_submissions() { ExtBuilder::default().build_and_execute(|| { roll_to_signed(); - assert!(MultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); let solution = raw_solution(); diff --git a/substrate/frame/election-provider-multi-phase/src/unsigned.rs b/substrate/frame/election-provider-multi-phase/src/unsigned.rs index 728ab93023895..4c56f02db526b 100644 --- a/substrate/frame/election-provider-multi-phase/src/unsigned.rs +++ b/substrate/frame/election-provider-multi-phase/src/unsigned.rs @@ -18,8 +18,9 @@ //! The unsigned phase, and its miner. use crate::{ - helpers, Call, Config, ElectionCompute, Error, FeasibilityError, Pallet, RawSolution, - ReadySolution, RoundSnapshot, SolutionAccuracyOf, SolutionOf, SolutionOrSnapshotSize, Weight, + helpers, Call, Config, CurrentPhase, DesiredTargets, ElectionCompute, Error, FeasibilityError, + Pallet, QueuedSolution, RawSolution, ReadySolution, Round, RoundSnapshot, Snapshot, + SolutionAccuracyOf, SolutionOf, SolutionOrSnapshotSize, Weight, }; use alloc::{boxed::Box, vec::Vec}; use codec::Encode; @@ -188,15 +189,15 @@ impl Pallet { MinerError, > { let RoundSnapshot { voters, targets } = - Self::snapshot().ok_or(MinerError::SnapshotUnAvailable)?; - let desired_targets = Self::desired_targets().ok_or(MinerError::SnapshotUnAvailable)?; + Snapshot::::get().ok_or(MinerError::SnapshotUnAvailable)?; + let desired_targets = DesiredTargets::::get().ok_or(MinerError::SnapshotUnAvailable)?; let (solution, score, size, is_trimmed) = Miner::::mine_solution_with_snapshot::( voters, targets, desired_targets, )?; - let round = Self::round(); + let round = Round::::get(); Ok((RawSolution { solution, score, round }, size, is_trimmed)) } @@ -370,21 +371,24 @@ impl Pallet { raw_solution: &RawSolution>, ) -> DispatchResult { // ensure solution is timely. Don't panic yet. This is a cheap check. - ensure!(Self::current_phase().is_unsigned_open(), Error::::PreDispatchEarlySubmission); + ensure!( + CurrentPhase::::get().is_unsigned_open(), + Error::::PreDispatchEarlySubmission + ); // ensure round is current - ensure!(Self::round() == raw_solution.round, Error::::OcwCallWrongEra); + ensure!(Round::::get() == raw_solution.round, Error::::OcwCallWrongEra); // ensure correct number of winners. ensure!( - Self::desired_targets().unwrap_or_default() == + DesiredTargets::::get().unwrap_or_default() == raw_solution.solution.unique_targets().len() as u32, Error::::PreDispatchWrongWinnerCount, ); // ensure score is being improved. Panic henceforth. ensure!( - Self::queued_solution() + QueuedSolution::::get() .map_or(true, |q: ReadySolution<_, _>| raw_solution.score > q.score), Error::::PreDispatchWeakSubmission, ); @@ -1043,7 +1047,7 @@ mod tests { }; // initial - assert_eq!(MultiPhase::current_phase(), Phase::Off); + assert_eq!(CurrentPhase::::get(), Phase::Off); assert!(matches!( ::validate_unsigned( TransactionSource::Local, @@ -1059,7 +1063,7 @@ mod tests { // signed roll_to_signed(); - assert_eq!(MultiPhase::current_phase(), Phase::Signed); + assert_eq!(CurrentPhase::::get(), Phase::Signed); assert!(matches!( ::validate_unsigned( TransactionSource::Local, @@ -1075,7 +1079,7 @@ mod tests { // unsigned roll_to_unsigned(); - assert!(MultiPhase::current_phase().is_unsigned()); + assert!(CurrentPhase::::get().is_unsigned()); assert!(::validate_unsigned( TransactionSource::Local, @@ -1086,7 +1090,7 @@ mod tests { // unsigned -- but not enabled. MultiPhase::phase_transition(Phase::Unsigned((false, 25))); - assert!(MultiPhase::current_phase().is_unsigned()); + assert!(CurrentPhase::::get().is_unsigned()); assert!(matches!( ::validate_unsigned( TransactionSource::Local, @@ -1106,7 +1110,7 @@ mod tests { fn validate_unsigned_retracts_low_score() { ExtBuilder::default().desired_targets(0).build_and_execute(|| { roll_to_unsigned(); - assert!(MultiPhase::current_phase().is_unsigned()); + assert!(CurrentPhase::::get().is_unsigned()); let solution = RawSolution:: { score: ElectionScore { minimal_stake: 5, ..Default::default() }, @@ -1130,7 +1134,7 @@ mod tests { score: ElectionScore { minimal_stake: 10, ..Default::default() }, ..Default::default() }; - >::put(ready); + QueuedSolution::::put(ready); // won't work anymore. assert!(matches!( @@ -1152,7 +1156,7 @@ mod tests { fn validate_unsigned_retracts_incorrect_winner_count() { ExtBuilder::default().desired_targets(1).build_and_execute(|| { roll_to_unsigned(); - assert!(MultiPhase::current_phase().is_unsigned()); + assert!(CurrentPhase::::get().is_unsigned()); let raw = RawSolution:: { score: ElectionScore { minimal_stake: 5, ..Default::default() }, @@ -1181,7 +1185,7 @@ mod tests { .desired_targets(0) .build_and_execute(|| { roll_to_unsigned(); - assert!(MultiPhase::current_phase().is_unsigned()); + assert!(CurrentPhase::::get().is_unsigned()); let solution = RawSolution:: { score: ElectionScore { minimal_stake: 5, ..Default::default() }, @@ -1212,7 +1216,7 @@ mod tests { fn unfeasible_solution_panics() { ExtBuilder::default().build_and_execute(|| { roll_to_unsigned(); - assert!(MultiPhase::current_phase().is_unsigned()); + assert!(CurrentPhase::::get().is_unsigned()); // This is in itself an invalid BS solution. let solution = RawSolution:: { @@ -1234,7 +1238,7 @@ mod tests { fn wrong_witness_panics() { ExtBuilder::default().build_and_execute(|| { roll_to_unsigned(); - assert!(MultiPhase::current_phase().is_unsigned()); + assert!(CurrentPhase::::get().is_unsigned()); // This solution is unfeasible as well, but we won't even get there. let solution = RawSolution:: { @@ -1258,23 +1262,23 @@ mod tests { fn miner_works() { ExtBuilder::default().build_and_execute(|| { roll_to_unsigned(); - assert!(MultiPhase::current_phase().is_unsigned()); + assert!(CurrentPhase::::get().is_unsigned()); // ensure we have snapshots in place. - assert!(MultiPhase::snapshot().is_some()); - assert_eq!(MultiPhase::desired_targets().unwrap(), 2); + assert!(Snapshot::::get().is_some()); + assert_eq!(DesiredTargets::::get().unwrap(), 2); // mine seq_phragmen solution with 2 iters. let (solution, witness, _) = MultiPhase::mine_solution().unwrap(); // ensure this solution is valid. - assert!(MultiPhase::queued_solution().is_none()); + assert!(QueuedSolution::::get().is_none()); assert_ok!(MultiPhase::submit_unsigned( RuntimeOrigin::none(), Box::new(solution), witness )); - assert!(MultiPhase::queued_solution().is_some()); + assert!(QueuedSolution::::get().is_some()); assert_eq!( multi_phase_events(), vec![ @@ -1301,7 +1305,7 @@ mod tests { .mock_weight_info(crate::mock::MockedWeightInfo::Basic) .build_and_execute(|| { roll_to_unsigned(); - assert!(MultiPhase::current_phase().is_unsigned()); + assert!(CurrentPhase::::get().is_unsigned()); let (raw, witness, t) = MultiPhase::mine_solution().unwrap(); let solution_weight = ::solution_weight( @@ -1337,7 +1341,7 @@ mod tests { let (mut ext, _) = ExtBuilder::default().desired_targets(8).build_offchainify(0); ext.execute_with(|| { roll_to_unsigned(); - assert!(MultiPhase::current_phase().is_unsigned()); + assert!(CurrentPhase::::get().is_unsigned()); // Force the number of winners to be bigger to fail let (mut solution, _, _) = MultiPhase::mine_solution().unwrap(); @@ -1363,8 +1367,8 @@ mod tests { .add_voter(9, 1, bounded_vec![10]) .build_and_execute(|| { roll_to_unsigned(); - assert!(MultiPhase::current_phase().is_unsigned()); - assert_eq!(MultiPhase::desired_targets().unwrap(), 1); + assert!(CurrentPhase::::get().is_unsigned()); + assert_eq!(DesiredTargets::::get().unwrap(), 1); // an initial solution let result = ElectionResult { @@ -1379,8 +1383,8 @@ mod tests { ], }; - let RoundSnapshot { voters, targets } = MultiPhase::snapshot().unwrap(); - let desired_targets = MultiPhase::desired_targets().unwrap(); + let RoundSnapshot { voters, targets } = Snapshot::::get().unwrap(); + let desired_targets = DesiredTargets::::get().unwrap(); let (raw, score, witness, _) = Miner::::prepare_election_result_with_snapshot( @@ -1390,14 +1394,14 @@ mod tests { desired_targets, ) .unwrap(); - let solution = RawSolution { solution: raw, score, round: MultiPhase::round() }; + let solution = RawSolution { solution: raw, score, round: Round::::get() }; assert_ok!(MultiPhase::unsigned_pre_dispatch_checks(&solution)); assert_ok!(MultiPhase::submit_unsigned( RuntimeOrigin::none(), Box::new(solution), witness )); - assert_eq!(MultiPhase::queued_solution().unwrap().score.minimal_stake, 12); + assert_eq!(QueuedSolution::::get().unwrap().score.minimal_stake, 12); // trial 1: a solution who's minimal stake is 10, i.e. worse than the first solution // of 12. @@ -1415,7 +1419,7 @@ mod tests { desired_targets, ) .unwrap(); - let solution = RawSolution { solution: raw, score, round: MultiPhase::round() }; + let solution = RawSolution { solution: raw, score, round: Round::::get() }; // 10 is not better than 12 assert_eq!(solution.score.minimal_stake, 10); // submitting this will actually panic. @@ -1445,7 +1449,7 @@ mod tests { desired_targets, ) .unwrap(); - let solution = RawSolution { solution: raw, score, round: MultiPhase::round() }; + let solution = RawSolution { solution: raw, score, round: Round::::get() }; // 12 is not better than 12. We need score of at least 13 to be accepted. assert_eq!(solution.score.minimal_stake, 12); // submitting this will panic. @@ -1472,7 +1476,7 @@ mod tests { desired_targets, ) .unwrap(); - let solution = RawSolution { solution: raw, score, round: MultiPhase::round() }; + let solution = RawSolution { solution: raw, score, round: Round::::get() }; assert_eq!(solution.score.minimal_stake, 13); // this should work @@ -1505,7 +1509,7 @@ mod tests { desired_targets, ) .unwrap(); - let solution = RawSolution { solution: raw, score, round: MultiPhase::round() }; + let solution = RawSolution { solution: raw, score, round: Round::::get() }; assert_eq!(solution.score.minimal_stake, 17); // and it is fine @@ -1525,7 +1529,7 @@ mod tests { let offchain_repeat = ::OffchainRepeat::get(); roll_to_unsigned(); - assert!(MultiPhase::current_phase().is_unsigned()); + assert!(CurrentPhase::::get().is_unsigned()); // first execution -- okay. assert!(MultiPhase::ensure_offchain_repeat_frequency(25).is_ok()); @@ -1566,7 +1570,7 @@ mod tests { let last_block = StorageValueRef::persistent(OFFCHAIN_LAST_BLOCK); roll_to_unsigned(); - assert!(MultiPhase::current_phase().is_unsigned()); + assert!(CurrentPhase::::get().is_unsigned()); // initially, the lock is not set. assert!(guard.get::().unwrap().is_none()); @@ -1587,7 +1591,7 @@ mod tests { let (mut ext, pool) = ExtBuilder::default().build_offchainify(0); ext.execute_with(|| { roll_to_unsigned(); - assert!(MultiPhase::current_phase().is_unsigned()); + assert!(CurrentPhase::::get().is_unsigned()); // artificially set the value, as if another thread is mid-way. let mut lock = StorageLock::>::with_block_deadline( @@ -1615,7 +1619,7 @@ mod tests { let (mut ext, pool) = ExtBuilder::default().build_offchainify(0); ext.execute_with(|| { roll_to_unsigned(); - assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, 25))); + assert_eq!(CurrentPhase::::get(), Phase::Unsigned((true, 25))); // we must clear the offchain storage to ensure the offchain execution check doesn't get // in the way. @@ -1647,7 +1651,7 @@ mod tests { roll_to(BLOCK); // we are on the first block of the unsigned phase - assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, BLOCK))); + assert_eq!(CurrentPhase::::get(), Phase::Unsigned((true, BLOCK))); assert!( !ocw_solution_exists::(), @@ -1730,7 +1734,7 @@ mod tests { let offchain_repeat = ::OffchainRepeat::get(); roll_to(BLOCK); - assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, BLOCK))); + assert_eq!(CurrentPhase::::get(), Phase::Unsigned((true, BLOCK))); // we must clear the offchain storage to ensure the offchain execution check doesn't get // in the way. @@ -1768,7 +1772,7 @@ mod tests { let offchain_repeat = ::OffchainRepeat::get(); roll_to(BLOCK); - assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, BLOCK))); + assert_eq!(CurrentPhase::::get(), Phase::Unsigned((true, BLOCK))); // we must clear the offchain storage to ensure the offchain execution check doesn't get // in the way. @@ -1809,7 +1813,7 @@ mod tests { let (mut ext, pool) = ExtBuilder::default().build_offchainify(0); ext.execute_with(|| { roll_to_with_ocw(25); - assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, 25))); + assert_eq!(CurrentPhase::::get(), Phase::Unsigned((true, 25))); // OCW must have submitted now let encoded = pool.read().transactions[0].clone(); @@ -1824,10 +1828,10 @@ mod tests { let (mut ext, pool) = ExtBuilder::default().build_offchainify(0); ext.execute_with(|| { roll_to_with_ocw(25); - assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, 25))); + assert_eq!(CurrentPhase::::get(), Phase::Unsigned((true, 25))); // OCW must have submitted now // now, before we check the call, update the round - >::mutate(|round| *round += 1); + crate::Round::::mutate(|round| *round += 1); let encoded = pool.read().transactions[0].clone(); let extrinsic = Extrinsic::decode(&mut &*encoded).unwrap(); diff --git a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs index aaffbb6681cd2..0dc202ff21153 100644 --- a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs +++ b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs @@ -28,6 +28,8 @@ use sp_runtime::Perbill; use crate::mock::RuntimeOrigin; +use pallet_election_provider_multi_phase::CurrentPhase; + // syntactic sugar for logging. #[macro_export] macro_rules! log { @@ -46,7 +48,7 @@ fn log_current_time() { System::block_number(), Session::current_index(), Staking::current_era(), - ElectionProviderMultiPhase::current_phase(), + CurrentPhase::::get(), Now::::get() ); } @@ -58,16 +60,16 @@ fn block_progression_works() { execute_with(ext, || { assert_eq!(active_era(), 0); assert_eq!(Session::current_index(), 0); - assert!(ElectionProviderMultiPhase::current_phase().is_off()); + assert!(CurrentPhase::::get().is_off()); assert!(start_next_active_era(pool_state.clone()).is_ok()); assert_eq!(active_era(), 1); assert_eq!(Session::current_index(), >::get()); - assert!(ElectionProviderMultiPhase::current_phase().is_off()); + assert!(CurrentPhase::::get().is_off()); roll_to_epm_signed(); - assert!(ElectionProviderMultiPhase::current_phase().is_signed()); + assert!(CurrentPhase::::get().is_signed()); }); let (ext, pool_state, _) = ExtBuilder::default().build_offchainify(); @@ -75,11 +77,11 @@ fn block_progression_works() { execute_with(ext, || { assert_eq!(active_era(), 0); assert_eq!(Session::current_index(), 0); - assert!(ElectionProviderMultiPhase::current_phase().is_off()); + assert!(CurrentPhase::::get().is_off()); assert!(start_next_active_era_delayed_solution(pool_state).is_ok()); // if the solution is delayed, EPM will end up in emergency mode.. - assert!(ElectionProviderMultiPhase::current_phase().is_emergency()); + assert!(CurrentPhase::::get().is_emergency()); // .. era won't progress.. assert_eq!(active_era(), 0); // .. but session does. @@ -103,7 +105,7 @@ fn offchainify_works() { // not delayed. for _ in 0..100 { roll_one(pool_state.clone(), false); - let current_phase = ElectionProviderMultiPhase::current_phase(); + let current_phase = CurrentPhase::::get(); assert!( match QueuedSolution::::get() { @@ -209,7 +211,7 @@ fn continuous_slashes_below_offending_threshold() { // break loop when era does not progress; EPM is in emergency phase as election // failed due to election minimum score. if start_next_active_era(pool_state.clone()).is_err() { - assert!(ElectionProviderMultiPhase::current_phase().is_emergency()); + assert!(CurrentPhase::::get().is_emergency()); break; } diff --git a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs index d148c05e4d0d0..e45452c1ddf9d 100644 --- a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs +++ b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs @@ -46,8 +46,8 @@ use frame_election_provider_support::{ SequentialPhragmen, Weight, }; use pallet_election_provider_multi_phase::{ - unsigned::MinerConfig, Call, ElectionCompute, GeometricDepositBase, QueuedSolution, - SolutionAccuracyOf, + unsigned::MinerConfig, Call, CurrentPhase, ElectionCompute, GeometricDepositBase, + QueuedSolution, SolutionAccuracyOf, }; use pallet_staking::StakerStatus; use parking_lot::RwLock; @@ -653,7 +653,7 @@ pub fn roll_to(n: BlockNumber, delay_solution: bool) { // /~https://github.com/paritytech/substrate/issues/13589 // if there's no solution queued and the solution should not be delayed, try mining and // queue a solution. - if ElectionProviderMultiPhase::current_phase().is_signed() && !delay_solution { + if CurrentPhase::::get().is_signed() && !delay_solution { let _ = try_queue_solution(ElectionCompute::Signed).map_err(|e| { log!(info, "failed to mine/queue solution: {:?}", e); }); @@ -807,7 +807,7 @@ pub(crate) fn current_era() -> EraIndex { // Fast forward until EPM signed phase. pub fn roll_to_epm_signed() { while !matches!( - ElectionProviderMultiPhase::current_phase(), + CurrentPhase::::get(), pallet_election_provider_multi_phase::Phase::Signed ) { roll_to(System::block_number() + 1, false); @@ -817,7 +817,7 @@ pub fn roll_to_epm_signed() { // Fast forward until EPM unsigned phase. pub fn roll_to_epm_unsigned() { while !matches!( - ElectionProviderMultiPhase::current_phase(), + CurrentPhase::::get(), pallet_election_provider_multi_phase::Phase::Unsigned(_) ) { roll_to(System::block_number() + 1, false); @@ -827,7 +827,7 @@ pub fn roll_to_epm_unsigned() { // Fast forward until EPM off. pub fn roll_to_epm_off() { while !matches!( - ElectionProviderMultiPhase::current_phase(), + CurrentPhase::::get(), pallet_election_provider_multi_phase::Phase::Off ) { roll_to(System::block_number() + 1, false);