From cf761156b7a5593739a51b8cb1511d626b22d2fd Mon Sep 17 00:00:00 2001 From: muraca Date: Mon, 13 Feb 2023 10:41:58 +0100 Subject: [PATCH] deprecate and remove every usage of `#[pallet::getter]` Signed-off-by: muraca --- bin/node-template/pallets/template/src/lib.rs | 1 - .../pallets/template/src/tests.rs | 4 +- bin/node/executor/tests/fees.rs | 10 +- bin/node/runtime/src/impls.rs | 4 +- bin/node/runtime/src/lib.rs | 8 +- frame/alliance/src/benchmarking.rs | 10 +- frame/alliance/src/migration.rs | 12 +- frame/alliance/src/mock.rs | 2 +- frame/alliance/src/tests.rs | 57 +- frame/aura/src/lib.rs | 14 +- frame/aura/src/tests.rs | 9 +- frame/babe/src/lib.rs | 33 +- frame/babe/src/mock.rs | 12 +- frame/babe/src/tests.rs | 90 +-- frame/balances/src/lib.rs | 9 +- frame/beefy-mmr/src/lib.rs | 6 +- frame/beefy/src/lib.rs | 12 +- frame/beefy/src/mock.rs | 6 +- frame/beefy/src/tests.rs | 29 +- frame/benchmarking/src/tests.rs | 1 - frame/benchmarking/src/tests_instance.rs | 1 - frame/bounties/src/lib.rs | 2 +- frame/bounties/src/tests.rs | 50 +- frame/child-bounties/src/benchmarking.rs | 2 +- frame/child-bounties/src/lib.rs | 10 +- frame/child-bounties/src/tests.rs | 57 +- frame/collective/src/benchmarking.rs | 32 +- frame/collective/src/lib.rs | 28 +- frame/collective/src/tests.rs | 38 +- frame/democracy/src/benchmarking.rs | 28 +- frame/democracy/src/lib.rs | 22 +- frame/democracy/src/tests.rs | 2 +- frame/democracy/src/tests/cancellation.rs | 8 +- frame/democracy/src/tests/lock_voting.rs | 74 +-- frame/democracy/src/tests/metadata.rs | 4 +- frame/democracy/src/tests/scheduling.rs | 12 +- frame/democracy/src/tests/voting.rs | 6 +- .../src/benchmarking.rs | 48 +- .../election-provider-multi-phase/src/lib.rs | 232 ++++---- .../election-provider-multi-phase/src/mock.rs | 22 +- .../src/signed.rs | 54 +- .../src/unsigned.rs | 88 +-- frame/elections-phragmen/src/benchmarking.rs | 16 +- frame/elections-phragmen/src/lib.rs | 146 ++--- frame/examples/basic/src/benchmarking.rs | 2 +- frame/examples/basic/src/lib.rs | 8 - frame/examples/basic/src/tests.rs | 12 +- frame/grandpa/src/benchmarking.rs | 4 +- frame/grandpa/src/lib.rs | 19 +- frame/grandpa/src/mock.rs | 6 +- frame/grandpa/src/tests.rs | 85 +-- frame/identity/src/lib.rs | 15 +- frame/identity/src/tests.rs | 56 +- frame/im-online/src/lib.rs | 7 +- frame/im-online/src/mock.rs | 7 +- frame/im-online/src/tests.rs | 53 +- .../src/lib.rs | 8 +- frame/membership/src/lib.rs | 101 ++-- frame/merkle-mountain-range/src/lib.rs | 8 +- frame/merkle-mountain-range/src/tests.rs | 152 ++--- .../nomination-pools/test-staking/src/lib.rs | 10 +- frame/offences/benchmarking/src/lib.rs | 4 +- frame/recovery/src/lib.rs | 12 +- frame/recovery/src/tests.rs | 8 +- frame/root-offences/src/lib.rs | 6 +- frame/root-offences/src/mock.rs | 6 +- frame/scored-pool/src/mock.rs | 4 +- frame/scored-pool/src/tests.rs | 34 +- frame/session/README.md | 4 +- frame/session/benchmarking/src/lib.rs | 8 +- frame/session/src/historical/mod.rs | 32 +- frame/session/src/historical/offchain.rs | 8 +- frame/session/src/historical/onchain.rs | 6 +- frame/session/src/lib.rs | 14 +- frame/session/src/tests.rs | 34 +- frame/society/src/lib.rs | 18 +- frame/society/src/tests.rs | 180 +++--- frame/staking/src/benchmarking.rs | 4 +- frame/staking/src/lib.rs | 7 +- frame/staking/src/mock.rs | 49 +- frame/staking/src/pallet/impls.rs | 96 ++-- frame/staking/src/pallet/mod.rs | 34 +- frame/staking/src/slashing.rs | 8 +- frame/staking/src/testing_utils.rs | 2 +- frame/staking/src/tests.rs | 531 +++++++++--------- frame/state-trie-migration/src/lib.rs | 63 +-- frame/sudo/src/extension.rs | 4 +- frame/sudo/src/lib.rs | 8 +- frame/sudo/src/mock.rs | 6 +- frame/sudo/src/tests.rs | 25 +- .../procedural/src/pallet/expand/storage.rs | 1 + frame/support/test/tests/pallet.rs | 8 - frame/support/test/tests/pallet_instance.rs | 3 - .../pallet_ui/storage_multiple_getters.rs | 3 +- frame/system/src/extensions/check_genesis.rs | 4 +- .../system/src/extensions/check_mortality.rs | 8 +- frame/system/src/extensions/check_weight.rs | 4 +- frame/system/src/lib.rs | 43 +- frame/timestamp/src/benchmarking.rs | 4 +- frame/timestamp/src/lib.rs | 12 +- frame/timestamp/src/tests.rs | 4 +- frame/transaction-payment/src/lib.rs | 2 +- frame/treasury/src/benchmarking.rs | 2 +- frame/treasury/src/lib.rs | 12 +- frame/treasury/src/tests.rs | 6 +- frame/vesting/src/benchmarking.rs | 16 +- frame/vesting/src/lib.rs | 10 +- frame/vesting/src/tests.rs | 84 +-- test-utils/runtime/src/lib.rs | 7 +- 109 files changed, 1703 insertions(+), 1609 deletions(-) diff --git a/bin/node-template/pallets/template/src/lib.rs b/bin/node-template/pallets/template/src/lib.rs index 4630e344add31..dc093742a6627 100644 --- a/bin/node-template/pallets/template/src/lib.rs +++ b/bin/node-template/pallets/template/src/lib.rs @@ -33,7 +33,6 @@ pub mod pallet { // The pallet's runtime storage items. // https://docs.substrate.io/main-docs/build/runtime-storage/ #[pallet::storage] - #[pallet::getter(fn something)] // Learn more about declaring storage items: // https://docs.substrate.io/main-docs/build/runtime-storage/#declaring-storage-items pub type Something = StorageValue<_, u32>; diff --git a/bin/node-template/pallets/template/src/tests.rs b/bin/node-template/pallets/template/src/tests.rs index 7c2b853ee4dc5..83e4bea7377b3 100644 --- a/bin/node-template/pallets/template/src/tests.rs +++ b/bin/node-template/pallets/template/src/tests.rs @@ -1,4 +1,4 @@ -use crate::{mock::*, Error, Event}; +use crate::{mock::*, Error, Event, Something}; use frame_support::{assert_noop, assert_ok}; #[test] @@ -9,7 +9,7 @@ fn it_works_for_default_value() { // Dispatch a signed extrinsic. assert_ok!(TemplateModule::do_something(RuntimeOrigin::signed(1), 42)); // Read pallet storage and assert an expected result. - assert_eq!(TemplateModule::something(), Some(42)); + assert_eq!(Something::::get(), Some(42)); // Assert that the correct event was deposited System::assert_last_event(Event::SomethingStored { something: 42, who: 1 }.into()); }); diff --git a/bin/node/executor/tests/fees.rs b/bin/node/executor/tests/fees.rs index 3c696d595040b..83b928156f00e 100644 --- a/bin/node/executor/tests/fees.rs +++ b/bin/node/executor/tests/fees.rs @@ -24,7 +24,6 @@ use frame_support::{ use kitchensink_runtime::{ constants::{currency::*, time::SLOT_DURATION}, Balances, CheckedExtrinsic, Multiplier, Runtime, RuntimeCall, TransactionByteFee, - TransactionPayment, }; use node_primitives::Balance; use node_testing::keyring::*; @@ -41,7 +40,10 @@ fn fee_multiplier_increases_and_decreases_on_big_weight() { let mut prev_multiplier = Multiplier::one(); t.execute_with(|| { - assert_eq!(TransactionPayment::next_fee_multiplier(), prev_multiplier); + assert_eq!( + pallet_transaction_payment::NextFeeMultiplier::::get(), + prev_multiplier + ); }); let mut tt = new_test_ext(compact_code_unwrap()); @@ -99,7 +101,7 @@ fn fee_multiplier_increases_and_decreases_on_big_weight() { // weight multiplier is increased for next block. t.execute_with(|| { - let fm = TransactionPayment::next_fee_multiplier(); + let fm = pallet_transaction_payment::NextFeeMultiplier::::get(); println!("After a big block: {:?} -> {:?}", prev_multiplier, fm); assert!(fm > prev_multiplier); prev_multiplier = fm; @@ -110,7 +112,7 @@ fn fee_multiplier_increases_and_decreases_on_big_weight() { // weight multiplier is increased for next block. t.execute_with(|| { - let fm = TransactionPayment::next_fee_multiplier(); + let fm = pallet_transaction_payment::NextFeeMultiplier::::get(); println!("After a small block: {:?} -> {:?}", prev_multiplier, fm); assert!(fm < prev_multiplier); }); diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index b3f58ea5d24ab..d2e35be701cfb 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -123,7 +123,7 @@ mod multiplier_tests { use crate::{ constants::{currency::*, time::*}, AdjustmentVariable, MaximumMultiplier, MinimumMultiplier, Runtime, - RuntimeBlockWeights as BlockWeights, System, TargetBlockFullness, TransactionPayment, + RuntimeBlockWeights as BlockWeights, System, TargetBlockFullness, }; use frame_support::{ dispatch::DispatchClass, @@ -293,7 +293,7 @@ mod multiplier_tests { run_with_system_weight(block_weight, || { // initial value configured on module let mut fm = Multiplier::one(); - assert_eq!(fm, TransactionPayment::next_fee_multiplier()); + assert_eq!(fm, pallet_transaction_payment::NextFeeMultiplier::::get()); let mut iterations: u64 = 0; loop { diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 2c7969ebcd6b9..58cb0847528c4 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -1998,8 +1998,8 @@ impl_runtime_apis! { slot_duration: Babe::slot_duration(), epoch_length: EpochDuration::get(), c: epoch_config.c, - authorities: Babe::authorities().to_vec(), - randomness: Babe::randomness(), + authorities: pallet_babe::Authorities::::get().to_vec(), + randomness: pallet_babe::Randomness::::get(), allowed_slots: epoch_config.allowed_slots, } } @@ -2165,11 +2165,11 @@ impl_runtime_apis! { BlockNumber, > for Runtime { fn mmr_root() -> Result { - Ok(Mmr::mmr_root()) + Ok(pallet_mmr::RootHash::::get()) } fn mmr_leaf_count() -> Result { - Ok(Mmr::mmr_leaves()) + Ok(pallet_mmr::NumberOfLeaves::::get()) } fn generate_proof( diff --git a/frame/alliance/src/benchmarking.rs b/frame/alliance/src/benchmarking.rs index 01b81ed66e999..24ec422a3b846 100644 --- a/frame/alliance/src/benchmarking.rs +++ b/frame/alliance/src/benchmarking.rs @@ -531,8 +531,8 @@ benchmarks_instance_pallet! { fellows: fellows.clone(), allies: allies.clone(), }.into()); - assert_eq!(Alliance::::members(MemberRole::Fellow), fellows); - assert_eq!(Alliance::::members(MemberRole::Ally), allies); + assert_eq!(Members::::get(MemberRole::Fellow), fellows); + assert_eq!(Members::::get(MemberRole::Ally), allies); } disband { @@ -585,7 +585,7 @@ benchmarks_instance_pallet! { T::AdminOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; }: { call.dispatch_bypass_filter(origin)? } verify { - assert_eq!(Alliance::::rule(), Some(rule.clone())); + assert_eq!(Rule::::get(), Some(rule.clone())); assert_last_event::(Event::NewRuleSet { rule }.into()); } @@ -599,7 +599,7 @@ benchmarks_instance_pallet! { T::AnnouncementOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; }: { call.dispatch_bypass_filter(origin)? } verify { - assert!(Alliance::::announcements().contains(&announcement)); + assert!(Announcements::::get().contains(&announcement)); assert_last_event::(Event::Announced { announcement }.into()); } @@ -615,7 +615,7 @@ benchmarks_instance_pallet! { T::AnnouncementOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; }: { call.dispatch_bypass_filter(origin)? } verify { - assert!(Alliance::::announcements().is_empty()); + assert!(Announcements::::get().is_empty()); assert_last_event::(Event::AnnouncementRemoved { announcement }.into()); } diff --git a/frame/alliance/src/migration.rs b/frame/alliance/src/migration.rs index ea07f8c1279b1..d58247fb611e1 100644 --- a/frame/alliance/src/migration.rs +++ b/frame/alliance/src/migration.rs @@ -162,18 +162,18 @@ pub(crate) mod v1_to_v2 { #[cfg(test)] mod test { use super::*; - use crate::{mock::*, MemberRole}; + use crate::{mock::*, MemberRole, Members}; #[test] fn migration_v1_to_v2_works() { new_test_ext().execute_with(|| { assert_ok!(Alliance::join_alliance(RuntimeOrigin::signed(4))); - assert_eq!(Alliance::members(MemberRole::Ally), vec![4]); - assert_eq!(Alliance::members(MemberRole::Fellow), vec![1, 2, 3]); + assert_eq!(Members::::get(MemberRole::Ally), vec![4]); + assert_eq!(Members::::get(MemberRole::Fellow), vec![1, 2, 3]); v1_to_v2::migrate::(); - assert_eq!(Alliance::members(MemberRole::Fellow), vec![1, 2, 3, 4]); - assert_eq!(Alliance::members(MemberRole::Ally), vec![]); - assert_eq!(Alliance::members(MemberRole::Retiring), vec![]); + assert_eq!(Members::::get(MemberRole::Fellow), vec![1, 2, 3, 4]); + assert_eq!(Members::::get(MemberRole::Ally), vec![]); + assert_eq!(Members::::get(MemberRole::Retiring), vec![]); }); } } diff --git a/frame/alliance/src/mock.rs b/frame/alliance/src/mock.rs index 0f774dc4853fa..0b378b8bf27a1 100644 --- a/frame/alliance/src/mock.rs +++ b/frame/alliance/src/mock.rs @@ -193,7 +193,7 @@ impl ProposalProvider for AllianceProposalProvider } fn proposal_of(proposal_hash: H256) -> Option { - AllianceMotion::proposal_of(proposal_hash) + pallet_collective::ProposalOf::::get(proposal_hash) } } diff --git a/frame/alliance/src/tests.rs b/frame/alliance/src/tests.rs index 363b19429b80f..1b337f6226985 100644 --- a/frame/alliance/src/tests.rs +++ b/frame/alliance/src/tests.rs @@ -115,7 +115,7 @@ fn disband_works() { // join alliance and reserve funds assert_eq!(Balances::free_balance(9), 40); assert_ok!(Alliance::join_alliance(RuntimeOrigin::signed(9))); - assert_eq!(Alliance::deposit_of(9), Some(25)); + assert_eq!(DepositOf::::get(9), Some(25)); assert_eq!(Balances::free_balance(9), 15); assert!(Alliance::is_member_of(&9, MemberRole::Ally)); @@ -184,8 +184,8 @@ fn propose_works() { Box::new(proposal.clone()), proposal_len )); - assert_eq!(*AllianceMotion::proposals(), vec![hash]); - assert_eq!(AllianceMotion::proposal_of(&hash), Some(proposal)); + assert_eq!(*pallet_collective::Proposals::::get(), vec![hash]); // + assert_eq!(pallet_collective::ProposalOf::::get(&hash), Some(proposal)); assert_eq!( System::events(), vec![EventRecord { @@ -311,7 +311,7 @@ fn set_rule_works() { new_test_ext().execute_with(|| { let cid = test_cid(); assert_ok!(Alliance::set_rule(RuntimeOrigin::signed(1), cid.clone())); - assert_eq!(Alliance::rule(), Some(cid.clone())); + assert_eq!(Rule::::get(), Some(cid.clone())); System::assert_last_event(mock::RuntimeEvent::Alliance(crate::Event::NewRuleSet { rule: cid, @@ -327,7 +327,7 @@ fn announce_works() { assert_noop!(Alliance::announce(RuntimeOrigin::signed(2), cid.clone()), BadOrigin); assert_ok!(Alliance::announce(RuntimeOrigin::signed(3), cid.clone())); - assert_eq!(Alliance::announcements(), vec![cid.clone()]); + assert_eq!(Announcements::::get(), vec![cid.clone()]); System::assert_last_event(mock::RuntimeEvent::Alliance(crate::Event::Announced { announcement: cid, @@ -340,7 +340,7 @@ fn remove_announcement_works() { new_test_ext().execute_with(|| { let cid = test_cid(); assert_ok!(Alliance::announce(RuntimeOrigin::signed(3), cid.clone())); - assert_eq!(Alliance::announcements(), vec![cid.clone()]); + assert_eq!(Announcements::::get(), vec![cid.clone()]); System::assert_last_event(mock::RuntimeEvent::Alliance(crate::Event::Announced { announcement: cid.clone(), })); @@ -348,7 +348,7 @@ fn remove_announcement_works() { System::set_block_number(2); assert_ok!(Alliance::remove_announcement(RuntimeOrigin::signed(3), cid.clone())); - assert_eq!(Alliance::announcements(), vec![]); + assert_eq!(Announcements::::get(), vec![]); System::assert_last_event(mock::RuntimeEvent::Alliance( crate::Event::AnnouncementRemoved { announcement: cid }, )); @@ -386,8 +386,8 @@ fn join_alliance_works() { // success to submit assert_ok!(Alliance::join_alliance(RuntimeOrigin::signed(4))); - assert_eq!(Alliance::deposit_of(4), Some(25)); - assert_eq!(Alliance::members(MemberRole::Ally), vec![4]); + assert_eq!(DepositOf::::get(4), Some(25)); + assert_eq!(Members::::get(MemberRole::Ally), vec![4]); // check already member assert_noop!( @@ -441,8 +441,8 @@ fn nominate_ally_works() { // success to nominate assert_ok!(Alliance::nominate_ally(RuntimeOrigin::signed(1), 4)); - assert_eq!(Alliance::deposit_of(4), None); - assert_eq!(Alliance::members(MemberRole::Ally), vec![4]); + assert_eq!(DepositOf::::get(4), None); + assert_eq!(Members::::get(MemberRole::Ally), vec![4]); // check already member assert_noop!( @@ -474,12 +474,12 @@ fn elevate_ally_works() { ); assert_ok!(Alliance::join_alliance(RuntimeOrigin::signed(4))); - assert_eq!(Alliance::members(MemberRole::Ally), vec![4]); - assert_eq!(Alliance::members(MemberRole::Fellow), vec![1, 2, 3]); + assert_eq!(Members::::get(MemberRole::Ally), vec![4]); + assert_eq!(Members::::get(MemberRole::Fellow), vec![1, 2, 3]); assert_ok!(Alliance::elevate_ally(RuntimeOrigin::signed(2), 4)); - assert_eq!(Alliance::members(MemberRole::Ally), Vec::::new()); - assert_eq!(Alliance::members(MemberRole::Fellow), vec![1, 2, 3, 4]); + assert_eq!(Members::::get(MemberRole::Ally), Vec::::new()); + assert_eq!(Members::::get(MemberRole::Fellow), vec![1, 2, 3, 4]); }); } @@ -491,10 +491,10 @@ fn give_retirement_notice_work() { Error::::NotMember ); - assert_eq!(Alliance::members(MemberRole::Fellow), vec![1, 2, 3]); + assert_eq!(Members::::get(MemberRole::Fellow), vec![1, 2, 3]); assert_ok!(Alliance::give_retirement_notice(RuntimeOrigin::signed(3))); - assert_eq!(Alliance::members(MemberRole::Fellow), vec![1, 2]); - assert_eq!(Alliance::members(MemberRole::Retiring), vec![3]); + assert_eq!(Members::::get(MemberRole::Fellow), vec![1, 2]); + assert_eq!(Members::::get(MemberRole::Retiring), vec![3]); System::assert_last_event(mock::RuntimeEvent::Alliance( crate::Event::MemberRetirementPeriodStarted { member: (3) }, )); @@ -519,7 +519,7 @@ fn retire_works() { Error::::RetirementNoticeNotGiven ); - assert_eq!(Alliance::members(MemberRole::Fellow), vec![1, 2, 3]); + assert_eq!(Members::::get(MemberRole::Fellow), vec![1, 2, 3]); assert_ok!(Alliance::give_retirement_notice(RuntimeOrigin::signed(3))); assert_noop!( Alliance::retire(RuntimeOrigin::signed(3)), @@ -527,7 +527,7 @@ fn retire_works() { ); System::set_block_number(System::block_number() + RetirementPeriod::get()); assert_ok!(Alliance::retire(RuntimeOrigin::signed(3))); - assert_eq!(Alliance::members(MemberRole::Fellow), vec![1, 2]); + assert_eq!(Members::::get(MemberRole::Fellow), vec![1, 2]); System::assert_last_event(mock::RuntimeEvent::Alliance(crate::Event::MemberRetired { member: (3), unreserved: None, @@ -543,7 +543,7 @@ fn retire_works() { #[test] fn abdicate_works() { new_test_ext().execute_with(|| { - assert_eq!(Alliance::members(MemberRole::Fellow), vec![1, 2, 3]); + assert_eq!(Members::::get(MemberRole::Fellow), vec![1, 2, 3]); assert_ok!(Alliance::abdicate_fellow_status(RuntimeOrigin::signed(3))); System::assert_last_event(mock::RuntimeEvent::Alliance(crate::Event::FellowAbdicated { @@ -565,9 +565,9 @@ fn kick_member_works() { ); >::insert(2, 25); - assert_eq!(Alliance::members(MemberRole::Fellow), vec![1, 2, 3]); + assert_eq!(Members::::get(MemberRole::Fellow), vec![1, 2, 3]); assert_ok!(Alliance::kick_member(RuntimeOrigin::signed(2), 2)); - assert_eq!(Alliance::members(MemberRole::Fellow), vec![1, 3]); + assert_eq!(Members::::get(MemberRole::Fellow), vec![1, 3]); assert_eq!(>::get(2), None); System::assert_last_event(mock::RuntimeEvent::Alliance(crate::Event::MemberKicked { member: (2), @@ -588,8 +588,11 @@ fn add_unscrupulous_items_works() { UnscrupulousItem::Website("abc".as_bytes().to_vec().try_into().unwrap()) ] )); - assert_eq!(Alliance::unscrupulous_accounts().into_inner(), vec![3]); - assert_eq!(Alliance::unscrupulous_websites().into_inner(), vec!["abc".as_bytes().to_vec()]); + assert_eq!(UnscrupulousAccounts::::get().into_inner(), vec![3]); + assert_eq!( + UnscrupulousWebsites::::get().into_inner(), + vec!["abc".as_bytes().to_vec()] + ); assert_noop!( Alliance::add_unscrupulous_items( @@ -621,11 +624,11 @@ fn remove_unscrupulous_items_works() { RuntimeOrigin::signed(3), vec![UnscrupulousItem::AccountId(3)] )); - assert_eq!(Alliance::unscrupulous_accounts(), vec![3]); + assert_eq!(UnscrupulousAccounts::::get(), vec![3]); assert_ok!(Alliance::remove_unscrupulous_items( RuntimeOrigin::signed(3), vec![UnscrupulousItem::AccountId(3)] )); - assert_eq!(Alliance::unscrupulous_accounts(), Vec::::new()); + assert_eq!(UnscrupulousAccounts::::get(), Vec::::new()); }); } diff --git a/frame/aura/src/lib.rs b/frame/aura/src/lib.rs index b19fbd57c5030..69e161cb96b82 100644 --- a/frame/aura/src/lib.rs +++ b/frame/aura/src/lib.rs @@ -117,7 +117,6 @@ pub mod pallet { /// The current authority set. #[pallet::storage] - #[pallet::getter(fn authorities)] pub(super) type Authorities = StorageValue<_, BoundedVec, ValueQuery>; @@ -204,6 +203,11 @@ impl Pallet { // the majority of its slot. ::MinimumPeriod::get().saturating_mul(2u32.into()) } + + /// The current authority set. + pub fn authorities() -> BoundedVec { + Authorities::::get() + } } impl sp_runtime::BoundToRuntimeAppPublic for Pallet { @@ -228,7 +232,7 @@ impl OneSessionHandler for Pallet { // instant changes if changed { let next_authorities = validators.map(|(_, k)| k).collect::>(); - let last_authorities = Self::authorities(); + let last_authorities = Authorities::::get(); if last_authorities != next_authorities { if next_authorities.len() as u32 > T::MaxAuthorities::get() { log::warn!( @@ -261,7 +265,7 @@ impl FindAuthor for Pallet { for (id, mut data) in digests.into_iter() { if id == AURA_ENGINE_ID { let slot = Slot::decode(&mut data).ok()?; - let author_index = *slot % Self::authorities().len() as u64; + let author_index = *slot % Authorities::::get().len() as u64; return Some(author_index as u32) } } @@ -284,7 +288,7 @@ impl> FindAuthor { let i = Inner::find_author(digests)?; - let validators = >::authorities(); + let validators = Authorities::::get(); validators.get(i as usize).cloned() } } @@ -294,7 +298,7 @@ pub type AuraAuthorId = FindAccountFromAuthorIndex>; impl IsMember for Pallet { fn is_member(authority_id: &T::AuthorityId) -> bool { - Self::authorities().iter().any(|id| id == authority_id) + Authorities::::get().iter().any(|id| id == authority_id) } } diff --git a/frame/aura/src/tests.rs b/frame/aura/src/tests.rs index ce09f85678c00..078f6883e59e2 100644 --- a/frame/aura/src/tests.rs +++ b/frame/aura/src/tests.rs @@ -19,7 +19,10 @@ #![cfg(test)] -use crate::mock::{new_test_ext, Aura, MockDisabledValidators, System}; +use crate::{ + mock::{new_test_ext, Aura, MockDisabledValidators, System, Test}, + Authorities, CurrentSlot, +}; use codec::Encode; use frame_support::traits::OnInitialize; use sp_consensus_aura::{Slot, AURA_ENGINE_ID}; @@ -28,8 +31,8 @@ use sp_runtime::{Digest, DigestItem}; #[test] fn initial_values() { new_test_ext(vec![0, 1, 2, 3]).execute_with(|| { - assert_eq!(Aura::current_slot(), 0u64); - assert_eq!(Aura::authorities().len(), 4); + assert_eq!(CurrentSlot::::get(), 0u64); + assert_eq!(Authorities::::get().len(), 4); }); } diff --git a/frame/babe/src/lib.rs b/frame/babe/src/lib.rs index 69c89fdcea776..7d77a515b73a2 100644 --- a/frame/babe/src/lib.rs +++ b/frame/babe/src/lib.rs @@ -100,7 +100,7 @@ pub struct SameAuthoritiesForever; impl EpochChangeTrigger for SameAuthoritiesForever { fn trigger(now: T::BlockNumber) { if >::should_epoch_change(now) { - let authorities = >::authorities(); + let authorities = Authorities::::get(); let next_authorities = authorities.clone(); >::enact_epoch_change(authorities, next_authorities, None); @@ -306,10 +306,9 @@ pub mod pallet { #[pallet::getter(fn lateness)] pub(super) type Lateness = StorageValue<_, T::BlockNumber, ValueQuery>; - /// The configuration for the current epoch. Should never be `None` as it is initialized in - /// genesis. + /// The configuration for the current epoch. + /// Should never be `None` as it is initialized in genesis. #[pallet::storage] - #[pallet::getter(fn epoch_config)] pub(super) type EpochConfig = StorageValue<_, BabeEpochConfiguration>; /// The configuration for the next epoch, `None` if the config will not change @@ -383,7 +382,7 @@ pub mod pallet { let current_slot = CurrentSlot::::get(); let transcript = sp_consensus_babe::make_transcript( - &Self::randomness(), + &Randomness::::get(), current_slot, EpochIndex::::get(), ); @@ -517,7 +516,7 @@ impl FindAuthor for Pallet { impl IsMember for Pallet { fn is_member(authority_id: &AuthorityId) -> bool { - >::authorities().iter().any(|id| &id.0 == authority_id) + Authorities::::get().iter().any(|id| &id.0 == authority_id) } } @@ -533,6 +532,12 @@ impl pallet_session::ShouldEndSession for Pallet { } impl Pallet { + /// The configuration for the current epoch. + /// Should never be `None` as it is initialized in genesis. + pub fn epoch_config() -> Option { + EpochConfig::::get() + } + /// Determine the BABE slot duration based on the Timestamp module configuration. pub fn slot_duration() -> T::Moment { // we double the minimum block-period so each author can always propose within @@ -595,7 +600,7 @@ impl Pallet { ) { // PRECONDITION: caller has done initialization and is guaranteed // by the session module to be called before this. - debug_assert!(Self::initialized().is_some()); + debug_assert!(Initialized::::get().is_some()); if authorities.is_empty() { log::warn!(target: LOG_TARGET, "Ignoring empty epoch change."); @@ -709,8 +714,8 @@ impl Pallet { epoch_index: EpochIndex::::get(), start_slot: Self::current_epoch_start(), duration: T::EpochDuration::get(), - authorities: Self::authorities().to_vec(), - randomness: Self::randomness(), + authorities: Authorities::::get().to_vec(), + randomness: Randomness::::get(), config: EpochConfig::::get() .expect("EpochConfig is initialized in genesis; we never `take` or `kill` it; qed"), } @@ -787,8 +792,8 @@ impl Pallet { // we use the same values as genesis because we haven't collected any // randomness yet. let next = NextEpochDescriptor { - authorities: Self::authorities().to_vec(), - randomness: Self::randomness(), + authorities: Authorities::::get().to_vec(), + randomness: Randomness::::get(), }; Self::deposit_consensus(ConsensusLog::NextEpochData(next)); @@ -797,7 +802,7 @@ impl Pallet { fn initialize(now: T::BlockNumber) { // since `initialize` can be called twice (e.g. if session module is present) // let's ensure that we only do the initialization once per block - let initialized = Self::initialized().is_some(); + let initialized = Initialized::::get().is_some(); if initialized { return } @@ -991,7 +996,7 @@ impl frame_support::traits::EstimateNextSessionRotation frame_support::traits::Lateness for Pallet { fn lateness(&self) -> T::BlockNumber { - Self::lateness() + Lateness::::get() } } @@ -1035,7 +1040,7 @@ where ), ); - let session_index = >::current_index(); + let session_index = >::get(); Self::enact_epoch_change(bounded_authorities, next_bounded_authorities, Some(session_index)) } diff --git a/frame/babe/src/mock.rs b/frame/babe/src/mock.rs index b09dc29f6d60a..027f3c045f48d 100644 --- a/frame/babe/src/mock.rs +++ b/frame/babe/src/mock.rs @@ -17,7 +17,7 @@ //! Test utilities -use crate::{self as pallet_babe, Config, CurrentSlot}; +use crate::{self as pallet_babe, Config, CurrentSlot, Randomness}; use codec::Encode; use frame_election_provider_support::{onchain, SequentialPhragmen}; use frame_support::{ @@ -267,7 +267,7 @@ pub fn go_to_block(n: u64, s: u64) { /// Slots will grow accordingly to blocks pub fn progress_to_block(n: u64) { - let mut slot = u64::from(Babe::current_slot()) + 1; + let mut slot = u64::from(CurrentSlot::::get()) + 1; for i in System::block_number() + 1..=n { go_to_block(i, slot); slot += 1; @@ -276,15 +276,15 @@ pub fn progress_to_block(n: u64) { /// Progress to the first block at the given session pub fn start_session(session_index: SessionIndex) { - let missing = (session_index - Session::current_index()) * 3; + let missing = (session_index - pallet_session::CurrentIndex::::get()) * 3; progress_to_block(System::block_number() + missing as u64 + 1); - assert_eq!(Session::current_index(), session_index); + assert_eq!(pallet_session::CurrentIndex::::get(), session_index); } /// Progress to the first block at the given era pub fn start_era(era_index: EraIndex) { start_session((era_index * 3).into()); - assert_eq!(Staking::current_era(), Some(era_index)); + assert_eq!(pallet_staking::CurrentEra::::get(), Some(era_index)); } pub fn make_primary_pre_digest( @@ -339,7 +339,7 @@ pub fn make_vrf_output( pair: &sp_consensus_babe::AuthorityPair, ) -> (VRFOutput, VRFProof, [u8; 32]) { let pair = sp_core::sr25519::Pair::from_ref(pair).as_ref(); - let transcript = sp_consensus_babe::make_transcript(&Babe::randomness(), slot, 0); + let transcript = sp_consensus_babe::make_transcript(&Randomness::::get(), slot, 0); let vrf_inout = pair.vrf_sign(transcript); let vrf_randomness: sp_consensus_vrf::schnorrkel::Randomness = vrf_inout.0.make_bytes::<[u8; 32]>(&sp_consensus_babe::BABE_VRF_INOUT_CONTEXT); diff --git a/frame/babe/src/tests.rs b/frame/babe/src/tests.rs index 938269a6cfa62..64ad1a73bca1a 100644 --- a/frame/babe/src/tests.rs +++ b/frame/babe/src/tests.rs @@ -42,7 +42,7 @@ fn empty_randomness_is_correct() { #[test] fn initial_values() { - new_test_ext(4).execute_with(|| assert_eq!(Babe::authorities().len(), 4)) + new_test_ext(4).execute_with(|| assert_eq!(Authorities::::get().len(), 4)) } #[test] @@ -67,25 +67,25 @@ fn first_block_epoch_zero_start() { let first_vrf = vrf_output; let pre_digest = make_primary_pre_digest(0, genesis_slot, first_vrf.clone(), vrf_proof); - assert_eq!(Babe::genesis_slot(), Slot::from(0)); + assert_eq!(GenesisSlot::::get(), Slot::from(0)); System::reset_events(); System::initialize(&1, &Default::default(), &pre_digest); // see implementation of the function for details why: we issue an // epoch-change digest but don't do it via the normal session mechanism. assert!(!Babe::should_end_session(1)); - assert_eq!(Babe::genesis_slot(), genesis_slot); - assert_eq!(Babe::current_slot(), genesis_slot); - assert_eq!(Babe::epoch_index(), 0); + assert_eq!(GenesisSlot::::get(), genesis_slot); + assert_eq!(CurrentSlot::::get(), genesis_slot); + assert_eq!(EpochIndex::::get(), 0); Babe::on_finalize(1); let header = System::finalize(); - assert_eq!(Babe::author_vrf_randomness(), Some(vrf_randomness)); + assert_eq!(AuthorVrfRandomness::::get(), Some(vrf_randomness)); assert_eq!(SegmentIndex::::get(), 0); assert_eq!(UnderConstruction::::get(0), vec![vrf_randomness]); - assert_eq!(Babe::randomness(), [0; 32]); - assert_eq!(Babe::author_vrf_randomness(), Some(vrf_randomness)); + assert_eq!(Randomness::::get(), [0; 32]); + assert_eq!(AuthorVrfRandomness::::get(), Some(vrf_randomness)); assert_eq!(NextRandomness::::get(), [0; 32]); assert_eq!(header.digest.logs.len(), 2); @@ -94,8 +94,8 @@ fn first_block_epoch_zero_start() { let consensus_log = sp_consensus_babe::ConsensusLog::NextEpochData( sp_consensus_babe::digests::NextEpochDescriptor { - authorities: Babe::authorities().to_vec(), - randomness: Babe::randomness(), + authorities: Authorities::::get().to_vec(), + randomness: Randomness::::get(), }, ); let consensus_digest = DigestItem::Consensus(BABE_ENGINE_ID, consensus_log.encode()); @@ -116,19 +116,19 @@ fn current_slot_is_processed_on_initialization() { System::reset_events(); System::initialize(&1, &Default::default(), &pre_digest); - assert_eq!(Babe::current_slot(), Slot::from(0)); - assert!(Babe::initialized().is_none()); + assert_eq!(CurrentSlot::::get(), Slot::from(0)); + assert!(Initialized::::get().is_none()); // current slot is updated on initialization Babe::initialize(1); - assert_eq!(Babe::current_slot(), genesis_slot); - assert!(Babe::initialized().is_some()); + assert_eq!(CurrentSlot::::get(), genesis_slot); + assert!(Initialized::::get().is_some()); // but author vrf randomness isn't - assert_eq!(Babe::author_vrf_randomness(), None); + assert_eq!(AuthorVrfRandomness::::get(), None); // instead it is updated on block finalization Babe::on_finalize(1); - assert_eq!(Babe::author_vrf_randomness(), Some(vrf_randomness)); + assert_eq!(AuthorVrfRandomness::::get(), Some(vrf_randomness)); }) } @@ -148,16 +148,16 @@ where // author vrf randomness is not updated on initialization Babe::initialize(1); - assert_eq!(Babe::author_vrf_randomness(), None); + assert_eq!(AuthorVrfRandomness::::get(), None); // instead it is updated on block finalization to account for any // epoch changes that might happen during the block Babe::on_finalize(1); - assert_eq!(Babe::author_vrf_randomness(), Some(vrf_randomness)); + assert_eq!(AuthorVrfRandomness::::get(), Some(vrf_randomness)); // and it is kept after finalizing the block System::finalize(); - assert_eq!(Babe::author_vrf_randomness(), Some(vrf_randomness)); + assert_eq!(AuthorVrfRandomness::::get(), Some(vrf_randomness)); }) } @@ -179,14 +179,14 @@ fn no_author_vrf_output_for_secondary_plain() { System::reset_events(); System::initialize(&1, &Default::default(), &secondary_plain_pre_digest); - assert_eq!(Babe::author_vrf_randomness(), None); + assert_eq!(AuthorVrfRandomness::::get(), None); Babe::initialize(1); - assert_eq!(Babe::author_vrf_randomness(), None); + assert_eq!(AuthorVrfRandomness::::get(), None); Babe::on_finalize(1); System::finalize(); - assert_eq!(Babe::author_vrf_randomness(), None); + assert_eq!(AuthorVrfRandomness::::get(), None); }) } @@ -207,14 +207,14 @@ fn can_predict_next_epoch_change() { assert_eq!(::EpochDuration::get(), 3); // this sets the genesis slot to 6; go_to_block(1, 6); - assert_eq!(*Babe::genesis_slot(), 6); - assert_eq!(*Babe::current_slot(), 6); - assert_eq!(Babe::epoch_index(), 0); + assert_eq!(*GenesisSlot::::get(), 6); + assert_eq!(*CurrentSlot::::get(), 6); + assert_eq!(EpochIndex::::get(), 0); progress_to_block(5); - assert_eq!(Babe::epoch_index(), 5 / 3); - assert_eq!(*Babe::current_slot(), 10); + assert_eq!(EpochIndex::::get(), 5 / 3); + assert_eq!(*CurrentSlot::::get(), 10); // next epoch change will be at assert_eq!(*Babe::current_epoch_start(), 9); // next change will be 12, 2 slots from now @@ -263,9 +263,9 @@ fn can_enact_next_config() { assert_eq!(::EpochDuration::get(), 3); // this sets the genesis slot to 6; go_to_block(1, 6); - assert_eq!(*Babe::genesis_slot(), 6); - assert_eq!(*Babe::current_slot(), 6); - assert_eq!(Babe::epoch_index(), 0); + assert_eq!(*GenesisSlot::::get(), 6); + assert_eq!(*CurrentSlot::::get(), 6); + assert_eq!(EpochIndex::::get(), 0); go_to_block(2, 7); let current_config = BabeEpochConfiguration { @@ -411,7 +411,7 @@ fn disabled_validators_cannot_author_blocks() { // so we should still be able to author blocks start_era(2); - assert_eq!(Staking::current_era().unwrap(), 2); + assert_eq!(pallet_staking::CurrentEra::::get().unwrap(), 2); // let's disable the validator at index 0 Session::disable_index(0); @@ -428,8 +428,8 @@ fn report_equivocation_current_session_works() { ext.execute_with(|| { start_era(1); - let authorities = Babe::authorities(); - let validators = Session::validators(); + let authorities = Authorities::::get(); + let validators = pallet_session::Validators::::get(); // make sure that all authorities have the same balance for validator in &validators { @@ -437,14 +437,15 @@ fn report_equivocation_current_session_works() { assert_eq!(Staking::slashable_balance_of(validator), 10_000); assert_eq!( - Staking::eras_stakers(1, validator), + pallet_staking::ErasStakers::::get(1, validator), pallet_staking::Exposure { total: 10_000, own: 10_000, others: vec![] }, ); } // we will use the validator at index 1 as the offending authority let offending_validator_index = 1; - let offending_validator_id = Session::validators()[offending_validator_index]; + let offending_validator_id = + pallet_session::Validators::::get()[offending_validator_index]; let offending_authority_pair = pairs .into_iter() .find(|p| p.public() == authorities[offending_validator_index].0) @@ -478,7 +479,7 @@ fn report_equivocation_current_session_works() { assert_eq!(Balances::total_balance(&offending_validator_id), 10_000_000 - 10_000); assert_eq!(Staking::slashable_balance_of(&offending_validator_id), 0); assert_eq!( - Staking::eras_stakers(2, offending_validator_id), + pallet_staking::ErasStakers::::get(2, offending_validator_id), pallet_staking::Exposure { total: 0, own: 0, others: vec![] }, ); @@ -491,7 +492,7 @@ fn report_equivocation_current_session_works() { assert_eq!(Balances::total_balance(validator), 10_000_000); assert_eq!(Staking::slashable_balance_of(validator), 10_000); assert_eq!( - Staking::eras_stakers(2, validator), + pallet_staking::ErasStakers::::get(2, validator), pallet_staking::Exposure { total: 10_000, own: 10_000, others: vec![] }, ); } @@ -505,11 +506,12 @@ fn report_equivocation_old_session_works() { ext.execute_with(|| { start_era(1); - let authorities = Babe::authorities(); + let authorities = Authorities::::get(); // we will use the validator at index 0 as the offending authority let offending_validator_index = 1; - let offending_validator_id = Session::validators()[offending_validator_index]; + let offending_validator_id = + pallet_session::Validators::::get()[offending_validator_index]; let offending_authority_pair = pairs .into_iter() .find(|p| p.public() == authorities[offending_validator_index].0) @@ -550,7 +552,7 @@ fn report_equivocation_old_session_works() { assert_eq!(Balances::total_balance(&offending_validator_id), 10_000_000 - 10_000); assert_eq!(Staking::slashable_balance_of(&offending_validator_id), 0); assert_eq!( - Staking::eras_stakers(3, offending_validator_id), + pallet_staking::ErasStakers::::get(3, offending_validator_id), pallet_staking::Exposure { total: 0, own: 0, others: vec![] }, ); }) @@ -563,7 +565,7 @@ fn report_equivocation_invalid_key_owner_proof() { ext.execute_with(|| { start_era(1); - let authorities = Babe::authorities(); + let authorities = Authorities::::get(); // we will use the validator at index 0 as the offending authority let offending_validator_index = 0; @@ -626,7 +628,7 @@ fn report_equivocation_invalid_equivocation_proof() { ext.execute_with(|| { start_era(1); - let authorities = Babe::authorities(); + let authorities = Authorities::::get(); // we will use the validator at index 0 as the offending authority let offending_validator_index = 0; @@ -731,7 +733,7 @@ fn report_equivocation_validate_unsigned_prevents_duplicates() { ext.execute_with(|| { start_era(1); - let authorities = Babe::authorities(); + let authorities = Authorities::::get(); // generate and report an equivocation for the validator at index 0 let offending_validator_index = 0; @@ -845,7 +847,7 @@ fn report_equivocation_after_skipped_epochs_works() { assert_eq!(SkippedEpochs::::get(), vec![(10, 1)]); // generate an equivocation proof for validator at index 1 - let authorities = Babe::authorities(); + let authorities = Authorities::::get(); let offending_validator_index = 1; let offending_authority_pair = pairs .into_iter() diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index f62ea6be7d3eb..145e6198d4bdc 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -502,7 +502,6 @@ pub mod pallet { /// The total units issued in the system. #[pallet::storage] - #[pallet::getter(fn total_issuance)] #[pallet::whitelist_storage] pub type TotalIssuance, I: 'static = ()> = StorageValue<_, T::Balance, ValueQuery>; @@ -1913,7 +1912,7 @@ where type ReserveIdentifier = T::ReserveIdentifier; fn reserved_balance_named(id: &Self::ReserveIdentifier, who: &T::AccountId) -> Self::Balance { - let reserves = Self::reserves(who); + let reserves = Reserves::::get(who); reserves .binary_search_by_key(id, |data| data.id) .map(|index| reserves[index].amount) @@ -2153,7 +2152,7 @@ where return } let mut new_lock = Some(BalanceLock { id, amount, reasons: reasons.into() }); - let mut locks = Self::locks(who) + let mut locks = Locks::::get(who) .into_iter() .filter_map(|l| if l.id == id { new_lock.take() } else { Some(l) }) .collect::>(); @@ -2175,7 +2174,7 @@ where return } let mut new_lock = Some(BalanceLock { id, amount, reasons: reasons.into() }); - let mut locks = Self::locks(who) + let mut locks = Locks::::get(who) .into_iter() .filter_map(|l| { if l.id == id { @@ -2196,7 +2195,7 @@ where } fn remove_lock(id: LockIdentifier, who: &T::AccountId) { - let mut locks = Self::locks(who); + let mut locks = Locks::::get(who); locks.retain(|l| l.id != id); Self::update_locks(who, &locks[..]); } diff --git a/frame/beefy-mmr/src/lib.rs b/frame/beefy-mmr/src/lib.rs index eb030b71ddec6..d828e7fbb1924 100644 --- a/frame/beefy-mmr/src/lib.rs +++ b/frame/beefy-mmr/src/lib.rs @@ -151,7 +151,7 @@ impl LeafDataProvider for Pallet { version: T::LeafVersion::get(), parent_number_and_hash: ParentNumberAndHash::::leaf_data(), leaf_extra: T::BeefyDataProvider::extra_data(), - beefy_next_authority_set: Pallet::::beefy_next_authorities(), + beefy_next_authority_set: BeefyNextAuthorities::::get(), } } } @@ -176,12 +176,12 @@ where impl Pallet { /// Return the currently active BEEFY authority set proof. pub fn authority_set_proof() -> BeefyAuthoritySet> { - Pallet::::beefy_authorities() + BeefyAuthorities::::get() } /// Return the next/queued BEEFY authority set proof. pub fn next_authority_set_proof() -> BeefyNextAuthoritySet> { - Pallet::::beefy_next_authorities() + BeefyNextAuthorities::::get() } /// Returns details of a BEEFY authority set. diff --git a/frame/beefy/src/lib.rs b/frame/beefy/src/lib.rs index d29440457f5bf..3092709cdcc44 100644 --- a/frame/beefy/src/lib.rs +++ b/frame/beefy/src/lib.rs @@ -263,8 +263,8 @@ pub mod pallet { impl Pallet { /// Return the current active BEEFY validator set. pub fn validator_set() -> Option> { - let validators: BoundedVec = Self::authorities(); - let id: beefy_primitives::ValidatorSetId = Self::validator_set_id(); + let validators: BoundedVec = Authorities::::get(); + let id: beefy_primitives::ValidatorSetId = ValidatorSetId::::get(); ValidatorSet::::new(validators, id) } @@ -292,7 +292,7 @@ impl Pallet { ) { >::put(&new); - let new_id = Self::validator_set_id() + 1u64; + let new_id = ValidatorSetId::::get() + 1u64; >::put(new_id); >::put(&queued); @@ -463,8 +463,8 @@ where Self::change_authorities(bounded_next_authorities, bounded_next_queued_authorities); // Update the mapping for the new set id that corresponds to the latest session (i.e. now). - let session_index = >::current_index(); - SetIdSession::::insert(Self::validator_set_id(), &session_index); + let session_index = >::get(); + SetIdSession::::insert(ValidatorSetId::::get(), &session_index); } fn on_disabled(i: u32) { @@ -479,7 +479,7 @@ where impl IsMember for Pallet { fn is_member(authority_id: &T::BeefyId) -> bool { - Self::authorities().iter().any(|id| id == authority_id) + Authorities::::get().iter().any(|id| id == authority_id) } } diff --git a/frame/beefy/src/mock.rs b/frame/beefy/src/mock.rs index 8d8b831950d8e..6f68397ec8540 100644 --- a/frame/beefy/src/mock.rs +++ b/frame/beefy/src/mock.rs @@ -306,7 +306,7 @@ pub fn new_test_ext_raw_authorities(authorities: Vec) -> TestExternalit } pub fn start_session(session_index: SessionIndex) { - for i in Session::current_index()..session_index { + for i in pallet_session::CurrentIndex::::get()..session_index { System::on_finalize(System::block_number()); Session::on_finalize(System::block_number()); Staking::on_finalize(System::block_number()); @@ -330,10 +330,10 @@ pub fn start_session(session_index: SessionIndex) { Beefy::on_initialize(System::block_number()); } - assert_eq!(Session::current_index(), session_index); + assert_eq!(pallet_session::CurrentIndex::::get(), session_index); } pub fn start_era(era_index: EraIndex) { start_session((era_index * 3).into()); - assert_eq!(Staking::current_era(), Some(era_index)); + assert_eq!(pallet_staking::CurrentEra::::get(), Some(era_index)); } diff --git a/frame/beefy/src/tests.rs b/frame/beefy/src/tests.rs index a92f90b6107bc..61eecc2e28b0c 100644 --- a/frame/beefy/src/tests.rs +++ b/frame/beefy/src/tests.rs @@ -31,7 +31,9 @@ use frame_support::{ traits::{Currency, KeyOwnerProofSystem, OnInitialize}, }; -use crate::{mock::*, Call, Config, Error, Weight, WeightInfo}; +use crate::{ + mock::*, Authorities, Call, Config, Error, NextAuthorities, ValidatorSetId, Weight, WeightInfo, +}; fn init_block(block: u64) { System::set_block_number(block); @@ -48,15 +50,14 @@ fn genesis_session_initializes_authorities() { let want = authorities.clone(); new_test_ext_raw_authorities(authorities).execute_with(|| { - let authorities = Beefy::authorities(); - + let authorities = Authorities::::get(); assert_eq!(authorities.len(), 4); assert_eq!(want[0], authorities[0]); assert_eq!(want[1], authorities[1]); - assert!(Beefy::validator_set_id() == 0); + assert!(ValidatorSetId::::get() == 0); - let next_authorities = Beefy::next_authorities(); + let next_authorities = NextAuthorities::::get(); assert_eq!(next_authorities.len(), 4); assert_eq!(want[0], next_authorities[0]); @@ -70,11 +71,11 @@ fn session_change_updates_authorities() { let want_validators = authorities.clone(); new_test_ext(vec![1, 2, 3, 4]).execute_with(|| { - assert!(0 == Beefy::validator_set_id()); + assert!(0 == ValidatorSetId::::get()); init_block(1); - assert!(1 == Beefy::validator_set_id()); + assert!(1 == ValidatorSetId::::get()); let want = beefy_log(ConsensusLog::AuthoritiesChange( ValidatorSet::new(want_validators, 1).unwrap(), @@ -85,7 +86,7 @@ fn session_change_updates_authorities() { init_block(2); - assert!(2 == Beefy::validator_set_id()); + assert!(2 == ValidatorSetId::::get()); let want = beefy_log(ConsensusLog::AuthoritiesChange( ValidatorSet::new(vec![mock_beefy_id(2), mock_beefy_id(4)], 2).unwrap(), @@ -101,7 +102,7 @@ fn session_change_updates_next_authorities() { let want = vec![mock_beefy_id(1), mock_beefy_id(2), mock_beefy_id(3), mock_beefy_id(4)]; new_test_ext(vec![1, 2, 3, 4]).execute_with(|| { - let next_authorities = Beefy::next_authorities(); + let next_authorities = NextAuthorities::::get(); assert_eq!(next_authorities.len(), 4); assert_eq!(want[0], next_authorities[0]); @@ -111,7 +112,7 @@ fn session_change_updates_next_authorities() { init_block(1); - let next_authorities = Beefy::next_authorities(); + let next_authorities = NextAuthorities::::get(); assert_eq!(next_authorities.len(), 2); assert_eq!(want[1], next_authorities[0]); @@ -227,8 +228,8 @@ fn report_equivocation_current_set_works() { let authorities = test_authorities(); new_test_ext_raw_authorities(authorities).execute_with(|| { - assert_eq!(Staking::current_era(), Some(0)); - assert_eq!(Session::current_index(), 0); + assert_eq!(pallet_staking::CurrentEra::::get(), Some(0)); + assert_eq!(pallet_session::CurrentIndex::::get(), 0); start_era(1); @@ -236,7 +237,7 @@ fn report_equivocation_current_set_works() { let validator_set = Beefy::validator_set().unwrap(); let authorities = validator_set.validators(); let set_id = validator_set.id(); - let validators = Session::validators(); + let validators = pallet_session::Validators::::get(); // make sure that all validators have the same balance for validator in &validators { @@ -313,7 +314,7 @@ fn report_equivocation_old_set_works() { let block_num = System::block_number(); let validator_set = Beefy::validator_set().unwrap(); let authorities = validator_set.validators(); - let validators = Session::validators(); + let validators = pallet_session::Validators::::get(); let old_set_id = validator_set.id(); assert_eq!(authorities.len(), 2); diff --git a/frame/benchmarking/src/tests.rs b/frame/benchmarking/src/tests.rs index 1499f9c182fce..d9eb067d4605f 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -46,7 +46,6 @@ mod pallet_test { } #[pallet::storage] - #[pallet::getter(fn value)] pub(crate) type Value = StorageValue<_, u32, OptionQuery>; #[pallet::call] diff --git a/frame/benchmarking/src/tests_instance.rs b/frame/benchmarking/src/tests_instance.rs index ecc0a78a199b9..a34844b6e837c 100644 --- a/frame/benchmarking/src/tests_instance.rs +++ b/frame/benchmarking/src/tests_instance.rs @@ -50,7 +50,6 @@ mod pallet_test { } #[pallet::storage] - #[pallet::getter(fn value)] pub(crate) type Value, I: 'static = ()> = StorageValue<_, u32, OptionQuery>; #[pallet::event] diff --git a/frame/bounties/src/lib.rs b/frame/bounties/src/lib.rs index afdcfef8279bd..082d44babf0d7 100644 --- a/frame/bounties/src/lib.rs +++ b/frame/bounties/src/lib.rs @@ -829,7 +829,7 @@ impl, I: 'static> Pallet { description.try_into().map_err(|_| Error::::ReasonTooBig)?; ensure!(value >= T::BountyValueMinimum::get(), Error::::InvalidValue); - let index = Self::bounty_count(); + let index = BountyCount::::get(); // reserve deposit for new bounty let bond = T::BountyDepositBase::get() + diff --git a/frame/bounties/src/tests.rs b/frame/bounties/src/tests.rs index bc59e3a70fd82..53b5535100e5c 100644 --- a/frame/bounties/src/tests.rs +++ b/frame/bounties/src/tests.rs @@ -20,7 +20,7 @@ #![cfg(test)] use super::*; -use crate as pallet_bounties; +use crate::{self as pallet_bounties, Bounties as BountiesStorage}; use frame_support::{ assert_noop, assert_ok, @@ -455,7 +455,7 @@ fn propose_bounty_works() { assert_eq!(Balances::free_balance(0), 100 - deposit); assert_eq!( - Bounties::bounties(0).unwrap(), + BountiesStorage::::get(0).unwrap(), Bounty { proposer: 0, fee: 0, @@ -466,9 +466,9 @@ fn propose_bounty_works() { } ); - assert_eq!(Bounties::bounty_descriptions(0).unwrap(), b"1234567890".to_vec()); + assert_eq!(BountyDescriptions::::get(0).unwrap(), b"1234567890".to_vec()); - assert_eq!(Bounties::bounty_count(), 1); + assert_eq!(BountyCount::::get(), 1); }); } @@ -519,10 +519,10 @@ fn close_bounty_works() { assert_eq!(Balances::reserved_balance(0), 0); assert_eq!(Balances::free_balance(0), 100 - deposit); - assert_eq!(Bounties::bounties(0), None); + assert_eq!(BountiesStorage::::get(0), None); assert!(!pallet_treasury::Proposals::::contains_key(0)); - assert_eq!(Bounties::bounty_descriptions(0), None); + assert_eq!(BountyDescriptions::::get(0), None); }); } @@ -543,7 +543,7 @@ fn approve_bounty_works() { let deposit: u64 = 80 + 5; assert_eq!( - Bounties::bounties(0).unwrap(), + BountiesStorage::::get(0).unwrap(), Bounty { proposer: 0, fee: 0, @@ -553,7 +553,7 @@ fn approve_bounty_works() { status: BountyStatus::Approved, } ); - assert_eq!(Bounties::bounty_approvals(), vec![0]); + assert_eq!(BountyApprovals::::get(), vec![0]); assert_noop!( Bounties::close_bounty(RuntimeOrigin::root(), 0), @@ -571,7 +571,7 @@ fn approve_bounty_works() { assert_eq!(Balances::free_balance(0), 100); assert_eq!( - Bounties::bounties(0).unwrap(), + BountiesStorage::::get(0).unwrap(), Bounty { proposer: 0, fee: 0, @@ -614,7 +614,7 @@ fn assign_curator_works() { assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, fee)); assert_eq!( - Bounties::bounties(0).unwrap(), + BountiesStorage::::get(0).unwrap(), Bounty { proposer: 0, fee, @@ -641,7 +641,7 @@ fn assign_curator_works() { let expected_deposit = Bounties::calculate_curator_deposit(&fee); assert_eq!( - Bounties::bounties(0).unwrap(), + BountiesStorage::::get(0).unwrap(), Bounty { proposer: 0, fee, @@ -676,7 +676,7 @@ fn unassign_curator_works() { assert_ok!(Bounties::unassign_curator(RuntimeOrigin::signed(4), 0)); assert_eq!( - Bounties::bounties(0).unwrap(), + BountiesStorage::::get(0).unwrap(), Bounty { proposer: 0, fee, @@ -694,7 +694,7 @@ fn unassign_curator_works() { assert_ok!(Bounties::unassign_curator(RuntimeOrigin::root(), 0)); assert_eq!( - Bounties::bounties(0).unwrap(), + BountiesStorage::::get(0).unwrap(), Bounty { proposer: 0, fee, @@ -738,7 +738,7 @@ fn award_and_claim_bounty_works() { assert_ok!(Bounties::award_bounty(RuntimeOrigin::signed(4), 0, 3)); assert_eq!( - Bounties::bounties(0).unwrap(), + BountiesStorage::::get(0).unwrap(), Bounty { proposer: 0, fee, @@ -772,8 +772,8 @@ fn award_and_claim_bounty_works() { assert_eq!(Balances::free_balance(3), 56); assert_eq!(Balances::free_balance(Bounties::bounty_account_id(0)), 0); - assert_eq!(Bounties::bounties(0), None); - assert_eq!(Bounties::bounty_descriptions(0), None); + assert_eq!(BountiesStorage::::get(0), None); + assert_eq!(BountyDescriptions::::get(0), None); }); } @@ -813,8 +813,8 @@ fn claim_handles_high_fee() { assert_eq!(Balances::free_balance(3), 0); assert_eq!(Balances::free_balance(Bounties::bounty_account_id(0)), 0); - assert_eq!(Bounties::bounties(0), None); - assert_eq!(Bounties::bounty_descriptions(0), None); + assert_eq!(BountiesStorage::::get(0), None); + assert_eq!(BountyDescriptions::::get(0), None); }); } @@ -839,7 +839,7 @@ fn cancel_and_refund() { )); assert_eq!( - Bounties::bounties(0).unwrap(), + BountiesStorage::::get(0).unwrap(), Bounty { proposer: 0, fee: 0, @@ -899,8 +899,8 @@ fn award_and_cancel() { assert_eq!(Balances::free_balance(0), 95); assert_eq!(Balances::reserved_balance(0), 0); - assert_eq!(Bounties::bounties(0), None); - assert_eq!(Bounties::bounty_descriptions(0), None); + assert_eq!(BountiesStorage::::get(0), None); + assert_eq!(BountyDescriptions::::get(0), None); }); } @@ -936,7 +936,7 @@ fn expire_and_unassign() { assert_ok!(Bounties::unassign_curator(RuntimeOrigin::signed(0), 0)); assert_eq!( - Bounties::bounties(0).unwrap(), + BountiesStorage::::get(0).unwrap(), Bounty { proposer: 0, fee: 10, @@ -986,7 +986,7 @@ fn extend_expiry() { assert_ok!(Bounties::extend_bounty_expiry(RuntimeOrigin::signed(4), 0, Vec::new())); assert_eq!( - Bounties::bounties(0).unwrap(), + BountiesStorage::::get(0).unwrap(), Bounty { proposer: 0, fee: 10, @@ -1000,7 +1000,7 @@ fn extend_expiry() { assert_ok!(Bounties::extend_bounty_expiry(RuntimeOrigin::signed(4), 0, Vec::new())); assert_eq!( - Bounties::bounties(0).unwrap(), + BountiesStorage::::get(0).unwrap(), Bounty { proposer: 0, fee: 10, @@ -1109,7 +1109,7 @@ fn unassign_curator_self() { assert_ok!(Bounties::unassign_curator(RuntimeOrigin::signed(1), 0)); assert_eq!( - Bounties::bounties(0).unwrap(), + BountiesStorage::::get(0).unwrap(), Bounty { proposer: 0, fee: 10, diff --git a/frame/child-bounties/src/benchmarking.rs b/frame/child-bounties/src/benchmarking.rs index e7f18c1645823..794f3f41e95d0 100644 --- a/frame/child-bounties/src/benchmarking.rs +++ b/frame/child-bounties/src/benchmarking.rs @@ -103,7 +103,7 @@ fn activate_bounty( child_bounty_setup.reason.clone(), )?; - child_bounty_setup.bounty_id = Bounties::::bounty_count() - 1; + child_bounty_setup.bounty_id = >::get() - 1; let approve_origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; diff --git a/frame/child-bounties/src/lib.rs b/frame/child-bounties/src/lib.rs index 9eb784eaccd23..8eb431890fab5 100644 --- a/frame/child-bounties/src/lib.rs +++ b/frame/child-bounties/src/lib.rs @@ -252,7 +252,7 @@ pub mod pallet { description.try_into().map_err(|_| BountiesError::::ReasonTooBig)?; ensure!(value >= T::ChildBountyValueMinimum::get(), BountiesError::::InvalidValue); ensure!( - Self::parent_child_bounties(parent_bounty_id) <= + ParentChildBounties::::get(parent_bounty_id) <= T::MaxActiveChildBountyCount::get() as u32, Error::::TooManyChildBounties, ); @@ -277,7 +277,7 @@ pub mod pallet { )?; // Get child-bounty ID. - let child_bounty_id = Self::child_bounty_count(); + let child_bounty_id = ChildBountyCount::::get(); let child_bounty_account = Self::child_bounty_account_id(child_bounty_id); // Transfer funds from parent bounty to child-bounty. @@ -818,7 +818,7 @@ impl Pallet { fn ensure_bounty_active( bounty_id: BountyIndex, ) -> Result<(T::AccountId, T::BlockNumber), DispatchError> { - let parent_bounty = pallet_bounties::Pallet::::bounties(bounty_id) + let parent_bounty = pallet_bounties::Bounties::::get(bounty_id) .ok_or(BountiesError::::InvalidIndex)?; if let BountyStatus::Active { curator, update_due } = parent_bounty.get_status() { Ok((curator, update_due)) @@ -902,13 +902,13 @@ impl pallet_bounties::ChildBountyManager> for Pallet fn child_bounties_count( bounty_id: pallet_bounties::BountyIndex, ) -> pallet_bounties::BountyIndex { - Self::parent_child_bounties(bounty_id) + ParentChildBounties::::get(bounty_id) } fn children_curator_fees(bounty_id: pallet_bounties::BountyIndex) -> BalanceOf { // This is asked for when the parent bounty is being claimed. No use of // keeping it in state after that. Hence removing. - let children_fee_total = Self::children_curator_fees(bounty_id); + let children_fee_total = ChildrenCuratorFees::::get(bounty_id); >::remove(bounty_id); children_fee_total } diff --git a/frame/child-bounties/src/tests.rs b/frame/child-bounties/src/tests.rs index f3415c69df611..16e0a7e46b8a1 100644 --- a/frame/child-bounties/src/tests.rs +++ b/frame/child-bounties/src/tests.rs @@ -21,6 +21,7 @@ use super::*; use crate as pallet_child_bounties; +use crate::ChildBounties as ChildBountiesStorage; use frame_support::{ assert_noop, assert_ok, @@ -273,7 +274,7 @@ fn add_child_bounty() { // DB check. // Check the child-bounty status. assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -284,10 +285,10 @@ fn add_child_bounty() { ); // Check the child-bounty count. - assert_eq!(ChildBounties::parent_child_bounties(0), 1); + assert_eq!(ParentChildBounties::::get(0), 1); // Check the child-bounty description status. - assert_eq!(ChildBounties::child_bounty_descriptions(0).unwrap(), b"12345-p1".to_vec(),); + assert_eq!(ChildBountyDescriptions::::get(0).unwrap(), b"12345-p1".to_vec(),); }); } @@ -349,7 +350,7 @@ fn child_bounty_assign_curator() { assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, fee)); assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -373,7 +374,7 @@ fn child_bounty_assign_curator() { let expected_child_deposit = CuratorDepositMultiplier::get() * fee; assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -450,7 +451,7 @@ fn award_claim_child_bounty() { let expected_deposit = CuratorDepositMultiplier::get() * fee; assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -488,7 +489,7 @@ fn award_claim_child_bounty() { assert_eq!(Balances::reserved_balance(ChildBounties::child_bounty_account_id(0)), 0); // Check the child-bounty count. - assert_eq!(ChildBounties::parent_child_bounties(0), 0); + assert_eq!(ParentChildBounties::::get(0), 0); }); } @@ -537,7 +538,7 @@ fn close_child_bounty_added() { assert_ok!(ChildBounties::close_child_bounty(RuntimeOrigin::signed(4), 0, 0)); // Check the child-bounty count. - assert_eq!(ChildBounties::parent_child_bounties(0), 0); + assert_eq!(ParentChildBounties::::get(0), 0); // Parent-bounty account status. assert_eq!(Balances::free_balance(Bounties::bounty_account_id(0)), 50); @@ -591,7 +592,7 @@ fn close_child_bounty_active() { assert_ok!(ChildBounties::close_child_bounty(RuntimeOrigin::signed(4), 0, 0)); // Check the child-bounty count. - assert_eq!(ChildBounties::parent_child_bounties(0), 0); + assert_eq!(ParentChildBounties::::get(0), 0); // Ensure child-bounty curator balance is unreserved. assert_eq!(Balances::free_balance(8), 101); @@ -656,7 +657,7 @@ fn close_child_bounty_pending() { ); // Check the child-bounty count. - assert_eq!(ChildBounties::parent_child_bounties(0), 1); + assert_eq!(ParentChildBounties::::get(0), 1); // Ensure no changes in child-bounty curator balance. assert_eq!(Balances::reserved_balance(8), expected_child_deposit); @@ -748,7 +749,7 @@ fn child_bounty_curator_proposed_unassign_curator() { assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, 2)); assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -766,7 +767,7 @@ fn child_bounty_curator_proposed_unassign_curator() { // Verify updated child-bounty status. assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -829,7 +830,7 @@ fn child_bounty_active_unassign_curator() { let expected_child_deposit = CuratorDepositMultiplier::get() * fee; assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -847,7 +848,7 @@ fn child_bounty_active_unassign_curator() { // Verify updated child-bounty status. assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -868,7 +869,7 @@ fn child_bounty_active_unassign_curator() { let expected_child_deposit = CuratorDepositMin::get(); assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -886,7 +887,7 @@ fn child_bounty_active_unassign_curator() { // Verify updated child-bounty status. assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -905,7 +906,7 @@ fn child_bounty_active_unassign_curator() { assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(6), 0, 0)); assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -923,7 +924,7 @@ fn child_bounty_active_unassign_curator() { // Verify updated child-bounty status. assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -944,7 +945,7 @@ fn child_bounty_active_unassign_curator() { let expected_child_deposit = CuratorDepositMin::get(); assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -972,7 +973,7 @@ fn child_bounty_active_unassign_curator() { // Verify updated child-bounty status. assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -1034,7 +1035,7 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { let expected_child_deposit = CuratorDepositMultiplier::get() * fee; assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -1065,7 +1066,7 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { // Verify updated child-bounty status. assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -1096,7 +1097,7 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { let expected_deposit = CuratorDepositMin::get(); assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -1125,7 +1126,7 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { // Verify updated child-bounty status. assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -1195,7 +1196,7 @@ fn close_parent_with_child_bounty() { assert_ok!(ChildBounties::close_child_bounty(RuntimeOrigin::root(), 0, 0)); // Check the child-bounty count. - assert_eq!(ChildBounties::parent_child_bounties(0), 0); + assert_eq!(ParentChildBounties::::get(0), 0); // Try close parent-bounty again. // Should pass this time. @@ -1244,7 +1245,7 @@ fn children_curator_fee_calculation_test() { // Propose curator for child-bounty. assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, fee)); // Check curator fee added to the sum. - assert_eq!(ChildBounties::children_curator_fees(0), fee); + assert_eq!(ChildrenCuratorFees::::get(0), fee); // Accept curator for child-bounty. assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(8), 0, 0)); // Award child-bounty. @@ -1253,7 +1254,7 @@ fn children_curator_fee_calculation_test() { let expected_child_deposit = CuratorDepositMultiplier::get() * fee; assert_eq!( - ChildBounties::child_bounties(0, 0).unwrap(), + ChildBountiesStorage::::get(0, 0).unwrap(), ChildBounty { parent_bounty: 0, value: 10, @@ -1273,7 +1274,7 @@ fn children_curator_fee_calculation_test() { assert_ok!(ChildBounties::claim_child_bounty(RuntimeOrigin::signed(7), 0, 0)); // Check the child-bounty count. - assert_eq!(ChildBounties::parent_child_bounties(0), 0); + assert_eq!(ParentChildBounties::::get(0), 0); // Award the parent bounty. assert_ok!(Bounties::award_bounty(RuntimeOrigin::signed(4), 0, 9)); diff --git a/frame/collective/src/benchmarking.rs b/frame/collective/src/benchmarking.rs index 5c9e55862d1a4..812fabb7da1a0 100644 --- a/frame/collective/src/benchmarking.rs +++ b/frame/collective/src/benchmarking.rs @@ -103,7 +103,7 @@ benchmarks_instance_pallet! { }: _(SystemOrigin::Root, new_members.clone(), new_members.last().cloned(), T::MaxMembers::get()) verify { new_members.sort(); - assert_eq!(Collective::::members(), new_members); + assert_eq!(Members::::get(), new_members); } execute { @@ -197,14 +197,14 @@ benchmarks_instance_pallet! { )?; } - assert_eq!(Collective::::proposals().len(), (p - 1) as usize); + assert_eq!(Proposals::::get().len(), (p - 1) as usize); let proposal: T::Proposal = SystemCall::::remark { remark: id_to_remark_data(p, b as usize) }.into(); }: propose(SystemOrigin::Signed(caller.clone()), threshold, Box::new(proposal.clone()), bytes_in_storage) verify { // New proposal is recorded - assert_eq!(Collective::::proposals().len(), p as usize); + assert_eq!(Proposals::::get().len(), p as usize); let proposal_hash = T::Hashing::hash_of(&proposal); assert_last_event::(Event::Proposed { account: caller, proposal_index: p - 1, proposal_hash, threshold }.into()); } @@ -267,7 +267,7 @@ benchmarks_instance_pallet! { approve, )?; - assert_eq!(Collective::::proposals().len(), p as usize); + assert_eq!(Proposals::::get().len(), p as usize); // Voter switches vote to nay, but does not kill the vote, just updates + inserts let approve = false; @@ -278,8 +278,8 @@ benchmarks_instance_pallet! { }: _(SystemOrigin::Signed(voter), last_hash, index, approve) verify { // All proposals exist and the last proposal has just been updated. - assert_eq!(Collective::::proposals().len(), p as usize); - let voting = Collective::::voting(&last_hash).ok_or("Proposal Missing")?; + assert_eq!(Proposals::::get().len(), p as usize); + let voting = Voting::::get(&last_hash).ok_or("Proposal Missing")?; assert_eq!(voting.ayes.len(), (m - 3) as usize); assert_eq!(voting.nays.len(), 1); } @@ -342,7 +342,7 @@ benchmarks_instance_pallet! { approve, )?; - assert_eq!(Collective::::proposals().len(), p as usize); + assert_eq!(Proposals::::get().len(), p as usize); // Voter switches vote to nay, which kills the vote let approve = false; @@ -359,7 +359,7 @@ benchmarks_instance_pallet! { }: close(SystemOrigin::Signed(voter), last_hash, index, Weight::MAX, bytes_in_storage) verify { // The last proposal is removed. - assert_eq!(Collective::::proposals().len(), (p - 1) as usize); + assert_eq!(Proposals::::get().len(), (p - 1) as usize); assert_last_event::(Event::Disapproved { proposal_hash: last_hash }.into()); } @@ -426,7 +426,7 @@ benchmarks_instance_pallet! { true, )?; - assert_eq!(Collective::::proposals().len(), p as usize); + assert_eq!(Proposals::::get().len(), p as usize); // Caller switches vote to aye, which passes the vote let index = p - 1; @@ -440,7 +440,7 @@ benchmarks_instance_pallet! { }: close(SystemOrigin::Signed(caller), last_hash, index, Weight::MAX, bytes_in_storage) verify { // The last proposal is removed. - assert_eq!(Collective::::proposals().len(), (p - 1) as usize); + assert_eq!(Proposals::::get().len(), (p - 1) as usize); assert_last_event::(Event::Executed { proposal_hash: last_hash, result: Err(DispatchError::BadOrigin) }.into()); } @@ -517,12 +517,12 @@ benchmarks_instance_pallet! { )?; System::::set_block_number(T::BlockNumber::max_value()); - assert_eq!(Collective::::proposals().len(), p as usize); + assert_eq!(Proposals::::get().len(), p as usize); // Prime nay will close it as disapproved }: close(SystemOrigin::Signed(caller), last_hash, index, Weight::MAX, bytes_in_storage) verify { - assert_eq!(Collective::::proposals().len(), (p - 1) as usize); + assert_eq!(Proposals::::get().len(), (p - 1) as usize); assert_last_event::(Event::Disapproved { proposal_hash: last_hash }.into()); } @@ -589,12 +589,12 @@ benchmarks_instance_pallet! { // caller is prime, prime already votes aye by creating the proposal System::::set_block_number(T::BlockNumber::max_value()); - assert_eq!(Collective::::proposals().len(), p as usize); + assert_eq!(Proposals::::get().len(), p as usize); // Prime aye will close it as approved }: close(SystemOrigin::Signed(caller), last_hash, p - 1, Weight::MAX, bytes_in_storage) verify { - assert_eq!(Collective::::proposals().len(), (p - 1) as usize); + assert_eq!(Proposals::::get().len(), (p - 1) as usize); assert_last_event::(Event::Executed { proposal_hash: last_hash, result: Err(DispatchError::BadOrigin) }.into()); } @@ -638,11 +638,11 @@ benchmarks_instance_pallet! { } System::::set_block_number(T::BlockNumber::max_value()); - assert_eq!(Collective::::proposals().len(), p as usize); + assert_eq!(Proposals::::get().len(), p as usize); }: _(SystemOrigin::Root, last_hash) verify { - assert_eq!(Collective::::proposals().len(), (p - 1) as usize); + assert_eq!(Proposals::::get().len(), (p - 1) as usize); assert_last_event::(Event::Disapproved { proposal_hash: last_hash }.into()); } diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 8424527b154a4..d8033fff71d9d 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -260,7 +260,6 @@ pub mod pallet { /// Actual proposal for a given hash, if it's current. #[pallet::storage] - #[pallet::getter(fn proposal_of)] pub type ProposalOf, I: 'static = ()> = StorageMap<_, Identity, T::Hash, >::Proposal, OptionQuery>; @@ -439,7 +438,7 @@ pub mod pallet { #[pallet::compact] length_bound: u32, ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; - let members = Self::members(); + let members = Members::::get(); ensure!(members.contains(&who), Error::::NotMember); let proposal_len = proposal.encoded_size(); ensure!(proposal_len <= length_bound as usize, Error::::WrongProposalLength); @@ -499,7 +498,7 @@ pub mod pallet { #[pallet::compact] length_bound: u32, ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; - let members = Self::members(); + let members = Members::::get(); ensure!(members.contains(&who), Error::::NotMember); if threshold < 2 { @@ -545,7 +544,7 @@ pub mod pallet { approve: bool, ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; - let members = Self::members(); + let members = Members::::get(); ensure!(members.contains(&who), Error::::NotMember); // Detects first vote of the member in the motion @@ -697,11 +696,16 @@ fn get_result_weight(result: DispatchResultWithPostInfo) -> Option { } impl, I: 'static> Pallet { + /// Actual proposal for a given hash, if it's current. + pub fn proposal_of(who: T::Hash) -> Option<>::Proposal> { + ProposalOf::::get(who) + } + /// Check whether `who` is a member of the collective. pub fn is_member(who: &T::AccountId) -> bool { // Note: The dispatchables *do not* use this to check membership so make sure // to update those if this is changed. - Self::members().contains(who) + Members::::get().contains(who) } /// Execute immediately when adding a new proposal. @@ -715,7 +719,7 @@ impl, I: 'static> Pallet { let proposal_hash = T::Hashing::hash_of(&proposal); ensure!(!>::contains_key(proposal_hash), Error::::DuplicateProposal); - let seats = Self::members().len() as MemberCount; + let seats = Members::::get().len() as MemberCount; let result = proposal.dispatch(RawOrigin::Members(1, seats).into()); Self::deposit_event(Event::Executed { proposal_hash, @@ -743,7 +747,7 @@ impl, I: 'static> Pallet { Ok(proposals.len()) })?; - let index = Self::proposal_count(); + let index = ProposalCount::::get(); >::mutate(|i| *i += 1); >::insert(proposal_hash, proposal); let votes = { @@ -769,7 +773,7 @@ impl, I: 'static> Pallet { index: ProposalIndex, approve: bool, ) -> Result { - let mut voting = Self::voting(&proposal).ok_or(Error::::ProposalMissing)?; + let mut voting = Voting::::get(&proposal).ok_or(Error::::ProposalMissing)?; ensure!(voting.index == index, Error::::WrongIndex); let position_yes = voting.ayes.iter().position(|a| a == &who); @@ -820,12 +824,12 @@ impl, I: 'static> Pallet { proposal_weight_bound: Weight, length_bound: u32, ) -> DispatchResultWithPostInfo { - let voting = Self::voting(&proposal_hash).ok_or(Error::::ProposalMissing)?; + let voting = Voting::::get(&proposal_hash).ok_or(Error::::ProposalMissing)?; ensure!(voting.index == index, Error::::WrongIndex); let mut no_votes = voting.nays.len() as MemberCount; let mut yes_votes = voting.ayes.len() as MemberCount; - let seats = Self::members().len() as MemberCount; + let seats = Members::::get().len() as MemberCount; let approved = yes_votes >= voting.threshold; let disapproved = seats.saturating_sub(no_votes) < voting.threshold; // Allow (dis-)approving the proposal as soon as there are enough votes. @@ -859,7 +863,7 @@ impl, I: 'static> Pallet { // Only allow actual closing of the proposal after the voting period has ended. ensure!(frame_system::Pallet::::block_number() >= voting.end, Error::::TooEarly); - let prime_vote = Self::prime().map(|who| voting.ayes.iter().any(|a| a == &who)); + let prime_vote = Prime::::get().map(|who| voting.ayes.iter().any(|a| a == &who)); // default voting strategy. let default = T::DefaultVote::default_vote(prime_vote, yes_votes, no_votes, seats); @@ -998,7 +1002,7 @@ impl, I: 'static> ChangeMembers for Pallet { // remove accounts from all current voting in motions. let mut outgoing = outgoing.to_vec(); outgoing.sort(); - for h in Self::proposals().into_iter() { + for h in Proposals::::get().into_iter() { >::mutate(h, |v| { if let Some(mut votes) = v.take() { votes.ayes = votes diff --git a/frame/collective/src/tests.rs b/frame/collective/src/tests.rs index b7cdeb3383375..4f8a879f471c7 100644 --- a/frame/collective/src/tests.rs +++ b/frame/collective/src/tests.rs @@ -188,8 +188,8 @@ fn record(event: RuntimeEvent) -> EventRecord { #[test] fn motions_basic_environment_works() { new_test_ext().execute_with(|| { - assert_eq!(Collective::members(), vec![1, 2, 3]); - assert_eq!(*Collective::proposals(), Vec::::new()); + assert_eq!(Members::::get(), vec![1, 2, 3]); + assert_eq!(*Proposals::::get(), Vec::::new()); }); } @@ -567,12 +567,12 @@ fn removal_of_old_voters_votes_works() { assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, true)); assert_eq!( - Collective::voting(&hash), + Voting::::get(&hash), Some(Votes { index: 0, threshold: 3, ayes: vec![1, 2], nays: vec![], end }) ); Collective::change_members_sorted(&[4], &[1], &[2, 3, 4]); assert_eq!( - Collective::voting(&hash), + Voting::::get(&hash), Some(Votes { index: 0, threshold: 3, ayes: vec![2], nays: vec![], end }) ); @@ -588,12 +588,12 @@ fn removal_of_old_voters_votes_works() { assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 1, true)); assert_ok!(Collective::vote(RuntimeOrigin::signed(3), hash, 1, false)); assert_eq!( - Collective::voting(&hash), + Voting::::get(&hash), Some(Votes { index: 1, threshold: 2, ayes: vec![2], nays: vec![3], end }) ); Collective::change_members_sorted(&[], &[3], &[2, 4]); assert_eq!( - Collective::voting(&hash), + Voting::::get(&hash), Some(Votes { index: 1, threshold: 2, ayes: vec![2], nays: vec![], end }) ); }); @@ -615,7 +615,7 @@ fn removal_of_old_voters_votes_works_with_set_members() { assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, true)); assert_eq!( - Collective::voting(&hash), + Voting::::get(&hash), Some(Votes { index: 0, threshold: 3, ayes: vec![1, 2], nays: vec![], end }) ); assert_ok!(Collective::set_members( @@ -625,7 +625,7 @@ fn removal_of_old_voters_votes_works_with_set_members() { MaxMembers::get() )); assert_eq!( - Collective::voting(&hash), + Voting::::get(&hash), Some(Votes { index: 0, threshold: 3, ayes: vec![2], nays: vec![], end }) ); @@ -641,7 +641,7 @@ fn removal_of_old_voters_votes_works_with_set_members() { assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 1, true)); assert_ok!(Collective::vote(RuntimeOrigin::signed(3), hash, 1, false)); assert_eq!( - Collective::voting(&hash), + Voting::::get(&hash), Some(Votes { index: 1, threshold: 2, ayes: vec![2], nays: vec![3], end }) ); assert_ok!(Collective::set_members( @@ -651,7 +651,7 @@ fn removal_of_old_voters_votes_works_with_set_members() { MaxMembers::get() )); assert_eq!( - Collective::voting(&hash), + Voting::::get(&hash), Some(Votes { index: 1, threshold: 2, ayes: vec![2], nays: vec![], end }) ); }); @@ -670,10 +670,10 @@ fn propose_works() { Box::new(proposal.clone()), proposal_len )); - assert_eq!(*Collective::proposals(), vec![hash]); - assert_eq!(Collective::proposal_of(&hash), Some(proposal)); + assert_eq!(*Proposals::::get(), vec![hash]); + assert_eq!(ProposalOf::::get(&hash), Some(proposal)); assert_eq!( - Collective::voting(&hash), + Voting::::get(&hash), Some(Votes { index: 0, threshold: 3, ayes: vec![], nays: vec![], end }) ); @@ -833,13 +833,13 @@ fn motions_vote_after_works() { )); // Initially there a no votes when the motion is proposed. assert_eq!( - Collective::voting(&hash), + Voting::::get(&hash), Some(Votes { index: 0, threshold: 2, ayes: vec![], nays: vec![], end }) ); // Cast first aye vote. assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); assert_eq!( - Collective::voting(&hash), + Voting::::get(&hash), Some(Votes { index: 0, threshold: 2, ayes: vec![1], nays: vec![], end }) ); // Try to cast a duplicate aye vote. @@ -850,7 +850,7 @@ fn motions_vote_after_works() { // Cast a nay vote. assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, false)); assert_eq!( - Collective::voting(&hash), + Voting::::get(&hash), Some(Votes { index: 0, threshold: 2, ayes: vec![], nays: vec![1], end }) ); // Try to cast a duplicate nay vote. @@ -901,7 +901,7 @@ fn motions_all_first_vote_free_works() { proposal_len, )); assert_eq!( - Collective::voting(&hash), + Voting::::get(&hash), Some(Votes { index: 0, threshold: 2, ayes: vec![], nays: vec![], end }) ); @@ -966,14 +966,14 @@ fn motions_reproposing_disapproved_works() { proposal_weight, proposal_len )); - assert_eq!(*Collective::proposals(), vec![]); + assert_eq!(*Proposals::::get(), vec![]); assert_ok!(Collective::propose( RuntimeOrigin::signed(1), 2, Box::new(proposal.clone()), proposal_len )); - assert_eq!(*Collective::proposals(), vec![hash]); + assert_eq!(*Proposals::::get(), vec![hash]); }); } diff --git a/frame/democracy/src/benchmarking.rs b/frame/democracy/src/benchmarking.rs index f376b733aba6b..a5f83e7b801be 100644 --- a/frame/democracy/src/benchmarking.rs +++ b/frame/democracy/src/benchmarking.rs @@ -109,7 +109,7 @@ benchmarks! { whitelist_account!(caller); }: _(RawOrigin::Signed(caller), proposal, value) verify { - assert_eq!(Democracy::::public_props().len(), p as usize, "Proposals not created."); + assert_eq!(PublicProps::::get().len(), p as usize, "Proposals not created."); } second { @@ -123,12 +123,12 @@ benchmarks! { Democracy::::second(RawOrigin::Signed(seconder).into(), 0)?; } - let deposits = Democracy::::deposit_of(0).ok_or("Proposal not created")?; + let deposits = DepositOf::::get(0).ok_or("Proposal not created")?; assert_eq!(deposits.0.len(), (T::MaxDeposits::get() - 1) as usize, "Seconds not recorded"); whitelist_account!(caller); }: _(RawOrigin::Signed(caller), 0) verify { - let deposits = Democracy::::deposit_of(0).ok_or("Proposal not created")?; + let deposits = DepositOf::::get(0).ok_or("Proposal not created")?; assert_eq!(deposits.0.len(), (T::MaxDeposits::get()) as usize, "`second` benchmark did not work"); } @@ -176,7 +176,7 @@ benchmarks! { // Change vote from aye to nay let nay = Vote { aye: false, conviction: Conviction::Locked1x }; let new_vote = AccountVote::Standard { vote: nay, balance: 1000u32.into() }; - let ref_index = Democracy::::referendum_count() - 1; + let ref_index = ReferendumCount::::get() - 1; // This tests when a user changes a vote whitelist_account!(caller); @@ -187,7 +187,7 @@ benchmarks! { _ => return Err("Votes are not direct".into()), }; assert_eq!(votes.len(), T::MaxVotes::get() as usize, "Vote was incorrectly added"); - let referendum_info = Democracy::::referendum_info(ref_index) + let referendum_info = ReferendumInfoOf::::get(ref_index) .ok_or("referendum doesn't exist")?; let tally = match referendum_info { ReferendumInfo::Ongoing(r) => r.tally, @@ -304,7 +304,7 @@ benchmarks! { let delay = 0u32; }: _(origin_fast_track, proposal_hash, voting_period, delay.into()) verify { - assert_eq!(Democracy::::referendum_count(), 1, "referendum not created"); + assert_eq!(ReferendumCount::::get(), 1, "referendum not created"); assert_last_event::(crate::Event::MetadataTransferred { prev_owner: MetadataOwner::External, owner: MetadataOwner::Referendum(0), @@ -383,7 +383,7 @@ benchmarks! { add_referendum::(i); } - assert_eq!(Democracy::::referendum_count(), r, "referenda not created"); + assert_eq!(ReferendumCount::::get(), r, "referenda not created"); // Launch external LastTabledWasExternal::::put(false); @@ -401,7 +401,7 @@ benchmarks! { }: { Democracy::::on_initialize(block_number) } verify { // One extra because of next external - assert_eq!(Democracy::::referendum_count(), r + 1, "referenda not created"); + assert_eq!(ReferendumCount::::get(), r + 1, "referenda not created"); ensure!(!>::exists(), "External wasn't taken"); // All but the new next external should be finished @@ -423,7 +423,7 @@ benchmarks! { add_referendum::(i); } - assert_eq!(Democracy::::referendum_count(), r, "referenda not created"); + assert_eq!(ReferendumCount::::get(), r, "referenda not created"); // Launch public assert!(add_proposal::(r).is_ok(), "proposal not created"); @@ -434,7 +434,7 @@ benchmarks! { }: { Democracy::::on_initialize(block_number) } verify { // One extra because of next public - assert_eq!(Democracy::::referendum_count(), r + 1, "proposal not accepted"); + assert_eq!(ReferendumCount::::get(), r + 1, "proposal not accepted"); // All should be finished for i in 0 .. r { @@ -462,8 +462,8 @@ benchmarks! { ReferendumInfoOf::::insert(key, info); } - assert_eq!(Democracy::::referendum_count(), r, "referenda not created"); - assert_eq!(Democracy::::lowest_unbaked(), 0, "invalid referenda init"); + assert_eq!(ReferendumCount::::get(), r, "referenda not created"); + assert_eq!(LowestUnbaked::::get(), 0, "invalid referenda init"); }: { Democracy::::on_initialize(1u32.into()) } verify { @@ -492,8 +492,8 @@ benchmarks! { ReferendumInfoOf::::insert(key, info); } - assert_eq!(Democracy::::referendum_count(), r, "referenda not created"); - assert_eq!(Democracy::::lowest_unbaked(), 0, "invalid referenda init"); + assert_eq!(ReferendumCount::::get(), r, "referenda not created"); + assert_eq!(LowestUnbaked::::get(), 0, "invalid referenda init"); let block_number = T::LaunchPeriod::get(); diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index d9aae63ce6aae..41634f4a6ba4e 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -593,7 +593,7 @@ pub mod pallet { let who = ensure_signed(origin)?; ensure!(value >= T::MinimumDeposit::get(), Error::::ValueLow); - let index = Self::public_prop_count(); + let index = PublicPropCount::::get(); let real_prop_count = PublicProps::::decode_len().unwrap_or(0) as u32; let max_proposals = T::MaxProposals::get(); ensure!(real_prop_count < max_proposals, Error::::TooMany); @@ -636,7 +636,7 @@ pub mod pallet { let seconds = Self::len_of_deposit_of(proposal).ok_or(Error::::ProposalMissing)?; ensure!(seconds < T::MaxDeposits::get(), Error::::TooMany); - let mut deposit = Self::deposit_of(proposal).ok_or(Error::::ProposalMissing)?; + let mut deposit = DepositOf::::get(proposal).ok_or(Error::::ProposalMissing)?; T::Currency::reserve(&who, deposit.1)?; let ok = deposit.0.try_push(who.clone()).is_ok(); debug_assert!(ok, "`seconds` is below static limit; `try_insert` should succeed; qed"); @@ -1197,15 +1197,15 @@ impl Pallet { /// Get the amount locked in support of `proposal`; `None` if proposal isn't a valid proposal /// index. pub fn backing_for(proposal: PropIndex) -> Option> { - Self::deposit_of(proposal).map(|(l, d)| d.saturating_mul((l.len() as u32).into())) + DepositOf::::get(proposal).map(|(l, d)| d.saturating_mul((l.len() as u32).into())) } /// Get all referenda ready for tally at block `n`. pub fn maturing_referenda_at( n: T::BlockNumber, ) -> Vec<(ReferendumIndex, ReferendumStatus, BalanceOf>)> { - let next = Self::lowest_unbaked(); - let last = Self::referendum_count(); + let next = LowestUnbaked::::get(); + let last = ReferendumCount::::get(); Self::maturing_referenda_at_inner(n, next..last) } @@ -1215,7 +1215,7 @@ impl Pallet { ) -> Vec<(ReferendumIndex, ReferendumStatus, BalanceOf>)> { range .into_iter() - .map(|i| (i, Self::referendum_info(i))) + .map(|i| (i, ReferendumInfoOf::::get(i))) .filter_map(|(i, maybe_info)| match maybe_info { Some(ReferendumInfo::Ongoing(status)) => Some((i, status)), _ => None, @@ -1506,7 +1506,7 @@ impl Pallet { threshold: VoteThreshold, delay: T::BlockNumber, ) -> ReferendumIndex { - let ref_index = Self::referendum_count(); + let ref_index = ReferendumCount::::get(); ReferendumCount::::put(ref_index + 1); let status = ReferendumStatus { end, proposal, threshold, delay, tally: Default::default() }; @@ -1546,7 +1546,7 @@ impl Pallet { /// Table the waiting public proposal with the highest backing for a vote. fn launch_public(now: T::BlockNumber) -> DispatchResult { - let mut public_props = Self::public_props(); + let mut public_props = PublicProps::::get(); if let Some((winner_index, _)) = public_props.iter().enumerate().max_by_key( // defensive only: All current public proposals have an amount locked |x| Self::backing_for((x.1).0).defensive_unwrap_or_else(Zero::zero), @@ -1624,8 +1624,8 @@ impl Pallet { let max_block_weight = T::BlockWeights::get().max_block; let mut weight = Weight::zero(); - let next = Self::lowest_unbaked(); - let last = Self::referendum_count(); + let next = LowestUnbaked::::get(); + let last = ReferendumCount::::get(); let r = last.saturating_sub(next); // pick out another public referendum if it's time. @@ -1658,7 +1658,7 @@ impl Pallet { // runtime upgrade the formula should be adjusted but the bound should still be sensible. >::mutate(|ref_index| { while *ref_index < last && - Self::referendum_info(*ref_index) + ReferendumInfoOf::::get(*ref_index) .map_or(true, |info| matches!(info, ReferendumInfo::Finished { .. })) { *ref_index += 1 diff --git a/frame/democracy/src/tests.rs b/frame/democracy/src/tests.rs index 9c7ec2906c677..c60eed6e550c2 100644 --- a/frame/democracy/src/tests.rs +++ b/frame/democracy/src/tests.rs @@ -215,7 +215,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { #[test] fn params_should_work() { new_test_ext().execute_with(|| { - assert_eq!(Democracy::referendum_count(), 0); + assert_eq!(ReferendumCount::::get(), 0); assert_eq!(Balances::free_balance(42), 0); assert_eq!(Balances::total_issuance(), 210); }); diff --git a/frame/democracy/src/tests/cancellation.rs b/frame/democracy/src/tests/cancellation.rs index ff046d612c026..129ff6a8b685d 100644 --- a/frame/democracy/src/tests/cancellation.rs +++ b/frame/democracy/src/tests/cancellation.rs @@ -30,14 +30,14 @@ fn cancel_referendum_should_work() { ); assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); assert_ok!(Democracy::cancel_referendum(RuntimeOrigin::root(), r.into())); - assert_eq!(Democracy::lowest_unbaked(), 0); + assert_eq!(LowestUnbaked::::get(), 0); next_block(); next_block(); - assert_eq!(Democracy::lowest_unbaked(), 1); - assert_eq!(Democracy::lowest_unbaked(), Democracy::referendum_count()); + assert_eq!(LowestUnbaked::::get(), 1); + assert_eq!(LowestUnbaked::::get(), ReferendumCount::::get()); assert_eq!(Balances::free_balance(42), 0); }); } @@ -56,7 +56,7 @@ fn emergency_cancel_should_work() { assert_noop!(Democracy::emergency_cancel(RuntimeOrigin::signed(3), r), BadOrigin); assert_ok!(Democracy::emergency_cancel(RuntimeOrigin::signed(4), r)); - assert!(Democracy::referendum_info(r).is_none()); + assert!(ReferendumInfoOf::::get(r).is_none()); // some time later... diff --git a/frame/democracy/src/tests/lock_voting.rs b/frame/democracy/src/tests/lock_voting.rs index 540198ecf33a1..4f053da3cccd5 100644 --- a/frame/democracy/src/tests/lock_voting.rs +++ b/frame/democracy/src/tests/lock_voting.rs @@ -56,7 +56,7 @@ fn lock_voting_should_work() { // All balances are currently locked. for i in 1..=5 { - assert_eq!(Balances::locks(i), vec![the_lock(i * 10)]); + assert_eq!(pallet_balances::Locks::::get(i), vec![the_lock(i * 10)]); } fast_forward_to(3); @@ -77,11 +77,11 @@ fn lock_voting_should_work() { assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(2), r)); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(2), 2)); - assert_eq!(Balances::locks(1), vec![]); - assert_eq!(Balances::locks(2), vec![the_lock(20)]); - assert_eq!(Balances::locks(3), vec![the_lock(30)]); - assert_eq!(Balances::locks(4), vec![the_lock(40)]); - assert_eq!(Balances::locks(5), vec![]); + assert_eq!(pallet_balances::Locks::::get(1), vec![]); + assert_eq!(pallet_balances::Locks::::get(2), vec![the_lock(20)]); + assert_eq!(pallet_balances::Locks::::get(3), vec![the_lock(30)]); + assert_eq!(pallet_balances::Locks::::get(4), vec![the_lock(40)]); + assert_eq!(pallet_balances::Locks::::get(5), vec![]); assert_eq!(Balances::free_balance(42), 2); fast_forward_to(7); @@ -91,12 +91,12 @@ fn lock_voting_should_work() { Error::::NoPermission ); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(1), 4)); - assert_eq!(Balances::locks(4), vec![the_lock(40)]); + assert_eq!(pallet_balances::Locks::::get(4), vec![the_lock(40)]); fast_forward_to(8); // 4 should now be able to reap and unlock assert_ok!(Democracy::remove_other_vote(RuntimeOrigin::signed(1), 4, r)); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(1), 4)); - assert_eq!(Balances::locks(4), vec![]); + assert_eq!(pallet_balances::Locks::::get(4), vec![]); fast_forward_to(13); assert_noop!( @@ -104,19 +104,19 @@ fn lock_voting_should_work() { Error::::NoPermission ); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(1), 3)); - assert_eq!(Balances::locks(3), vec![the_lock(30)]); + assert_eq!(pallet_balances::Locks::::get(3), vec![the_lock(30)]); fast_forward_to(14); assert_ok!(Democracy::remove_other_vote(RuntimeOrigin::signed(1), 3, r)); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(1), 3)); - assert_eq!(Balances::locks(3), vec![]); + assert_eq!(pallet_balances::Locks::::get(3), vec![]); // 2 doesn't need to reap_vote here because it was already done before. fast_forward_to(25); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(1), 2)); - assert_eq!(Balances::locks(2), vec![the_lock(20)]); + assert_eq!(pallet_balances::Locks::::get(2), vec![the_lock(20)]); fast_forward_to(26); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(1), 2)); - assert_eq!(Balances::locks(2), vec![]); + assert_eq!(pallet_balances::Locks::::get(2), vec![]); }); } @@ -137,7 +137,7 @@ fn no_locks_without_conviction_should_work() { assert_eq!(Balances::free_balance(42), 2); assert_ok!(Democracy::remove_other_vote(RuntimeOrigin::signed(2), 1, r)); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(2), 1)); - assert_eq!(Balances::locks(1), vec![]); + assert_eq!(pallet_balances::Locks::::get(1), vec![]); }); } @@ -198,33 +198,33 @@ fn prior_lockvotes_should_be_enforced() { Error::::NoPermission ); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![the_lock(50)]); + assert_eq!(pallet_balances::Locks::::get(5), vec![the_lock(50)]); fast_forward_to(8); assert_ok!(Democracy::remove_other_vote(RuntimeOrigin::signed(1), 5, r.2)); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![the_lock(20)]); + assert_eq!(pallet_balances::Locks::::get(5), vec![the_lock(20)]); fast_forward_to(13); assert_noop!( Democracy::remove_other_vote(RuntimeOrigin::signed(1), 5, r.1), Error::::NoPermission ); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![the_lock(20)]); + assert_eq!(pallet_balances::Locks::::get(5), vec![the_lock(20)]); fast_forward_to(14); assert_ok!(Democracy::remove_other_vote(RuntimeOrigin::signed(1), 5, r.1)); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![the_lock(10)]); + assert_eq!(pallet_balances::Locks::::get(5), vec![the_lock(10)]); fast_forward_to(25); assert_noop!( Democracy::remove_other_vote(RuntimeOrigin::signed(1), 5, r.0), Error::::NoPermission ); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![the_lock(10)]); + assert_eq!(pallet_balances::Locks::::get(5), vec![the_lock(10)]); fast_forward_to(26); assert_ok!(Democracy::remove_other_vote(RuntimeOrigin::signed(1), 5, r.0)); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![]); + assert_eq!(pallet_balances::Locks::::get(5), vec![]); }); } @@ -239,26 +239,26 @@ fn single_consolidation_of_lockvotes_should_work_as_before() { fast_forward_to(7); assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(5), r.2)); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![the_lock(50)]); + assert_eq!(pallet_balances::Locks::::get(5), vec![the_lock(50)]); fast_forward_to(8); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![the_lock(20)]); + assert_eq!(pallet_balances::Locks::::get(5), vec![the_lock(20)]); fast_forward_to(13); assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(5), r.1)); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![the_lock(20)]); + assert_eq!(pallet_balances::Locks::::get(5), vec![the_lock(20)]); fast_forward_to(14); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![the_lock(10)]); + assert_eq!(pallet_balances::Locks::::get(5), vec![the_lock(10)]); fast_forward_to(25); assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(5), r.0)); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![the_lock(10)]); + assert_eq!(pallet_balances::Locks::::get(5), vec![the_lock(10)]); fast_forward_to(26); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![]); + assert_eq!(pallet_balances::Locks::::get(5), vec![]); }); } @@ -276,15 +276,15 @@ fn multi_consolidation_of_lockvotes_should_be_conservative() { fast_forward_to(8); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert!(Balances::locks(5)[0].amount >= 20); + assert!(pallet_balances::Locks::::get(5)[0].amount >= 20); fast_forward_to(14); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert!(Balances::locks(5)[0].amount >= 10); + assert!(pallet_balances::Locks::::get(5)[0].amount >= 10); fast_forward_to(26); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![]); + assert_eq!(pallet_balances::Locks::::get(5), vec![]); }); } @@ -305,26 +305,26 @@ fn locks_should_persist_from_voting_to_delegation() { assert_ok!(Democracy::delegate(RuntimeOrigin::signed(5), 1, Conviction::Locked3x, 20)); // locked 20. - assert!(Balances::locks(5)[0].amount == 20); + assert!(pallet_balances::Locks::::get(5)[0].amount == 20); assert_ok!(Democracy::undelegate(RuntimeOrigin::signed(5))); // locked 20 until #14 fast_forward_to(13); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert!(Balances::locks(5)[0].amount == 20); + assert!(pallet_balances::Locks::::get(5)[0].amount == 20); fast_forward_to(14); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert!(Balances::locks(5)[0].amount >= 10); + assert!(pallet_balances::Locks::::get(5)[0].amount >= 10); fast_forward_to(25); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert!(Balances::locks(5)[0].amount >= 10); + assert!(pallet_balances::Locks::::get(5)[0].amount >= 10); fast_forward_to(26); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![]); + assert_eq!(pallet_balances::Locks::::get(5), vec![]); }); } @@ -347,18 +347,18 @@ fn locks_should_persist_from_delegation_to_voting() { fast_forward_to(8); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert!(Balances::locks(5)[0].amount >= 20); + assert!(pallet_balances::Locks::::get(5)[0].amount >= 20); fast_forward_to(14); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert!(Balances::locks(5)[0].amount >= 10); + assert!(pallet_balances::Locks::::get(5)[0].amount >= 10); fast_forward_to(26); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert!(Balances::locks(5)[0].amount >= 5); + assert!(pallet_balances::Locks::::get(5)[0].amount >= 5); fast_forward_to(48); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![]); + assert_eq!(pallet_balances::Locks::::get(5), vec![]); }); } diff --git a/frame/democracy/src/tests/metadata.rs b/frame/democracy/src/tests/metadata.rs index 95b617e37b199..427cf65acb0bd 100644 --- a/frame/democracy/src/tests/metadata.rs +++ b/frame/democracy/src/tests/metadata.rs @@ -89,7 +89,7 @@ fn set_proposal_metadata_works() { // create an external proposal. assert_ok!(propose_set_balance(1, 2, 5)); // metadata owner is a public proposal. - let owner = MetadataOwner::Proposal(Democracy::public_prop_count() - 1); + let owner = MetadataOwner::Proposal(PublicPropCount::::get() - 1); // fails to set non-existing preimage. assert_noop!( Democracy::set_metadata(RuntimeOrigin::signed(1), owner.clone(), Some(invalid_hash),), @@ -117,7 +117,7 @@ fn clear_proposal_metadata_works() { // create an external proposal. assert_ok!(propose_set_balance(1, 2, 5)); // metadata owner is a public proposal. - let owner = MetadataOwner::Proposal(Democracy::public_prop_count() - 1); + let owner = MetadataOwner::Proposal(PublicPropCount::::get() - 1); // set metadata. let hash = note_preimage(1); assert_ok!(Democracy::set_metadata(RuntimeOrigin::signed(1), owner.clone(), Some(hash),)); diff --git a/frame/democracy/src/tests/scheduling.rs b/frame/democracy/src/tests/scheduling.rs index 5e133f38945d6..cbb0b9259a7d6 100644 --- a/frame/democracy/src/tests/scheduling.rs +++ b/frame/democracy/src/tests/scheduling.rs @@ -30,10 +30,10 @@ fn simple_passing_should_work() { ); assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); assert_eq!(tally(r), Tally { ayes: 1, nays: 0, turnout: 10 }); - assert_eq!(Democracy::lowest_unbaked(), 0); + assert_eq!(LowestUnbaked::::get(), 0); next_block(); next_block(); - assert_eq!(Democracy::lowest_unbaked(), 1); + assert_eq!(LowestUnbaked::::get(), 1); assert_eq!(Balances::free_balance(42), 2); }); } @@ -140,16 +140,16 @@ fn lowest_unbaked_should_be_sensible() { assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r2, aye(1))); // r3 is canceled assert_ok!(Democracy::cancel_referendum(RuntimeOrigin::root(), r3.into())); - assert_eq!(Democracy::lowest_unbaked(), 0); + assert_eq!(LowestUnbaked::::get(), 0); next_block(); // r2 ends with approval - assert_eq!(Democracy::lowest_unbaked(), 0); + assert_eq!(LowestUnbaked::::get(), 0); next_block(); // r1 ends with approval - assert_eq!(Democracy::lowest_unbaked(), 3); - assert_eq!(Democracy::lowest_unbaked(), Democracy::referendum_count()); + assert_eq!(LowestUnbaked::::get(), 3); + assert_eq!(LowestUnbaked::::get(), ReferendumCount::::get()); // r2 is executed assert_eq!(Balances::free_balance(42), 2); diff --git a/frame/democracy/src/tests/voting.rs b/frame/democracy/src/tests/voting.rs index 482cd430e0e7f..ee2b2974a7a2a 100644 --- a/frame/democracy/src/tests/voting.rs +++ b/frame/democracy/src/tests/voting.rs @@ -55,7 +55,7 @@ fn split_vote_cancellation_should_work() { assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(5), r)); assert_eq!(tally(r), Tally { ayes: 0, nays: 0, turnout: 0 }); assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![]); + assert_eq!(pallet_balances::Locks::::get(5), vec![]); }); } @@ -65,13 +65,13 @@ fn single_proposal_should_work() { System::set_block_number(0); assert_ok!(propose_set_balance(1, 2, 1)); let r = 0; - assert!(Democracy::referendum_info(r).is_none()); + assert!(ReferendumInfoOf::::get(r).is_none()); // start of 2 => next referendum scheduled. fast_forward_to(2); assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); - assert_eq!(Democracy::referendum_count(), 1); + assert_eq!(ReferendumCount::::get(), 1); assert_eq!( Democracy::referendum_status(0), Ok(ReferendumStatus { diff --git a/frame/election-provider-multi-phase/src/benchmarking.rs b/frame/election-provider-multi-phase/src/benchmarking.rs index 16263d97da586..b3a430af95e51 100644 --- a/frame/election-provider-multi-phase/src/benchmarking.rs +++ b/frame/election-provider-multi-phase/src/benchmarking.rs @@ -146,7 +146,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 = >::get(); assert!( score.minimal_stake > 0, @@ -189,32 +189,32 @@ fn set_up_data_provider(v: u32, t: u32) { frame_benchmarking::benchmarks! { on_initialize_nothing { - assert!(>::current_phase().is_off()); + assert!(>::get().is_off()); }: { >::on_initialize(1u32.into()); } verify { - assert!(>::current_phase().is_off()); + assert!(>::get().is_off()); } on_initialize_open_signed { - assert!(>::snapshot().is_none()); - assert!(>::current_phase().is_off()); + assert!(>::get().is_none()); + assert!(>::get().is_off()); }: { >::phase_transition(Phase::Signed); } verify { - assert!(>::snapshot().is_none()); - assert!(>::current_phase().is_signed()); + assert!(>::get().is_none()); + assert!(>::get().is_signed()); } on_initialize_open_unsigned { - assert!(>::snapshot().is_none()); - assert!(>::current_phase().is_off()); + assert!(>::get().is_none()); + assert!(>::get().is_off()); }: { let now = frame_system::Pallet::::block_number(); >::phase_transition(Phase::Unsigned((true, now))); } verify { - assert!(>::snapshot().is_none()); - assert!(>::current_phase().is_unsigned()); + assert!(>::get().is_none()); + assert!(>::get().is_unsigned()); } finalize_signed_phase_accept_solution { @@ -271,13 +271,13 @@ frame_benchmarking::benchmarks! { let targets = T::DataProvider::electable_targets(None)?; let voters = T::DataProvider::electing_voters(None)?; let desired_targets = T::DataProvider::desired_targets()?; - assert!(>::snapshot().is_none()); + assert!(>::get().is_none()); }: { >::create_snapshot_internal(targets, voters, desired_targets) } verify { - assert!(>::snapshot().is_some()); - assert_eq!(>::snapshot_metadata().ok_or("metadata missing")?.voters, v + t); - assert_eq!(>::snapshot_metadata().ok_or("metadata missing")?.targets, t); + assert!(>::get().is_some()); + assert_eq!(>::get().ok_or("metadata missing")?.voters, v + t); + assert_eq!(>::get().ok_or("metadata missing")?.targets, t); } // a call to `::elect` where we only return the queued solution. @@ -309,7 +309,7 @@ frame_benchmarking::benchmarks! { }: { assert_ok!( as ElectionProvider>::elect()); } verify { - assert!(>::queued_solution().is_none()); + assert!(>::get().is_none()); assert!(>::get().is_none()); assert!(>::get().is_none()); assert!(>::get().is_none()); @@ -349,7 +349,7 @@ 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); @@ -375,11 +375,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()); + assert!(>::get().is_none()); >::put(Phase::Unsigned((true, 1u32.into()))); }: _(RawOrigin::None, Box::new(raw_solution), witness) verify { - assert!(>::queued_solution().is_some()); + assert!(>::get().is_some()); } // This is checking a valid solution. The worse case is indeed a valid solution. @@ -445,13 +445,13 @@ frame_benchmarking::benchmarks! { let t = T::BenchmarkingConfig::MAXIMUM_TARGETS; set_up_data_provider::(v, t); - assert!(>::snapshot().is_none()); + assert!(>::get().is_none()); }: { >::create_snapshot().map_err(|_| "could not create snapshot")?; } verify { - assert!(>::snapshot().is_some()); - assert_eq!(>::snapshot_metadata().ok_or("snapshot missing")?.voters, v + t); - assert_eq!(>::snapshot_metadata().ok_or("snapshot missing")?.targets, t); + assert!(>::get().is_some()); + assert_eq!(>::get().ok_or("snapshot missing")?.voters, v + t); + assert_eq!(>::get().ok_or("snapshot missing")?.targets, t); } #[extra] @@ -476,7 +476,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/frame/election-provider-multi-phase/src/lib.rs b/frame/election-provider-multi-phase/src/lib.rs index 6c1b1d163d0fb..ad8148c7a709f 100644 --- a/frame/election-provider-multi-phase/src/lib.rs +++ b/frame/election-provider-multi-phase/src/lib.rs @@ -744,14 +744,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 => { @@ -916,7 +916,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); @@ -969,7 +969,7 @@ pub mod pallet { supports: Supports, ) -> DispatchResult { T::ForceOrigin::ensure_origin(origin)?; - ensure!(Self::current_phase().is_emergency(), >::CallNotAllowed); + ensure!(CurrentPhase::::get().is_emergency(), >::CallNotAllowed); // bound supports with T::MaxWinners let supports = supports.try_into().map_err(|_| Error::::TooManyWinners)?; @@ -1010,14 +1010,14 @@ pub mod pallet { let who = ensure_signed(origin)?; // ensure solution is timely. - ensure!(Self::current_phase().is_signed(), Error::::PreDispatchEarlySubmission); + ensure!(CurrentPhase::::get().is_signed(), Error::::PreDispatchEarlySubmission); // 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()), @@ -1080,7 +1080,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(), >::CallNotAllowed); let supports = T::GovernanceFallback::instant_elect(maybe_max_voters, maybe_max_targets).map_err( @@ -1332,7 +1332,7 @@ impl Pallet { /// Internal logic of the offchain worker, to be executed only when the offchain lock is /// acquired with success. fn do_synchronized_offchain_worker(now: T::BlockNumber) { - 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 => { @@ -1358,11 +1358,11 @@ 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(), to, - round: Self::round(), + round: Round::::get(), }); >::put(to); } @@ -1483,13 +1483,13 @@ impl Pallet { let RawSolution { solution, score, round } = raw_solution; // First, check round. - ensure!(Self::round() == round, FeasibilityError::InvalidRound); + ensure!(Round::::get() == round, FeasibilityError::InvalidRound); // Winners are not directly encoded in the solution. let winners = solution.unique_targets(); let desired_targets = - Self::desired_targets().ok_or(FeasibilityError::SnapshotUnavailable)?; + DesiredTargets::::get().ok_or(FeasibilityError::SnapshotUnavailable)?; ensure!(winners.len() as u32 == desired_targets, FeasibilityError::WrongWinnerCount); // Fail early if targets requested by data provider exceed maximum winners supported. @@ -1501,7 +1501,7 @@ impl Pallet { // Ensure that the solution's score can pass absolute min-score. let submitted_score = raw_solution.score; ensure!( - Self::minimum_untrusted_score().map_or(true, |min_score| { + MinimumUntrustedScore::::get().map_or(true, |min_score| { submitted_score.strict_threshold_better(min_score, Perbill::zero()) }), FeasibilityError::UntrustedScoreTooLow @@ -1509,7 +1509,7 @@ impl Pallet { // Read the entire snapshot. let RoundSnapshot { voters: snapshot_voters, targets: snapshot_targets } = - Self::snapshot().ok_or(FeasibilityError::SnapshotUnavailable)?; + Snapshot::::get().ok_or(FeasibilityError::SnapshotUnavailable)?; // ----- Start building. First, we need some closures. let cache = helpers::generate_voter_cache::(&snapshot_voters); @@ -1604,14 +1604,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 @@ -1639,7 +1639,7 @@ impl ElectionProviderBase for Pallet { impl ElectionProvider for Pallet { fn ongoing() -> bool { - match Self::current_phase() { + match CurrentPhase::::get() { Phase::Off => false, _ => true, } @@ -1691,7 +1691,7 @@ 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(); // For whatever reason it might be: @@ -1708,7 +1708,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; @@ -1723,13 +1723,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)); @@ -1740,13 +1740,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; @@ -1763,10 +1763,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 @@ -1797,10 +1797,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. @@ -1824,10 +1824,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 @@ -1853,10 +1853,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; @@ -1891,30 +1891,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![ @@ -1926,35 +1926,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(), @@ -1993,22 +1993,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(), @@ -2040,22 +2040,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(), @@ -2079,21 +2079,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(), @@ -2123,8 +2123,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()); @@ -2142,11 +2142,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()); }) } @@ -2162,8 +2162,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() { @@ -2181,11 +2181,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!( @@ -2240,7 +2240,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( @@ -2288,23 +2288,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()); @@ -2344,10 +2344,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!( @@ -2386,15 +2386,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(), @@ -2420,16 +2420,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!( @@ -2440,10 +2440,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(), @@ -2483,11 +2483,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(); @@ -2520,16 +2520,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(), @@ -2552,10 +2552,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 } ); }) @@ -2565,7 +2565,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 })); diff --git a/frame/election-provider-multi-phase/src/mock.rs b/frame/election-provider-multi-phase/src/mock.rs index 347a4f19185f9..17c063a44966c 100644 --- a/frame/election-provider-multi-phase/src/mock.rs +++ b/frame/election-provider-multi-phase/src/mock.rs @@ -100,12 +100,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); } } @@ -135,7 +135,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(); @@ -149,7 +149,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 = DesiredTargets::::get().unwrap(); let ElectionResult::<_, SolutionAccuracyOf> { mut assignments, .. } = seq_phragmen(desired_targets as usize, targets.clone(), voters.clone(), None).unwrap(); @@ -175,8 +175,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 = DesiredTargets::::get().unwrap(); let ElectionResult::<_, SolutionAccuracyOf> { winners: _, assignments } = seq_phragmen(desired_targets as usize, targets.clone(), voters.clone(), None).unwrap(); @@ -194,12 +194,12 @@ pub fn raw_solution() -> RawSolution> { let solution = >::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, @@ -278,7 +278,7 @@ parameter_types! { (40, 40, bounded_vec![40]), ]; - pub static DesiredTargets: u32 = 2; + pub static DesiredTargetsCount: u32 = 2; pub static SignedPhase: BlockNumber = 10; pub static UnsignedPhase: BlockNumber = 5; pub static SignedMaxSubmissions: u32 = 5; @@ -458,7 +458,7 @@ impl ElectionDataProvider for StakingMock { } fn desired_targets() -> data_provider::Result { - Ok(DesiredTargets::get()) + Ok(DesiredTargetsCount::get()) } fn next_election_prediction(now: u64) -> u64 { @@ -537,7 +537,7 @@ impl ExtBuilder { self } pub fn desired_targets(self, t: u32) -> Self { - ::set(t); + ::set(t); self } pub fn add_voter( diff --git a/frame/election-provider-multi-phase/src/signed.rs b/frame/election-provider-multi-phase/src/signed.rs index 895f3670a7f0d..5924d3e96542f 100644 --- a/frame/election-provider-multi-phase/src/signed.rs +++ b/frame/election-provider-multi-phase/src/signed.rs @@ -18,9 +18,9 @@ //! The signed phase implementation. use crate::{ - unsigned::MinerConfig, Config, ElectionCompute, Pallet, QueuedSolution, RawSolution, - ReadySolution, SignedSubmissionIndices, SignedSubmissionNextIndex, SignedSubmissionsMap, - SolutionOf, SolutionOrSnapshotSize, Weight, WeightInfo, + unsigned::MinerConfig, Config, DesiredTargets, ElectionCompute, Pallet, QueuedSolution, + RawSolution, ReadySolution, SignedSubmissionIndices, SignedSubmissionNextIndex, + SignedSubmissionsMap, SnapshotMetadata, SolutionOf, SolutionOrSnapshotSize, Weight, WeightInfo, }; use codec::{Decode, Encode, HasCompact}; use frame_election_provider_support::NposSolution; @@ -378,7 +378,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!( @@ -391,7 +391,7 @@ 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 = DesiredTargets::::get().defensive_unwrap_or_default(); T::WeightInfo::feasibility_check(voters, targets, active_voters, desired_targets) }; @@ -537,14 +537,16 @@ impl Pallet { #[cfg(test)] mod tests { use super::*; - use crate::{mock::*, ElectionCompute, ElectionError, Error, Event, Perbill, Phase}; + use crate::{ + mock::*, CurrentPhase, ElectionCompute, ElectionError, Error, Event, Perbill, Phase, + }; use frame_support::{assert_noop, assert_ok, assert_storage_noop}; #[test] 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(); @@ -591,7 +593,7 @@ mod tests { fn desired_targets_greater_than_max_winners() { ExtBuilder::default().build_and_execute(|| { // given desired_targets bigger than MaxWinners - DesiredTargets::set(4); + DesiredTargetsCount::set(4); MaxWinners::set(3); // snapshot not created because data provider returned an unexpected number of @@ -607,7 +609,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)); @@ -635,7 +637,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)); @@ -665,7 +667,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)); @@ -700,7 +702,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)); @@ -746,7 +748,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 @@ -774,7 +776,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); @@ -855,7 +857,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 { @@ -916,7 +918,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; @@ -963,7 +965,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 @@ -1010,7 +1012,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 @@ -1042,7 +1044,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 { @@ -1077,7 +1079,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() }, @@ -1129,7 +1131,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()); @@ -1189,7 +1191,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)); @@ -1258,7 +1260,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( @@ -1292,7 +1294,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(); @@ -1312,7 +1314,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 @@ -1358,7 +1360,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/frame/election-provider-multi-phase/src/unsigned.rs b/frame/election-provider-multi-phase/src/unsigned.rs index cdc71f7bf5bf0..345784ef9c326 100644 --- a/frame/election-provider-multi-phase/src/unsigned.rs +++ b/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 codec::Encode; use frame_election_provider_support::{NposSolution, NposSolver, PerThing128, VoteWeight}; @@ -160,12 +161,12 @@ impl Pallet { pub fn mine_solution( ) -> Result<(RawSolution>, SolutionOrSnapshotSize), 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) = Miner::::mine_solution_with_snapshot::< T::Solver, >(voters, targets, desired_targets)?; - let round = Self::round(); + let round = Round::::get(); Ok((RawSolution { solution, score, round }, size)) } @@ -337,21 +338,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().map_or(true, |q: ReadySolution<_>| raw_solution + QueuedSolution::::get().map_or(true, |q: ReadySolution<_>| raw_solution .score .strict_threshold_better(q.score, T::BetterUnsignedThreshold::get())), Error::::PreDispatchWeakSubmission, @@ -1086,7 +1090,7 @@ mod tests { }; // initial - assert_eq!(MultiPhase::current_phase(), Phase::Off); + assert_eq!(CurrentPhase::::get(), Phase::Off); assert!(matches!( ::validate_unsigned( TransactionSource::Local, @@ -1102,7 +1106,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, @@ -1118,7 +1122,7 @@ mod tests { // unsigned roll_to_unsigned(); - assert!(MultiPhase::current_phase().is_unsigned()); + assert!(CurrentPhase::::get().is_unsigned()); assert!(::validate_unsigned( TransactionSource::Local, @@ -1129,7 +1133,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, @@ -1149,7 +1153,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() }, @@ -1195,7 +1199,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() }, @@ -1224,7 +1228,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() }, @@ -1255,7 +1259,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:: { @@ -1277,7 +1281,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:: { @@ -1301,23 +1305,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![ @@ -1344,7 +1348,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) = MultiPhase::mine_solution().unwrap(); let solution_weight = ::solution_weight( @@ -1378,7 +1382,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(); @@ -1404,8 +1408,8 @@ mod tests { .better_unsigned_threshold(Perbill::from_percent(50)) .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 { @@ -1417,8 +1421,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( @@ -1428,14 +1432,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, 10); + assert_eq!(QueuedSolution::::get().unwrap().score.minimal_stake, 10); // trial 1: a solution who's score is only 2, i.e. 20% better in the first element. let result = ElectionResult { @@ -1456,7 +1460,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 50% more than 10 assert_eq!(solution.score.minimal_stake, 12); assert_noop!( @@ -1486,7 +1490,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 @@ -1506,7 +1510,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()); @@ -1547,7 +1551,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()); @@ -1568,7 +1572,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( @@ -1596,7 +1600,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. @@ -1628,7 +1632,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::(), @@ -1711,7 +1715,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. @@ -1749,7 +1753,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. @@ -1790,7 +1794,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(); @@ -1805,7 +1809,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 // now, before we check the call, update the round >::mutate(|round| *round += 1); diff --git a/frame/elections-phragmen/src/benchmarking.rs b/frame/elections-phragmen/src/benchmarking.rs index b7c04bad318b0..f8c3ce3c74a47 100644 --- a/frame/elections-phragmen/src/benchmarking.rs +++ b/frame/elections-phragmen/src/benchmarking.rs @@ -121,18 +121,18 @@ fn distribute_voters( /// members, or members and runners-up. fn fill_seats_up_to(m: u32) -> Result, &'static str> { let _ = submit_candidates_with_self_vote::(m, "fill_seats_up_to")?; - assert_eq!(>::candidates().len() as u32, m, "wrong number of candidates."); + assert_eq!(>::get().len() as u32, m, "wrong number of candidates."); >::do_phragmen(); - assert_eq!(>::candidates().len(), 0, "some candidates remaining."); + assert_eq!(>::get().len(), 0, "some candidates remaining."); assert_eq!( - >::members().len() + >::runners_up().len(), + >::get().len() + RunnersUp::::get().len(), m as usize, "wrong number of members and runners-up", ); - Ok(>::members() + Ok(>::get() .into_iter() .map(|m| m.who) - .chain(>::runners_up().into_iter().map(|r| r.who)) + .chain(RunnersUp::::get().into_iter().map(|r| r.who)) .collect()) } @@ -349,7 +349,7 @@ benchmarks! { }: remove_member(RawOrigin::Root, removing, true, false) verify { // must still have enough members. - assert_eq!(>::members().len() as u32, T::DesiredMembers::get()); + assert_eq!(>::get().len() as u32, T::DesiredMembers::get()); #[cfg(test)] { // reset members in between benchmark tests. @@ -407,9 +407,9 @@ benchmarks! { >::on_initialize(T::TermDuration::get()); } verify { - assert_eq!(>::members().len() as u32, T::DesiredMembers::get().min(c)); + assert_eq!(>::get().len() as u32, T::DesiredMembers::get().min(c)); assert_eq!( - >::runners_up().len() as u32, + RunnersUp::::get().len() as u32, T::DesiredRunnersUp::get().min(c.saturating_sub(T::DesiredMembers::get())), ); diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 37ee44f34dc3d..15f13c10ff44d 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -838,7 +838,7 @@ impl Pallet { })?; let remaining_member_ids_sorted = - Self::members().into_iter().map(|x| x.who).collect::>(); + Members::::get().into_iter().map(|x| x.who).collect::>(); let outgoing = &[who.clone()]; let maybe_current_prime = T::ChangeMembers::get_prime(); let return_value = match maybe_replacement { @@ -875,7 +875,7 @@ impl Pallet { /// Check if `who` is a candidate. It returns the insert index if the element does not exists as /// an error. fn is_candidate(who: &T::AccountId) -> Result<(), usize> { - Self::candidates().binary_search_by(|c| c.0.cmp(who)).map(|_| ()) + Candidates::::get().binary_search_by(|c| c.0.cmp(who)).map(|_| ()) } /// Check if `who` is a voter. It may or may not be a _current_ one. @@ -885,17 +885,17 @@ impl Pallet { /// Check if `who` is currently an active member. fn is_member(who: &T::AccountId) -> bool { - Self::members().binary_search_by(|m| m.who.cmp(who)).is_ok() + Members::::get().binary_search_by(|m| m.who.cmp(who)).is_ok() } /// Check if `who` is currently an active runner-up. fn is_runner_up(who: &T::AccountId) -> bool { - Self::runners_up().iter().any(|r| &r.who == who) + RunnersUp::::get().iter().any(|r| &r.who == who) } /// Get the members' account ids. fn members_ids() -> Vec { - Self::members().into_iter().map(|m| m.who).collect::>() + Members::::get().into_iter().map(|m| m.who).collect::>() } /// Get a concatenation of previous members and runners-up and their deposits. @@ -903,10 +903,10 @@ impl Pallet { /// These accounts are essentially treated as candidates. fn implicit_candidates_with_deposit() -> Vec<(T::AccountId, BalanceOf)> { // invariant: these two are always without duplicates. - Self::members() + Members::::get() .into_iter() .map(|m| (m.who, m.deposit)) - .chain(Self::runners_up().into_iter().map(|r| (r.who, r.deposit))) + .chain(RunnersUp::::get().into_iter().map(|r| (r.who, r.deposit))) .collect::>() } @@ -943,7 +943,7 @@ impl Pallet { let desired_runners_up = T::DesiredRunnersUp::get() as usize; let num_to_elect = desired_runners_up + desired_seats; - let mut candidates_and_deposit = Self::candidates(); + let mut candidates_and_deposit = Candidates::::get(); // add all the previous members and runners-up as candidates as well. candidates_and_deposit.append(&mut Self::implicit_candidates_with_deposit()); @@ -1197,6 +1197,7 @@ impl ContainsLengthBound for Pallet { mod tests { use super::*; use crate as elections_phragmen; + use crate::Members as MembersStorage; use frame_support::{ assert_noop, assert_ok, dispatch::DispatchResultWithPostInfo, @@ -1420,22 +1421,22 @@ mod tests { } fn candidate_ids() -> Vec { - Elections::candidates().into_iter().map(|(c, _)| c).collect::>() + Candidates::::get().into_iter().map(|(c, _)| c).collect::>() } fn candidate_deposit(who: &u64) -> u64 { - Elections::candidates() + Candidates::::get() .into_iter() .find_map(|(c, d)| if c == *who { Some(d) } else { None }) .unwrap_or_default() } fn voter_deposit(who: &u64) -> u64 { - Elections::voting(who).deposit + Voting::::get(who).deposit } fn runners_up_ids() -> Vec { - Elections::runners_up().into_iter().map(|r| r.who).collect::>() + RunnersUp::::get().into_iter().map(|r| r.who).collect::>() } fn members_ids() -> Vec { @@ -1443,11 +1444,14 @@ mod tests { } fn members_and_stake() -> Vec<(u64, u64)> { - Elections::members().into_iter().map(|m| (m.who, m.stake)).collect::>() + MembersStorage::::get() + .into_iter() + .map(|m| (m.who, m.stake)) + .collect::>() } fn runners_up_and_stake() -> Vec<(u64, u64)> { - Elections::runners_up() + RunnersUp::::get() .into_iter() .map(|r| (r.who, r.stake)) .collect::>() @@ -1462,7 +1466,7 @@ mod tests { } fn has_lock(who: &u64) -> u64 { - Balances::locks(who) + pallet_balances::Locks::::get(who) .get(0) .cloned() .map(|lock| { @@ -1477,15 +1481,15 @@ mod tests { } fn ensure_members_sorted() { - let mut members = Elections::members().clone(); + let mut members = MembersStorage::::get().clone(); members.sort_by_key(|m| m.who); - assert_eq!(Elections::members(), members); + assert_eq!(MembersStorage::::get(), members); } fn ensure_candidates_sorted() { - let mut candidates = Elections::candidates().clone(); + let mut candidates = Candidates::::get().clone(); candidates.sort_by_key(|(c, _)| *c); - assert_eq!(Elections::candidates(), candidates); + assert_eq!(Candidates::::get(), candidates); } fn locked_stake_of(who: &u64) -> u64 { @@ -1495,9 +1499,9 @@ mod tests { fn ensure_members_has_approval_stake() { // we filter members that have no approval state. This means that even we have more seats // than candidates, we will never ever chose a member with no votes. - assert!(Elections::members() + assert!(MembersStorage::::get() .iter() - .chain(Elections::runners_up().iter()) + .chain(RunnersUp::::get().iter()) .all(|s| s.stake != u64::zero())); } @@ -1523,7 +1527,7 @@ mod tests { } fn submit_candidacy(origin: RuntimeOrigin) -> sp_runtime::DispatchResult { - Elections::submit_candidacy(origin, Elections::candidates().len() as u32) + Elections::submit_candidacy(origin, Candidates::::get().len() as u32) } fn vote(origin: RuntimeOrigin, votes: Vec, stake: u64) -> DispatchResultWithPostInfo { @@ -1547,10 +1551,10 @@ mod tests { assert_eq!(::VotingBondFactor::get(), 0); assert_eq!(::CandidacyBond::get(), 3); assert_eq!(::TermDuration::get(), 5); - assert_eq!(Elections::election_rounds(), 0); + assert_eq!(ElectionRounds::::get(), 0); - assert!(Elections::members().is_empty()); - assert!(Elections::runners_up().is_empty()); + assert!(MembersStorage::::get().is_empty()); + assert!(RunnersUp::::get().is_empty()); assert!(candidate_ids().is_empty()); assert_eq!(>::decode_len(), None); @@ -1568,7 +1572,7 @@ mod tests { .build_and_execute(|| { System::set_block_number(1); assert_eq!( - Elections::members(), + MembersStorage::::get(), vec![ SeatHolder { who: 1, stake: 10, deposit: 0 }, SeatHolder { who: 2, stake: 20, deposit: 0 } @@ -1576,11 +1580,11 @@ mod tests { ); assert_eq!( - Elections::voting(1), + Voting::::get(1), Voter { stake: 10u64, votes: vec![1], deposit: 0 } ); assert_eq!( - Elections::voting(2), + Voting::::get(2), Voter { stake: 20u64, votes: vec![2], deposit: 0 } ); @@ -1600,19 +1604,19 @@ mod tests { System::set_block_number(1); assert_eq!( - Elections::voting(1), + Voting::::get(1), Voter { stake: 10u64, votes: vec![1], deposit: 0 } ); assert_eq!( - Elections::voting(2), + Voting::::get(2), Voter { stake: 20u64, votes: vec![2], deposit: 0 } ); assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(1))); assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(2))); - assert_eq!(Elections::voting(1), Default::default()); - assert_eq!(Elections::voting(2), Default::default()); + assert_eq!(Voting::::get(1), Default::default()); + assert_eq!(Voting::::get(2), Default::default()); }) } @@ -1623,7 +1627,7 @@ mod tests { .build_and_execute(|| { System::set_block_number(1); assert_eq!( - Elections::members(), + MembersStorage::::get(), vec![ SeatHolder { who: 1, stake: 10, deposit: 0 }, SeatHolder { who: 2, stake: 20, deposit: 0 }, @@ -1631,11 +1635,11 @@ mod tests { ); assert_eq!( - Elections::voting(1), + Voting::::get(1), Voter { stake: 10u64, votes: vec![1], deposit: 0 } ); assert_eq!( - Elections::voting(2), + Voting::::get(2), Voter { stake: 20u64, votes: vec![2], deposit: 0 } ); @@ -1679,17 +1683,17 @@ mod tests { ExtBuilder::default().term_duration(0).build_and_execute(|| { assert_eq!(::TermDuration::get(), 0); assert_eq!(::DesiredMembers::get(), 2); - assert_eq!(Elections::election_rounds(), 0); + assert_eq!(ElectionRounds::::get(), 0); assert!(members_ids().is_empty()); - assert!(Elections::runners_up().is_empty()); + assert!(RunnersUp::::get().is_empty()); assert!(candidate_ids().is_empty()); System::set_block_number(5); Elections::on_initialize(System::block_number()); assert!(members_ids().is_empty()); - assert!(Elections::runners_up().is_empty()); + assert!(RunnersUp::::get().is_empty()); assert!(candidate_ids().is_empty()); }); } @@ -1730,14 +1734,14 @@ mod tests { ExtBuilder::default().build_and_execute(|| { assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); - assert_eq!(Elections::candidates(), vec![(5, 3)]); + assert_eq!(Candidates::::get(), vec![(5, 3)]); // a runtime upgrade changes the bond. CANDIDACY_BOND.with(|v| *v.borrow_mut() = 4); assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); - assert_eq!(Elections::candidates(), vec![(4, 4), (5, 3)]); + assert_eq!(Candidates::::get(), vec![(4, 4), (5, 3)]); // once elected, they each hold their candidacy bond, no more. System::set_block_number(5); @@ -1746,7 +1750,7 @@ mod tests { assert_eq!(balances(&4), (34, 6)); assert_eq!(balances(&5), (45, 5)); assert_eq!( - Elections::members(), + MembersStorage::::get(), vec![ SeatHolder { who: 4, stake: 34, deposit: 4 }, SeatHolder { who: 5, stake: 45, deposit: 3 }, @@ -1795,7 +1799,7 @@ mod tests { Elections::on_initialize(System::block_number()); assert_eq!(members_ids(), vec![5]); - assert!(Elections::runners_up().is_empty()); + assert!(RunnersUp::::get().is_empty()); assert!(candidate_ids().is_empty()); assert_noop!(submit_candidacy(RuntimeOrigin::signed(5)), Error::::MemberSubmit); @@ -1921,7 +1925,7 @@ mod tests { // 2 + 1 assert_eq!(balances(&2), (17, 3)); - assert_eq!(Elections::voting(&2).deposit, 3); + assert_eq!(Voting::::get(&2).deposit, 3); assert_eq!(has_lock(&2), 10); assert_eq!(locked_stake_of(&2), 10); @@ -1929,7 +1933,7 @@ mod tests { assert_ok!(vote(RuntimeOrigin::signed(2), vec![5, 4], 15)); // 2 + 2 assert_eq!(balances(&2), (16, 4)); - assert_eq!(Elections::voting(&2).deposit, 4); + assert_eq!(Voting::::get(&2).deposit, 4); assert_eq!(has_lock(&2), 15); assert_eq!(locked_stake_of(&2), 15); @@ -1937,7 +1941,7 @@ mod tests { assert_ok!(vote(RuntimeOrigin::signed(2), vec![5, 3], 18)); // 2 + 2 assert_eq!(balances(&2), (16, 4)); - assert_eq!(Elections::voting(&2).deposit, 4); + assert_eq!(Voting::::get(&2).deposit, 4); assert_eq!(has_lock(&2), 16); assert_eq!(locked_stake_of(&2), 16); @@ -1945,7 +1949,7 @@ mod tests { assert_ok!(vote(RuntimeOrigin::signed(2), vec![4], 12)); // 2 + 1 assert_eq!(balances(&2), (17, 3)); - assert_eq!(Elections::voting(&2).deposit, 3); + assert_eq!(Voting::::get(&2).deposit, 3); assert_eq!(has_lock(&2), 12); assert_eq!(locked_stake_of(&2), 12); }); @@ -2154,7 +2158,7 @@ mod tests { assert_eq!(locked_stake_of(&2), 0); assert_eq!(balances(&2), (20, 0)); - assert_eq!(Balances::locks(&2).len(), 0); + assert_eq!(pallet_balances::Locks::::get(&2).len(), 0); }); } @@ -2224,7 +2228,7 @@ mod tests { assert_eq!(candidate_ids(), vec![3, 4, 5]); assert_eq!(>::decode_len().unwrap(), 3); - assert_eq!(Elections::election_rounds(), 0); + assert_eq!(ElectionRounds::::get(), 0); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2233,13 +2237,13 @@ mod tests { // votes for 5 assert_eq!(balances(&2), (18, 2)); assert_eq!(members_and_stake(), vec![(3, 25), (5, 18)]); - assert!(Elections::runners_up().is_empty()); + assert!(RunnersUp::::get().is_empty()); assert_eq_uvec!(all_voters(), vec![2, 3, 4]); assert!(candidate_ids().is_empty()); assert_eq!(>::decode_len(), None); - assert_eq!(Elections::election_rounds(), 1); + assert_eq!(ElectionRounds::::get(), 1); }); } @@ -2302,7 +2306,7 @@ mod tests { Elections::on_initialize(System::block_number()); assert_eq!(members_and_stake(), vec![(5, 45)]); - assert_eq!(Elections::election_rounds(), 1); + assert_eq!(ElectionRounds::::get(), 1); // but now it has a valid target. assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); @@ -2312,7 +2316,7 @@ mod tests { // candidate 4 is affected by an old vote. assert_eq!(members_and_stake(), vec![(4, 28), (5, 45)]); - assert_eq!(Elections::election_rounds(), 2); + assert_eq!(ElectionRounds::::get(), 2); assert_eq_uvec!(all_voters(), vec![3, 5]); }); } @@ -2333,7 +2337,7 @@ mod tests { System::set_block_number(5); Elections::on_initialize(System::block_number()); - assert_eq!(Elections::election_rounds(), 1); + assert_eq!(ElectionRounds::::get(), 1); assert_eq!(members_ids(), vec![4, 5]); }); } @@ -2348,7 +2352,7 @@ mod tests { Elections::on_initialize(System::block_number()); assert!(candidate_ids().is_empty()); - assert_eq!(Elections::election_rounds(), 1); + assert_eq!(ElectionRounds::::get(), 1); assert!(members_ids().is_empty()); System::assert_last_event(RuntimeEvent::Elections(super::Event::NewTerm { @@ -2502,7 +2506,7 @@ mod tests { Elections::on_initialize(System::block_number()); assert_eq!(members_ids(), vec![4, 5]); - assert_eq!(Elections::election_rounds(), 1); + assert_eq!(ElectionRounds::::get(), 1); assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); assert_ok!(vote(RuntimeOrigin::signed(2), vec![2], 20)); @@ -2546,7 +2550,7 @@ mod tests { assert_eq!(runners_up_and_stake(), vec![(2, 15), (3, 25)]); // no new candidates but old members and runners-up are always added. assert!(candidate_ids().is_empty()); - assert_eq!(Elections::election_rounds(), b / 5); + assert_eq!(ElectionRounds::::get(), b / 5); assert_eq_uvec!(all_voters(), vec![2, 3, 4, 5]); }; @@ -2570,7 +2574,7 @@ mod tests { System::set_block_number(5); Elections::on_initialize(System::block_number()); assert_eq!(members_ids(), vec![4, 5]); - assert_eq!(Elections::election_rounds(), 1); + assert_eq!(ElectionRounds::::get(), 1); // a new candidate assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); @@ -2579,7 +2583,7 @@ mod tests { assert_ok!(Elections::remove_member(RuntimeOrigin::root(), 4, true, true)); assert_eq!(balances(&4), (35, 2)); // slashed - assert_eq!(Elections::election_rounds(), 2); // new election round + assert_eq!(ElectionRounds::::get(), 2); // new election round assert_eq!(members_ids(), vec![3, 5]); // new members }); } @@ -2598,12 +2602,12 @@ mod tests { assert_eq!(>::decode_len().unwrap(), 3); - assert_eq!(Elections::election_rounds(), 0); + assert_eq!(ElectionRounds::::get(), 0); System::set_block_number(5); Elections::on_initialize(System::block_number()); assert_eq!(members_ids(), vec![3, 5]); - assert_eq!(Elections::election_rounds(), 1); + assert_eq!(ElectionRounds::::get(), 1); assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(2))); assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(3))); @@ -2614,7 +2618,7 @@ mod tests { System::set_block_number(10); Elections::on_initialize(System::block_number()); assert!(members_ids().is_empty()); - assert_eq!(Elections::election_rounds(), 2); + assert_eq!(ElectionRounds::::get(), 2); }); } @@ -2679,7 +2683,7 @@ mod tests { Elections::on_initialize(System::block_number()); assert_eq_uvec!(members_ids(), vec![3, 4]); - assert_eq!(Elections::election_rounds(), 1); + assert_eq!(ElectionRounds::::get(), 1); }); } @@ -3124,13 +3128,13 @@ mod tests { .desired_members(0) .desired_runners_up(0) .build_and_execute(|| { - assert_eq!(Elections::candidates().len(), 0); + assert_eq!(Candidates::::get().len(), 0); assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_eq!(Elections::candidates().len(), 3); + assert_eq!(Candidates::::get().len(), 3); assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); @@ -3142,7 +3146,7 @@ mod tests { assert_eq!(members_ids().len(), 0); assert_eq!(runners_up_ids().len(), 0); assert_eq!(all_voters().len(), 3); - assert_eq!(Elections::candidates().len(), 0); + assert_eq!(Candidates::::get().len(), 0); }); // not interested in members @@ -3150,13 +3154,13 @@ mod tests { .desired_members(0) .desired_runners_up(2) .build_and_execute(|| { - assert_eq!(Elections::candidates().len(), 0); + assert_eq!(Candidates::::get().len(), 0); assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_eq!(Elections::candidates().len(), 3); + assert_eq!(Candidates::::get().len(), 3); assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); @@ -3168,7 +3172,7 @@ mod tests { assert_eq!(members_ids().len(), 0); assert_eq!(runners_up_ids(), vec![3, 4]); assert_eq!(all_voters().len(), 3); - assert_eq!(Elections::candidates().len(), 0); + assert_eq!(Candidates::::get().len(), 0); }); // not interested in runners-up @@ -3176,13 +3180,13 @@ mod tests { .desired_members(2) .desired_runners_up(0) .build_and_execute(|| { - assert_eq!(Elections::candidates().len(), 0); + assert_eq!(Candidates::::get().len(), 0); assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_eq!(Elections::candidates().len(), 3); + assert_eq!(Candidates::::get().len(), 3); assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); @@ -3194,7 +3198,7 @@ mod tests { assert_eq!(members_ids(), vec![3, 4]); assert_eq!(runners_up_ids().len(), 0); assert_eq!(all_voters().len(), 3); - assert_eq!(Elections::candidates().len(), 0); + assert_eq!(Candidates::::get().len(), 0); }); } diff --git a/frame/examples/basic/src/benchmarking.rs b/frame/examples/basic/src/benchmarking.rs index a9e2013b0446c..82ce3a9a97069 100644 --- a/frame/examples/basic/src/benchmarking.rs +++ b/frame/examples/basic/src/benchmarking.rs @@ -52,7 +52,7 @@ mod benchmarks { set_dummy(RawOrigin::Root, value); // The execution phase is just running `set_dummy` extrinsic call // This is the optional benchmark verification phase, asserting certain states. - assert_eq!(Pallet::::dummy(), Some(value)) + assert_eq!(Dummy::::get(), Some(value)) } // This will measure the execution time of `accumulate_dummy`. diff --git a/frame/examples/basic/src/lib.rs b/frame/examples/basic/src/lib.rs index d5045157dade7..457dc725e2450 100644 --- a/frame/examples/basic/src/lib.rs +++ b/frame/examples/basic/src/lib.rs @@ -506,8 +506,6 @@ pub mod pallet { let _sender = ensure_signed(origin)?; // Read the value of dummy from storage. - // let dummy = Self::dummy(); - // Will also work using the `::get` on the storage item type itself: // let dummy = >::get(); // Calculate the new value. @@ -601,20 +599,14 @@ pub mod pallet { // - `Foo::put(1); Foo::get()` returns `1`; // - `Foo::kill(); Foo::get()` returns `0` (u32::default()). #[pallet::storage] - // The getter attribute generate a function on `Pallet` placeholder: - // `fn getter_name() -> Type` for basic value items or - // `fn getter_name(key: KeyType) -> ValueType` for map items. - #[pallet::getter(fn dummy)] pub(super) type Dummy = StorageValue<_, T::Balance>; // A map that has enumerable entries. #[pallet::storage] - #[pallet::getter(fn bar)] pub(super) type Bar = StorageMap<_, Blake2_128Concat, T::AccountId, T::Balance>; // this one uses the query kind: `ValueQuery`, we'll demonstrate the usage of 'mutate' API. #[pallet::storage] - #[pallet::getter(fn foo)] pub(super) type Foo = StorageValue<_, T::Balance, ValueQuery>; #[pallet::storage] diff --git a/frame/examples/basic/src/tests.rs b/frame/examples/basic/src/tests.rs index 891c7c78628a1..6070ed712a3f5 100644 --- a/frame/examples/basic/src/tests.rs +++ b/frame/examples/basic/src/tests.rs @@ -120,25 +120,25 @@ fn it_works_for_optional_value() { // Check that GenesisBuilder works properly. let val1 = 42; let val2 = 27; - assert_eq!(Example::dummy(), Some(val1)); + assert_eq!(Dummy::::get(), Some(val1)); // Check that accumulate works when we have Some value in Dummy already. assert_ok!(Example::accumulate_dummy(RuntimeOrigin::signed(1), val2)); - assert_eq!(Example::dummy(), Some(val1 + val2)); + assert_eq!(Dummy::::get(), Some(val1 + val2)); // Check that accumulate works when we Dummy has None in it. >::on_initialize(2); assert_ok!(Example::accumulate_dummy(RuntimeOrigin::signed(1), val1)); - assert_eq!(Example::dummy(), Some(val1 + val2 + val1)); + assert_eq!(Dummy::::get(), Some(val1 + val2 + val1)); }); } #[test] fn it_works_for_default_value() { new_test_ext().execute_with(|| { - assert_eq!(Example::foo(), 24); + assert_eq!(Foo::::get(), 24); assert_ok!(Example::accumulate_foo(RuntimeOrigin::signed(1), 1)); - assert_eq!(Example::foo(), 25); + assert_eq!(Foo::::get(), 25); }); } @@ -147,7 +147,7 @@ fn set_dummy_works() { new_test_ext().execute_with(|| { let test_val = 133; assert_ok!(Example::set_dummy(RuntimeOrigin::root(), test_val.into())); - assert_eq!(Example::dummy(), Some(test_val)); + assert_eq!(Dummy::::get(), Some(test_val)); }); } diff --git a/frame/grandpa/src/benchmarking.rs b/frame/grandpa/src/benchmarking.rs index 6eee12ad98dbf..bc82ca6c19cf2 100644 --- a/frame/grandpa/src/benchmarking.rs +++ b/frame/grandpa/src/benchmarking.rs @@ -17,7 +17,7 @@ //! Benchmarks for the GRANDPA pallet. -use super::{Pallet as Grandpa, *}; +use super::*; use frame_benchmarking::v1::benchmarks; use frame_system::RawOrigin; use sp_core::H256; @@ -66,7 +66,7 @@ benchmarks! { }: _(RawOrigin::Root, delay, best_finalized_block_number) verify { - assert!(Grandpa::::stalled().is_some()); + assert!(Stalled::::get().is_some()); } impl_benchmark_test_suite!( diff --git a/frame/grandpa/src/lib.rs b/frame/grandpa/src/lib.rs index ea534947ddd37..741a77195b520 100644 --- a/frame/grandpa/src/lib.rs +++ b/frame/grandpa/src/lib.rs @@ -326,7 +326,6 @@ pub mod pallet { /// The number of changes (both in terms of keys and underlying economic responsibilities) /// in the "set" of Grandpa validators from genesis. #[pallet::storage] - #[pallet::getter(fn current_set_id)] pub(super) type CurrentSetId = StorageValue<_, SetId, ValueQuery>; /// A mapping from grandpa set ID to the index of the *most recent* session for which its @@ -424,6 +423,12 @@ pub enum StoredState { } impl Pallet { + /// The number of changes (both in terms of keys and underlying economic responsibilities) + /// in the "set" of Grandpa validators from genesis. + pub fn current_set_id() -> SetId { + CurrentSetId::::get() + } + /// Get the current set of authorities, along with their respective weights. pub fn grandpa_authorities() -> AuthorityList { storage::unhashed::get_or_default::(GRANDPA_AUTHORITIES_KEY).into() @@ -482,7 +487,7 @@ impl Pallet { let scheduled_at = >::block_number(); if forced.is_some() { - if Self::next_forced().map_or(false, |next| next > scheduled_at) { + if NextForced::::get().map_or(false, |next| next > scheduled_at) { return Err(Error::::TooSoon.into()) } @@ -565,13 +570,13 @@ impl Pallet { None } else { let session_index = - Self::session_for_set(set_id - 1).ok_or(Error::::InvalidEquivocationProof)?; + SetIdSession::::get(set_id - 1).ok_or(Error::::InvalidEquivocationProof)?; Some(session_index) }; let set_id_session_index = - Self::session_for_set(set_id).ok_or(Error::::InvalidEquivocationProof)?; + SetIdSession::::get(set_id).ok_or(Error::::InvalidEquivocationProof)?; // check that the session id for the membership proof is within the // bounds of the set id reported in the equivocation. @@ -673,17 +678,17 @@ where // either the session module signalled that the validators have changed // or the set was stalled. but since we didn't successfully schedule // an authority set change we do not increment the set id. - Self::current_set_id() + CurrentSetId::::get() } } else { // nothing's changed, neither economic conditions nor session keys. update the pointer // of the current set. - Self::current_set_id() + CurrentSetId::::get() }; // update the mapping to note that the current set corresponds to the // latest equivalent session (i.e. now). - let session_index = >::current_index(); + let session_index = >::get(); SetIdSession::::insert(current_set_id, &session_index); } diff --git a/frame/grandpa/src/mock.rs b/frame/grandpa/src/mock.rs index 7d54966a498a6..c24e0a1bffc0c 100644 --- a/frame/grandpa/src/mock.rs +++ b/frame/grandpa/src/mock.rs @@ -313,7 +313,7 @@ pub fn new_test_ext_raw_authorities(authorities: AuthorityList) -> sp_io::TestEx } pub fn start_session(session_index: SessionIndex) { - for i in Session::current_index()..session_index { + for i in pallet_session::CurrentIndex::::get()..session_index { System::on_finalize(System::block_number()); Session::on_finalize(System::block_number()); Staking::on_finalize(System::block_number()); @@ -337,12 +337,12 @@ pub fn start_session(session_index: SessionIndex) { Grandpa::on_initialize(System::block_number()); } - assert_eq!(Session::current_index(), session_index); + assert_eq!(pallet_session::CurrentIndex::::get(), session_index); } pub fn start_era(era_index: EraIndex) { start_session((era_index * 3).into()); - assert_eq!(Staking::current_era(), Some(era_index)); + assert_eq!(pallet_staking::CurrentEra::::get(), Some(era_index)); } pub fn initialize_block(number: u64, parent_hash: H256) { diff --git a/frame/grandpa/src/tests.rs b/frame/grandpa/src/tests.rs index e090dcebb60bf..766317b34602f 100644 --- a/frame/grandpa/src/tests.rs +++ b/frame/grandpa/src/tests.rs @@ -157,7 +157,7 @@ fn dispatch_forced_change() { for i in 2..7 { initialize_block(i, header.hash()); assert!(>::get().unwrap().forced.is_some()); - assert_eq!(Grandpa::next_forced(), Some(11)); + assert_eq!(NextForced::::get(), Some(11)); assert_noop!( Grandpa::schedule_change(to_authorities(vec![(5, 1)]), 1, None), Error::::ChangePending @@ -207,7 +207,7 @@ fn dispatch_forced_change() { initialize_block(i, header.hash()); assert!(!>::exists()); assert_eq!(Grandpa::grandpa_authorities(), to_authorities(vec![(5, 1)])); - assert_eq!(Grandpa::next_forced(), Some(11)); + assert_eq!(NextForced::::get(), Some(11)); assert_noop!( Grandpa::schedule_change(to_authorities(vec![(5, 1), (6, 1)]), 5, Some(0)), Error::::TooSoon @@ -224,7 +224,7 @@ fn dispatch_forced_change() { 5, Some(0) )); - assert_eq!(Grandpa::next_forced(), Some(21)); + assert_eq!(NextForced::::get(), Some(21)); Grandpa::on_finalize(11); header = System::finalize(); } @@ -240,7 +240,10 @@ fn schedule_pause_only_when_live() { Grandpa::schedule_pause(1).unwrap(); // we've switched to the pending pause state - assert_eq!(Grandpa::state(), StoredState::PendingPause { scheduled_at: 1u64, delay: 1 }); + assert_eq!( + State::::get(), + StoredState::PendingPause { scheduled_at: 1u64, delay: 1 } + ); Grandpa::on_finalize(1); let _ = System::finalize(); @@ -254,7 +257,7 @@ fn schedule_pause_only_when_live() { let _ = System::finalize(); // after finalizing block 2 the set should have switched to paused state - assert_eq!(Grandpa::state(), StoredState::Paused); + assert_eq!(State::::get(), StoredState::Paused); }); } @@ -266,14 +269,14 @@ fn schedule_resume_only_when_paused() { // the set is currently live, resuming it is an error assert_noop!(Grandpa::schedule_resume(1), Error::::ResumeFailed); - assert_eq!(Grandpa::state(), StoredState::Live); + assert_eq!(State::::get(), StoredState::Live); // we schedule a pause to be applied instantly Grandpa::schedule_pause(0).unwrap(); Grandpa::on_finalize(1); let _ = System::finalize(); - assert_eq!(Grandpa::state(), StoredState::Paused); + assert_eq!(State::::get(), StoredState::Paused); // we schedule the set to go back live in 2 blocks initialize_block(2, Default::default()); @@ -290,7 +293,7 @@ fn schedule_resume_only_when_paused() { let _ = System::finalize(); // it should be live at block 4 - assert_eq!(Grandpa::state(), StoredState::Live); + assert_eq!(State::::get(), StoredState::Live); }); } @@ -320,13 +323,13 @@ fn report_equivocation_current_set_works() { let authorities = test_authorities(); new_test_ext_raw_authorities(authorities).execute_with(|| { - assert_eq!(Staking::current_era(), Some(0)); - assert_eq!(Session::current_index(), 0); + assert_eq!(pallet_staking::CurrentEra::::get(), Some(0)); + assert_eq!(pallet_session::CurrentIndex::::get(), 0); start_era(1); let authorities = Grandpa::grandpa_authorities(); - let validators = Session::validators(); + let validators = pallet_session::Validators::::get(); // make sure that all validators have the same balance for validator in &validators { @@ -334,7 +337,7 @@ fn report_equivocation_current_set_works() { assert_eq!(Staking::slashable_balance_of(validator), 10_000); assert_eq!( - Staking::eras_stakers(1, validator), + pallet_staking::ErasStakers::::get(1, validator), pallet_staking::Exposure { total: 10_000, own: 10_000, others: vec![] }, ); } @@ -343,7 +346,7 @@ fn report_equivocation_current_set_works() { let equivocation_key = &authorities[equivocation_authority_index].0; let equivocation_keyring = extract_keyring(equivocation_key); - let set_id = Grandpa::current_set_id(); + let set_id = CurrentSetId::::get(); // generate an equivocation proof, with two votes in the same round for // different block hashes signed by the same key @@ -372,7 +375,7 @@ fn report_equivocation_current_set_works() { assert_eq!(Balances::total_balance(&equivocation_validator_id), 10_000_000 - 10_000); assert_eq!(Staking::slashable_balance_of(&equivocation_validator_id), 0); assert_eq!( - Staking::eras_stakers(2, equivocation_validator_id), + pallet_staking::ErasStakers::::get(2, equivocation_validator_id), pallet_staking::Exposure { total: 0, own: 0, others: vec![] }, ); @@ -386,7 +389,7 @@ fn report_equivocation_current_set_works() { assert_eq!(Staking::slashable_balance_of(validator), 10_000); assert_eq!( - Staking::eras_stakers(2, validator), + pallet_staking::ErasStakers::::get(2, validator), pallet_staking::Exposure { total: 10_000, own: 10_000, others: vec![] }, ); } @@ -401,7 +404,7 @@ fn report_equivocation_old_set_works() { start_era(1); let authorities = Grandpa::grandpa_authorities(); - let validators = Session::validators(); + let validators = pallet_session::Validators::::get(); let equivocation_authority_index = 0; let equivocation_key = &authorities[equivocation_authority_index].0; @@ -418,14 +421,14 @@ fn report_equivocation_old_set_works() { assert_eq!(Staking::slashable_balance_of(validator), 10_000); assert_eq!( - Staking::eras_stakers(2, validator), + pallet_staking::ErasStakers::::get(2, validator), pallet_staking::Exposure { total: 10_000, own: 10_000, others: vec![] }, ); } let equivocation_keyring = extract_keyring(equivocation_key); - let set_id = Grandpa::current_set_id(); + let set_id = CurrentSetId::::get(); // generate an equivocation proof for the old set, let equivocation_proof = generate_equivocation_proof( @@ -451,7 +454,7 @@ fn report_equivocation_old_set_works() { assert_eq!(Staking::slashable_balance_of(&equivocation_validator_id), 0); assert_eq!( - Staking::eras_stakers(3, equivocation_validator_id), + pallet_staking::ErasStakers::::get(3, equivocation_validator_id), pallet_staking::Exposure { total: 0, own: 0, others: vec![] }, ); @@ -465,7 +468,7 @@ fn report_equivocation_old_set_works() { assert_eq!(Staking::slashable_balance_of(validator), 10_000); assert_eq!( - Staking::eras_stakers(3, validator), + pallet_staking::ErasStakers::::get(3, validator), pallet_staking::Exposure { total: 10_000, own: 10_000, others: vec![] }, ); } @@ -488,7 +491,7 @@ fn report_equivocation_invalid_set_id() { let key_owner_proof = Historical::prove((sp_finality_grandpa::KEY_TYPE, &equivocation_key)).unwrap(); - let set_id = Grandpa::current_set_id(); + let set_id = CurrentSetId::::get(); // generate an equivocation for a future set let equivocation_proof = generate_equivocation_proof( @@ -528,7 +531,7 @@ fn report_equivocation_invalid_session() { start_era(2); - let set_id = Grandpa::current_set_id(); + let set_id = CurrentSetId::::get(); // generate an equivocation proof at set id = 2 let equivocation_proof = generate_equivocation_proof( @@ -569,7 +572,7 @@ fn report_equivocation_invalid_key_owner_proof() { let equivocation_key = &authorities[equivocation_authority_index].0; let equivocation_keyring = extract_keyring(equivocation_key); - let set_id = Grandpa::current_set_id(); + let set_id = CurrentSetId::::get(); // generate an equivocation proof for the authority at index 0 let equivocation_proof = generate_equivocation_proof( @@ -612,7 +615,7 @@ fn report_equivocation_invalid_equivocation_proof() { let key_owner_proof = Historical::prove((sp_finality_grandpa::KEY_TYPE, &equivocation_key)).unwrap(); - let set_id = Grandpa::current_set_id(); + let set_id = CurrentSetId::::get(); let assert_invalid_equivocation_proof = |equivocation_proof| { assert_err!( @@ -676,7 +679,7 @@ fn report_equivocation_validate_unsigned_prevents_duplicates() { let equivocation_authority_index = 0; let equivocation_key = &authorities[equivocation_authority_index].0; let equivocation_keyring = extract_keyring(equivocation_key); - let set_id = Grandpa::current_set_id(); + let set_id = CurrentSetId::::get(); let equivocation_proof = generate_equivocation_proof( set_id, @@ -749,12 +752,12 @@ fn report_equivocation_validate_unsigned_prevents_duplicates() { #[test] fn on_new_session_doesnt_start_new_set_if_schedule_change_failed() { new_test_ext(vec![(1, 1), (2, 1), (3, 1)]).execute_with(|| { - assert_eq!(Grandpa::current_set_id(), 0); + assert_eq!(CurrentSetId::::get(), 0); // starting a new era should lead to a change in the session // validators and trigger a new set start_era(1); - assert_eq!(Grandpa::current_set_id(), 1); + assert_eq!(CurrentSetId::::get(), 1); // we schedule a change delayed by 2 blocks, this should make it so that // when we try to rotate the session at the beginning of the era we will @@ -762,11 +765,11 @@ fn on_new_session_doesnt_start_new_set_if_schedule_change_failed() { // not increment the set id. Grandpa::schedule_change(to_authorities(vec![(1, 1)]), 2, None).unwrap(); start_era(2); - assert_eq!(Grandpa::current_set_id(), 1); + assert_eq!(CurrentSetId::::get(), 1); // everything should go back to normal after. start_era(3); - assert_eq!(Grandpa::current_set_id(), 2); + assert_eq!(CurrentSetId::::get(), 2); // session rotation might also fail to schedule a change if it's for a // forced change (i.e. grandpa is stalled) and it is too soon. @@ -777,7 +780,7 @@ fn on_new_session_doesnt_start_new_set_if_schedule_change_failed() { // defined will also trigger a new set (regardless of whether the // session validators changed) Grandpa::on_new_session(true, std::iter::empty(), std::iter::empty()); - assert_eq!(Grandpa::current_set_id(), 2); + assert_eq!(CurrentSetId::::get(), 2); }); } @@ -791,19 +794,19 @@ fn cleans_up_old_set_id_session_mappings() { // we should have a session id mapping for all the set ids from // `max_set_id_session_entries` eras we have observed for i in 1..=max_set_id_session_entries { - assert!(Grandpa::session_for_set(i as u64).is_some()); + assert!(SetIdSession::::get(i as u64).is_some()); } start_era(max_set_id_session_entries * 2); // we should keep tracking the new mappings for new eras for i in max_set_id_session_entries + 1..=max_set_id_session_entries * 2 { - assert!(Grandpa::session_for_set(i as u64).is_some()); + assert!(SetIdSession::::get(i as u64).is_some()); } // but the old ones should have been pruned by now for i in 1..=max_set_id_session_entries { - assert!(Grandpa::session_for_set(i as u64).is_none()); + assert!(SetIdSession::::get(i as u64).is_none()); } }); } @@ -813,24 +816,24 @@ fn always_schedules_a_change_on_new_session_when_stalled() { new_test_ext(vec![(1, 1), (2, 1), (3, 1)]).execute_with(|| { start_era(1); - assert!(Grandpa::pending_change().is_none()); - assert_eq!(Grandpa::current_set_id(), 1); + assert!(PendingChange::::get().is_none()); + assert_eq!(CurrentSetId::::get(), 1); // if the session handler reports no change then we should not schedule // any pending change Grandpa::on_new_session(false, std::iter::empty(), std::iter::empty()); - assert!(Grandpa::pending_change().is_none()); - assert_eq!(Grandpa::current_set_id(), 1); + assert!(PendingChange::::get().is_none()); + assert_eq!(CurrentSetId::::get(), 1); // if grandpa is stalled then we should **always** schedule a forced // change on a new session >::put((10, 1)); Grandpa::on_new_session(false, std::iter::empty(), std::iter::empty()); - assert!(Grandpa::pending_change().is_some()); - assert!(Grandpa::pending_change().unwrap().forced.is_some()); - assert_eq!(Grandpa::current_set_id(), 2); + assert!(PendingChange::::get().is_some()); + assert!(PendingChange::::get().unwrap().forced.is_some()); + assert_eq!(CurrentSetId::::get(), 2); }); } @@ -862,7 +865,7 @@ fn valid_equivocation_reports_dont_pay_fees() { let equivocation_key = &Grandpa::grandpa_authorities()[0].0; let equivocation_keyring = extract_keyring(equivocation_key); - let set_id = Grandpa::current_set_id(); + let set_id = CurrentSetId::::get(); // generate an equivocation proof. let equivocation_proof = generate_equivocation_proof( diff --git a/frame/identity/src/lib.rs b/frame/identity/src/lib.rs index 39d828ef26f83..b61f00a3238da 100644 --- a/frame/identity/src/lib.rs +++ b/frame/identity/src/lib.rs @@ -159,7 +159,6 @@ pub mod pallet { /// /// TWOX-NOTE: OK ― `AccountId` is a secure hash. #[pallet::storage] - #[pallet::getter(fn identity)] pub(super) type IdentityOf = StorageMap< _, Twox64Concat, @@ -171,7 +170,6 @@ pub mod pallet { /// The super-identity of an alternative "sub" identity together with its name, within that /// context. If the account is not some other account's sub-identity, then just `None`. #[pallet::storage] - #[pallet::getter(fn super_of)] pub(super) type SuperOf = StorageMap<_, Blake2_128Concat, T::AccountId, (T::AccountId, Data), OptionQuery>; @@ -978,4 +976,17 @@ impl Pallet { IdentityOf::::get(who) .map_or(false, |registration| (registration.info.fields().0.bits() & fields) == fields) } + + /// Information that is pertinent to identify the entity behind an account. + pub fn identity( + who: &T::AccountId, + ) -> Option, T::MaxRegistrars, T::MaxAdditionalFields>> { + IdentityOf::::get(who) + } + + /// The super-identity of an alternative "sub" identity together with its name, within that + /// context. If the account is not some other account's sub-identity, then just `None`. + pub fn super_of(who: &T::AccountId) -> Option<(T::AccountId, Data)> { + SuperOf::::get(who) + } } diff --git a/frame/identity/src/tests.rs b/frame/identity/src/tests.rs index baca70e2795fc..2dc02fb6b2843 100644 --- a/frame/identity/src/tests.rs +++ b/frame/identity/src/tests.rs @@ -236,7 +236,7 @@ fn adding_registrar_should_work() { let fields = IdentityFields(IdentityField::Display | IdentityField::Legal); assert_ok!(Identity::set_fields(RuntimeOrigin::signed(3), 0, fields)); assert_eq!( - Identity::registrars(), + Registrars::::get(), vec![Some(RegistrarInfo { account: 3, fee: 10, fields })] ); }); @@ -266,7 +266,7 @@ fn registration_should_work() { three_fields.additional.try_push(Default::default()).unwrap(); assert!(three_fields.additional.try_push(Default::default()).is_err()); assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten()))); - assert_eq!(Identity::identity(10).unwrap().info, ten()); + assert_eq!(IdentityOf::::get(10).unwrap().info, ten()); assert_eq!(Balances::free_balance(10), 90); assert_ok!(Identity::clear_identity(RuntimeOrigin::signed(10))); assert_eq!(Balances::free_balance(10), 100); @@ -342,7 +342,10 @@ fn uninvited_judgement_should_work() { Judgement::Reasonable, identity_hash )); - assert_eq!(Identity::identity(10).unwrap().judgements, vec![(0, Judgement::Reasonable)]); + assert_eq!( + IdentityOf::::get(10).unwrap().judgements, + vec![(0, Judgement::Reasonable)] + ); }); } @@ -359,7 +362,7 @@ fn clearing_judgement_should_work() { BlakeTwo256::hash_of(&ten()) )); assert_ok!(Identity::clear_identity(RuntimeOrigin::signed(10))); - assert_eq!(Identity::identity(10), None); + assert_eq!(IdentityOf::::get(10), None); }); } @@ -369,7 +372,7 @@ fn killing_slashing_should_work() { assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten()))); assert_noop!(Identity::kill_identity(RuntimeOrigin::signed(1), 10), BadOrigin); assert_ok!(Identity::kill_identity(RuntimeOrigin::signed(2), 10)); - assert_eq!(Identity::identity(10), None); + assert_eq!(IdentityOf::::get(10), None); assert_eq!(Balances::free_balance(10), 90); assert_noop!( Identity::kill_identity(RuntimeOrigin::signed(2), 10), @@ -390,32 +393,47 @@ fn setting_subaccounts_should_work() { assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten()))); assert_ok!(Identity::set_subs(RuntimeOrigin::signed(10), subs.clone())); assert_eq!(Balances::free_balance(10), 80); - assert_eq!(Identity::subs_of(10), (10, vec![20].try_into().unwrap())); - assert_eq!(Identity::super_of(20), Some((10, Data::Raw(vec![40; 1].try_into().unwrap())))); + assert_eq!(SubsOf::::get(10), (10, vec![20].try_into().unwrap())); + assert_eq!( + SuperOf::::get(20), + Some((10, Data::Raw(vec![40; 1].try_into().unwrap()))) + ); // push another item and re-set it. subs.push((30, Data::Raw(vec![50; 1].try_into().unwrap()))); assert_ok!(Identity::set_subs(RuntimeOrigin::signed(10), subs.clone())); assert_eq!(Balances::free_balance(10), 70); - assert_eq!(Identity::subs_of(10), (20, vec![20, 30].try_into().unwrap())); - assert_eq!(Identity::super_of(20), Some((10, Data::Raw(vec![40; 1].try_into().unwrap())))); - assert_eq!(Identity::super_of(30), Some((10, Data::Raw(vec![50; 1].try_into().unwrap())))); + assert_eq!(SubsOf::::get(10), (20, vec![20, 30].try_into().unwrap())); + assert_eq!( + SuperOf::::get(20), + Some((10, Data::Raw(vec![40; 1].try_into().unwrap()))) + ); + assert_eq!( + SuperOf::::get(30), + Some((10, Data::Raw(vec![50; 1].try_into().unwrap()))) + ); // switch out one of the items and re-set. subs[0] = (40, Data::Raw(vec![60; 1].try_into().unwrap())); assert_ok!(Identity::set_subs(RuntimeOrigin::signed(10), subs.clone())); assert_eq!(Balances::free_balance(10), 70); // no change in the balance - assert_eq!(Identity::subs_of(10), (20, vec![40, 30].try_into().unwrap())); - assert_eq!(Identity::super_of(20), None); - assert_eq!(Identity::super_of(30), Some((10, Data::Raw(vec![50; 1].try_into().unwrap())))); - assert_eq!(Identity::super_of(40), Some((10, Data::Raw(vec![60; 1].try_into().unwrap())))); + assert_eq!(SubsOf::::get(10), (20, vec![40, 30].try_into().unwrap())); + assert_eq!(SuperOf::::get(20), None); + assert_eq!( + SuperOf::::get(30), + Some((10, Data::Raw(vec![50; 1].try_into().unwrap()))) + ); + assert_eq!( + SuperOf::::get(40), + Some((10, Data::Raw(vec![60; 1].try_into().unwrap()))) + ); // clear assert_ok!(Identity::set_subs(RuntimeOrigin::signed(10), vec![])); assert_eq!(Balances::free_balance(10), 90); - assert_eq!(Identity::subs_of(10), (0, BoundedVec::default())); - assert_eq!(Identity::super_of(30), None); - assert_eq!(Identity::super_of(40), None); + assert_eq!(SubsOf::::get(10), (0, BoundedVec::default())); + assert_eq!(SuperOf::::get(30), None); + assert_eq!(SuperOf::::get(40), None); subs.push((20, Data::Raw(vec![40; 1].try_into().unwrap()))); assert_noop!( @@ -435,7 +453,7 @@ fn clearing_account_should_remove_subaccounts_and_refund() { )); assert_ok!(Identity::clear_identity(RuntimeOrigin::signed(10))); assert_eq!(Balances::free_balance(10), 100); - assert!(Identity::super_of(20).is_none()); + assert!(SuperOf::::get(20).is_none()); }); } @@ -449,7 +467,7 @@ fn killing_account_should_remove_subaccounts_and_not_refund() { )); assert_ok!(Identity::kill_identity(RuntimeOrigin::signed(2), 10)); assert_eq!(Balances::free_balance(10), 80); - assert!(Identity::super_of(20).is_none()); + assert!(SuperOf::::get(20).is_none()); }); } diff --git a/frame/im-online/src/lib.rs b/frame/im-online/src/lib.rs index 3be1f53fc418d..e8f174f7605a2 100644 --- a/frame/im-online/src/lib.rs +++ b/frame/im-online/src/lib.rs @@ -405,7 +405,6 @@ pub mod pallet { /// The current set of keys that may issue a heartbeat. #[pallet::storage] - #[pallet::getter(fn keys)] pub(crate) type Keys = StorageValue<_, WeakBoundedVec, ValueQuery>; @@ -431,7 +430,6 @@ pub mod pallet { /// For each session index, we keep a mapping of `ValidatorId` to the /// number of blocks authored by the given authority. #[pallet::storage] - #[pallet::getter(fn authored_blocks)] pub(crate) type AuthoredBlocks = StorageDoubleMap< _, Twox64Concat, @@ -606,6 +604,11 @@ impl } impl Pallet { + /// The current set of keys that may issue a heartbeat. + pub fn keys() -> WeakBoundedVec { + Keys::::get() + } + /// Returns `true` if a heartbeat has been received for the authority at /// `authority_index` in the authorities series or if the authority has /// authored at least one block, during the current session. Otherwise diff --git a/frame/im-online/src/mock.rs b/frame/im-online/src/mock.rs index 783e68dfede9f..5bc4eb5664955 100644 --- a/frame/im-online/src/mock.rs +++ b/frame/im-online/src/mock.rs @@ -232,7 +232,10 @@ pub fn advance_session() { let now = System::block_number().max(1); System::set_block_number(now + 1); Session::rotate_session(); - let keys = Session::validators().into_iter().map(UintAuthorityId).collect(); + let keys = pallet_session::Validators::::get() + .into_iter() + .map(UintAuthorityId) + .collect(); ImOnline::set_keys(keys); - assert_eq!(Session::current_index(), (now / Period::get()) as u32); + assert_eq!(pallet_session::CurrentIndex::::get(), (now / Period::get()) as u32); } diff --git a/frame/im-online/src/tests.rs b/frame/im-online/src/tests.rs index 2c026f7176b65..82a9ac9090964 100644 --- a/frame/im-online/src/tests.rs +++ b/frame/im-online/src/tests.rs @@ -91,7 +91,14 @@ fn should_report_offline_validators() { // should not report when heartbeat is sent for (idx, v) in validators.into_iter().take(4).enumerate() { - let _ = heartbeat(block, 3, idx as u32, v.into(), Session::validators()).unwrap(); + let _ = heartbeat( + block, + 3, + idx as u32, + v.into(), + pallet_session::Validators::::get(), + ) + .unwrap(); } advance_session(); @@ -150,19 +157,19 @@ fn should_mark_online_validator_when_heartbeat_is_received() { advance_session(); // given Validators::mutate(|l| *l = Some(vec![1, 2, 3, 4, 5, 6])); - assert_eq!(Session::validators(), Vec::::new()); + assert_eq!(pallet_session::Validators::::get(), Vec::::new()); // enact the change and buffer another one advance_session(); - assert_eq!(Session::current_index(), 2); - assert_eq!(Session::validators(), vec![1, 2, 3]); + assert_eq!(pallet_session::CurrentIndex::::get(), 2); + assert_eq!(pallet_session::Validators::::get(), vec![1, 2, 3]); assert!(!ImOnline::is_online(0)); assert!(!ImOnline::is_online(1)); assert!(!ImOnline::is_online(2)); // when - let _ = heartbeat(1, 2, 0, 1.into(), Session::validators()).unwrap(); + let _ = heartbeat(1, 2, 0, 1.into(), pallet_session::Validators::::get()).unwrap(); // then assert!(ImOnline::is_online(0)); @@ -170,7 +177,7 @@ fn should_mark_online_validator_when_heartbeat_is_received() { assert!(!ImOnline::is_online(2)); // and when - let _ = heartbeat(1, 2, 2, 3.into(), Session::validators()).unwrap(); + let _ = heartbeat(1, 2, 2, 3.into(), pallet_session::Validators::::get()).unwrap(); // then assert!(ImOnline::is_online(0)); @@ -185,20 +192,20 @@ fn late_heartbeat_and_invalid_keys_len_should_fail() { advance_session(); // given Validators::mutate(|l| *l = Some(vec![1, 2, 3, 4, 5, 6])); - assert_eq!(Session::validators(), Vec::::new()); + assert_eq!(pallet_session::Validators::::get(), Vec::::new()); // enact the change and buffer another one advance_session(); - assert_eq!(Session::current_index(), 2); - assert_eq!(Session::validators(), vec![1, 2, 3]); + assert_eq!(pallet_session::CurrentIndex::::get(), 2); + assert_eq!(pallet_session::Validators::::get(), vec![1, 2, 3]); // when assert_noop!( - heartbeat(1, 3, 0, 1.into(), Session::validators()), + heartbeat(1, 3, 0, 1.into(), pallet_session::Validators::::get()), "Transaction is outdated" ); assert_noop!( - heartbeat(1, 1, 0, 1.into(), Session::validators()), + heartbeat(1, 1, 0, 1.into(), pallet_session::Validators::::get()), "Transaction is outdated" ); @@ -264,26 +271,26 @@ fn should_cleanup_received_heartbeats_on_session_end() { advance_session(); Validators::mutate(|l| *l = Some(vec![1, 2, 3])); - assert_eq!(Session::validators(), Vec::::new()); + assert_eq!(pallet_session::Validators::::get(), Vec::::new()); // enact the change and buffer another one advance_session(); - assert_eq!(Session::current_index(), 2); - assert_eq!(Session::validators(), vec![1, 2, 3]); + assert_eq!(pallet_session::CurrentIndex::::get(), 2); + assert_eq!(pallet_session::Validators::::get(), vec![1, 2, 3]); // send an heartbeat from authority id 0 at session 2 - let _ = heartbeat(1, 2, 0, 1.into(), Session::validators()).unwrap(); + let _ = heartbeat(1, 2, 0, 1.into(), pallet_session::Validators::::get()).unwrap(); // the heartbeat is stored - assert!(!ImOnline::received_heartbeats(&2, &0).is_none()); + assert!(!ReceivedHeartbeats::::get(&2, &0).is_none()); advance_session(); // after the session has ended we have already processed the heartbeat // message, so any messages received on the previous session should have // been pruned. - assert!(ImOnline::received_heartbeats(&2, &0).is_none()); + assert!(ReceivedHeartbeats::::get(&2, &0).is_none()); }); } @@ -295,12 +302,12 @@ fn should_mark_online_validator_when_block_is_authored() { advance_session(); // given Validators::mutate(|l| *l = Some(vec![1, 2, 3, 4, 5, 6])); - assert_eq!(Session::validators(), Vec::::new()); + assert_eq!(pallet_session::Validators::::get(), Vec::::new()); // enact the change and buffer another one advance_session(); - assert_eq!(Session::current_index(), 2); - assert_eq!(Session::validators(), vec![1, 2, 3]); + assert_eq!(pallet_session::CurrentIndex::::get(), 2); + assert_eq!(pallet_session::Validators::::get(), vec![1, 2, 3]); for i in 0..3 { assert!(!ImOnline::is_online(i)); @@ -331,11 +338,11 @@ fn should_not_send_a_report_if_already_online() { advance_session(); // given Validators::mutate(|l| *l = Some(vec![1, 2, 3, 4, 5, 6])); - assert_eq!(Session::validators(), Vec::::new()); + assert_eq!(pallet_session::Validators::::get(), Vec::::new()); // enact the change and buffer another one advance_session(); - assert_eq!(Session::current_index(), 2); - assert_eq!(Session::validators(), vec![1, 2, 3]); + assert_eq!(pallet_session::CurrentIndex::::get(), 2); + assert_eq!(pallet_session::Validators::::get(), vec![1, 2, 3]); ImOnline::note_author(2); ImOnline::note_author(3); diff --git a/frame/insecure-randomness-collective-flip/src/lib.rs b/frame/insecure-randomness-collective-flip/src/lib.rs index 1d7ddc371173c..7f20106eb1c61 100644 --- a/frame/insecure-randomness-collective-flip/src/lib.rs +++ b/frame/insecure-randomness-collective-flip/src/lib.rs @@ -257,7 +257,7 @@ mod tests { setup_blocks(38); - let random_material = CollectiveFlip::random_material(); + let random_material = RandomMaterial::::get(); assert_eq!(random_material.len(), 38); assert_eq!(random_material[0], genesis_hash); @@ -271,7 +271,7 @@ mod tests { setup_blocks(81); - let random_material = CollectiveFlip::random_material(); + let random_material = RandomMaterial::::get(); assert_eq!(random_material.len(), 81); assert_ne!(random_material[0], random_material[1]); @@ -286,7 +286,7 @@ mod tests { setup_blocks(162); - let random_material = CollectiveFlip::random_material(); + let random_material = RandomMaterial::::get(); assert_eq!(random_material.len(), 81); assert_ne!(random_material[0], random_material[1]); @@ -307,7 +307,7 @@ mod tests { assert_eq!(known_since, 162 - RANDOM_MATERIAL_LEN as u64); assert_ne!(random, H256::zero()); - assert!(!CollectiveFlip::random_material().contains(&random)); + assert!(!RandomMaterial::::get().contains(&random)); }); } } diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index 8b39a08ce6699..e9d7d648adc59 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -312,7 +312,10 @@ pub mod pallet { pub fn set_prime(origin: OriginFor, who: AccountIdLookupOf) -> DispatchResult { T::PrimeOrigin::ensure_origin(origin)?; let who = T::Lookup::lookup(who)?; - Self::members().binary_search(&who).ok().ok_or(Error::::NotMember)?; + Members::::get() + .binary_search(&who) + .ok() + .ok_or(Error::::NotMember)?; Prime::::put(&who); T::MembershipChanged::set_prime(Some(who)); Ok(()) @@ -345,13 +348,13 @@ impl, I: 'static> Pallet { impl, I: 'static> Contains for Pallet { fn contains(t: &T::AccountId) -> bool { - Self::members().binary_search(t).is_ok() + Members::::get().binary_search(t).is_ok() } } impl, I: 'static> SortedMembers for Pallet { fn sorted_members() -> Vec { - Self::members().to_vec() + Members::::get().to_vec() } fn count() -> usize { @@ -661,7 +664,7 @@ mod tests { #[test] fn query_membership_works() { new_test_ext().execute_with(|| { - assert_eq!(Membership::members(), vec![10, 20, 30]); + assert_eq!(pallet_membership::Members::::get(), vec![10, 20, 30]); assert_eq!(MEMBERS.with(|m| m.borrow().clone()), vec![10, 20, 30]); }); } @@ -675,12 +678,12 @@ mod tests { Error::::NotMember ); assert_ok!(Membership::set_prime(RuntimeOrigin::signed(5), 20)); - assert_eq!(Membership::prime(), Some(20)); - assert_eq!(PRIME.with(|m| *m.borrow()), Membership::prime()); + assert_eq!(pallet_membership::Prime::::get(), Some(20)); + assert_eq!(PRIME.with(|m| *m.borrow()), pallet_membership::Prime::::get()); assert_ok!(Membership::clear_prime(RuntimeOrigin::signed(5))); - assert_eq!(Membership::prime(), None); - assert_eq!(PRIME.with(|m| *m.borrow()), Membership::prime()); + assert_eq!(pallet_membership::Prime::::get(), None); + assert_eq!(PRIME.with(|m| *m.borrow()), pallet_membership::Prime::::get()); }); } @@ -693,8 +696,11 @@ mod tests { Error::::AlreadyMember ); assert_ok!(Membership::add_member(RuntimeOrigin::signed(1), 15)); - assert_eq!(Membership::members(), vec![10, 15, 20, 30]); - assert_eq!(MEMBERS.with(|m| m.borrow().clone()), Membership::members().to_vec()); + assert_eq!(pallet_membership::Members::::get(), vec![10, 15, 20, 30]); + assert_eq!( + MEMBERS.with(|m| m.borrow().clone()), + pallet_membership::Members::::get().to_vec() + ); }); } @@ -708,10 +714,13 @@ mod tests { ); assert_ok!(Membership::set_prime(RuntimeOrigin::signed(5), 20)); assert_ok!(Membership::remove_member(RuntimeOrigin::signed(2), 20)); - assert_eq!(Membership::members(), vec![10, 30]); - assert_eq!(MEMBERS.with(|m| m.borrow().clone()), Membership::members().to_vec()); - assert_eq!(Membership::prime(), None); - assert_eq!(PRIME.with(|m| *m.borrow()), Membership::prime()); + assert_eq!(pallet_membership::Members::::get(), vec![10, 30]); + assert_eq!( + MEMBERS.with(|m| m.borrow().clone()), + pallet_membership::Members::::get().to_vec() + ); + assert_eq!(pallet_membership::Prime::::get(), None); + assert_eq!(PRIME.with(|m| *m.borrow()), pallet_membership::Prime::::get()); }); } @@ -730,16 +739,19 @@ mod tests { assert_ok!(Membership::set_prime(RuntimeOrigin::signed(5), 20)); assert_ok!(Membership::swap_member(RuntimeOrigin::signed(3), 20, 20)); - assert_eq!(Membership::members(), vec![10, 20, 30]); - assert_eq!(Membership::prime(), Some(20)); - assert_eq!(PRIME.with(|m| *m.borrow()), Membership::prime()); + assert_eq!(pallet_membership::Members::::get(), vec![10, 20, 30]); + assert_eq!(pallet_membership::Prime::::get(), Some(20)); + assert_eq!(PRIME.with(|m| *m.borrow()), pallet_membership::Prime::::get()); assert_ok!(Membership::set_prime(RuntimeOrigin::signed(5), 10)); assert_ok!(Membership::swap_member(RuntimeOrigin::signed(3), 10, 25)); - assert_eq!(Membership::members(), vec![20, 25, 30]); - assert_eq!(MEMBERS.with(|m| m.borrow().clone()), Membership::members().to_vec()); - assert_eq!(Membership::prime(), None); - assert_eq!(PRIME.with(|m| *m.borrow()), Membership::prime()); + assert_eq!(pallet_membership::Members::::get(), vec![20, 25, 30]); + assert_eq!( + MEMBERS.with(|m| m.borrow().clone()), + pallet_membership::Members::::get().to_vec() + ); + assert_eq!(pallet_membership::Prime::::get(), None); + assert_eq!(PRIME.with(|m| *m.borrow()), pallet_membership::Prime::::get()); }); } @@ -747,8 +759,11 @@ mod tests { fn swap_member_works_that_does_not_change_order() { new_test_ext().execute_with(|| { assert_ok!(Membership::swap_member(RuntimeOrigin::signed(3), 10, 5)); - assert_eq!(Membership::members(), vec![5, 20, 30]); - assert_eq!(MEMBERS.with(|m| m.borrow().clone()), Membership::members().to_vec()); + assert_eq!(pallet_membership::Members::::get(), vec![5, 20, 30]); + assert_eq!( + MEMBERS.with(|m| m.borrow().clone()), + pallet_membership::Members::::get().to_vec() + ); }); } @@ -765,10 +780,13 @@ mod tests { Error::::AlreadyMember ); assert_ok!(Membership::change_key(RuntimeOrigin::signed(10), 40)); - assert_eq!(Membership::members(), vec![20, 30, 40]); - assert_eq!(MEMBERS.with(|m| m.borrow().clone()), Membership::members().to_vec()); - assert_eq!(Membership::prime(), Some(40)); - assert_eq!(PRIME.with(|m| *m.borrow()), Membership::prime()); + assert_eq!(pallet_membership::Members::::get(), vec![20, 30, 40]); + assert_eq!( + MEMBERS.with(|m| m.borrow().clone()), + pallet_membership::Members::::get().to_vec() + ); + assert_eq!(pallet_membership::Prime::::get(), Some(40)); + assert_eq!(PRIME.with(|m| *m.borrow()), pallet_membership::Prime::::get()); }); } @@ -776,8 +794,11 @@ mod tests { fn change_key_works_that_does_not_change_order() { new_test_ext().execute_with(|| { assert_ok!(Membership::change_key(RuntimeOrigin::signed(10), 5)); - assert_eq!(Membership::members(), vec![5, 20, 30]); - assert_eq!(MEMBERS.with(|m| m.borrow().clone()), Membership::members().to_vec()); + assert_eq!(pallet_membership::Members::::get(), vec![5, 20, 30]); + assert_eq!( + MEMBERS.with(|m| m.borrow().clone()), + pallet_membership::Members::::get().to_vec() + ); }); } @@ -791,16 +812,22 @@ mod tests { ); assert_ok!(Membership::reset_members(RuntimeOrigin::signed(4), vec![20, 40, 30])); - assert_eq!(Membership::members(), vec![20, 30, 40]); - assert_eq!(MEMBERS.with(|m| m.borrow().clone()), Membership::members().to_vec()); - assert_eq!(Membership::prime(), Some(20)); - assert_eq!(PRIME.with(|m| *m.borrow()), Membership::prime()); + assert_eq!(pallet_membership::Members::::get(), vec![20, 30, 40]); + assert_eq!( + MEMBERS.with(|m| m.borrow().clone()), + pallet_membership::Members::::get().to_vec() + ); + assert_eq!(pallet_membership::Prime::::get(), Some(20)); + assert_eq!(PRIME.with(|m| *m.borrow()), pallet_membership::Prime::::get()); assert_ok!(Membership::reset_members(RuntimeOrigin::signed(4), vec![10, 40, 30])); - assert_eq!(Membership::members(), vec![10, 30, 40]); - assert_eq!(MEMBERS.with(|m| m.borrow().clone()), Membership::members().to_vec()); - assert_eq!(Membership::prime(), None); - assert_eq!(PRIME.with(|m| *m.borrow()), Membership::prime()); + assert_eq!(pallet_membership::Members::::get(), vec![10, 30, 40]); + assert_eq!( + MEMBERS.with(|m| m.borrow().clone()), + pallet_membership::Members::::get().to_vec() + ); + assert_eq!(pallet_membership::Prime::::get(), None); + assert_eq!(PRIME.with(|m| *m.borrow()), pallet_membership::Prime::::get()); }); } diff --git a/frame/merkle-mountain-range/src/lib.rs b/frame/merkle-mountain-range/src/lib.rs index 170c1d724f3a2..09ed678e60c98 100644 --- a/frame/merkle-mountain-range/src/lib.rs +++ b/frame/merkle-mountain-range/src/lib.rs @@ -221,7 +221,7 @@ pub mod pallet { impl, I: 'static> Hooks> for Pallet { fn on_initialize(_n: T::BlockNumber) -> Weight { use primitives::LeafDataProvider; - let leaves = Self::mmr_leaves(); + let leaves = NumberOfLeaves::::get(); let peaks_before = sp_mmr_primitives::utils::NodesUtils::new(leaves).number_of_peaks(); let data = T::LeafData::leaf_data(); @@ -322,7 +322,7 @@ impl, I: 'static> Pallet { { let first_mmr_block = utils::first_mmr_block_num::( >::block_number(), - Self::mmr_leaves(), + NumberOfLeaves::::get(), )?; utils::block_num_to_leaf_index::(block_num, first_mmr_block) @@ -362,7 +362,7 @@ impl, I: 'static> Pallet { /// Return the on-chain MMR root hash. pub fn mmr_root() -> >::Hash { - Self::mmr_root_hash() + RootHash::::get() } /// Verify MMR proof for given `leaves`. @@ -375,7 +375,7 @@ impl, I: 'static> Pallet { leaves: Vec>, proof: primitives::Proof<>::Hash>, ) -> Result<(), primitives::Error> { - if proof.leaf_count > Self::mmr_leaves() || + if proof.leaf_count > NumberOfLeaves::::get() || proof.leaf_count == 0 || (proof.items.len().saturating_add(leaves.len())) as u64 > proof.leaf_count { diff --git a/frame/merkle-mountain-range/src/tests.rs b/frame/merkle-mountain-range/src/tests.rs index b5f9a78ede010..019af86001881 100644 --- a/frame/merkle-mountain-range/src/tests.rs +++ b/frame/merkle-mountain-range/src/tests.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{mock::*, *}; +use crate::{mock::*, primitives::DataOrHash, Pallet as Mmr, *}; use frame_support::traits::{Get, OnInitialize}; use sp_core::{ @@ -58,7 +58,6 @@ type BlockNumber = ::BlockNumber; fn decode_node( v: Vec, ) -> mmr::Node<::Hashing, ((BlockNumber, H256), LeafData)> { - use crate::primitives::DataOrHash; type A = DataOrHash<::Hashing, (BlockNumber, H256)>; type B = DataOrHash<::Hashing, LeafData>; type Node = mmr::Node<::Hashing, (A, B)>; @@ -84,25 +83,25 @@ fn should_start_empty() { new_test_ext().execute_with(|| { // given assert_eq!( - crate::RootHash::::get(), + RootHash::::get(), "0000000000000000000000000000000000000000000000000000000000000000" .parse() .unwrap() ); - assert_eq!(crate::NumberOfLeaves::::get(), 0); - assert_eq!(crate::Nodes::::get(0), None); + assert_eq!(NumberOfLeaves::::get(), 0); + assert_eq!(Nodes::::get(0), None); // when let weight = new_block(); // then - assert_eq!(crate::NumberOfLeaves::::get(), 1); + assert_eq!(NumberOfLeaves::::get(), 1); assert_eq!( - crate::Nodes::::get(0), + Nodes::::get(0), Some(hex("4320435e8c3318562dba60116bdbcc0b82ffcecb9bb39aae3300cfda3ad0b8b0")) ); assert_eq!( - crate::RootHash::::get(), + RootHash::::get(), hex("4320435e8c3318562dba60116bdbcc0b82ffcecb9bb39aae3300cfda3ad0b8b0") ); assert!(weight != Weight::zero()); @@ -119,13 +118,9 @@ fn should_append_to_mmr_when_on_initialize_is_called() { let parent_b1 = >::parent_hash(); // then - assert_eq!(crate::NumberOfLeaves::::get(), 1); + assert_eq!(NumberOfLeaves::::get(), 1); assert_eq!( - ( - crate::Nodes::::get(0), - crate::Nodes::::get(1), - crate::RootHash::::get(), - ), + (Nodes::::get(0), Nodes::::get(1), RootHash::::get(),), ( Some(hex("4320435e8c3318562dba60116bdbcc0b82ffcecb9bb39aae3300cfda3ad0b8b0")), None, @@ -138,16 +133,16 @@ fn should_append_to_mmr_when_on_initialize_is_called() { let parent_b2 = >::parent_hash(); // then - assert_eq!(crate::NumberOfLeaves::::get(), 2); + assert_eq!(NumberOfLeaves::::get(), 2); let peaks = peaks_from_leaves_count(2); assert_eq!(peaks, vec![2]); assert_eq!( ( - crate::Nodes::::get(0), - crate::Nodes::::get(1), - crate::Nodes::::get(2), - crate::Nodes::::get(3), - crate::RootHash::::get(), + Nodes::::get(0), + Nodes::::get(1), + Nodes::::get(2), + Nodes::::get(3), + RootHash::::get(), ), ( None, @@ -196,18 +191,18 @@ fn should_construct_larger_mmr_correctly() { add_blocks(7); // then - assert_eq!(crate::NumberOfLeaves::::get(), 7); + assert_eq!(NumberOfLeaves::::get(), 7); let peaks = peaks_from_leaves_count(7); assert_eq!(peaks, vec![6, 9, 10]); for i in (0..=10).filter(|p| !peaks.contains(p)) { - assert!(crate::Nodes::::get(i).is_none()); + assert!(Nodes::::get(i).is_none()); } assert_eq!( ( - crate::Nodes::::get(6), - crate::Nodes::::get(9), - crate::Nodes::::get(10), - crate::RootHash::::get(), + Nodes::::get(6), + Nodes::::get(9), + Nodes::::get(10), + RootHash::::get(), ), ( Some(hex("ae88a0825da50e953e7a359c55fe13c8015e48d03d301b8bdfc9193874da9252")), @@ -257,7 +252,7 @@ fn should_generate_proofs_correctly() { // when generate proofs for all leaves. let proofs = (1_u64..=best_block_number) .into_iter() - .map(|block_num| crate::Pallet::::generate_proof(vec![block_num], None).unwrap()) + .map(|block_num| Mmr::::generate_proof(vec![block_num], None).unwrap()) .collect::>(); // when generate historical proofs for all leaves let historical_proofs = (1_u64..best_block_number) @@ -266,11 +261,8 @@ fn should_generate_proofs_correctly() { let mut proofs = vec![]; for historical_best_block in block_num..=num_blocks { proofs.push( - crate::Pallet::::generate_proof( - vec![block_num], - Some(historical_best_block), - ) - .unwrap(), + Mmr::::generate_proof(vec![block_num], Some(historical_best_block)) + .unwrap(), ) } proofs @@ -428,7 +420,7 @@ fn should_generate_batch_proof_correctly() { register_offchain_ext(&mut ext); ext.execute_with(|| { // when generate proofs for a batch of leaves - let (.., proof) = crate::Pallet::::generate_proof(vec![1, 5, 6], None).unwrap(); + let (.., proof) = Mmr::::generate_proof(vec![1, 5, 6], None).unwrap(); // then assert_eq!( proof, @@ -445,8 +437,7 @@ fn should_generate_batch_proof_correctly() { ); // when generate historical proofs for a batch of leaves - let (.., historical_proof) = - crate::Pallet::::generate_proof(vec![1, 5, 6], Some(6)).unwrap(); + let (.., historical_proof) = Mmr::::generate_proof(vec![1, 5, 6], Some(6)).unwrap(); // then assert_eq!( historical_proof, @@ -461,8 +452,7 @@ fn should_generate_batch_proof_correctly() { ); // when generate historical proofs for a batch of leaves - let (.., historical_proof) = - crate::Pallet::::generate_proof(vec![1, 5, 6], None).unwrap(); + let (.., historical_proof) = Mmr::::generate_proof(vec![1, 5, 6], None).unwrap(); // then assert_eq!(historical_proof, proof); }); @@ -483,33 +473,27 @@ fn should_verify() { register_offchain_ext(&mut ext); let (leaves, proof5) = ext.execute_with(|| { // when - crate::Pallet::::generate_proof(vec![5], None).unwrap() + Mmr::::generate_proof(vec![5], None).unwrap() }); let (simple_historical_leaves, simple_historical_proof5) = ext.execute_with(|| { // when - crate::Pallet::::generate_proof(vec![5], Some(6)).unwrap() + Mmr::::generate_proof(vec![5], Some(6)).unwrap() }); let (advanced_historical_leaves, advanced_historical_proof5) = ext.execute_with(|| { // when - crate::Pallet::::generate_proof(vec![5], Some(7)).unwrap() + Mmr::::generate_proof(vec![5], Some(7)).unwrap() }); ext.execute_with(|| { add_blocks(7); // then - assert_eq!(crate::Pallet::::verify_leaves(leaves, proof5), Ok(())); + assert_eq!(Mmr::::verify_leaves(leaves, proof5), Ok(())); assert_eq!( - crate::Pallet::::verify_leaves( - simple_historical_leaves, - simple_historical_proof5 - ), + Mmr::::verify_leaves(simple_historical_leaves, simple_historical_proof5), Ok(()) ); assert_eq!( - crate::Pallet::::verify_leaves( - advanced_historical_leaves, - advanced_historical_proof5 - ), + Mmr::::verify_leaves(advanced_historical_leaves, advanced_historical_proof5), Ok(()) ); }); @@ -522,9 +506,8 @@ fn should_verify_batch_proofs() { block_numbers: &Vec, blocks_to_add: usize, ) { - let (leaves, proof) = ext.execute_with(|| { - crate::Pallet::::generate_proof(block_numbers.to_vec(), None).unwrap() - }); + let (leaves, proof) = + ext.execute_with(|| Mmr::::generate_proof(block_numbers.to_vec(), None).unwrap()); let max_block_number = ext.execute_with(|| frame_system::Pallet::::block_number()); let min_block_number = block_numbers.iter().max().unwrap(); @@ -533,8 +516,7 @@ fn should_verify_batch_proofs() { let historical_proofs = (*min_block_number..=max_block_number) .map(|best_block| { ext.execute_with(|| { - crate::Pallet::::generate_proof(block_numbers.to_vec(), Some(best_block)) - .unwrap() + Mmr::::generate_proof(block_numbers.to_vec(), Some(best_block)).unwrap() }) }) .collect::>(); @@ -542,12 +524,9 @@ fn should_verify_batch_proofs() { ext.execute_with(|| { add_blocks(blocks_to_add); // then - assert_eq!(crate::Pallet::::verify_leaves(leaves, proof), Ok(())); + assert_eq!(Mmr::::verify_leaves(leaves, proof), Ok(())); historical_proofs.iter().for_each(|(leaves, proof)| { - assert_eq!( - crate::Pallet::::verify_leaves(leaves.clone(), proof.clone()), - Ok(()) - ); + assert_eq!(Mmr::::verify_leaves(leaves.clone(), proof.clone()), Ok(())); }); }) } @@ -607,9 +586,9 @@ fn verification_should_be_stateless() { let mut ext = new_test_ext(); let (root_6, root_7) = ext.execute_with(|| { add_blocks(6); - let root_6 = crate::Pallet::::mmr_root_hash(); + let root_6 = RootHash::::get(); add_blocks(1); - let root_7 = crate::Pallet::::mmr_root_hash(); + let root_7 = RootHash::::get(); (root_6, root_7) }); ext.persist_offchain_overlay(); @@ -619,15 +598,15 @@ fn verification_should_be_stateless() { register_offchain_ext(&mut ext); let (leaves, proof5) = ext.execute_with(|| { // when - crate::Pallet::::generate_proof(vec![5], None).unwrap() + Mmr::::generate_proof(vec![5], None).unwrap() }); let (_, historical_proof5) = ext.execute_with(|| { // when - crate::Pallet::::generate_proof(vec![5], Some(6)).unwrap() + Mmr::::generate_proof(vec![5], Some(6)).unwrap() }); // Verify proof without relying on any on-chain data. - let leaf = crate::primitives::DataOrHash::Data(leaves[0].clone()); + let leaf = DataOrHash::Data(leaves[0].clone()); assert_eq!( crate::verify_leaves_proof::<::Hashing, _>( root_7, @@ -655,9 +634,9 @@ fn should_verify_batch_proof_statelessly() { let mut ext = new_test_ext(); let (root_6, root_7) = ext.execute_with(|| { add_blocks(6); - let root_6 = crate::Pallet::::mmr_root_hash(); + let root_6 = RootHash::::get(); add_blocks(1); - let root_7 = crate::Pallet::::mmr_root_hash(); + let root_7 = RootHash::::get(); (root_6, root_7) }); ext.persist_offchain_overlay(); @@ -667,21 +646,18 @@ fn should_verify_batch_proof_statelessly() { register_offchain_ext(&mut ext); let (leaves, proof) = ext.execute_with(|| { // when - crate::Pallet::::generate_proof(vec![1, 4, 5], None).unwrap() + Mmr::::generate_proof(vec![1, 4, 5], None).unwrap() }); let (historical_leaves, historical_proof) = ext.execute_with(|| { // when - crate::Pallet::::generate_proof(vec![1, 4, 5], Some(6)).unwrap() + Mmr::::generate_proof(vec![1, 4, 5], Some(6)).unwrap() }); // Verify proof without relying on any on-chain data. assert_eq!( crate::verify_leaves_proof::<::Hashing, _>( root_7, - leaves - .into_iter() - .map(|leaf| crate::primitives::DataOrHash::Data(leaf)) - .collect(), + leaves.into_iter().map(|leaf| DataOrHash::Data(leaf)).collect(), proof ), Ok(()) @@ -689,10 +665,7 @@ fn should_verify_batch_proof_statelessly() { assert_eq!( crate::verify_leaves_proof::<::Hashing, _>( root_6, - historical_leaves - .into_iter() - .map(|leaf| crate::primitives::DataOrHash::Data(leaf)) - .collect(), + historical_leaves.into_iter().map(|leaf| DataOrHash::Data(leaf)).collect(), historical_proof ), Ok(()) @@ -711,11 +684,11 @@ fn should_verify_on_the_next_block_since_there_is_no_pruning_yet() { ext.execute_with(|| { // when - let (leaves, proof5) = crate::Pallet::::generate_proof(vec![5], None).unwrap(); + let (leaves, proof5) = Mmr::::generate_proof(vec![5], None).unwrap(); new_block(); // then - assert_eq!(crate::Pallet::::verify_leaves(leaves, proof5), Ok(())); + assert_eq!(Mmr::::verify_leaves(leaves, proof5), Ok(())); }); } @@ -743,20 +716,19 @@ fn should_verify_canonicalized() { // Generate proofs for some blocks. let (leaves, proofs) = - ext.execute_with(|| crate::Pallet::::generate_proof(vec![1, 4, 5, 7], None).unwrap()); + ext.execute_with(|| Mmr::::generate_proof(vec![1, 4, 5, 7], None).unwrap()); // Verify all previously generated proofs. ext.execute_with(|| { - assert_eq!(crate::Pallet::::verify_leaves(leaves, proofs), Ok(())); + assert_eq!(Mmr::::verify_leaves(leaves, proofs), Ok(())); }); // Generate proofs for some new blocks. - let (leaves, proofs) = ext.execute_with(|| { - crate::Pallet::::generate_proof(vec![block_hash_size + 7], None).unwrap() - }); + let (leaves, proofs) = + ext.execute_with(|| Mmr::::generate_proof(vec![block_hash_size + 7], None).unwrap()); // Add some more blocks then verify all previously generated proofs. ext.execute_with(|| { add_blocks(7); - assert_eq!(crate::Pallet::::verify_leaves(leaves, proofs), Ok(())); + assert_eq!(Mmr::::verify_leaves(leaves, proofs), Ok(())); }); } @@ -774,18 +746,12 @@ fn does_not_panic_when_generating_historical_proofs() { register_offchain_ext(&mut ext); ext.execute_with(|| { // when leaf index is invalid - assert_eq!(crate::Pallet::::generate_proof(vec![10], None), Err(Error::LeafNotFound),); + assert_eq!(Mmr::::generate_proof(vec![10], None), Err(Error::LeafNotFound),); // when leaves count is invalid - assert_eq!( - crate::Pallet::::generate_proof(vec![3], Some(100)), - Err(Error::GenerateProof), - ); + assert_eq!(Mmr::::generate_proof(vec![3], Some(100)), Err(Error::GenerateProof),); // when both leaf index and leaves count are invalid - assert_eq!( - crate::Pallet::::generate_proof(vec![10], Some(100)), - Err(Error::LeafNotFound), - ); + assert_eq!(Mmr::::generate_proof(vec![10], Some(100)), Err(Error::LeafNotFound),); }); } diff --git a/frame/nomination-pools/test-staking/src/lib.rs b/frame/nomination-pools/test-staking/src/lib.rs index 933e42578d1a6..7e90cfb5d6786 100644 --- a/frame/nomination-pools/test-staking/src/lib.rs +++ b/frame/nomination-pools/test-staking/src/lib.rs @@ -32,7 +32,7 @@ use sp_runtime::traits::Zero; fn pool_lifecycle_e2e() { new_test_ext().execute_with(|| { assert_eq!(Balances::minimum_balance(), 5); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 50, 10, 10, 10)); @@ -196,7 +196,7 @@ fn pool_slash_e2e() { new_test_ext().execute_with(|| { ExistentialDeposit::set(1); assert_eq!(Balances::minimum_balance(), 1); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); @@ -403,7 +403,7 @@ fn pool_slash_proportional() { ExistentialDeposit::set(1); BondingDuration::set(28); assert_eq!(Balances::minimum_balance(), 1); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); @@ -540,7 +540,7 @@ fn pool_slash_non_proportional_only_bonded_pool() { ExistentialDeposit::set(1); BondingDuration::set(28); assert_eq!(Balances::minimum_balance(), 1); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); @@ -619,7 +619,7 @@ fn pool_slash_non_proportional_bonded_pool_and_chunks() { ExistentialDeposit::set(1); BondingDuration::set(28); assert_eq!(Balances::minimum_balance(), 1); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); diff --git a/frame/offences/benchmarking/src/lib.rs b/frame/offences/benchmarking/src/lib.rs index b71321906cbdd..e7c048d0af841 100644 --- a/frame/offences/benchmarking/src/lib.rs +++ b/frame/offences/benchmarking/src/lib.rs @@ -301,7 +301,7 @@ benchmarks! { Staking::::set_slash_reward_fraction(Perbill::one()); let (offenders, raw_offenders) = make_offenders_im_online::(o, n)?; - let keys = ImOnline::::keys(); + let keys = ImOnline::::keys(); let validator_set_count = keys.len() as u32; let offenders_count = offenders.len() as u32; let offence = UnresponsivenessOffence { @@ -442,7 +442,7 @@ benchmarks! { Staking::::set_slash_reward_fraction(Perbill::one()); let (mut offenders, raw_offenders) = make_offenders::(1, n)?; - let keys = ImOnline::::keys(); + let keys = ImOnline::::keys(); let offence = BabeEquivocationOffence { slot: 0u64.into(), diff --git a/frame/recovery/src/lib.rs b/frame/recovery/src/lib.rs index 9c57ca79d2e47..e8876835d5df6 100644 --- a/frame/recovery/src/lib.rs +++ b/frame/recovery/src/lib.rs @@ -389,7 +389,7 @@ pub mod pallet { let who = ensure_signed(origin)?; let account = T::Lookup::lookup(account)?; // Check `who` is allowed to make a call on behalf of `account` - let target = Self::proxy(&who).ok_or(Error::::NotAllowed)?; + let target = Proxy::::get(&who).ok_or(Error::::NotAllowed)?; ensure!(target == account, Error::::NotAllowed); call.dispatch(frame_system::RawOrigin::Signed(account).into()) .map(|_| ()) @@ -547,10 +547,10 @@ pub mod pallet { let lost = T::Lookup::lookup(lost)?; let rescuer = T::Lookup::lookup(rescuer)?; // Get the recovery configuration for the lost account. - let recovery_config = Self::recovery_config(&lost).ok_or(Error::::NotRecoverable)?; + let recovery_config = Recoverable::::get(&lost).ok_or(Error::::NotRecoverable)?; // Get the active recovery process for the rescuer. let mut active_recovery = - Self::active_recovery(&lost, &rescuer).ok_or(Error::::NotStarted)?; + ActiveRecoveries::::get(&lost, &rescuer).ok_or(Error::::NotStarted)?; // Make sure the voter is a friend ensure!(Self::is_friend(&recovery_config.friends, &who), Error::::NotFriend); // Either insert the vouch, or return an error that the user already vouched. @@ -590,10 +590,10 @@ pub mod pallet { let account = T::Lookup::lookup(account)?; // Get the recovery configuration for the lost account let recovery_config = - Self::recovery_config(&account).ok_or(Error::::NotRecoverable)?; + Recoverable::::get(&account).ok_or(Error::::NotRecoverable)?; // Get the active recovery process for the rescuer let active_recovery = - Self::active_recovery(&account, &who).ok_or(Error::::NotStarted)?; + ActiveRecoveries::::get(&account, &who).ok_or(Error::::NotStarted)?; ensure!(!Proxy::::contains_key(&who), Error::::AlreadyProxy); // Make sure the delay period has passed let current_block_number = >::block_number(); @@ -698,7 +698,7 @@ pub mod pallet { let who = ensure_signed(origin)?; let account = T::Lookup::lookup(account)?; // Check `who` is allowed to make a call on behalf of `account` - ensure!(Self::proxy(&who) == Some(account), Error::::NotAllowed); + ensure!(Proxy::::get(&who) == Some(account), Error::::NotAllowed); Proxy::::remove(&who); frame_system::Pallet::::dec_consumers(&who); diff --git a/frame/recovery/src/tests.rs b/frame/recovery/src/tests.rs index b037a8110147d..85a4390af7fb0 100644 --- a/frame/recovery/src/tests.rs +++ b/frame/recovery/src/tests.rs @@ -29,9 +29,9 @@ use sp_runtime::traits::BadOrigin; fn basic_setup_works() { new_test_ext().execute_with(|| { // Nothing in storage to start - assert_eq!(Recovery::proxy(&2), None); - assert_eq!(Recovery::active_recovery(&1, &2), None); - assert_eq!(Recovery::recovery_config(&1), None); + assert_eq!(Proxy::::get(&2), None); + assert_eq!(ActiveRecoveries::::get(&1, &2), None); + assert_eq!(Recoverable::::get(&1), None); // Everyone should have starting balance of 100 assert_eq!(Balances::free_balance(1), 100); }); @@ -238,7 +238,7 @@ fn create_recovery_works() { friends: friends.try_into().unwrap(), threshold, }; - assert_eq!(Recovery::recovery_config(5), Some(recovery_config)); + assert_eq!(Recoverable::::get(5), Some(recovery_config)); }); } diff --git a/frame/root-offences/src/lib.rs b/frame/root-offences/src/lib.rs index ed039f46becc8..07611f379441a 100644 --- a/frame/root-offences/src/lib.rs +++ b/frame/root-offences/src/lib.rs @@ -28,7 +28,7 @@ mod mock; mod tests; use pallet_session::historical::IdentificationTuple; -use pallet_staking::{BalanceOf, Exposure, ExposureOf, Pallet as Staking}; +use pallet_staking::{BalanceOf, Exposure, ExposureOf}; use sp_runtime::Perbill; use sp_staking::offence::{DisableStrategy, OnOffenceHandler}; @@ -104,7 +104,7 @@ pub mod pallet { fn get_offence_details( offenders: Vec<(T::AccountId, Perbill)>, ) -> Result>, DispatchError> { - let now = Staking::::active_era() + let now = pallet_staking::ActiveEra::::get() .map(|e| e.index) .ok_or(Error::::FailedToGetActiveEra)?; @@ -112,7 +112,7 @@ pub mod pallet { .clone() .into_iter() .map(|(o, _)| OffenceDetails:: { - offender: (o.clone(), Staking::::eras_stakers(now, o)), + offender: (o.clone(), pallet_staking::ErasStakers::::get(now, o)), reporters: vec![], }) .collect()) diff --git a/frame/root-offences/src/mock.rs b/frame/root-offences/src/mock.rs index 273fbf614169d..476bb4b33a18d 100644 --- a/frame/root-offences/src/mock.rs +++ b/frame/root-offences/src/mock.rs @@ -323,10 +323,10 @@ pub(crate) fn start_session(session_index: SessionIndex) { run_to_block(end); // session must have progressed properly. assert_eq!( - Session::current_index(), + pallet_session::CurrentIndex::::get(), session_index, "current session index = {}, expected = {}", - Session::current_index(), + pallet_session::CurrentIndex::::get(), session_index, ); } @@ -350,5 +350,5 @@ pub(crate) fn run_to_block(n: BlockNumber) { } pub(crate) fn active_era() -> EraIndex { - Staking::active_era().unwrap().index + pallet_staking::ActiveEra::::get().unwrap().index } diff --git a/frame/scored-pool/src/mock.rs b/frame/scored-pool/src/mock.rs index 951871dd83c5c..2a421d217b790 100644 --- a/frame/scored-pool/src/mock.rs +++ b/frame/scored-pool/src/mock.rs @@ -159,11 +159,11 @@ pub fn new_test_ext() -> sp_io::TestExternalities { /// Fetch an entity from the pool, if existent. pub fn fetch_from_pool(who: u64) -> Option<(u64, Option)> { - >::pool().into_iter().find(|item| item.0 == who) + >::get().into_iter().find(|item| item.0 == who) } /// Find an entity in the pool. /// Returns its position in the `Pool` vec, if existent. pub fn find_in_pool(who: u64) -> Option { - >::pool().into_iter().position(|item| item.0 == who) + >::get().into_iter().position(|item| item.0 == who) } diff --git a/frame/scored-pool/src/tests.rs b/frame/scored-pool/src/tests.rs index 8f4daff47cc44..6538935825c6e 100644 --- a/frame/scored-pool/src/tests.rs +++ b/frame/scored-pool/src/tests.rs @@ -30,7 +30,7 @@ type Balances = pallet_balances::Pallet; #[test] fn query_membership_works() { new_test_ext().execute_with(|| { - assert_eq!(ScoredPool::members(), vec![20, 40]); + assert_eq!(Members::::get(), vec![20, 40]); assert_eq!(Balances::reserved_balance(31), CandidateDeposit::get()); assert_eq!(Balances::reserved_balance(40), CandidateDeposit::get()); assert_eq!(MembersTestValue::get().clone(), vec![20, 40]); @@ -127,8 +127,8 @@ fn kicking_works() { // then assert_eq!(find_in_pool(who), None); - assert_eq!(ScoredPool::members(), vec![20, 31]); - assert_eq!(MembersTestValue::get().clone(), ScoredPool::members()); + assert_eq!(Members::::get(), vec![20, 31]); + assert_eq!(MembersTestValue::get().clone(), Members::::get()); assert_eq!(Balances::reserved_balance(who), 0); // deposit must have been returned }); } @@ -142,7 +142,7 @@ fn unscored_entities_must_not_be_used_for_filling_members() { // when // we remove every scored member - ScoredPool::pool().into_iter().for_each(|(who, score)| { + Pool::::get().into_iter().for_each(|(who, score)| { if let Some(_) = score { let index = find_in_pool(who).expect("entity must be in pool") as u32; assert_ok!(ScoredPool::kick(RuntimeOrigin::signed(KickOrigin::get()), who, index)); @@ -151,8 +151,8 @@ fn unscored_entities_must_not_be_used_for_filling_members() { // then // the `None` candidates should not have been filled in - assert!(ScoredPool::members().is_empty()); - assert_eq!(MembersTestValue::get().clone(), ScoredPool::members()); + assert!(Members::::get().is_empty()); + assert_eq!(MembersTestValue::get().clone(), Members::::get()); }); } @@ -166,11 +166,11 @@ fn refreshing_works() { assert_ok!(ScoredPool::score(RuntimeOrigin::signed(ScoreOrigin::get()), who, index, 99)); // when - ScoredPool::refresh_members(ScoredPool::pool(), ChangeReceiver::MembershipChanged); + ScoredPool::refresh_members(Pool::::get(), ChangeReceiver::MembershipChanged); // then - assert_eq!(ScoredPool::members(), vec![15, 40]); - assert_eq!(MembersTestValue::get().clone(), ScoredPool::members()); + assert_eq!(Members::::get(), vec![15, 40]); + assert_eq!(MembersTestValue::get().clone(), Members::::get()); }); } @@ -182,15 +182,15 @@ fn refreshing_happens_every_period() { assert_ok!(ScoredPool::submit_candidacy(RuntimeOrigin::signed(15))); let index = find_in_pool(15).expect("entity must be in pool") as u32; assert_ok!(ScoredPool::score(RuntimeOrigin::signed(ScoreOrigin::get()), 15, index, 99)); - assert_eq!(ScoredPool::members(), vec![20, 40]); + assert_eq!(Members::::get(), vec![20, 40]); // when System::set_block_number(4); ScoredPool::on_initialize(4); // then - assert_eq!(ScoredPool::members(), vec![15, 40]); - assert_eq!(MembersTestValue::get().clone(), ScoredPool::members()); + assert_eq!(Members::::get(), vec![15, 40]); + assert_eq!(MembersTestValue::get().clone(), Members::::get()); }); } @@ -210,7 +210,7 @@ fn withdraw_candidacy_must_only_work_for_members() { fn oob_index_should_abort() { new_test_ext().execute_with(|| { let who = 40; - let oob_index = ScoredPool::pool().len() as u32; + let oob_index = Pool::::get().len() as u32; assert_noop!( ScoredPool::withdraw_candidacy(RuntimeOrigin::signed(who), oob_index), Error::::InvalidIndex @@ -274,7 +274,7 @@ fn withdraw_scored_candidacy_must_work() { // then assert_eq!(fetch_from_pool(who), None); - assert_eq!(ScoredPool::members(), vec![20, 31]); + assert_eq!(Members::::get(), vec![20, 31]); assert_eq!(Balances::reserved_balance(who), 0); }); } @@ -287,14 +287,14 @@ fn candidacy_resubmitting_works() { // when assert_ok!(ScoredPool::submit_candidacy(RuntimeOrigin::signed(who))); - assert_eq!(ScoredPool::candidate_exists(who), true); + assert_eq!(CandidateExists::::get(who), true); let index = find_in_pool(who).expect("entity must be in pool") as u32; assert_ok!(ScoredPool::withdraw_candidacy(RuntimeOrigin::signed(who), index)); - assert_eq!(ScoredPool::candidate_exists(who), false); + assert_eq!(CandidateExists::::get(who), false); assert_ok!(ScoredPool::submit_candidacy(RuntimeOrigin::signed(who))); // then - assert_eq!(ScoredPool::candidate_exists(who), true); + assert_eq!(CandidateExists::::get(who), true); }); } diff --git a/frame/session/README.md b/frame/session/README.md index 09132470d4433..755cc14aeac3a 100644 --- a/frame/session/README.md +++ b/frame/session/README.md @@ -69,10 +69,8 @@ for next session rotation. The [Staking pallet](https://docs.rs/pallet-staking/latest/pallet_staking/) uses the Session pallet to get the validator set. ```rust -use pallet_session as session; - fn validators() -> Vec<::ValidatorId> { - >::validators() + pallet_session::Validators::::get() } ``` diff --git a/frame/session/benchmarking/src/lib.rs b/frame/session/benchmarking/src/lib.rs index a6c25f5e10549..d32af7be2171f 100644 --- a/frame/session/benchmarking/src/lib.rs +++ b/frame/session/benchmarking/src/lib.rs @@ -61,7 +61,7 @@ benchmarks! { false, RewardDestination::Staked, )?; - let v_controller = pallet_staking::Pallet::::bonded(&v_stash).ok_or("not stash")?; + let v_controller = pallet_staking::Bonded::::get(&v_stash).ok_or("not stash")?; let keys = T::Keys::decode(&mut TrailingZeroInput::zeroes()).unwrap(); let proof: Vec = vec![0,1,2,3]; @@ -78,7 +78,7 @@ benchmarks! { false, RewardDestination::Staked )?; - let v_controller = pallet_staking::Pallet::::bonded(&v_stash).ok_or("not stash")?; + let v_controller = pallet_staking::Bonded::::get(&v_stash).ok_or("not stash")?; let keys = T::Keys::decode(&mut TrailingZeroInput::zeroes()).unwrap(); let proof: Vec = vec![0,1,2,3]; Session::::set_keys(RawOrigin::Signed(v_controller.clone()).into(), keys, proof)?; @@ -134,7 +134,7 @@ fn check_membership_proof_setup( use rand::{RngCore, SeedableRng}; let validator = T::Lookup::lookup(who).unwrap(); - let controller = pallet_staking::Pallet::::bonded(validator).unwrap(); + let controller = pallet_staking::Bonded::::get(validator).unwrap(); let keys = { let mut keys = [0u8; 128]; @@ -157,7 +157,7 @@ fn check_membership_proof_setup( Pallet::::on_initialize(T::BlockNumber::one()); // skip sessions until the new validator set is enacted - while Session::::validators().len() < n as usize { + while Validators::::get().len() < n as usize { Session::::rotate_session(); } diff --git a/frame/session/src/historical/mod.rs b/frame/session/src/historical/mod.rs index 45b4ba3c0a799..274ae3aec4969 100644 --- a/frame/session/src/historical/mod.rs +++ b/frame/session/src/historical/mod.rs @@ -49,7 +49,7 @@ use frame_support::{ Parameter, }; -use crate::{self as pallet_session, Pallet as Session}; +use crate::{self as pallet_session, CurrentIndex, Pallet as Session, Validators}; pub use pallet::*; @@ -84,7 +84,6 @@ pub mod pallet { /// Mapping from historical session indices to session-data root hash and validator count. #[pallet::storage] - #[pallet::getter(fn historical_root)] pub type HistoricalSessions = StorageMap<_, Twox64Concat, SessionIndex, (T::Hash, ValidatorCount), OptionQuery>; @@ -126,11 +125,11 @@ impl ValidatorSet for Pallet { type ValidatorIdOf = T::ValidatorIdOf; fn session_index() -> sp_staking::SessionIndex { - super::Pallet::::current_index() + CurrentIndex::::get() } fn validators() -> Vec { - super::Pallet::::validators() + Validators::::get() } } @@ -322,8 +321,8 @@ impl> KeyOwnerProofSystem<(KeyTypeId, D)> for Pallet; fn prove(key: (KeyTypeId, D)) -> Option { - let session = >::current_index(); - let validators = >::validators() + let session = CurrentIndex::::get(); + let validators = Validators::::get() .into_iter() .filter_map(|validator| { T::FullIdentificationOf::convert(validator.clone()) @@ -346,10 +345,10 @@ impl> KeyOwnerProofSystem<(KeyTypeId, D)> for Pallet Option> { let (id, data) = key; - if proof.session == >::current_index() { + if proof.session == CurrentIndex::::get() { >::key_owner(id, data.as_ref()).and_then(|owner| { T::FullIdentificationOf::convert(owner.clone()).and_then(move |id| { - let count = >::validators().len() as ValidatorCount; + let count = Validators::::get().len() as ValidatorCount; if count != proof.validator_count { return None @@ -374,8 +373,9 @@ impl> KeyOwnerProofSystem<(KeyTypeId, D)> for Pallet proof.session); + assert!(HistoricalSessions::::get(proof.session).is_some()); + assert!(CurrentIndex::::get() > proof.session); // proof-checking in the next session is also OK. assert!(Historical::check_proof((DUMMY, &encoded_key_1[..]), proof.clone()).is_some()); @@ -454,7 +454,7 @@ pub(crate) mod tests { assert_eq!(>::get(), Some((0, 100))); for i in 0..100 { - assert!(Historical::historical_root(i).is_some()) + assert!(HistoricalSessions::::get(i).is_some()) } Historical::prune_up_to(10); @@ -464,7 +464,7 @@ pub(crate) mod tests { assert_eq!(>::get(), Some((10, 100))); for i in 10..100 { - assert!(Historical::historical_root(i).is_some()) + assert!(HistoricalSessions::::get(i).is_some()) } Historical::prune_up_to(99); @@ -484,14 +484,14 @@ pub(crate) mod tests { assert_eq!(>::get(), Some((100, 200))); for i in 100..200 { - assert!(Historical::historical_root(i).is_some()) + assert!(HistoricalSessions::::get(i).is_some()) } Historical::prune_up_to(9999); assert_eq!(>::get(), None); for i in 100..200 { - assert!(Historical::historical_root(i).is_none()) + assert!(HistoricalSessions::::get(i).is_none()) } }); } diff --git a/frame/session/src/historical/offchain.rs b/frame/session/src/historical/offchain.rs index ececb8af5ad58..31cb83bca9dc6 100644 --- a/frame/session/src/historical/offchain.rs +++ b/frame/session/src/historical/offchain.rs @@ -33,7 +33,7 @@ use sp_session::MembershipProof; use sp_std::prelude::*; use super::{shared, Config, IdentificationTuple, ProvingTrie}; -use crate::{Pallet as SessionModule, SessionIndex}; +use crate::{CurrentIndex, SessionIndex}; /// A set of validators, which was used for a fixed session index. struct ValidatorSet { @@ -129,7 +129,7 @@ pub fn prune_older_than(first_to_keep: SessionIndex) { /// Keep the newest `n` items, and prune all items older than that. pub fn keep_newest(n_to_keep: usize) { - let session_index = >::current_index(); + let session_index = CurrentIndex::::get(); let n_to_keep = n_to_keep as SessionIndex; if n_to_keep < session_index { prune_older_than::(session_index - n_to_keep) @@ -239,7 +239,7 @@ mod tests { // "on-chain" onchain::store_current_session_validator_set_to_offchain::(); - assert_eq!(>::current_index(), 1); + assert_eq!(CurrentIndex::::get(), 1); set_next_validators(vec![7, 8]); @@ -251,7 +251,7 @@ mod tests { ext.execute_with(|| { System::set_block_number(2); Session::on_initialize(2); - assert_eq!(>::current_index(), 2); + assert_eq!(CurrentIndex::::get(), 2); // "off-chain" let proof = prove_session_membership::(1, (DUMMY, &encoded_key_1)); diff --git a/frame/session/src/historical/onchain.rs b/frame/session/src/historical/onchain.rs index c7160e2fcf531..54558622f6e2d 100644 --- a/frame/session/src/historical/onchain.rs +++ b/frame/session/src/historical/onchain.rs @@ -22,7 +22,7 @@ use sp_runtime::traits::Convert; use sp_std::prelude::*; use super::{shared, Config as HistoricalConfig}; -use crate::{Config as SessionConfig, Pallet as SessionModule, SessionIndex}; +use crate::{Config as SessionConfig, CurrentIndex, SessionIndex, Validators}; /// Store the validator-set associated to the `session_index` to the off-chain database. /// @@ -35,7 +35,7 @@ use crate::{Config as SessionConfig, Pallet as SessionModule, SessionIndex}; pub fn store_session_validator_set_to_offchain( session_index: SessionIndex, ) { - let encoded_validator_list = >::validators() + let encoded_validator_list = Validators::::get() .into_iter() .filter_map(|validator_id: ::ValidatorId| { let full_identification = @@ -55,5 +55,5 @@ pub fn store_session_validator_set_to_offchain() { - store_session_validator_set_to_offchain::(>::current_index()); + store_session_validator_set_to_offchain::(CurrentIndex::::get()); } diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index 38a5c0f57f73c..4be33efeb7bb5 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -92,10 +92,8 @@ //! set. //! //! ``` -//! use pallet_session as session; -//! //! fn validators() -> Vec<::ValidatorId> { -//! >::validators() +//! pallet_session::Validators::::get() //! } //! # fn main(){} //! ``` @@ -730,7 +728,7 @@ impl Pallet { /// Returns `false` either if the validator could not be found or it was already /// disabled. pub fn disable(c: &T::ValidatorId) -> bool { - Self::validators() + Validators::::get() .iter() .position(|i| i == c) .map(|i| Self::disable_index(i as u32)) @@ -900,11 +898,11 @@ impl ValidatorSet for Pallet { type ValidatorIdOf = T::ValidatorIdOf; fn session_index() -> sp_staking::SessionIndex { - Pallet::::current_index() + CurrentIndex::::get() } fn validators() -> Vec { - Pallet::::validators() + Validators::::get() } } @@ -922,7 +920,7 @@ impl EstimateNextNewSession for Pallet { impl frame_support::traits::DisabledValidators for Pallet { fn is_disabled(index: u32) -> bool { - >::disabled_validators().binary_search(&index).is_ok() + DisabledValidators::::get().binary_search(&index).is_ok() } } @@ -940,7 +938,7 @@ impl> FindAuthor { let i = Inner::find_author(digests)?; - let validators = >::validators(); + let validators = Validators::::get(); validators.get(i as usize).cloned() } } diff --git a/frame/session/src/tests.rs b/frame/session/src/tests.rs index 43809cc3a9de0..5e256b8de98ab 100644 --- a/frame/session/src/tests.rs +++ b/frame/session/src/tests.rs @@ -44,7 +44,7 @@ fn initialize_block(block: u64) { fn simple_setup_should_work() { new_test_ext().execute_with(|| { assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]); - assert_eq!(Session::validators(), vec![1, 2, 3]); + assert_eq!(Validators::::get(), vec![1, 2, 3]); }); } @@ -60,7 +60,7 @@ fn put_get_keys() { fn keys_cleared_on_kill() { let mut ext = new_test_ext(); ext.execute_with(|| { - assert_eq!(Session::validators(), vec![1, 2, 3]); + assert_eq!(Validators::::get(), vec![1, 2, 3]); assert_eq!(Session::load_keys(&1), Some(UintAuthorityId(1).into())); let id = DUMMY; @@ -79,7 +79,7 @@ fn keys_cleared_on_kill() { fn purge_keys_works_for_stash_id() { let mut ext = new_test_ext(); ext.execute_with(|| { - assert_eq!(Session::validators(), vec![1, 2, 3]); + assert_eq!(Validators::::get(), vec![1, 2, 3]); TestValidatorIdOf::set(vec![(10, 1), (20, 2), (3, 3)].into_iter().collect()); assert_eq!(Session::load_keys(&1), Some(UintAuthorityId(1).into())); assert_eq!(Session::load_keys(&2), Some(UintAuthorityId(2).into())); @@ -108,10 +108,10 @@ fn authorities_should_track_validators() { force_new_session(); initialize_block(1); assert_eq!( - Session::queued_keys(), + QueuedKeys::::get(), vec![(1, UintAuthorityId(1).into()), (2, UintAuthorityId(2).into()),] ); - assert_eq!(Session::validators(), vec![1, 2, 3]); + assert_eq!(Validators::::get(), vec![1, 2, 3]); assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]); assert!(before_session_end_called()); reset_before_session_end_called(); @@ -119,10 +119,10 @@ fn authorities_should_track_validators() { force_new_session(); initialize_block(2); assert_eq!( - Session::queued_keys(), + QueuedKeys::::get(), vec![(1, UintAuthorityId(1).into()), (2, UintAuthorityId(2).into()),] ); - assert_eq!(Session::validators(), vec![1, 2]); + assert_eq!(Validators::::get(), vec![1, 2]); assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2)]); assert!(before_session_end_called()); reset_before_session_end_called(); @@ -132,28 +132,28 @@ fn authorities_should_track_validators() { force_new_session(); initialize_block(3); assert_eq!( - Session::queued_keys(), + QueuedKeys::::get(), vec![ (1, UintAuthorityId(1).into()), (2, UintAuthorityId(2).into()), (4, UintAuthorityId(4).into()), ] ); - assert_eq!(Session::validators(), vec![1, 2]); + assert_eq!(Validators::::get(), vec![1, 2]); assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2)]); assert!(before_session_end_called()); force_new_session(); initialize_block(4); assert_eq!( - Session::queued_keys(), + QueuedKeys::::get(), vec![ (1, UintAuthorityId(1).into()), (2, UintAuthorityId(2).into()), (4, UintAuthorityId(4).into()), ] ); - assert_eq!(Session::validators(), vec![1, 2, 4]); + assert_eq!(Validators::::get(), vec![1, 2, 4]); assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(4)]); }); } @@ -164,20 +164,20 @@ fn should_work_with_early_exit() { set_session_length(10); initialize_block(1); - assert_eq!(Session::current_index(), 0); + assert_eq!(CurrentIndex::::get(), 0); initialize_block(2); - assert_eq!(Session::current_index(), 0); + assert_eq!(CurrentIndex::::get(), 0); force_new_session(); initialize_block(3); - assert_eq!(Session::current_index(), 1); + assert_eq!(CurrentIndex::::get(), 1); initialize_block(9); - assert_eq!(Session::current_index(), 1); + assert_eq!(CurrentIndex::::get(), 1); initialize_block(10); - assert_eq!(Session::current_index(), 2); + assert_eq!(CurrentIndex::::get(), 2); }); } @@ -446,7 +446,7 @@ fn upgrade_keys() { // Check queued keys. assert_eq!( - Session::queued_keys(), + QueuedKeys::::get(), vec![(1, mock_keys_for(1)), (2, mock_keys_for(2)), (3, mock_keys_for(3)),], ); diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index 4e83d938b2e2d..f2d134a4a9062 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -834,7 +834,7 @@ pub mod pallet { pub fn unvouch(origin: OriginFor, pos: u32) -> DispatchResult { let voucher = ensure_signed(origin)?; ensure!( - Self::vouching(&voucher) == Some(VouchingStatus::Vouching), + Vouching::::get(&voucher) == Some(VouchingStatus::Vouching), Error::::NotVouching ); @@ -1106,7 +1106,7 @@ pub mod pallet { Judgement::Approve => { // Suspension Judgement origin has approved this candidate // Make sure we can pay them - let pot = Self::pot(); + let pot = Pot::::get(); ensure!(pot >= value, Error::::InsufficientPot); // Try to add user as a member! Can fail with `MaxMember` limit. Self::add_member(&who)?; @@ -1114,7 +1114,7 @@ pub mod pallet { >::put(pot - value); // Add payout for new candidate let maturity = >::block_number() + - Self::lock_duration(Self::members().len() as u32); + Self::lock_duration(Members::::get().len() as u32); Self::pay_accepted_candidate(&who, value, kind, maturity); }, Judgement::Reject => { @@ -1179,7 +1179,7 @@ pub struct EnsureFounder(sp_std::marker::PhantomData); impl EnsureOrigin for EnsureFounder { type Success = T::AccountId; fn try_origin(o: T::RuntimeOrigin) -> Result { - o.into().and_then(|o| match (o, Founder::::get()) { + o.into().and_then(|o| match (o, Founder::::get()) { (frame_system::RawOrigin::Signed(ref who), Some(ref f)) if who == f => Ok(who.clone()), (r, _) => Err(T::RuntimeOrigin::from(r)), }) @@ -1187,7 +1187,7 @@ impl EnsureOrigin for EnsureFounder { #[cfg(feature = "runtime-benchmarks")] fn try_successful_origin() -> Result { - let founder = Founder::::get().ok_or(())?; + let founder = Founder::::get().ok_or(())?; Ok(T::RuntimeOrigin::from(frame_system::RawOrigin::Signed(founder))) } } @@ -1303,8 +1303,8 @@ impl, I: 'static> Pallet { /// NOTE: This does not correctly clean up a member from storage. It simply /// removes them from the Members storage item. pub fn remove_member(m: &T::AccountId) -> DispatchResult { - ensure!(Self::head() != Some(m.clone()), Error::::Head); - ensure!(Self::founder() != Some(m.clone()), Error::::Founder); + ensure!(Head::::get() != Some(m.clone()), Error::::Head); + ensure!(Founder::::get() != Some(m.clone()), Error::::Founder); let mut members = >::get(); match members.binary_search(m) { @@ -1597,7 +1597,7 @@ impl, I: 'static> Pallet { // Assume there are members, else don't run this logic. if !members.is_empty() { // End current defender rotation - if let Some(defender) = Self::defender() { + if let Some(defender) = Defender::::get() { let mut approval_count = 0; let mut rejection_count = 0; // Tallies total number of approve and reject votes for the defender. @@ -1609,7 +1609,7 @@ impl, I: 'static> Pallet { if approval_count <= rejection_count { // User has failed the challenge Self::suspend_member(&defender); - *members = Self::members(); + *members = Members::::get(); } // Clean up all votes. diff --git a/frame/society/src/tests.rs b/frame/society/src/tests.rs index 0b42f77035776..49ff2d5e52733 100644 --- a/frame/society/src/tests.rs +++ b/frame/society/src/tests.rs @@ -28,27 +28,27 @@ use sp_runtime::traits::BadOrigin; fn founding_works() { EnvBuilder::new().with_max_members(0).with_members(vec![]).execute(|| { // Not set up initially. - assert_eq!(Society::founder(), None); - assert_eq!(Society::max_members(), 0); - assert_eq!(Society::pot(), 0); + assert_eq!(Founder::::get(), None); + assert_eq!(MaxMembers::::get(), 0); + assert_eq!(Pot::::get(), 0); // Account 1 is set as the founder origin // Account 5 cannot start a society assert_noop!(Society::found(RuntimeOrigin::signed(5), 20, 100, vec![]), BadOrigin); // Account 1 can start a society, where 10 is the founding member assert_ok!(Society::found(RuntimeOrigin::signed(1), 10, 100, b"be cool".to_vec())); // Society members only include 10 - assert_eq!(Society::members(), vec![10]); + assert_eq!(Members::::get(), vec![10]); // 10 is the head of the society - assert_eq!(Society::head(), Some(10)); + assert_eq!(Head::::get(), Some(10)); // ...and also the founder - assert_eq!(Society::founder(), Some(10)); + assert_eq!(Founder::::get(), Some(10)); // 100 members max - assert_eq!(Society::max_members(), 100); + assert_eq!(MaxMembers::::get(), 100); // rules are correct - assert_eq!(Society::rules(), Some(blake2_256(b"be cool").into())); + assert_eq!(Rules::::get(), Some(blake2_256(b"be cool").into())); // Pot grows after first rotation period run_to_block(4); - assert_eq!(Society::pot(), 1000); + assert_eq!(Pot::::get(), 1000); // Cannot start another society assert_noop!( Society::found(RuntimeOrigin::signed(1), 20, 100, vec![]), @@ -91,13 +91,13 @@ fn basic_new_member_works() { // Rotate period every 4 blocks run_to_block(4); // 20 is now a candidate - assert_eq!(Society::candidates(), vec![create_bid(0, 20, BidKind::Deposit(25))]); + assert_eq!(Candidates::::get(), vec![create_bid(0, 20, BidKind::Deposit(25))]); // 10 (a member) can vote for the candidate assert_ok!(Society::vote(RuntimeOrigin::signed(10), 20, true)); // Rotate period every 4 blocks run_to_block(8); // 20 is now a member of the society - assert_eq!(Society::members(), vec![10, 20]); + assert_eq!(Members::::get(), vec![10, 20]); // Reserved balance is returned assert_eq!(Balances::free_balance(20), 50); assert_eq!(Balances::reserved_balance(20), 0); @@ -115,11 +115,11 @@ fn bidding_works() { // Rotate period run_to_block(4); // Pot is 1000 after "PeriodSpend" - assert_eq!(Society::pot(), 1000); + assert_eq!(Pot::::get(), 1000); assert_eq!(Balances::free_balance(Society::account_id()), 10_000); // Choose smallest bidding users whose total is less than pot assert_eq!( - Society::candidates(), + Candidates::::get(), vec![ create_bid(300, 30, BidKind::Deposit(25)), create_bid(400, 40, BidKind::Deposit(25)), @@ -130,40 +130,40 @@ fn bidding_works() { assert_ok!(Society::vote(RuntimeOrigin::signed(10), 40, true)); run_to_block(8); // Candidates become members after a period rotation - assert_eq!(Society::members(), vec![10, 30, 40]); + assert_eq!(Members::::get(), vec![10, 30, 40]); // Pot is increased by 1000, but pays out 700 to the members assert_eq!(Balances::free_balance(Society::account_id()), 9_300); - assert_eq!(Society::pot(), 1_300); + assert_eq!(Pot::::get(), 1_300); // Left over from the original bids is 50 who satisfies the condition of bid less than pot. - assert_eq!(Society::candidates(), vec![create_bid(500, 50, BidKind::Deposit(25))]); + assert_eq!(Candidates::::get(), vec![create_bid(500, 50, BidKind::Deposit(25))]); // 40, now a member, can vote for 50 assert_ok!(Society::vote(RuntimeOrigin::signed(40), 50, true)); run_to_block(12); // 50 is now a member - assert_eq!(Society::members(), vec![10, 30, 40, 50]); + assert_eq!(Members::::get(), vec![10, 30, 40, 50]); // Pot is increased by 1000, and 500 is paid out. Total payout so far is 1200. - assert_eq!(Society::pot(), 1_800); + assert_eq!(Pot::::get(), 1_800); assert_eq!(Balances::free_balance(Society::account_id()), 8_800); // No more candidates satisfy the requirements - assert_eq!(Society::candidates(), vec![]); + assert_eq!(Candidates::::get(), vec![]); assert_ok!(Society::defender_vote(RuntimeOrigin::signed(10), true)); // Keep defender around // Next period run_to_block(16); // Same members - assert_eq!(Society::members(), vec![10, 30, 40, 50]); + assert_eq!(Members::::get(), vec![10, 30, 40, 50]); // Pot is increased by 1000 again - assert_eq!(Society::pot(), 2_800); + assert_eq!(Pot::::get(), 2_800); // No payouts assert_eq!(Balances::free_balance(Society::account_id()), 8_800); // Candidate 60 now qualifies based on the increased pot size. - assert_eq!(Society::candidates(), vec![create_bid(1900, 60, BidKind::Deposit(25))]); + assert_eq!(Candidates::::get(), vec![create_bid(1900, 60, BidKind::Deposit(25))]); // Candidate 60 is voted in. assert_ok!(Society::vote(RuntimeOrigin::signed(50), 60, true)); run_to_block(20); // 60 joins as a member - assert_eq!(Society::members(), vec![10, 30, 40, 50, 60]); + assert_eq!(Members::::get(), vec![10, 30, 40, 50, 60]); // Pay them - assert_eq!(Society::pot(), 1_900); + assert_eq!(Pot::::get(), 1_900); assert_eq!(Balances::free_balance(Society::account_id()), 6_900); }); } @@ -186,7 +186,7 @@ fn unbidding_works() { assert_eq!(Balances::reserved_balance(30), 0); // 20 wins candidacy run_to_block(4); - assert_eq!(Society::candidates(), vec![create_bid(1000, 20, BidKind::Deposit(25))]); + assert_eq!(Candidates::::get(), vec![create_bid(1000, 20, BidKind::Deposit(25))]); }); } @@ -217,9 +217,9 @@ fn basic_new_member_skeptic_works() { assert_eq!(Strikes::::get(10), 0); assert_ok!(Society::bid(RuntimeOrigin::signed(20), 0)); run_to_block(4); - assert_eq!(Society::candidates(), vec![create_bid(0, 20, BidKind::Deposit(25))]); + assert_eq!(Candidates::::get(), vec![create_bid(0, 20, BidKind::Deposit(25))]); run_to_block(8); - assert_eq!(Society::members(), vec![10]); + assert_eq!(Members::::get(), vec![10]); assert_eq!(Strikes::::get(10), 1); System::assert_last_event(mock::RuntimeEvent::Society(crate::Event::SkepticsChosen { @@ -239,15 +239,15 @@ fn basic_new_member_reject_works() { assert_eq!(Balances::reserved_balance(20), 25); // Rotation Period run_to_block(4); - assert_eq!(Society::candidates(), vec![create_bid(0, 20, BidKind::Deposit(25))]); + assert_eq!(Candidates::::get(), vec![create_bid(0, 20, BidKind::Deposit(25))]); // We say no assert_ok!(Society::vote(RuntimeOrigin::signed(10), 20, false)); run_to_block(8); // User is not added as member - assert_eq!(Society::members(), vec![10]); + assert_eq!(Members::::get(), vec![10]); // User is suspended - assert_eq!(Society::candidates(), vec![]); - assert_eq!(Society::suspended_candidate(20).is_some(), true); + assert_eq!(Candidates::::get(), vec![]); + assert_eq!(SuspendedCandidates::::get(20).is_some(), true); }); } @@ -352,15 +352,15 @@ fn suspended_candidate_rejected_works() { assert_eq!(Balances::reserved_balance(20), 25); // Rotation Period run_to_block(4); - assert_eq!(Society::candidates(), vec![create_bid(0, 20, BidKind::Deposit(25))]); + assert_eq!(Candidates::::get(), vec![create_bid(0, 20, BidKind::Deposit(25))]); // We say no assert_ok!(Society::vote(RuntimeOrigin::signed(10), 20, false)); run_to_block(8); // User is not added as member - assert_eq!(Society::members(), vec![10]); + assert_eq!(Members::::get(), vec![10]); // User is suspended - assert_eq!(Society::candidates(), vec![]); - assert_eq!(Society::suspended_candidate(20).is_some(), true); + assert_eq!(Candidates::::get(), vec![]); + assert_eq!(SuspendedCandidates::::get(20).is_some(), true); // Normal user cannot make judgement on suspended candidate assert_noop!( @@ -377,15 +377,15 @@ fn suspended_candidate_rejected_works() { // They are placed back in bid pool, repeat suspension process // Rotation Period run_to_block(12); - assert_eq!(Society::candidates(), vec![create_bid(0, 20, BidKind::Deposit(25))]); + assert_eq!(Candidates::::get(), vec![create_bid(0, 20, BidKind::Deposit(25))]); // We say no assert_ok!(Society::vote(RuntimeOrigin::signed(10), 20, false)); run_to_block(16); // User is not added as member - assert_eq!(Society::members(), vec![10]); + assert_eq!(Members::::get(), vec![10]); // User is suspended - assert_eq!(Society::candidates(), vec![]); - assert_eq!(Society::suspended_candidate(20).is_some(), true); + assert_eq!(Candidates::::get(), vec![]); + assert_eq!(SuspendedCandidates::::get(20).is_some(), true); // Suspension judgement origin rejects the candidate assert_ok!(Society::judge_suspended_candidate( @@ -399,7 +399,7 @@ fn suspended_candidate_rejected_works() { // Funds are deposited to society account assert_eq!(Balances::free_balance(Society::account_id()), 10025); // Cleaned up - assert_eq!(Society::candidates(), vec![]); + assert_eq!(Candidates::::get(), vec![]); assert_eq!(>::get(20), None); }); } @@ -408,7 +408,7 @@ fn suspended_candidate_rejected_works() { fn vouch_works() { EnvBuilder::new().execute(|| { // 10 is the only member - assert_eq!(Society::members(), vec![10]); + assert_eq!(Members::::get(), vec![10]); // A non-member cannot vouch assert_noop!( Society::vouch(RuntimeOrigin::signed(1), 20, 1000, 100), @@ -426,12 +426,12 @@ fn vouch_works() { assert_eq!(>::get(), vec![create_bid(1000, 20, BidKind::Vouch(10, 100))]); // Vouched user can become candidate run_to_block(4); - assert_eq!(Society::candidates(), vec![create_bid(1000, 20, BidKind::Vouch(10, 100))]); + assert_eq!(Candidates::::get(), vec![create_bid(1000, 20, BidKind::Vouch(10, 100))]); // Vote yes assert_ok!(Society::vote(RuntimeOrigin::signed(10), 20, true)); // Vouched user can win run_to_block(8); - assert_eq!(Society::members(), vec![10, 20]); + assert_eq!(Members::::get(), vec![10, 20]); // Voucher wins a portion of the payment assert_eq!(>::get(10), vec![(9, 100)]); // Vouched user wins the rest @@ -445,19 +445,19 @@ fn vouch_works() { fn voucher_cannot_win_more_than_bid() { EnvBuilder::new().execute(|| { // 10 is the only member - assert_eq!(Society::members(), vec![10]); + assert_eq!(Members::::get(), vec![10]); // 10 vouches, but asks for more than the bid assert_ok!(Society::vouch(RuntimeOrigin::signed(10), 20, 100, 1000)); // Vouching creates the right kind of bid assert_eq!(>::get(), vec![create_bid(100, 20, BidKind::Vouch(10, 1000))]); // Vouched user can become candidate run_to_block(4); - assert_eq!(Society::candidates(), vec![create_bid(100, 20, BidKind::Vouch(10, 1000))]); + assert_eq!(Candidates::::get(), vec![create_bid(100, 20, BidKind::Vouch(10, 1000))]); // Vote yes assert_ok!(Society::vote(RuntimeOrigin::signed(10), 20, true)); // Vouched user can win run_to_block(8); - assert_eq!(Society::members(), vec![10, 20]); + assert_eq!(Members::::get(), vec![10, 20]); // Voucher wins as much as the bid assert_eq!(>::get(10), vec![(9, 100)]); // Vouched user gets nothing @@ -469,7 +469,7 @@ fn voucher_cannot_win_more_than_bid() { fn unvouch_works() { EnvBuilder::new().execute(|| { // 10 is the only member - assert_eq!(Society::members(), vec![10]); + assert_eq!(Members::::get(), vec![10]); // 10 vouches for 20 assert_ok!(Society::vouch(RuntimeOrigin::signed(10), 20, 100, 0)); // 20 has a bid @@ -488,14 +488,14 @@ fn unvouch_works() { // Cannot unvouch after they become candidate assert_ok!(Society::vouch(RuntimeOrigin::signed(10), 20, 100, 0)); run_to_block(4); - assert_eq!(Society::candidates(), vec![create_bid(100, 20, BidKind::Vouch(10, 0))]); + assert_eq!(Candidates::::get(), vec![create_bid(100, 20, BidKind::Vouch(10, 0))]); assert_noop!(Society::unvouch(RuntimeOrigin::signed(10), 0), Error::::BadPosition); // 10 is still vouching until candidate is approved or rejected assert_eq!(>::get(10), Some(VouchingStatus::Vouching)); run_to_block(8); // In this case candidate is denied and suspended - assert!(Society::suspended_candidate(&20).is_some()); - assert_eq!(Society::members(), vec![10]); + assert!(SuspendedCandidates::::get(&20).is_some()); + assert_eq!(Members::::get(), vec![10]); // User is stuck vouching until judgement origin resolves suspended candidate assert_eq!(>::get(10), Some(VouchingStatus::Vouching)); // Judge denies candidate @@ -506,7 +506,7 @@ fn unvouch_works() { )); // 10 is banned from vouching assert_eq!(>::get(10), Some(VouchingStatus::Banned)); - assert_eq!(Society::members(), vec![10]); + assert_eq!(Members::::get(), vec![10]); // 10 cannot vouch again assert_noop!( @@ -522,7 +522,7 @@ fn unvouch_works() { fn unbid_vouch_works() { EnvBuilder::new().execute(|| { // 10 is the only member - assert_eq!(Society::members(), vec![10]); + assert_eq!(Members::::get(), vec![10]); // 10 vouches for 20 assert_ok!(Society::vouch(RuntimeOrigin::signed(10), 20, 100, 0)); // 20 has a bid @@ -541,9 +541,9 @@ fn unbid_vouch_works() { fn founder_and_head_cannot_be_removed() { EnvBuilder::new().execute(|| { // 10 is the only member, founder, and head - assert_eq!(Society::members(), vec![10]); - assert_eq!(Society::founder(), Some(10)); - assert_eq!(Society::head(), Some(10)); + assert_eq!(Members::::get(), vec![10]); + assert_eq!(Founder::::get(), Some(10)); + assert_eq!(Head::::get(), Some(10)); // 10 can still accumulate strikes assert_ok!(Society::bid(RuntimeOrigin::signed(20), 0)); run_to_block(8); @@ -562,10 +562,10 @@ fn founder_and_head_cannot_be_removed() { assert_ok!(Society::vote(RuntimeOrigin::signed(10), 50, true)); assert_ok!(Society::defender_vote(RuntimeOrigin::signed(10), true)); // Keep defender around run_to_block(32); - assert_eq!(Society::members(), vec![10, 50]); - assert_eq!(Society::head(), Some(50)); + assert_eq!(Members::::get(), vec![10, 50]); + assert_eq!(Head::::get(), Some(50)); // Founder is unchanged - assert_eq!(Society::founder(), Some(10)); + assert_eq!(Founder::::get(), Some(10)); // 50 can still accumulate strikes assert_ok!(Society::bid(RuntimeOrigin::signed(60), 0)); @@ -582,9 +582,9 @@ fn founder_and_head_cannot_be_removed() { assert_ok!(Society::vote(RuntimeOrigin::signed(50), 80, true)); assert_ok!(Society::defender_vote(RuntimeOrigin::signed(10), true)); // Keep defender around run_to_block(56); - assert_eq!(Society::members(), vec![10, 50, 80]); - assert_eq!(Society::head(), Some(80)); - assert_eq!(Society::founder(), Some(10)); + assert_eq!(Members::::get(), vec![10, 50, 80]); + assert_eq!(Head::::get(), Some(80)); + assert_eq!(Founder::::get(), Some(10)); // 50 can now be suspended for strikes assert_ok!(Society::bid(RuntimeOrigin::signed(90), 0)); @@ -594,7 +594,7 @@ fn founder_and_head_cannot_be_removed() { run_to_block(64); assert_eq!(Strikes::::get(50), 0); assert_eq!(>::get(50), true); - assert_eq!(Society::members(), vec![10, 80]); + assert_eq!(Members::::get(), vec![10, 80]); }); } @@ -611,18 +611,18 @@ fn challenges_work() { assert_eq!(>::get(30), None); assert_eq!(>::get(40), None); // Check starting point - assert_eq!(Society::members(), vec![10, 20, 30, 40]); - assert_eq!(Society::defender(), None); + assert_eq!(Members::::get(), vec![10, 20, 30, 40]); + assert_eq!(Defender::::get(), None); // 20 will be challenged during the challenge rotation run_to_block(8); - assert_eq!(Society::defender(), Some(30)); + assert_eq!(Defender::::get(), Some(30)); // They can always free vote for themselves assert_ok!(Society::defender_vote(RuntimeOrigin::signed(30), true)); // If no one else votes, nothing happens run_to_block(16); - assert_eq!(Society::members(), vec![10, 20, 30, 40]); + assert_eq!(Members::::get(), vec![10, 20, 30, 40]); // New challenge period - assert_eq!(Society::defender(), Some(30)); + assert_eq!(Defender::::get(), Some(30)); // Non-member cannot challenge assert_noop!( Society::defender_vote(RuntimeOrigin::signed(1), true), @@ -635,14 +635,14 @@ fn challenges_work() { assert_ok!(Society::defender_vote(RuntimeOrigin::signed(40), false)); run_to_block(24); // 20 survives - assert_eq!(Society::members(), vec![10, 20, 30, 40]); + assert_eq!(Members::::get(), vec![10, 20, 30, 40]); // Votes are reset assert_eq!(>::get(10), None); assert_eq!(>::get(20), None); assert_eq!(>::get(30), None); assert_eq!(>::get(40), None); // One more time - assert_eq!(Society::defender(), Some(30)); + assert_eq!(Defender::::get(), Some(30)); // 2 people say accept, 2 reject assert_ok!(Society::defender_vote(RuntimeOrigin::signed(10), true)); assert_ok!(Society::defender_vote(RuntimeOrigin::signed(20), true)); @@ -650,10 +650,10 @@ fn challenges_work() { assert_ok!(Society::defender_vote(RuntimeOrigin::signed(40), false)); run_to_block(32); // 20 is suspended - assert_eq!(Society::members(), vec![10, 20, 40]); - assert_eq!(Society::suspended_member(30), true); + assert_eq!(Members::::get(), vec![10, 20, 40]); + assert_eq!(SuspendedMembers::::get(30), true); // New defender is chosen - assert_eq!(Society::defender(), Some(20)); + assert_eq!(Defender::::get(), Some(20)); // Votes are reset assert_eq!(>::get(10), None); assert_eq!(>::get(20), None); @@ -675,7 +675,7 @@ fn bad_vote_slash_works() { Society::bump_payout(&30, 5, 100); Society::bump_payout(&40, 5, 100); // Check starting point - assert_eq!(Society::members(), vec![10, 20, 30, 40]); + assert_eq!(Members::::get(), vec![10, 20, 30, 40]); assert_eq!(>::get(10), vec![(5, 100)]); assert_eq!(>::get(20), vec![(5, 100)]); assert_eq!(>::get(30), vec![(5, 100)]); @@ -755,22 +755,22 @@ fn vouching_handles_removed_member_with_candidate() { assert_eq!(>::get(20), Some(VouchingStatus::Vouching)); // Make that bid a candidate run_to_block(4); - assert_eq!(Society::candidates(), vec![create_bid(1000, 30, BidKind::Vouch(20, 100))]); + assert_eq!(Candidates::::get(), vec![create_bid(1000, 30, BidKind::Vouch(20, 100))]); // Suspend that member Society::suspend_member(&20); assert_eq!(>::get(20), true); // Nothing changes yet - assert_eq!(Society::candidates(), vec![create_bid(1000, 30, BidKind::Vouch(20, 100))]); + assert_eq!(Candidates::::get(), vec![create_bid(1000, 30, BidKind::Vouch(20, 100))]); assert_eq!(>::get(20), Some(VouchingStatus::Vouching)); // Remove member assert_ok!(Society::judge_suspended_member(RuntimeOrigin::signed(2), 20, false)); // Vouching status is removed, but candidate is still in the queue assert_eq!(>::get(20), None); - assert_eq!(Society::candidates(), vec![create_bid(1000, 30, BidKind::Vouch(20, 100))]); + assert_eq!(Candidates::::get(), vec![create_bid(1000, 30, BidKind::Vouch(20, 100))]); // Candidate wins assert_ok!(Society::vote(RuntimeOrigin::signed(10), 30, true)); run_to_block(8); - assert_eq!(Society::members(), vec![10, 30]); + assert_eq!(Members::::get(), vec![10, 30]); // Payout does not go to removed member assert_eq!(>::get(20), vec![]); assert_eq!(>::get(30), vec![(9, 1000)]); @@ -800,7 +800,7 @@ fn votes_are_working() { assert_eq!(>::get(50, 10), None); run_to_block(8); // Candidates become members after a period rotation - assert_eq!(Society::members(), vec![10, 30, 40]); + assert_eq!(Members::::get(), vec![10, 30, 40]); // Votes are cleaned up assert_eq!(>::get(30, 10), None); assert_eq!(>::get(40, 10), None); @@ -827,17 +827,17 @@ fn max_limits_work() { // Rotate period run_to_block(4); // Max of 10 candidates - assert_eq!(Society::candidates().len(), 10); + assert_eq!(Candidates::::get().len(), 10); // Fill up membership, max 100, we will do just 95 for i in 2000..2095 { assert_ok!(Society::add_member(&(i as u128))); } // Remember there was 1 original member, so 96 total - assert_eq!(Society::members().len(), 96); + assert_eq!(Members::::get().len(), 96); // Rotate period run_to_block(8); // Only of 4 candidates possible now - assert_eq!(Society::candidates().len(), 4); + assert_eq!(Candidates::::get().len(), 4); // Fill up members with suspended candidates from the first rotation for i in 100..104 { assert_ok!(Society::judge_suspended_candidate( @@ -846,12 +846,12 @@ fn max_limits_work() { Judgement::Approve )); } - assert_eq!(Society::members().len(), 100); + assert_eq!(Members::::get().len(), 100); // Can't add any more members assert_noop!(Society::add_member(&98), Error::::MaxMembers); // However, a fringe scenario allows for in-progress candidates to increase the membership // pool, but it has no real after-effects. - for i in Society::members().iter() { + for i in Members::::get().iter() { assert_ok!(Society::vote(RuntimeOrigin::signed(*i), 110, true)); assert_ok!(Society::vote(RuntimeOrigin::signed(*i), 111, true)); assert_ok!(Society::vote(RuntimeOrigin::signed(*i), 112, true)); @@ -859,15 +859,15 @@ fn max_limits_work() { // Rotate period run_to_block(12); // Members length is over 100, no problem... - assert_eq!(Society::members().len(), 103); + assert_eq!(Members::::get().len(), 103); // No candidates because full - assert_eq!(Society::candidates().len(), 0); + assert_eq!(Candidates::::get().len(), 0); // Increase member limit assert_ok!(Society::set_max_members(RuntimeOrigin::root(), 200)); // Rotate period run_to_block(16); // Candidates are back! - assert_eq!(Society::candidates().len(), 10); + assert_eq!(Candidates::::get().len(), 10); }); } @@ -887,11 +887,11 @@ fn zero_bid_works() { // Rotate period run_to_block(4); // Pot is 1000 after "PeriodSpend" - assert_eq!(Society::pot(), 1000); + assert_eq!(Pot::::get(), 1000); assert_eq!(Balances::free_balance(Society::account_id()), 10_000); // Choose smallest bidding users whose total is less than pot, with only one zero bid. assert_eq!( - Society::candidates(), + Candidates::::get(), vec![ create_bid(0, 30, BidKind::Deposit(25)), create_bid(300, 50, BidKind::Deposit(25)), @@ -908,9 +908,9 @@ fn zero_bid_works() { assert_ok!(Society::vote(RuntimeOrigin::signed(10), 60, true)); run_to_block(8); // Candidates become members after a period rotation - assert_eq!(Society::members(), vec![10, 30, 50, 60]); + assert_eq!(Members::::get(), vec![10, 30, 50, 60]); // The zero bid is selected as head - assert_eq!(Society::head(), Some(30)); + assert_eq!(Head::::get(), Some(30)); }); } diff --git a/frame/staking/src/benchmarking.rs b/frame/staking/src/benchmarking.rs index a4366bbd8aa9a..838269e414736 100644 --- a/frame/staking/src/benchmarking.rs +++ b/frame/staking/src/benchmarking.rs @@ -556,7 +556,7 @@ benchmarks! { let current_era = CurrentEra::::get().unwrap(); // set the commission for this particular era as well. - >::insert(current_era, validator.clone(), >::validators(&validator)); + >::insert(current_era, validator.clone(), Validators::::get(&validator)); let caller = whitelisted_caller(); let validator_controller = >::get(&validator).unwrap(); @@ -589,7 +589,7 @@ benchmarks! { let current_era = CurrentEra::::get().unwrap(); // set the commission for this particular era as well. - >::insert(current_era, validator.clone(), >::validators(&validator)); + >::insert(current_era, validator.clone(), Validators::::get(&validator)); let caller = whitelisted_caller(); let balance_before = T::Currency::free_balance(&validator); diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index 3672056534b75..bd07929936086 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -793,7 +793,7 @@ where } fn validators() -> Vec<::AccountId> { - >::validators() + pallet_session::Validators::::get() } fn prune_historical_up_to(up_to: SessionIndex) { @@ -887,7 +887,7 @@ pub struct StashOf(sp_std::marker::PhantomData); impl Convert> for StashOf { fn convert(controller: T::AccountId) -> Option { - >::ledger(&controller).map(|l| l.stash) + Ledger::::get(&controller).map(|l| l.stash) } } @@ -902,8 +902,7 @@ impl Convert for ExposureOf { fn convert(validator: T::AccountId) -> Option>> { - >::active_era() - .map(|active_era| >::eras_stakers(active_era.index, &validator)) + ActiveEra::::get().map(|active_era| ErasStakers::::get(active_era.index, &validator)) } } diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index 30db036d00056..38463c34d13a9 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -73,13 +73,14 @@ impl sp_runtime::BoundToRuntimeAppPublic for OtherSessionHandler { } pub fn is_disabled(controller: AccountId) -> bool { - let stash = Staking::ledger(&controller).unwrap().stash; - let validator_index = match Session::validators().iter().position(|v| *v == stash) { - Some(index) => index as u32, - None => return false, - }; + let stash = Ledger::::get(&controller).unwrap().stash; + let validator_index = + match pallet_session::Validators::::get().iter().position(|v| *v == stash) { + Some(index) => index as u32, + None => return false, + }; - Session::disabled_validators().contains(&validator_index) + pallet_session::DisabledValidators::::get().contains(&validator_index) } type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -552,11 +553,11 @@ impl ExtBuilder { } pub(crate) fn active_era() -> EraIndex { - Staking::active_era().unwrap().index + ActiveEra::::get().unwrap().index } pub(crate) fn current_era() -> EraIndex { - Staking::current_era().unwrap() + CurrentEra::::get().unwrap() } pub(crate) fn bond(stash: AccountId, ctrl: AccountId, val: Balance) { @@ -618,17 +619,17 @@ pub(crate) fn start_session(session_index: SessionIndex) { run_to_block(end); // session must have progressed properly. assert_eq!( - Session::current_index(), + pallet_session::CurrentIndex::::get(), session_index, "current session index = {}, expected = {}", - Session::current_index(), + pallet_session::CurrentIndex::::get(), session_index, ); } /// Go one session forward. pub(crate) fn advance_session() { - let current_index = Session::current_index(); + let current_index = pallet_session::CurrentIndex::::get(); start_session(current_index + 1); } @@ -643,7 +644,7 @@ pub(crate) fn start_active_era(era_index: EraIndex) { pub(crate) fn current_total_payout_for_duration(duration: u64) -> Balance { let (payout, _rest) = ::EraPayout::era_payout( - Staking::eras_total_stake(active_era()), + ErasTotalStake::::get(active_era()), Balances::total_issuance(), duration, ); @@ -653,7 +654,7 @@ pub(crate) fn current_total_payout_for_duration(duration: u64) -> Balance { pub(crate) fn maximum_payout_for_duration(duration: u64) -> Balance { let (payout, rest) = ::EraPayout::era_payout( - Staking::eras_total_stake(active_era()), + ErasTotalStake::::get(active_era()), Balances::total_issuance(), duration, ); @@ -688,9 +689,9 @@ pub(crate) fn reward_all_elected() { } pub(crate) fn validator_controllers() -> Vec { - Session::validators() + pallet_session::Validators::::get() .into_iter() - .map(|s| Staking::bonded(&s).expect("no controller for validator")) + .map(|s| Bonded::::get(&s).expect("no controller for validator")) .collect() } @@ -713,11 +714,11 @@ pub(crate) fn on_offence_in_era( } } - if Staking::active_era().unwrap().index == era { + if ActiveEra::::get().unwrap().index == era { let _ = Staking::on_offence( offenders, slash_fraction, - Staking::eras_start_session_index(era).unwrap(), + ErasStartSessionIndex::::get(era).unwrap(), disable_strategy, ); } else { @@ -732,14 +733,14 @@ pub(crate) fn on_offence_now( >], slash_fraction: &[Perbill], ) { - let now = Staking::active_era().unwrap().index; + let now = ActiveEra::::get().unwrap().index; on_offence_in_era(offenders, slash_fraction, now, DisableStrategy::WhenSlashed) } pub(crate) fn add_slash(who: &AccountId) { on_offence_now( &[OffenceDetails { - offender: (*who, Staking::eras_stakers(active_era(), *who)), + offender: (*who, ErasStakers::::get(active_era(), *who)), reporters: vec![], }], &[Perbill::from_percent(10)], @@ -755,7 +756,7 @@ pub(crate) fn make_all_reward_payment(era: EraIndex) { .collect::>(); // reward validators - for validator_controller in validators_with_reward.iter().filter_map(Staking::bonded) { + for validator_controller in validators_with_reward.iter().filter_map(Bonded::::get) { let ledger = >::get(&validator_controller).unwrap(); assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), ledger.stash, era)); } @@ -765,17 +766,17 @@ pub(crate) fn make_all_reward_payment(era: EraIndex) { macro_rules! assert_session_era { ($session:expr, $era:expr) => { assert_eq!( - Session::current_index(), + pallet_session::CurrentIndex::::get(), $session, "wrong session {} != {}", - Session::current_index(), + pallet_session::CurrentIndex::::get(), $session, ); assert_eq!( - Staking::current_era().unwrap(), + CurrentEra::::get().unwrap(), $era, "wrong current era {} != {}", - Staking::current_era().unwrap(), + CurrentEra::::get().unwrap(), $era, ); }; diff --git a/frame/staking/src/pallet/impls.rs b/frame/staking/src/pallet/impls.rs index 6a35e2b861565..2d7dd4568f34a 100644 --- a/frame/staking/src/pallet/impls.rs +++ b/frame/staking/src/pallet/impls.rs @@ -62,7 +62,10 @@ impl Pallet { /// The total balance that can be slashed from a stash account as of right now. pub fn slashable_balance_of(stash: &T::AccountId) -> BalanceOf { // Weight note: consider making the stake accessible through stash. - Self::bonded(stash).and_then(Self::ledger).map(|l| l.active).unwrap_or_default() + Bonded::::get(stash) + .and_then(Ledger::::get) + .map(|l| l.active) + .unwrap_or_default() } /// Internal impl of [`Self::slashable_balance_of`] that returns [`VoteWeight`]. @@ -96,9 +99,9 @@ impl Pallet { controller: &T::AccountId, num_slashing_spans: u32, ) -> Result { - let mut ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; + let mut ledger = Ledger::::get(&controller).ok_or(Error::::NotController)?; let (stash, old_total) = (ledger.stash.clone(), ledger.total); - if let Some(current_era) = Self::current_era() { + if let Some(current_era) = CurrentEra::::get() { ledger = ledger.consolidate_unlocked(current_era) } @@ -154,7 +157,7 @@ impl Pallet { .with_weight(T::WeightInfo::payout_stakers_alive_staked(0)) })?; - let controller = Self::bonded(&validator_stash).ok_or_else(|| { + let controller = Bonded::::get(&validator_stash).ok_or_else(|| { Error::::NotStash.with_weight(T::WeightInfo::payout_stakers_alive_staked(0)) })?; let mut ledger = >::get(&controller).ok_or(Error::::NotController)?; @@ -210,7 +213,7 @@ impl Pallet { // This is how much validator + nominators are entitled to. let validator_total_payout = validator_total_reward_part * era_payout; - let validator_prefs = Self::eras_validator_prefs(&era, &validator_stash); + let validator_prefs = ErasValidatorPrefs::::get(&era, &validator_stash); // Validator first gets a cut off the top. let validator_commission = validator_prefs.commission; let validator_commission_payout = validator_commission * validator_total_payout; @@ -285,13 +288,13 @@ impl Pallet { /// Actually make a payment to a staker. This uses the currency's reward function /// to pay the right payee for the given staker account. fn make_payout(stash: &T::AccountId, amount: BalanceOf) -> Option> { - let dest = Self::payee(stash); + let dest = Payee::::get(stash); match dest { - RewardDestination::Controller => Self::bonded(stash) + RewardDestination::Controller => Bonded::::get(stash) .map(|controller| T::Currency::deposit_creating(&controller, amount)), RewardDestination::Stash => T::Currency::deposit_into_existing(stash, amount).ok(), - RewardDestination::Staked => Self::bonded(stash) - .and_then(|c| Self::ledger(&c).map(|l| (c, l))) + RewardDestination::Staked => Bonded::::get(stash) + .and_then(|c| Ledger::::get(&c).map(|l| (c, l))) .and_then(|(controller, mut l)| { l.active += amount; l.total += amount; @@ -310,9 +313,9 @@ impl Pallet { session_index: SessionIndex, is_genesis: bool, ) -> Option>> { - if let Some(current_era) = Self::current_era() { + if let Some(current_era) = CurrentEra::::get() { // Initial era has been set. - let current_era_start_session_index = Self::eras_start_session_index(current_era) + let current_era_start_session_index = ErasStartSessionIndex::::get(current_era) .unwrap_or_else(|| { frame_support::print("Error: start_session_index must be set for current_era"); 0 @@ -352,12 +355,12 @@ impl Pallet { /// Start a session potentially starting an era. fn start_session(start_session: SessionIndex) { - let next_active_era = Self::active_era().map(|e| e.index + 1).unwrap_or(0); + let next_active_era = ActiveEra::::get().map(|e| e.index + 1).unwrap_or(0); // This is only `Some` when current era has already progressed to the next era, while the // active era is one behind (i.e. in the *last session of the active era*, or *first session // of the new current era*, depending on how you look at it). if let Some(next_active_era_start_session_index) = - Self::eras_start_session_index(next_active_era) + ErasStartSessionIndex::::get(next_active_era) { if next_active_era_start_session_index == start_session { Self::start_era(start_session); @@ -379,9 +382,9 @@ impl Pallet { /// End a session potentially ending an era. fn end_session(session_index: SessionIndex) { - if let Some(active_era) = Self::active_era() { + if let Some(active_era) = ActiveEra::::get() { if let Some(next_active_era_start_session_index) = - Self::eras_start_session_index(active_era.index + 1) + ErasStartSessionIndex::::get(active_era.index + 1) { if next_active_era_start_session_index == session_index + 1 { Self::end_era(active_era, session_index); @@ -439,7 +442,7 @@ impl Pallet { let now_as_millis_u64 = T::UnixTime::now().as_millis().saturated_into::(); let era_duration = (now_as_millis_u64 - active_era_start).saturated_into::(); - let staked = Self::eras_total_stake(&active_era.index); + let staked = ErasTotalStake::::get(&active_era.index); let issuance = T::Currency::total_issuance(); let (validator_payout, remainder) = T::EraPayout::era_payout(staked, issuance, era_duration); @@ -521,7 +524,7 @@ impl Pallet { }; let exposures = Self::collect_exposures(election_result); - if (exposures.len() as u32) < Self::minimum_validator_count().max(1) { + if (exposures.len() as u32) < MinimumValidatorCount::::get().max(1) { // Session will panic if we ever return an empty validator set, thus max(1) ^^. match CurrentEra::::get() { Some(current_era) if current_era > 0 => log!( @@ -530,7 +533,7 @@ impl Pallet { elected, minimum is {})", CurrentEra::::get().unwrap_or(0), exposures.len(), - Self::minimum_validator_count(), + MinimumValidatorCount::::get(), ), None => { // The initial era is allowed to have no exposures. @@ -589,7 +592,7 @@ impl Pallet { // Collect the pref of all winners. for stash in &elected_stashes { - let pref = Self::validators(stash); + let pref = Validators::::get(stash); >::insert(&new_planned_era, stash, pref); } @@ -707,7 +710,7 @@ impl Pallet { /// /// COMPLEXITY: Complexity is `number_of_validator_to_reward x current_elected_len`. pub fn reward_by_ids(validators_points: impl IntoIterator) { - if let Some(active_era) = Self::active_era() { + if let Some(active_era) = ActiveEra::::get() { >::mutate(active_era.index, |era_rewards| { for (validator, points) in validators_points.into_iter() { *era_rewards.individual.entry(validator).or_default() += points; @@ -979,7 +982,7 @@ impl ElectionDataProvider for Pallet { fn desired_targets() -> data_provider::Result { Self::register_weight(T::DbWeight::get().reads(1)); - Ok(Self::validator_count()) + Ok(ValidatorCount::::get()) } fn electing_voters(maybe_max_len: Option) -> data_provider::Result>> { @@ -1002,10 +1005,10 @@ impl ElectionDataProvider for Pallet { } fn next_election_prediction(now: T::BlockNumber) -> T::BlockNumber { - let current_era = Self::current_era().unwrap_or(0); - let current_session = Self::current_planned_session(); + let current_era = CurrentEra::::get().unwrap_or(0); + let current_session = CurrentPlannedSession::::get(); let current_era_start_session_index = - Self::eras_start_session_index(current_era).unwrap_or(0); + ErasStartSessionIndex::::get(current_era).unwrap_or(0); // Number of session in the current era or the maximum session per era if reached. let era_progress = current_session .saturating_sub(current_era_start_session_index) @@ -1175,14 +1178,14 @@ impl historical::SessionManager Option>)>> { >::new_session(new_index).map(|validators| { - let current_era = Self::current_era() + let current_era = CurrentEra::::get() // Must be some as a new era has been created. .unwrap_or(0); validators .into_iter() .map(|v| { - let exposure = Self::eras_stakers(current_era, &v); + let exposure = ErasStakers::::get(current_era, &v); (v, exposure) }) .collect() @@ -1193,14 +1196,14 @@ impl historical::SessionManager Option>)>> { >::new_session_genesis(new_index).map( |validators| { - let current_era = Self::current_era() + let current_era = CurrentEra::::get() // Must be some as a new era has been created. .unwrap_or(0); validators .into_iter() .map(|v| { - let exposure = Self::eras_stakers(current_era, &v); + let exposure = ErasStakers::::get(current_era, &v); (v, exposure) }) .collect() @@ -1259,7 +1262,7 @@ where }; let active_era = { - let active_era = Self::active_era(); + let active_era = ActiveEra::::get(); add_db_reads_writes(1, 0); if active_era.is_none() { // This offence need not be re-submitted. @@ -1267,7 +1270,7 @@ where } active_era.expect("value checked not to be `None`; qed").index }; - let active_era_start_session_index = Self::eras_start_session_index(active_era) + let active_era_start_session_index = ErasStartSessionIndex::::get(active_era) .unwrap_or_else(|| { frame_support::print("Error: start_session_index must be set for current_era"); 0 @@ -1296,7 +1299,7 @@ where let slash_defer_duration = T::SlashDeferDuration::get(); - let invulnerables = Self::invulnerables(); + let invulnerables = Invulnerables::::get(); add_db_reads_writes(1, 0); for (details, slash_fraction) in offenders.iter().zip(slash_fraction) { @@ -1382,7 +1385,7 @@ impl ScoreProvider for Pallet { // this will clearly results in an inconsistent state, but it should not matter for a // benchmark. let active: BalanceOf = weight.try_into().map_err(|_| ()).unwrap(); - let mut ledger = match Self::ledger(who) { + let mut ledger = match Ledger::::get(who) { None => StakingLedger::default_from(who.clone()), Some(l) => l, }; @@ -1570,12 +1573,13 @@ impl StakingInterface for Pallet { } fn force_unstake(who: Self::AccountId) -> sp_runtime::DispatchResult { - let num_slashing_spans = Self::slashing_spans(&who).map_or(0, |s| s.iter().count() as u32); + let num_slashing_spans = + SlashingSpans::::get(&who).map_or(0, |s| s.iter().count() as u32); Self::force_unstake(RawOrigin::Root.into(), who.clone(), num_slashing_spans) } fn stash_by_ctrl(controller: &Self::AccountId) -> Result { - Self::ledger(controller) + Ledger::::get(controller) .map(|l| l.stash) .ok_or(Error::::NotController.into()) } @@ -1591,12 +1595,12 @@ impl StakingInterface for Pallet { } fn current_era() -> EraIndex { - Self::current_era().unwrap_or(Zero::zero()) + CurrentEra::::get().unwrap_or(Zero::zero()) } fn stake(who: &Self::AccountId) -> Result, DispatchError> { - Self::bonded(who) - .and_then(|c| Self::ledger(c)) + Bonded::::get(who) + .and_then(|c| Ledger::::get(c)) .map(|l| Stake { stash: l.stash, total: l.total, active: l.active }) .ok_or(Error::::NotStash.into()) } @@ -1606,7 +1610,7 @@ impl StakingInterface for Pallet { } fn unbond(who: &Self::AccountId, value: Self::Balance) -> DispatchResult { - let ctrl = Self::bonded(who).ok_or(Error::::NotStash)?; + let ctrl = Bonded::::get(who).ok_or(Error::::NotStash)?; Self::unbond(RawOrigin::Signed(ctrl).into(), value) .map_err(|with_post| with_post.error) .map(|_| ()) @@ -1615,7 +1619,7 @@ impl StakingInterface for Pallet { fn chill(who: &Self::AccountId) -> DispatchResult { // defensive-only: any account bonded via this interface has the stash set as the // controller, but we have to be sure. Same comment anywhere else that we read this. - let ctrl = Self::bonded(who).ok_or(Error::::NotStash)?; + let ctrl = Bonded::::get(who).ok_or(Error::::NotStash)?; Self::chill(RawOrigin::Signed(ctrl).into()) } @@ -1623,7 +1627,7 @@ impl StakingInterface for Pallet { who: Self::AccountId, num_slashing_spans: u32, ) -> Result { - let ctrl = Self::bonded(who).ok_or(Error::::NotStash)?; + let ctrl = Bonded::::get(who).ok_or(Error::::NotStash)?; Self::withdraw_unbonded(RawOrigin::Signed(ctrl.clone()).into(), num_slashing_spans) .map(|_| !Ledger::::contains_key(&ctrl)) .map_err(|with_post| with_post.error) @@ -1643,7 +1647,7 @@ impl StakingInterface for Pallet { } fn nominate(who: &Self::AccountId, targets: Vec) -> DispatchResult { - let ctrl = Self::bonded(who).ok_or(Error::::NotStash)?; + let ctrl = Bonded::::get(who).ok_or(Error::::NotStash)?; let targets = targets.into_iter().map(T::Lookup::unlookup).collect::>(); Self::nominate(RawOrigin::Signed(ctrl).into(), targets) } @@ -1713,7 +1717,7 @@ impl Pallet { fn check_exposures() -> Result<(), &'static str> { // a check per validator to ensure the exposure struct is always sane. - let era = Self::active_era().unwrap().index; + let era = ActiveEra::::get().unwrap().index; ErasStakers::::iter_prefix_values(era) .map(|expo| { ensure!( @@ -1733,7 +1737,7 @@ impl Pallet { fn check_nominators() -> Result<(), &'static str> { // a check per nominator to ensure their entire stake is correctly distributed. Will only // kick-in if the nomination was submitted before the current era. - let era = Self::active_era().unwrap().index; + let era = ActiveEra::::get().unwrap().index; >::iter() .filter_map( |(nominator, nomination)| { @@ -1750,7 +1754,7 @@ impl Pallet { let mut sum = BalanceOf::::zero(); T::SessionInterface::validators() .iter() - .map(|v| Self::eras_stakers(era, v)) + .map(|v| ErasStakers::::get(era, v)) .map(|e| { let individual = e.others.iter().filter(|e| e.who == nominator).collect::>(); @@ -1768,13 +1772,13 @@ impl Pallet { } fn ensure_is_stash(who: &T::AccountId) -> Result<(), &'static str> { - ensure!(Self::bonded(who).is_some(), "Not a stash."); + ensure!(Bonded::::get(who).is_some(), "Not a stash."); Ok(()) } fn ensure_ledger_consistent(ctrl: T::AccountId) -> Result<(), &'static str> { // ensures ledger.total == ledger.active + sum(ledger.unlocking). - let ledger = Self::ledger(ctrl.clone()).ok_or("Not a controller.")?; + let ledger = Ledger::::get(ctrl.clone()).ok_or("Not a controller.")?; let real_total: BalanceOf = ledger.unlocking.iter().fold(ledger.active, |a, c| a + c.value); ensure!(real_total == ledger.total, "ledger.total corrupt"); diff --git a/frame/staking/src/pallet/mod.rs b/frame/staking/src/pallet/mod.rs index 4b0e8133bc0b6..f71e4b06554c6 100644 --- a/frame/staking/src/pallet/mod.rs +++ b/frame/staking/src/pallet/mod.rs @@ -785,7 +785,7 @@ pub mod pallet { fn on_finalize(_n: BlockNumberFor) { // Set the start of the first era. - if let Some(mut active_era) = Self::active_era() { + if let Some(mut active_era) = ActiveEra::::get() { if active_era.start.is_none() { let now_as_millis_u64 = T::UnixTime::now().as_millis().saturated_into::(); active_era.start = Some(now_as_millis_u64); @@ -924,8 +924,8 @@ pub mod pallet { ) -> DispatchResult { let stash = ensure_signed(origin)?; - let controller = Self::bonded(&stash).ok_or(Error::::NotStash)?; - let mut ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; + let controller = Bonded::::get(&stash).ok_or(Error::::NotStash)?; + let mut ledger = Ledger::::get(&controller).ok_or(Error::::NotController)?; let stash_balance = T::Currency::free_balance(&stash); if let Some(extra) = stash_balance.checked_sub(&ledger.total) { @@ -979,7 +979,7 @@ pub mod pallet { #[pallet::compact] value: BalanceOf, ) -> DispatchResultWithPostInfo { let controller = ensure_signed(origin)?; - let unlocking = Self::ledger(&controller) + let unlocking = Ledger::::get(&controller) .map(|l| l.unlocking.len()) .ok_or(Error::::NotController)?; @@ -988,7 +988,7 @@ pub mod pallet { let maybe_withdraw_weight = { if unlocking == T::MaxUnlockingChunks::get() as usize { let real_num_slashing_spans = - Self::slashing_spans(&controller).map_or(0, |s| s.iter().count()); + SlashingSpans::::get(&controller).map_or(0, |s| s.iter().count()); Some(Self::do_withdraw_unbonded(&controller, real_num_slashing_spans as u32)?) } else { None @@ -997,7 +997,7 @@ pub mod pallet { // we need to fetch the ledger again because it may have been mutated in the call // to `Self::do_withdraw_unbonded` above. - let mut ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; + let mut ledger = Ledger::::get(&controller).ok_or(Error::::NotController)?; let mut value = value.min(ledger.active); ensure!( @@ -1027,7 +1027,7 @@ pub mod pallet { ensure!(ledger.active >= min_active_bond, Error::::InsufficientBond); // Note: in case there is no current era it is fine to bond one era more. - let era = Self::current_era().unwrap_or(0) + T::BondingDuration::get(); + let era = CurrentEra::::get().unwrap_or(0) + T::BondingDuration::get(); if let Some(mut chunk) = ledger.unlocking.last_mut().filter(|chunk| chunk.era == era) { @@ -1098,7 +1098,7 @@ pub mod pallet { pub fn validate(origin: OriginFor, prefs: ValidatorPrefs) -> DispatchResult { let controller = ensure_signed(origin)?; - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; + let ledger = Ledger::::get(&controller).ok_or(Error::::NotController)?; ensure!(ledger.active >= MinValidatorBond::::get(), Error::::InsufficientBond); let stash = &ledger.stash; @@ -1144,7 +1144,7 @@ pub mod pallet { ) -> DispatchResult { let controller = ensure_signed(origin)?; - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; + let ledger = Ledger::::get(&controller).ok_or(Error::::NotController)?; ensure!(ledger.active >= MinNominatorBond::::get(), Error::::InsufficientBond); let stash = &ledger.stash; @@ -1185,7 +1185,7 @@ pub mod pallet { let nominations = Nominations { targets, // Initial nominations are considered submitted at era 0. See `Nominations` doc. - submitted_in: Self::current_era().unwrap_or(0), + submitted_in: CurrentEra::::get().unwrap_or(0), suppressed: false, }; @@ -1208,7 +1208,7 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::chill())] pub fn chill(origin: OriginFor) -> DispatchResult { let controller = ensure_signed(origin)?; - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; + let ledger = Ledger::::get(&controller).ok_or(Error::::NotController)?; Self::chill_stash(&ledger.stash); Ok(()) } @@ -1232,7 +1232,7 @@ pub mod pallet { payee: RewardDestination, ) -> DispatchResult { let controller = ensure_signed(origin)?; - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; + let ledger = Ledger::::get(&controller).ok_or(Error::::NotController)?; let stash = &ledger.stash; >::insert(stash, payee); Ok(()) @@ -1256,7 +1256,7 @@ pub mod pallet { controller: AccountIdLookupOf, ) -> DispatchResult { let stash = ensure_signed(origin)?; - let old_controller = Self::bonded(&stash).ok_or(Error::::NotStash)?; + let old_controller = Bonded::::get(&stash).ok_or(Error::::NotStash)?; let controller = T::Lookup::lookup(controller)?; if >::contains_key(&controller) { return Err(Error::::AlreadyPaired.into()) @@ -1503,7 +1503,7 @@ pub mod pallet { #[pallet::compact] value: BalanceOf, ) -> DispatchResultWithPostInfo { let controller = ensure_signed(origin)?; - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; + let ledger = Ledger::::get(&controller).ok_or(Error::::NotController)?; ensure!(!ledger.unlocking.is_empty(), Error::::NoUnlockChunk); let initial_unlocking = ledger.unlocking.len() as u32; @@ -1552,7 +1552,7 @@ pub mod pallet { let ed = T::Currency::minimum_balance(); let reapable = T::Currency::total_balance(&stash) < ed || - Self::ledger(Self::bonded(stash.clone()).ok_or(Error::::NotStash)?) + Ledger::::get(Bonded::::get(stash.clone()).ok_or(Error::::NotStash)?) .map(|l| l.total) .unwrap_or_default() < ed; ensure!(reapable, Error::::FundedTarget); @@ -1578,7 +1578,7 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::kick(who.len() as u32))] pub fn kick(origin: OriginFor, who: Vec>) -> DispatchResult { let controller = ensure_signed(origin)?; - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; + let ledger = Ledger::::get(&controller).ok_or(Error::::NotController)?; let stash = &ledger.stash; for nom_stash in who @@ -1687,7 +1687,7 @@ pub mod pallet { pub fn chill_other(origin: OriginFor, controller: T::AccountId) -> DispatchResult { // Anyone can call this function. let caller = ensure_signed(origin)?; - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; + let ledger = Ledger::::get(&controller).ok_or(Error::::NotController)?; let stash = ledger.stash; // In order for one user to chill another user, the following conditions must be met: diff --git a/frame/staking/src/slashing.rs b/frame/staking/src/slashing.rs index aeea0a1a58c63..19762e49b7476 100644 --- a/frame/staking/src/slashing.rs +++ b/frame/staking/src/slashing.rs @@ -50,8 +50,8 @@ //! Based on research at use crate::{ - BalanceOf, Config, Error, Exposure, NegativeImbalanceOf, Pallet, Perbill, SessionInterface, - Store, UnappliedSlash, + BalanceOf, Bonded, Config, Error, Exposure, Ledger, NegativeImbalanceOf, Pallet, Perbill, + SessionInterface, Store, UnappliedSlash, }; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ @@ -598,12 +598,12 @@ pub fn do_slash( slashed_imbalance: &mut NegativeImbalanceOf, slash_era: EraIndex, ) { - let controller = match >::bonded(stash).defensive() { + let controller = match Bonded::::get(stash).defensive() { None => return, Some(c) => c, }; - let mut ledger = match >::ledger(&controller) { + let mut ledger = match Ledger::::get(&controller) { Some(ledger) => ledger, None => return, // nothing to do. }; diff --git a/frame/staking/src/testing_utils.rs b/frame/staking/src/testing_utils.rs index 0e0ac76523471..ae00ec671cd01 100644 --- a/frame/staking/src/testing_utils.rs +++ b/frame/staking/src/testing_utils.rs @@ -227,5 +227,5 @@ pub fn create_validators_with_nominators_for_era( /// get the current era. pub fn current_era() -> EraIndex { - >::current_era().unwrap_or(0) + CurrentEra::::get().unwrap_or(0) } diff --git a/frame/staking/src/tests.rs b/frame/staking/src/tests.rs index e200f621b3742..8d9fd3d196103 100644 --- a/frame/staking/src/tests.rs +++ b/frame/staking/src/tests.rs @@ -93,7 +93,7 @@ fn set_staking_configs_works() { fn force_unstake_works() { ExtBuilder::default().build_and_execute(|| { // Account 11 is stashed and locked, and account 10 is the controller - assert_eq!(Staking::bonded(&11), Some(10)); + assert_eq!(Bonded::::get(&11), Some(10)); // Adds 2 slashing spans add_slash(&11); // Cant transfer @@ -111,7 +111,7 @@ fn force_unstake_works() { // We now force them to unstake assert_ok!(Staking::force_unstake(RuntimeOrigin::root(), 11, 2)); // No longer bonded. - assert_eq!(Staking::bonded(&11), None); + assert_eq!(Bonded::::get(&11), None); // Transfer works. assert_ok!(Balances::transfer(RuntimeOrigin::signed(11), 1, 10)); }); @@ -121,7 +121,7 @@ fn force_unstake_works() { fn kill_stash_works() { ExtBuilder::default().build_and_execute(|| { // Account 11 is stashed and locked, and account 10 is the controller - assert_eq!(Staking::bonded(&11), Some(10)); + assert_eq!(Bonded::::get(&11), Some(10)); // Adds 2 slashing spans add_slash(&11); // Only can kill a stash account @@ -131,7 +131,7 @@ fn kill_stash_works() { // Correct inputs, everything works assert_ok!(Staking::kill_stash(&11, 2)); // No longer bonded. - assert_eq!(Staking::bonded(&11), None); + assert_eq!(Bonded::::get(&11), None); }); } @@ -140,15 +140,15 @@ fn basic_setup_works() { // Verifies initial conditions of mock ExtBuilder::default().build_and_execute(|| { // Account 11 is stashed and locked, and account 10 is the controller - assert_eq!(Staking::bonded(&11), Some(10)); + assert_eq!(Bonded::::get(&11), Some(10)); // Account 21 is stashed and locked, and account 20 is the controller - assert_eq!(Staking::bonded(&21), Some(20)); + assert_eq!(Bonded::::get(&21), Some(20)); // Account 1 is not a stashed - assert_eq!(Staking::bonded(&1), None); + assert_eq!(Bonded::::get(&1), None); // Account 10 controls the stash from account 11, which is 100 * balance_factor units assert_eq!( - Staking::ledger(&10).unwrap(), + Ledger::::get(&10).unwrap(), StakingLedger { stash: 11, total: 1000, @@ -159,7 +159,7 @@ fn basic_setup_works() { ); // Account 20 controls the stash from account 21, which is 200 * balance_factor units assert_eq!( - Staking::ledger(&20), + Ledger::::get(&20), Some(StakingLedger { stash: 21, total: 1000, @@ -169,7 +169,7 @@ fn basic_setup_works() { }) ); // Account 1 does not control any stash - assert_eq!(Staking::ledger(&1), None); + assert_eq!(Ledger::::get(&1), None); // ValidatorPrefs are default assert_eq_uvec!( @@ -182,7 +182,7 @@ fn basic_setup_works() { ); assert_eq!( - Staking::ledger(100), + Ledger::::get(100), Some(StakingLedger { stash: 101, total: 500, @@ -191,10 +191,10 @@ fn basic_setup_works() { claimed_rewards: bounded_vec![], }) ); - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); assert_eq!( - Staking::eras_stakers(active_era(), 11), + ErasStakers::::get(active_era(), 11), Exposure { total: 1125, own: 1000, @@ -202,7 +202,7 @@ fn basic_setup_works() { }, ); assert_eq!( - Staking::eras_stakers(active_era(), 21), + ErasStakers::::get(active_era(), 21), Exposure { total: 1375, own: 1000, @@ -211,10 +211,10 @@ fn basic_setup_works() { ); // initial total stake = 1125 + 1375 - assert_eq!(Staking::eras_total_stake(active_era()), 2500); + assert_eq!(ErasTotalStake::::get(active_era()), 2500); // The number of validators required. - assert_eq!(Staking::validator_count(), 2); + assert_eq!(ValidatorCount::::get(), 2); // Initial Era and session assert_eq!(active_era(), 0); @@ -224,7 +224,7 @@ fn basic_setup_works() { assert_eq!(Balances::free_balance(10), 1); // New era is not being forced - assert_eq!(Staking::force_era(), Forcing::NotForcing); + assert_eq!(ForceEra::::get(), Forcing::NotForcing); }); } @@ -232,14 +232,14 @@ fn basic_setup_works() { fn change_controller_works() { ExtBuilder::default().build_and_execute(|| { // 10 and 11 are bonded as stash controller. - assert_eq!(Staking::bonded(&11), Some(10)); + assert_eq!(Bonded::::get(&11), Some(10)); // 10 can control 11 who is initially a validator. assert_ok!(Staking::chill(RuntimeOrigin::signed(10))); // change controller assert_ok!(Staking::set_controller(RuntimeOrigin::signed(11), 5)); - assert_eq!(Staking::bonded(&11), Some(5)); + assert_eq!(Bonded::::get(&11), Some(5)); mock::start_active_era(1); // 10 is no longer in control. @@ -276,7 +276,7 @@ fn rewards_should_work() { let maximum_payout = maximum_payout_for_duration(reward_time_per_era()); start_session(1); - assert_eq_uvec!(Session::validators(), vec![11, 21]); + assert_eq_uvec!(pallet_session::Validators::::get(), vec![11, 21]); assert_eq!(Balances::total_balance(&10), init_balance_10); assert_eq!(Balances::total_balance(&11), init_balance_11); @@ -285,7 +285,7 @@ fn rewards_should_work() { assert_eq!(Balances::total_balance(&100), init_balance_100); assert_eq!(Balances::total_balance(&101), init_balance_101); assert_eq!( - Staking::eras_reward_points(active_era()), + ErasRewardPoints::::get(active_era()), EraRewardPoints { total: 50 * 3, individual: vec![(11, 100), (21, 50)].into_iter().collect(), @@ -332,7 +332,7 @@ fn rewards_should_work() { ); assert_eq_error_rate!(Balances::total_balance(&101), init_balance_101, 2); - assert_eq_uvec!(Session::validators(), vec![11, 21]); + assert_eq_uvec!(pallet_session::Validators::::get(), vec![11, 21]); Pallet::::reward_by_ids(vec![(11, 1)]); // Compute total payout now for whole duration as other parameter won't change @@ -435,7 +435,7 @@ fn staking_should_work() { // Note: the stashed value of 4 is still lock assert_eq!( - Staking::ledger(&4), + Ledger::::get(&4), Some(StakingLedger { stash: 3, total: 1500, @@ -485,8 +485,8 @@ fn less_than_needed_candidates_works() { .validator_count(4) .nominate(false) .build_and_execute(|| { - assert_eq!(Staking::validator_count(), 4); - assert_eq!(Staking::minimum_validator_count(), 1); + assert_eq!(ValidatorCount::::get(), 4); + assert_eq!(MinimumValidatorCount::::get(), 1); assert_eq_uvec!(validator_controllers(), vec![30, 20, 10]); mock::start_active_era(1); @@ -618,7 +618,7 @@ fn nominating_and_rewards_should_work() { assert_eq!(ErasStakers::::iter_prefix_values(active_era()).count(), 2); assert_eq!( - Staking::eras_stakers(active_era(), 11), + ErasStakers::::get(active_era(), 11), Exposure { total: 1000 + 800, own: 1000, @@ -629,7 +629,7 @@ fn nominating_and_rewards_should_work() { }, ); assert_eq!( - Staking::eras_stakers(active_era(), 21), + ErasStakers::::get(active_era(), 21), Exposure { total: 1000 + 1200, own: 1000, @@ -689,14 +689,14 @@ fn nominators_also_get_slashed_pro_rata() { ExtBuilder::default().build_and_execute(|| { mock::start_active_era(1); let slash_percent = Perbill::from_percent(5); - let initial_exposure = Staking::eras_stakers(active_era(), 11); + let initial_exposure = ErasStakers::::get(active_era(), 11); // 101 is a nominator for 11 assert_eq!(initial_exposure.others.first().unwrap().who, 101); // staked values; - let nominator_stake = Staking::ledger(100).unwrap().active; + let nominator_stake = Ledger::::get(100).unwrap().active; let nominator_balance = balances(&101).0; - let validator_stake = Staking::ledger(10).unwrap().active; + let validator_stake = Ledger::::get(10).unwrap().active; let validator_balance = balances(&11).0; let exposed_stake = initial_exposure.total; let exposed_validator = initial_exposure.own; @@ -709,8 +709,8 @@ fn nominators_also_get_slashed_pro_rata() { ); // both stakes must have been decreased. - assert!(Staking::ledger(100).unwrap().active < nominator_stake); - assert!(Staking::ledger(10).unwrap().active < validator_stake); + assert!(Ledger::::get(100).unwrap().active < nominator_stake); + assert!(Ledger::::get(10).unwrap().active < validator_stake); let slash_amount = slash_percent * exposed_stake; let validator_share = @@ -723,8 +723,8 @@ fn nominators_also_get_slashed_pro_rata() { assert!(nominator_share > 0); // both stakes must have been decreased pro-rata. - assert_eq!(Staking::ledger(100).unwrap().active, nominator_stake - nominator_share); - assert_eq!(Staking::ledger(10).unwrap().active, validator_stake - validator_share); + assert_eq!(Ledger::::get(100).unwrap().active, nominator_stake - nominator_share); + assert_eq!(Ledger::::get(10).unwrap().active, validator_stake - validator_share); assert_eq!( balances(&101).0, // free balance nominator_balance - nominator_share, @@ -805,42 +805,42 @@ fn session_and_eras_work_simple() { ExtBuilder::default().period(1).build_and_execute(|| { assert_eq!(active_era(), 0); assert_eq!(current_era(), 0); - assert_eq!(Session::current_index(), 1); + assert_eq!(pallet_session::CurrentIndex::::get(), 1); assert_eq!(System::block_number(), 1); // Session 1: this is basically a noop. This has already been started. start_session(1); - assert_eq!(Session::current_index(), 1); + assert_eq!(pallet_session::CurrentIndex::::get(), 1); assert_eq!(active_era(), 0); assert_eq!(System::block_number(), 1); // Session 2: No change. start_session(2); - assert_eq!(Session::current_index(), 2); + assert_eq!(pallet_session::CurrentIndex::::get(), 2); assert_eq!(active_era(), 0); assert_eq!(System::block_number(), 2); // Session 3: Era increment. start_session(3); - assert_eq!(Session::current_index(), 3); + assert_eq!(pallet_session::CurrentIndex::::get(), 3); assert_eq!(active_era(), 1); assert_eq!(System::block_number(), 3); // Session 4: No change. start_session(4); - assert_eq!(Session::current_index(), 4); + assert_eq!(pallet_session::CurrentIndex::::get(), 4); assert_eq!(active_era(), 1); assert_eq!(System::block_number(), 4); // Session 5: No change. start_session(5); - assert_eq!(Session::current_index(), 5); + assert_eq!(pallet_session::CurrentIndex::::get(), 5); assert_eq!(active_era(), 1); assert_eq!(System::block_number(), 5); // Session 6: Era increment. start_session(6); - assert_eq!(Session::current_index(), 6); + assert_eq!(pallet_session::CurrentIndex::::get(), 6); assert_eq!(active_era(), 2); assert_eq!(System::block_number(), 6); }); @@ -850,36 +850,36 @@ fn session_and_eras_work_simple() { fn session_and_eras_work_complex() { ExtBuilder::default().period(5).build_and_execute(|| { assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 0); + assert_eq!(pallet_session::CurrentIndex::::get(), 0); assert_eq!(System::block_number(), 1); start_session(1); - assert_eq!(Session::current_index(), 1); + assert_eq!(pallet_session::CurrentIndex::::get(), 1); assert_eq!(active_era(), 0); assert_eq!(System::block_number(), 5); start_session(2); - assert_eq!(Session::current_index(), 2); + assert_eq!(pallet_session::CurrentIndex::::get(), 2); assert_eq!(active_era(), 0); assert_eq!(System::block_number(), 10); start_session(3); - assert_eq!(Session::current_index(), 3); + assert_eq!(pallet_session::CurrentIndex::::get(), 3); assert_eq!(active_era(), 1); assert_eq!(System::block_number(), 15); start_session(4); - assert_eq!(Session::current_index(), 4); + assert_eq!(pallet_session::CurrentIndex::::get(), 4); assert_eq!(active_era(), 1); assert_eq!(System::block_number(), 20); start_session(5); - assert_eq!(Session::current_index(), 5); + assert_eq!(pallet_session::CurrentIndex::::get(), 5); assert_eq!(active_era(), 1); assert_eq!(System::block_number(), 25); start_session(6); - assert_eq!(Session::current_index(), 6); + assert_eq!(pallet_session::CurrentIndex::::get(), 6); assert_eq!(active_era(), 2); assert_eq!(System::block_number(), 30); }); @@ -953,11 +953,11 @@ fn cannot_transfer_staked_balance() { // Tests that a stash account cannot transfer funds ExtBuilder::default().nominate(false).build_and_execute(|| { // Confirm account 11 is stashed - assert_eq!(Staking::bonded(&11), Some(10)); + assert_eq!(Bonded::::get(&11), Some(10)); // Confirm account 11 has some free balance assert_eq!(Balances::free_balance(11), 1000); // Confirm account 11 (via controller 10) is totally staked - assert_eq!(Staking::eras_stakers(active_era(), 11).total, 1000); + assert_eq!(ErasStakers::::get(active_era(), 11).total, 1000); // Confirm account 11 cannot transfer as a result assert_noop!( Balances::transfer(RuntimeOrigin::signed(11), 20, 1), @@ -978,11 +978,11 @@ fn cannot_transfer_staked_balance_2() { // 21 has 2000 free balance but 1000 at stake ExtBuilder::default().nominate(false).build_and_execute(|| { // Confirm account 21 is stashed - assert_eq!(Staking::bonded(&21), Some(20)); + assert_eq!(Bonded::::get(&21), Some(20)); // Confirm account 21 has some free balance assert_eq!(Balances::free_balance(21), 2000); // Confirm account 21 (via controller 20) is totally staked - assert_eq!(Staking::eras_stakers(active_era(), 21).total, 1000); + assert_eq!(ErasStakers::::get(active_era(), 21).total, 1000); // Confirm account 21 can transfer at most 1000 assert_noop!( Balances::transfer(RuntimeOrigin::signed(21), 20, 1001), @@ -997,11 +997,11 @@ fn cannot_reserve_staked_balance() { // Checks that a bonded account cannot reserve balance from free balance ExtBuilder::default().build_and_execute(|| { // Confirm account 11 is stashed - assert_eq!(Staking::bonded(&11), Some(10)); + assert_eq!(Bonded::::get(&11), Some(10)); // Confirm account 11 has some free balance assert_eq!(Balances::free_balance(11), 1000); // Confirm account 11 (via controller 10) is totally staked - assert_eq!(Staking::eras_stakers(active_era(), 11).own, 1000); + assert_eq!(ErasStakers::::get(active_era(), 11).own, 1000); // Confirm account 11 cannot reserve as a result assert_noop!(Balances::reserve(&11, 1), BalancesError::::LiquidityRestrictions); @@ -1017,14 +1017,14 @@ fn reward_destination_works() { // Rewards go to the correct destination as determined in Payee ExtBuilder::default().nominate(false).build_and_execute(|| { // Check that account 11 is a validator - assert!(Session::validators().contains(&11)); + assert!(pallet_session::Validators::::get().contains(&11)); // Check the balance of the validator account assert_eq!(Balances::free_balance(10), 1); // Check the balance of the stash account assert_eq!(Balances::free_balance(11), 1000); // Check how much is at stake assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1042,12 +1042,12 @@ fn reward_destination_works() { mock::make_all_reward_payment(0); // Check that RewardDestination is Staked (default) - assert_eq!(Staking::payee(&11), RewardDestination::Staked); + assert_eq!(Payee::::get(&11), RewardDestination::Staked); // Check that reward went to the stash account of validator assert_eq!(Balances::free_balance(11), 1000 + total_payout_0); // Check that amount at stake increased accordingly assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000 + total_payout_0, @@ -1068,14 +1068,14 @@ fn reward_destination_works() { mock::make_all_reward_payment(1); // Check that RewardDestination is Stash - assert_eq!(Staking::payee(&11), RewardDestination::Stash); + assert_eq!(Payee::::get(&11), RewardDestination::Stash); // Check that reward went to the stash account assert_eq!(Balances::free_balance(11), 1000 + total_payout_0 + total_payout_1); // Record this value let recorded_stash_balance = 1000 + total_payout_0 + total_payout_1; // Check that amount at stake is NOT increased assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000 + total_payout_0, @@ -1099,12 +1099,12 @@ fn reward_destination_works() { mock::make_all_reward_payment(2); // Check that RewardDestination is Controller - assert_eq!(Staking::payee(&11), RewardDestination::Controller); + assert_eq!(Payee::::get(&11), RewardDestination::Controller); // Check that reward went to the controller account assert_eq!(Balances::free_balance(10), 1 + total_payout_2); // Check that amount at stake is NOT increased assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000 + total_payout_0, @@ -1139,7 +1139,7 @@ fn validator_payment_prefs_work() { // Compute total payout now for whole duration as other parameter won't change let total_payout_1 = current_total_payout_for_duration(reward_time_per_era()); - let exposure_1 = Staking::eras_stakers(active_era(), 11); + let exposure_1 = ErasStakers::::get(active_era(), 11); Pallet::::reward_by_ids(vec![(11, 1)]); mock::start_active_era(2); @@ -1163,10 +1163,10 @@ fn bond_extra_works() { // Check that account 10 is a validator assert!(>::contains_key(11)); // Check that account 10 is bonded to account 11 - assert_eq!(Staking::bonded(&11), Some(10)); + assert_eq!(Bonded::::get(&11), Some(10)); // Check how much is at stake assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1183,7 +1183,7 @@ fn bond_extra_works() { assert_ok!(Staking::bond_extra(RuntimeOrigin::signed(11), 100)); // There should be 100 more `total` and `active` in the ledger assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000 + 100, @@ -1197,7 +1197,7 @@ fn bond_extra_works() { assert_ok!(Staking::bond_extra(RuntimeOrigin::signed(11), Balance::max_value())); // The full amount of the funds should now be in the total and active assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000000, @@ -1235,7 +1235,7 @@ fn bond_extra_and_withdraw_unbonded_works() { // Initial state of 10 assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1245,7 +1245,7 @@ fn bond_extra_and_withdraw_unbonded_works() { }) ); assert_eq!( - Staking::eras_stakers(active_era(), 11), + ErasStakers::::get(active_era(), 11), Exposure { total: 1000, own: 1000, others: vec![] } ); @@ -1253,7 +1253,7 @@ fn bond_extra_and_withdraw_unbonded_works() { Staking::bond_extra(RuntimeOrigin::signed(11), 100).unwrap(); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000 + 100, @@ -1264,7 +1264,7 @@ fn bond_extra_and_withdraw_unbonded_works() { ); // Exposure is a snapshot! only updated after the next era update. assert_ne!( - Staking::eras_stakers(active_era(), 11), + ErasStakers::::get(active_era(), 11), Exposure { total: 1000 + 100, own: 1000 + 100, others: vec![] } ); @@ -1274,7 +1274,7 @@ fn bond_extra_and_withdraw_unbonded_works() { // ledger should be the same. assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000 + 100, @@ -1285,14 +1285,14 @@ fn bond_extra_and_withdraw_unbonded_works() { ); // Exposure is now updated. assert_eq!( - Staking::eras_stakers(active_era(), 11), + ErasStakers::::get(active_era(), 11), Exposure { total: 1000 + 100, own: 1000 + 100, others: vec![] } ); // Unbond almost all of the funds in stash. Staking::unbond(RuntimeOrigin::signed(10), 1000).unwrap(); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000 + 100, @@ -1305,7 +1305,7 @@ fn bond_extra_and_withdraw_unbonded_works() { // Attempting to free the balances now will fail. 2 eras need to pass. assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(10), 0)); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000 + 100, @@ -1321,7 +1321,7 @@ fn bond_extra_and_withdraw_unbonded_works() { // nothing yet assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(10), 0)); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000 + 100, @@ -1337,7 +1337,7 @@ fn bond_extra_and_withdraw_unbonded_works() { assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(10), 0)); // Now the value is free and the staking ledger is updated. assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 100, @@ -1371,7 +1371,7 @@ fn many_unbond_calls_should_work() { // `BondingDuration` == 3). assert_ok!(Staking::unbond(RuntimeOrigin::signed(10), 1)); assert_eq!( - Staking::ledger(&10).map(|l| l.unlocking.len()).unwrap(), + Ledger::::get(&10).map(|l| l.unlocking.len()).unwrap(), <::MaxUnlockingChunks as Get>::get() as usize ); @@ -1386,7 +1386,7 @@ fn many_unbond_calls_should_work() { // only slots within last `BondingDuration` are filled. assert_eq!( - Staking::ledger(&10).map(|l| l.unlocking.len()).unwrap(), + Ledger::::get(&10).map(|l| l.unlocking.len()).unwrap(), <::BondingDuration>::get() as usize ); }) @@ -1440,7 +1440,7 @@ fn rebond_works() { // Initial state of 10 assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1459,7 +1459,7 @@ fn rebond_works() { // Unbond almost all of the funds in stash. Staking::unbond(RuntimeOrigin::signed(10), 900).unwrap(); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1472,7 +1472,7 @@ fn rebond_works() { // Re-bond all the funds unbonded. Staking::rebond(RuntimeOrigin::signed(10), 900).unwrap(); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1485,7 +1485,7 @@ fn rebond_works() { // Unbond almost all of the funds in stash. Staking::unbond(RuntimeOrigin::signed(10), 900).unwrap(); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1498,7 +1498,7 @@ fn rebond_works() { // Re-bond part of the funds unbonded. Staking::rebond(RuntimeOrigin::signed(10), 500).unwrap(); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1511,7 +1511,7 @@ fn rebond_works() { // Re-bond the remainder of the funds unbonded. Staking::rebond(RuntimeOrigin::signed(10), 500).unwrap(); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1526,7 +1526,7 @@ fn rebond_works() { Staking::unbond(RuntimeOrigin::signed(10), 300).unwrap(); Staking::unbond(RuntimeOrigin::signed(10), 300).unwrap(); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1539,7 +1539,7 @@ fn rebond_works() { // Re-bond part of the funds unbonded. Staking::rebond(RuntimeOrigin::signed(10), 500).unwrap(); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1566,7 +1566,7 @@ fn rebond_is_fifo() { // Initial state of 10 assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1581,7 +1581,7 @@ fn rebond_is_fifo() { // Unbond some of the funds in stash. Staking::unbond(RuntimeOrigin::signed(10), 400).unwrap(); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1596,7 +1596,7 @@ fn rebond_is_fifo() { // Unbond more of the funds in stash. Staking::unbond(RuntimeOrigin::signed(10), 300).unwrap(); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1614,7 +1614,7 @@ fn rebond_is_fifo() { // Unbond yet more of the funds in stash. Staking::unbond(RuntimeOrigin::signed(10), 200).unwrap(); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1631,7 +1631,7 @@ fn rebond_is_fifo() { // Re-bond half of the unbonding funds. Staking::rebond(RuntimeOrigin::signed(10), 400).unwrap(); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1663,7 +1663,7 @@ fn rebond_emits_right_value_in_event() { // Unbond almost all of the funds in stash. Staking::unbond(RuntimeOrigin::signed(10), 900).unwrap(); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1676,7 +1676,7 @@ fn rebond_emits_right_value_in_event() { // Re-bond less than the total Staking::rebond(RuntimeOrigin::signed(10), 100).unwrap(); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1691,7 +1691,7 @@ fn rebond_emits_right_value_in_event() { // Re-bond way more than available Staking::rebond(RuntimeOrigin::signed(10), 100_000).unwrap(); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -1713,12 +1713,12 @@ fn reward_to_stake_works() { .set_status(41, StakerStatus::Idle) .set_stake(21, 2000) .build_and_execute(|| { - assert_eq!(Staking::validator_count(), 2); + assert_eq!(ValidatorCount::::get(), 2); // Confirm account 10 and 20 are validators assert!(>::contains_key(&11) && >::contains_key(&21)); - assert_eq!(Staking::eras_stakers(active_era(), 11).total, 1000); - assert_eq!(Staking::eras_stakers(active_era(), 21).total, 2000); + assert_eq!(ErasStakers::::get(active_era(), 11).total, 1000); + assert_eq!(ErasStakers::::get(active_era(), 21).total, 2000); // Give the man some money. let _ = Balances::make_free_balance_be(&10, 1000); @@ -1746,8 +1746,8 @@ fn reward_to_stake_works() { mock::start_active_era(1); mock::make_all_reward_payment(0); - assert_eq!(Staking::eras_stakers(active_era(), 11).total, 1000); - assert_eq!(Staking::eras_stakers(active_era(), 21).total, 69); + assert_eq!(ErasStakers::::get(active_era(), 11).total, 1000); + assert_eq!(ErasStakers::::get(active_era(), 21).total, 69); let _11_balance = Balances::free_balance(&11); assert_eq!(_11_balance, 1000 + total_payout_0 / 2); @@ -1756,8 +1756,8 @@ fn reward_to_stake_works() { mock::start_active_era(2); // -- new infos - assert_eq!(Staking::eras_stakers(active_era(), 11).total, 1000 + total_payout_0 / 2); - assert_eq!(Staking::eras_stakers(active_era(), 21).total, 69 + total_payout_0 / 2); + assert_eq!(ErasStakers::::get(active_era(), 11).total, 1000 + total_payout_0 / 2); + assert_eq!(ErasStakers::::get(active_era(), 21).total, 69 + total_payout_0 / 2); }); } @@ -1770,7 +1770,7 @@ fn reap_stash_works() { // given assert_eq!(Balances::free_balance(10), 10); assert_eq!(Balances::free_balance(11), 10 * 1000); - assert_eq!(Staking::bonded(&11), Some(10)); + assert_eq!(Bonded::::get(&11), Some(10)); assert!(>::contains_key(&10)); assert!(>::contains_key(&11)); @@ -1893,8 +1893,8 @@ fn wrong_vote_is_moot() { assert_eq_uvec!(validator_controllers(), vec![20, 10]); // our new voter is taken into account - assert!(Staking::eras_stakers(active_era(), 11).others.iter().any(|i| i.who == 61)); - assert!(Staking::eras_stakers(active_era(), 21).others.iter().any(|i| i.who == 61)); + assert!(ErasStakers::::get(active_era(), 11).others.iter().any(|i| i.who == 61)); + assert!(ErasStakers::::get(active_era(), 21).others.iter().any(|i| i.who == 61)); }); } @@ -1921,12 +1921,12 @@ fn bond_with_no_staked_value() { 5, RewardDestination::Controller )); - assert_eq!(Balances::locks(&1)[0].amount, 5); + assert_eq!(pallet_balances::Locks::::get(&1)[0].amount, 5); // unbonding even 1 will cause all to be unbonded. assert_ok!(Staking::unbond(RuntimeOrigin::signed(2), 1)); assert_eq!( - Staking::ledger(2), + Ledger::::get(2), Some(StakingLedger { stash: 1, active: 0, @@ -1941,15 +1941,15 @@ fn bond_with_no_staked_value() { // not yet removed. assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(2), 0)); - assert!(Staking::ledger(2).is_some()); - assert_eq!(Balances::locks(&1)[0].amount, 5); + assert!(Ledger::::get(2).is_some()); + assert_eq!(pallet_balances::Locks::::get(&1)[0].amount, 5); mock::start_active_era(3); // poof. Account 1 is removed from the staking system. assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(2), 0)); - assert!(Staking::ledger(2).is_none()); - assert_eq!(Balances::locks(&1).len(), 0); + assert!(Ledger::::get(2).is_none()); + assert_eq!(pallet_balances::Locks::::get(&1).len(), 0); }); } @@ -1993,7 +1993,7 @@ fn bond_with_little_staked_value_bounded() { // 2 is elected. assert_eq_uvec!(validator_controllers(), vec![20, 10, 2]); - assert_eq!(Staking::eras_stakers(active_era(), 2).total, 0); + assert_eq!(ErasStakers::::get(active_era(), 2).total, 0); // Old ones are rewarded. assert_eq_error_rate!( @@ -2011,7 +2011,7 @@ fn bond_with_little_staked_value_bounded() { mock::make_all_reward_payment(1); assert_eq_uvec!(validator_controllers(), vec![20, 10, 2]); - assert_eq!(Staking::eras_stakers(active_era(), 2).total, 0); + assert_eq!(ErasStakers::::get(active_era(), 2).total, 0); // 2 is now rewarded. assert_eq_error_rate!( @@ -2038,7 +2038,7 @@ fn bond_with_duplicate_vote_should_be_ignored_by_election_provider() { // ensure all have equal stake. assert_eq!( >::iter() - .map(|(v, _)| (v, Staking::ledger(v - 1).unwrap().total)) + .map(|(v, _)| (v, Ledger::::get(v - 1).unwrap().total)) .collect::>(), vec![(31, 1000), (21, 1000), (11, 1000)], ); @@ -2092,7 +2092,7 @@ fn bond_with_duplicate_vote_should_be_ignored_by_election_provider_elected() { // ensure all have equal stake. assert_eq!( >::iter() - .map(|(v, _)| (v, Staking::ledger(v - 1).unwrap().total)) + .map(|(v, _)| (v, Ledger::::get(v - 1).unwrap().total)) .collect::>(), vec![(31, 1000), (21, 1000), (11, 1000)], ); @@ -2137,7 +2137,7 @@ fn bond_with_duplicate_vote_should_be_ignored_by_election_provider_elected() { #[test] fn new_era_elects_correct_number_of_validators() { ExtBuilder::default().nominate(true).validator_count(1).build_and_execute(|| { - assert_eq!(Staking::validator_count(), 1); + assert_eq!(ValidatorCount::::get(), 1); assert_eq!(validator_controllers().len(), 1); Session::on_initialize(System::block_number()); @@ -2166,8 +2166,8 @@ fn phragmen_should_not_overflow() { assert_eq_uvec!(validator_controllers(), vec![4, 2]); // We can safely convert back to values within [u64, u128]. - assert!(Staking::eras_stakers(active_era(), 3).total > Votes::max_value() as Balance); - assert!(Staking::eras_stakers(active_era(), 5).total > Votes::max_value() as Balance); + assert!(ErasStakers::::get(active_era(), 3).total > Votes::max_value() as Balance); + assert!(ErasStakers::::get(active_era(), 5).total > Votes::max_value() as Balance); }) } @@ -2218,7 +2218,7 @@ fn reward_validator_slashing_validator_does_not_overflow() { // Check slashing on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(100)], @@ -2240,7 +2240,7 @@ fn reward_from_authorship_event_handler_works() { Pallet::::note_author(11); // Not mandatory but must be coherent with rewards - assert_eq_uvec!(Session::validators(), vec![11, 21]); + assert_eq_uvec!(pallet_session::Validators::::get(), vec![11, 21]); // 21 is rewarded as an uncle producer // 11 is rewarded as a block producer and uncle referencer and uncle producer @@ -2255,7 +2255,7 @@ fn reward_from_authorship_event_handler_works() { fn add_reward_points_fns_works() { ExtBuilder::default().build_and_execute(|| { // Not mandatory but must be coherent with rewards - assert_eq_uvec!(Session::validators(), vec![21, 11]); + assert_eq_uvec!(pallet_session::Validators::::get(), vec![21, 11]); Pallet::::reward_by_ids(vec![(21, 1), (11, 1), (11, 1)]); @@ -2289,24 +2289,24 @@ fn era_is_always_same_length() { let session_per_era = >::get(); mock::start_active_era(1); - assert_eq!(Staking::eras_start_session_index(current_era()).unwrap(), session_per_era); + assert_eq!(ErasStartSessionIndex::::get(current_era()).unwrap(), session_per_era); mock::start_active_era(2); assert_eq!( - Staking::eras_start_session_index(current_era()).unwrap(), + ErasStartSessionIndex::::get(current_era()).unwrap(), session_per_era * 2u32 ); - let session = Session::current_index(); + let session = pallet_session::CurrentIndex::::get(); Staking::set_force_era(Forcing::ForceNew); advance_session(); advance_session(); assert_eq!(current_era(), 3); - assert_eq!(Staking::eras_start_session_index(current_era()).unwrap(), session + 2); + assert_eq!(ErasStartSessionIndex::::get(current_era()).unwrap(), session + 2); mock::start_active_era(4); assert_eq!( - Staking::eras_start_session_index(current_era()).unwrap(), + ErasStartSessionIndex::::get(current_era()).unwrap(), session + 2u32 + session_per_era ); }); @@ -2317,13 +2317,13 @@ fn offence_forces_new_era() { ExtBuilder::default().build_and_execute(|| { on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(5)], ); - assert_eq!(Staking::force_era(), Forcing::ForceNew); + assert_eq!(ForceEra::::get(), Forcing::ForceNew); }); } @@ -2331,40 +2331,40 @@ fn offence_forces_new_era() { fn offence_ensures_new_era_without_clobbering() { ExtBuilder::default().build_and_execute(|| { assert_ok!(Staking::force_new_era_always(RuntimeOrigin::root())); - assert_eq!(Staking::force_era(), Forcing::ForceAlways); + assert_eq!(ForceEra::::get(), Forcing::ForceAlways); on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(5)], ); - assert_eq!(Staking::force_era(), Forcing::ForceAlways); + assert_eq!(ForceEra::::get(), Forcing::ForceAlways); }); } #[test] fn offence_deselects_validator_even_when_slash_is_zero() { ExtBuilder::default().build_and_execute(|| { - assert!(Session::validators().contains(&11)); + assert!(pallet_session::Validators::::get().contains(&11)); assert!(>::contains_key(11)); on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(0)], ); - assert_eq!(Staking::force_era(), Forcing::ForceNew); + assert_eq!(ForceEra::::get(), Forcing::ForceNew); assert!(!>::contains_key(11)); mock::start_active_era(1); - assert!(!Session::validators().contains(&11)); + assert!(!pallet_session::Validators::::get().contains(&11)); assert!(!>::contains_key(11)); }); } @@ -2374,7 +2374,7 @@ fn slashing_performed_according_exposure() { // This test checks that slashing is performed according the exposure (or more precisely, // historical exposure), not the current balance. ExtBuilder::default().build_and_execute(|| { - assert_eq!(Staking::eras_stakers(active_era(), 11).own, 1000); + assert_eq!(ErasStakers::::get(active_era(), 11).own, 1000); // Handle an offence with a historical exposure. on_offence_now( @@ -2396,25 +2396,25 @@ fn slash_in_old_span_does_not_deselect() { mock::start_active_era(1); assert!(>::contains_key(11)); - assert!(Session::validators().contains(&11)); + assert!(pallet_session::Validators::::get().contains(&11)); on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(0)], ); - assert_eq!(Staking::force_era(), Forcing::ForceNew); + assert_eq!(ForceEra::::get(), Forcing::ForceNew); assert!(!>::contains_key(11)); mock::start_active_era(2); Staking::validate(RuntimeOrigin::signed(10), Default::default()).unwrap(); - assert_eq!(Staking::force_era(), Forcing::NotForcing); + assert_eq!(ForceEra::::get(), Forcing::NotForcing); assert!(>::contains_key(11)); - assert!(!Session::validators().contains(&11)); + assert!(!pallet_session::Validators::::get().contains(&11)); mock::start_active_era(3); @@ -2423,7 +2423,7 @@ fn slash_in_old_span_does_not_deselect() { on_offence_in_era( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(0)], @@ -2435,11 +2435,11 @@ fn slash_in_old_span_does_not_deselect() { assert!(::Validators::iter().any(|(stash, _)| stash == 11)); // but we are still forcing a new era - assert_eq!(Staking::force_era(), Forcing::ForceNew); + assert_eq!(ForceEra::::get(), Forcing::ForceNew); on_offence_in_era( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], // NOTE: A 100% slash here would clean up the account, causing de-registration. @@ -2454,7 +2454,7 @@ fn slash_in_old_span_does_not_deselect() { // but it's disabled assert!(is_disabled(10)); // and we are still forcing a new era - assert_eq!(Staking::force_era(), Forcing::ForceNew); + assert_eq!(ForceEra::::get(), Forcing::ForceNew); }); } @@ -2466,11 +2466,11 @@ fn reporters_receive_their_slice() { // The reporters' reward is calculated from the total exposure. let initial_balance = 1125; - assert_eq!(Staking::eras_stakers(active_era(), 11).total, initial_balance); + assert_eq!(ErasStakers::::get(active_era(), 11).total, initial_balance); on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![1, 2], }], &[Perbill::from_percent(50)], @@ -2493,11 +2493,11 @@ fn subsequent_reports_in_same_span_pay_out_less() { // The reporters' reward is calculated from the total exposure. let initial_balance = 1125; - assert_eq!(Staking::eras_stakers(active_era(), 11).total, initial_balance); + assert_eq!(ErasStakers::::get(active_era(), 11).total, initial_balance); on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![1], }], &[Perbill::from_percent(20)], @@ -2510,7 +2510,7 @@ fn subsequent_reports_in_same_span_pay_out_less() { on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![1], }], &[Perbill::from_percent(50)], @@ -2532,7 +2532,7 @@ fn invulnerables_are_not_slashed() { assert_eq!(Balances::free_balance(11), 1000); assert_eq!(Balances::free_balance(21), 2000); - let exposure = Staking::eras_stakers(active_era(), 21); + let exposure = ErasStakers::::get(active_era(), 21); let initial_balance = Staking::slashable_balance_of(&21); let nominator_balances: Vec<_> = @@ -2541,11 +2541,11 @@ fn invulnerables_are_not_slashed() { on_offence_now( &[ OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }, OffenceDetails { - offender: (21, Staking::eras_stakers(active_era(), 21)), + offender: (21, ErasStakers::::get(active_era(), 21)), reporters: vec![], }, ], @@ -2575,7 +2575,7 @@ fn dont_slash_if_fraction_is_zero() { on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(0)], @@ -2583,7 +2583,7 @@ fn dont_slash_if_fraction_is_zero() { // The validator hasn't been slashed. The new era is not forced. assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Staking::force_era(), Forcing::ForceNew); + assert_eq!(ForceEra::::get(), Forcing::ForceNew); }); } @@ -2596,7 +2596,7 @@ fn only_slash_for_max_in_era() { on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(50)], @@ -2604,11 +2604,11 @@ fn only_slash_for_max_in_era() { // The validator has been slashed and has been force-chilled. assert_eq!(Balances::free_balance(11), 500); - assert_eq!(Staking::force_era(), Forcing::ForceNew); + assert_eq!(ForceEra::::get(), Forcing::ForceNew); on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(25)], @@ -2619,7 +2619,7 @@ fn only_slash_for_max_in_era() { on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(60)], @@ -2641,7 +2641,7 @@ fn garbage_collection_after_slashing() { on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(10)], @@ -2653,7 +2653,7 @@ fn garbage_collection_after_slashing() { on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(100)], @@ -2690,12 +2690,15 @@ fn garbage_collection_on_window_pruning() { assert_eq!(Balances::free_balance(11), 1000); let now = active_era(); - let exposure = Staking::eras_stakers(now, 11); + let exposure = ErasStakers::::get(now, 11); assert_eq!(Balances::free_balance(101), 2000); let nominated_value = exposure.others.iter().find(|o| o.who == 101).unwrap().value; on_offence_now( - &[OffenceDetails { offender: (11, Staking::eras_stakers(now, 11)), reporters: vec![] }], + &[OffenceDetails { + offender: (11, ErasStakers::::get(now, 11)), + reporters: vec![], + }], &[Perbill::from_percent(10)], ); @@ -2730,14 +2733,14 @@ fn slashing_nominators_by_span_max() { assert_eq!(Balances::free_balance(101), 2000); assert_eq!(Staking::slashable_balance_of(&21), 1000); - let exposure_11 = Staking::eras_stakers(active_era(), 11); - let exposure_21 = Staking::eras_stakers(active_era(), 21); + let exposure_11 = ErasStakers::::get(active_era(), 11); + let exposure_21 = ErasStakers::::get(active_era(), 21); let nominated_value_11 = exposure_11.others.iter().find(|o| o.who == 101).unwrap().value; let nominated_value_21 = exposure_21.others.iter().find(|o| o.who == 101).unwrap().value; on_offence_in_era( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(10)], @@ -2764,7 +2767,7 @@ fn slashing_nominators_by_span_max() { // second slash: higher era, higher value, same span. on_offence_in_era( &[OffenceDetails { - offender: (21, Staking::eras_stakers(active_era(), 21)), + offender: (21, ErasStakers::::get(active_era(), 21)), reporters: vec![], }], &[Perbill::from_percent(30)], @@ -2786,7 +2789,7 @@ fn slashing_nominators_by_span_max() { // in-era value, but lower slash value than slash 2. on_offence_in_era( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(20)], @@ -2821,7 +2824,7 @@ fn slashes_are_summed_across_spans() { on_offence_now( &[OffenceDetails { - offender: (21, Staking::eras_stakers(active_era(), 21)), + offender: (21, ErasStakers::::get(active_era(), 21)), reporters: vec![], }], &[Perbill::from_percent(10)], @@ -2844,7 +2847,7 @@ fn slashes_are_summed_across_spans() { on_offence_now( &[OffenceDetails { - offender: (21, Staking::eras_stakers(active_era(), 21)), + offender: (21, ErasStakers::::get(active_era(), 21)), reporters: vec![], }], &[Perbill::from_percent(10)], @@ -2868,7 +2871,7 @@ fn deferred_slashes_are_deferred() { assert_eq!(Balances::free_balance(11), 1000); - let exposure = Staking::eras_stakers(active_era(), 11); + let exposure = ErasStakers::::get(active_era(), 11); assert_eq!(Balances::free_balance(101), 2000); let nominated_value = exposure.others.iter().find(|o| o.who == 101).unwrap().value; @@ -2876,14 +2879,14 @@ fn deferred_slashes_are_deferred() { on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(10)], ); // nominations are not removed regardless of the deferring. - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); assert_eq!(Balances::free_balance(11), 1000); assert_eq!(Balances::free_balance(101), 2000); @@ -2927,11 +2930,11 @@ fn retroactive_deferred_slashes_two_eras_before() { assert_eq!(BondingDuration::get(), 3); mock::start_active_era(1); - let exposure_11_at_era1 = Staking::eras_stakers(active_era(), 11); + let exposure_11_at_era1 = ErasStakers::::get(active_era(), 11); mock::start_active_era(3); - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); System::reset_events(); on_offence_in_era( @@ -2963,7 +2966,7 @@ fn retroactive_deferred_slashes_one_before() { assert_eq!(BondingDuration::get(), 3); mock::start_active_era(1); - let exposure_11_at_era1 = Staking::eras_stakers(active_era(), 11); + let exposure_11_at_era1 = ErasStakers::::get(active_era(), 11); // unbond at slash era. mock::start_active_era(2); @@ -2981,7 +2984,7 @@ fn retroactive_deferred_slashes_one_before() { mock::start_active_era(4); - assert_eq!(Staking::ledger(10).unwrap().total, 1000); + assert_eq!(Ledger::::get(10).unwrap().total, 1000); // slash happens after the next line. mock::start_active_era(5); @@ -2996,9 +2999,9 @@ fn retroactive_deferred_slashes_one_before() { )); // their ledger has already been slashed. - assert_eq!(Staking::ledger(10).unwrap().total, 900); + assert_eq!(Ledger::::get(10).unwrap().total, 900); assert_ok!(Staking::unbond(RuntimeOrigin::signed(10), 1000)); - assert_eq!(Staking::ledger(10).unwrap().total, 900); + assert_eq!(Ledger::::get(10).unwrap().total, 900); }) } @@ -3011,12 +3014,12 @@ fn staker_cannot_bail_deferred_slash() { assert_eq!(Balances::free_balance(11), 1000); assert_eq!(Balances::free_balance(101), 2000); - let exposure = Staking::eras_stakers(active_era(), 11); + let exposure = ErasStakers::::get(active_era(), 11); let nominated_value = exposure.others.iter().find(|o| o.who == 101).unwrap().value; on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(10)], @@ -3026,7 +3029,7 @@ fn staker_cannot_bail_deferred_slash() { assert_ok!(Staking::chill(RuntimeOrigin::signed(100))); assert_ok!(Staking::unbond(RuntimeOrigin::signed(100), 500)); - assert_eq!(Staking::current_era().unwrap(), 1); + assert_eq!(CurrentEra::::get().unwrap(), 1); assert_eq!(active_era(), 1); assert_eq!( @@ -3048,14 +3051,14 @@ fn staker_cannot_bail_deferred_slash() { mock::start_active_era(2); assert_eq!(Balances::free_balance(11), 1000); assert_eq!(Balances::free_balance(101), 2000); - assert_eq!(Staking::current_era().unwrap(), 2); + assert_eq!(CurrentEra::::get().unwrap(), 2); assert_eq!(active_era(), 2); // no slash yet. mock::start_active_era(3); assert_eq!(Balances::free_balance(11), 1000); assert_eq!(Balances::free_balance(101), 2000); - assert_eq!(Staking::current_era().unwrap(), 3); + assert_eq!(CurrentEra::::get().unwrap(), 3); assert_eq!(active_era(), 3); // and cannot yet unbond: @@ -3085,7 +3088,7 @@ fn remove_deferred() { assert_eq!(Balances::free_balance(11), 1000); - let exposure = Staking::eras_stakers(active_era(), 11); + let exposure = ErasStakers::::get(active_era(), 11); assert_eq!(Balances::free_balance(101), 2000); let nominated_value = exposure.others.iter().find(|o| o.who == 101).unwrap().value; @@ -3161,7 +3164,7 @@ fn remove_multi_deferred() { assert_eq!(Balances::free_balance(11), 1000); - let exposure = Staking::eras_stakers(active_era(), 11); + let exposure = ErasStakers::::get(active_era(), 11); assert_eq!(Balances::free_balance(101), 2000); on_offence_now( @@ -3171,7 +3174,7 @@ fn remove_multi_deferred() { on_offence_now( &[OffenceDetails { - offender: (21, Staking::eras_stakers(active_era(), 21)), + offender: (21, ErasStakers::::get(active_era(), 21)), reporters: vec![], }], &[Perbill::from_percent(10)], @@ -3223,18 +3226,18 @@ fn remove_multi_deferred() { fn slash_kicks_validators_not_nominators_and_disables_nominator_for_kicked_validator() { ExtBuilder::default().build_and_execute(|| { mock::start_active_era(1); - assert_eq_uvec!(Session::validators(), vec![11, 21]); + assert_eq_uvec!(pallet_session::Validators::::get(), vec![11, 21]); // pre-slash balance assert_eq!(Balances::free_balance(11), 1000); assert_eq!(Balances::free_balance(101), 2000); // 100 has approval for 11 as of now - assert!(Staking::nominators(101).unwrap().targets.contains(&11)); + assert!(Nominators::::get(101).unwrap().targets.contains(&11)); // 11 and 21 both have the support of 100 - let exposure_11 = Staking::eras_stakers(active_era(), &11); - let exposure_21 = Staking::eras_stakers(active_era(), &21); + let exposure_11 = ErasStakers::::get(active_era(), &11); + let exposure_21 = ErasStakers::::get(active_era(), &21); assert_eq!(exposure_11.total, 1000 + 125); assert_eq!(exposure_21.total, 1000 + 375); @@ -3273,8 +3276,8 @@ fn slash_kicks_validators_not_nominators_and_disables_nominator_for_kicked_valid assert_ok!(Staking::validate(RuntimeOrigin::signed(10), Default::default())); mock::start_active_era(2); - let exposure_11 = Staking::eras_stakers(active_era(), &11); - let exposure_21 = Staking::eras_stakers(active_era(), &21); + let exposure_11 = ErasStakers::::get(active_era(), &11); + let exposure_21 = ErasStakers::::get(active_era(), &21); // 11's own expo is reduced. sum of support from 11 is less (448), which is 500 // 900 + 146 @@ -3289,10 +3292,10 @@ fn slash_kicks_validators_not_nominators_and_disables_nominator_for_kicked_valid fn non_slashable_offence_doesnt_disable_validator() { ExtBuilder::default().build_and_execute(|| { mock::start_active_era(1); - assert_eq_uvec!(Session::validators(), vec![11, 21]); + assert_eq_uvec!(pallet_session::Validators::::get(), vec![11, 21]); - let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11); - let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21); + let exposure_11 = ErasStakers::::get(ActiveEra::::get().unwrap().index, &11); + let exposure_21 = ErasStakers::::get(ActiveEra::::get().unwrap().index, &21); // offence with no slash associated on_offence_now( @@ -3301,7 +3304,7 @@ fn non_slashable_offence_doesnt_disable_validator() { ); // it does NOT affect the nominator. - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); // offence that slashes 25% of the bond on_offence_now( @@ -3310,7 +3313,7 @@ fn non_slashable_offence_doesnt_disable_validator() { ); // it DOES NOT affect the nominator. - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); assert_eq!( staking_events_since_last_call(), @@ -3346,12 +3349,12 @@ fn non_slashable_offence_doesnt_disable_validator() { fn slashing_independent_of_disabling_validator() { ExtBuilder::default().build_and_execute(|| { mock::start_active_era(1); - assert_eq_uvec!(Session::validators(), vec![11, 21]); + assert_eq_uvec!(pallet_session::Validators::::get(), vec![11, 21]); - let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11); - let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21); + let exposure_11 = ErasStakers::::get(ActiveEra::::get().unwrap().index, &11); + let exposure_21 = ErasStakers::::get(ActiveEra::::get().unwrap().index, &21); - let now = Staking::active_era().unwrap().index; + let now = ActiveEra::::get().unwrap().index; // offence with no slash associated, BUT disabling on_offence_in_era( @@ -3362,7 +3365,7 @@ fn slashing_independent_of_disabling_validator() { ); // nomination remains untouched. - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); // offence that slashes 25% of the bond, BUT not disabling on_offence_in_era( @@ -3373,7 +3376,7 @@ fn slashing_independent_of_disabling_validator() { ); // nomination remains untouched. - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); assert_eq!( staking_events_since_last_call(), @@ -3412,7 +3415,7 @@ fn offence_threshold_triggers_new_era() { .set_status(41, StakerStatus::Validator) .build_and_execute(|| { mock::start_active_era(1); - assert_eq_uvec!(Session::validators(), vec![11, 21, 31, 41]); + assert_eq_uvec!(pallet_session::Validators::::get(), vec![11, 21, 31, 41]); assert_eq!( ::OffendingValidatorsThreshold::get(), @@ -3422,9 +3425,12 @@ fn offence_threshold_triggers_new_era() { // we have 4 validators and an offending validator threshold of 75%, // once the third validator commits an offence a new era should be forced - let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11); - let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21); - let exposure_31 = Staking::eras_stakers(Staking::active_era().unwrap().index, &31); + let exposure_11 = + ErasStakers::::get(ActiveEra::::get().unwrap().index, &11); + let exposure_21 = + ErasStakers::::get(ActiveEra::::get().unwrap().index, &21); + let exposure_31 = + ErasStakers::::get(ActiveEra::::get().unwrap().index, &31); on_offence_now( &[OffenceDetails { offender: (11, exposure_11.clone()), reporters: vec![] }], @@ -3456,11 +3462,13 @@ fn disabled_validators_are_kept_disabled_for_whole_era() { .set_status(41, StakerStatus::Validator) .build_and_execute(|| { mock::start_active_era(1); - assert_eq_uvec!(Session::validators(), vec![11, 21, 31, 41]); + assert_eq_uvec!(pallet_session::Validators::::get(), vec![11, 21, 31, 41]); assert_eq!(::SessionsPerEra::get(), 3); - let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11); - let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21); + let exposure_11 = + ErasStakers::::get(ActiveEra::::get().unwrap().index, &11); + let exposure_21 = + ErasStakers::::get(ActiveEra::::get().unwrap().index, &21); on_offence_now( &[OffenceDetails { offender: (11, exposure_11.clone()), reporters: vec![] }], @@ -3473,7 +3481,7 @@ fn disabled_validators_are_kept_disabled_for_whole_era() { ); // nominations are not updated. - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); // validator 10 should not be disabled since the offence wasn't slashable assert!(!is_disabled(10)); @@ -3493,7 +3501,7 @@ fn disabled_validators_are_kept_disabled_for_whole_era() { ); // nominations are not updated. - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); advance_session(); @@ -3557,7 +3565,7 @@ fn claim_reward_at_the_last_era_and_no_double_claim_and_invalid_claim() { let active_era = active_era(); // This is the latest planned era in staking, not the active era - let current_era = Staking::current_era().unwrap(); + let current_era = CurrentEra::::get().unwrap(); // Last kept is 1: assert!(current_era - HistoryDepth::get() == 1); @@ -3600,7 +3608,7 @@ fn zero_slash_keeps_nominators() { assert_eq!(Balances::free_balance(11), 1000); - let exposure = Staking::eras_stakers(active_era(), 11); + let exposure = ErasStakers::::get(active_era(), 11); assert_eq!(Balances::free_balance(101), 2000); on_offence_now( @@ -3614,7 +3622,7 @@ fn zero_slash_keeps_nominators() { // 11 is still removed.. assert!(::Validators::iter().all(|(stash, _)| stash != 11)); // but their nominations are kept. - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); }); } @@ -3623,8 +3631,8 @@ fn six_session_delay() { ExtBuilder::default().initialize_first_session(false).build_and_execute(|| { use pallet_session::SessionManager; - let val_set = Session::validators(); - let init_session = Session::current_index(); + let val_set = pallet_session::Validators::::get(); + let init_session = pallet_session::CurrentIndex::::get(); let init_active_era = active_era(); // pallet-session is delaying session by one, thus the next session to plan is +2. @@ -3673,8 +3681,8 @@ fn six_session_delay() { assert_eq!(active_era(), init_active_era + 2); // That reward are correct - assert_eq!(Staking::eras_reward_points(init_active_era).total, 1); - assert_eq!(Staking::eras_reward_points(init_active_era + 1).total, 2); + assert_eq!(ErasRewardPoints::::get(init_active_era).total, 1); + assert_eq!(ErasRewardPoints::::get(init_active_era + 1).total, 2); }); } @@ -3773,7 +3781,7 @@ fn test_payout_stakers() { // We track rewards in `claimed_rewards` vec assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -3804,7 +3812,7 @@ fn test_payout_stakers() { // We track rewards in `claimed_rewards` vec assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -3837,7 +3845,7 @@ fn test_payout_stakers() { expected_last_reward_era )); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -3852,7 +3860,7 @@ fn test_payout_stakers() { assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 23)); assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 42)); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -4064,7 +4072,7 @@ fn bond_during_era_correctly_populates_claimed_rewards() { // Era = None bond_validator(9, 8, 1000); assert_eq!( - Staking::ledger(&8), + Ledger::::get(&8), Some(StakingLedger { stash: 9, total: 1000, @@ -4076,7 +4084,7 @@ fn bond_during_era_correctly_populates_claimed_rewards() { mock::start_active_era(5); bond_validator(11, 10, 1000); assert_eq!( - Staking::ledger(&10), + Ledger::::get(&10), Some(StakingLedger { stash: 11, total: 1000, @@ -4092,7 +4100,7 @@ fn bond_during_era_correctly_populates_claimed_rewards() { mock::start_active_era(current_era); bond_validator(13, 12, 1000); assert_eq!( - Staking::ledger(&12), + Ledger::::get(&12), Some(StakingLedger { stash: 13, total: 1000, @@ -4130,7 +4138,7 @@ fn offences_weight_calculated_correctly() { >, > = (1..10) .map(|i| OffenceDetails { - offender: (i, Staking::eras_stakers(active_era(), i)), + offender: (i, ErasStakers::::get(active_era(), i)), reporters: vec![], }) .collect(); @@ -4146,7 +4154,7 @@ fn offences_weight_calculated_correctly() { // On Offence with one offenders, Applied let one_offender = [OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![1], }]; @@ -4240,44 +4248,44 @@ fn session_buffering_with_offset() { .build_and_execute(|| { assert_eq!(current_era(), 0); assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 0); + assert_eq!(pallet_session::CurrentIndex::::get(), 0); start_session(1); assert_eq!(current_era(), 0); assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 1); + assert_eq!(pallet_session::CurrentIndex::::get(), 1); assert_eq!(System::block_number(), 2); start_session(2); assert_eq!(current_era(), 0); assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 2); + assert_eq!(pallet_session::CurrentIndex::::get(), 2); assert_eq!(System::block_number(), 7); start_session(3); assert_eq!(current_era(), 0); assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 3); + assert_eq!(pallet_session::CurrentIndex::::get(), 3); assert_eq!(System::block_number(), 12); // active era is lagging behind by one session, because of how session module works. start_session(4); assert_eq!(current_era(), 1); assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 4); + assert_eq!(pallet_session::CurrentIndex::::get(), 4); assert_eq!(System::block_number(), 17); start_session(5); assert_eq!(current_era(), 1); assert_eq!(active_era(), 1); - assert_eq!(Session::current_index(), 5); + assert_eq!(pallet_session::CurrentIndex::::get(), 5); assert_eq!(System::block_number(), 22); // go all the way to active 2. start_active_era(2); assert_eq!(current_era(), 2); assert_eq!(active_era(), 2); - assert_eq!(Session::current_index(), 10); + assert_eq!(pallet_session::CurrentIndex::::get(), 10); }); } @@ -4291,44 +4299,44 @@ fn session_buffering_no_offset() { .build_and_execute(|| { assert_eq!(current_era(), 0); assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 0); + assert_eq!(pallet_session::CurrentIndex::::get(), 0); start_session(1); assert_eq!(current_era(), 0); assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 1); + assert_eq!(pallet_session::CurrentIndex::::get(), 1); assert_eq!(System::block_number(), 5); start_session(2); assert_eq!(current_era(), 0); assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 2); + assert_eq!(pallet_session::CurrentIndex::::get(), 2); assert_eq!(System::block_number(), 10); start_session(3); assert_eq!(current_era(), 0); assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 3); + assert_eq!(pallet_session::CurrentIndex::::get(), 3); assert_eq!(System::block_number(), 15); // active era is lagging behind by one session, because of how session module works. start_session(4); assert_eq!(current_era(), 1); assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 4); + assert_eq!(pallet_session::CurrentIndex::::get(), 4); assert_eq!(System::block_number(), 20); start_session(5); assert_eq!(current_era(), 1); assert_eq!(active_era(), 1); - assert_eq!(Session::current_index(), 5); + assert_eq!(pallet_session::CurrentIndex::::get(), 5); assert_eq!(System::block_number(), 25); // go all the way to active 2. start_active_era(2); assert_eq!(current_era(), 2); assert_eq!(active_era(), 2); - assert_eq!(Session::current_index(), 10); + assert_eq!(pallet_session::CurrentIndex::::get(), 10); }); } @@ -4340,7 +4348,7 @@ fn cannot_rebond_to_lower_than_ed() { .build_and_execute(|| { // initial stuff. assert_eq!( - Staking::ledger(&20).unwrap(), + Ledger::::get(&20).unwrap(), StakingLedger { stash: 21, total: 10 * 1000, @@ -4354,7 +4362,7 @@ fn cannot_rebond_to_lower_than_ed() { assert_ok!(Staking::chill(RuntimeOrigin::signed(20))); assert_ok!(Staking::unbond(RuntimeOrigin::signed(20), 10 * 1000)); assert_eq!( - Staking::ledger(&20).unwrap(), + Ledger::::get(&20).unwrap(), StakingLedger { stash: 21, total: 10 * 1000, @@ -4380,7 +4388,7 @@ fn cannot_bond_extra_to_lower_than_ed() { .build_and_execute(|| { // initial stuff. assert_eq!( - Staking::ledger(&20).unwrap(), + Ledger::::get(&20).unwrap(), StakingLedger { stash: 21, total: 10 * 1000, @@ -4394,7 +4402,7 @@ fn cannot_bond_extra_to_lower_than_ed() { assert_ok!(Staking::chill(RuntimeOrigin::signed(20))); assert_ok!(Staking::unbond(RuntimeOrigin::signed(20), 10 * 1000)); assert_eq!( - Staking::ledger(&20).unwrap(), + Ledger::::get(&20).unwrap(), StakingLedger { stash: 21, total: 10 * 1000, @@ -4421,7 +4429,7 @@ fn do_not_die_when_active_is_ed() { .build_and_execute(|| { // given assert_eq!( - Staking::ledger(&20).unwrap(), + Ledger::::get(&20).unwrap(), StakingLedger { stash: 21, total: 1000 * ed, @@ -4438,7 +4446,7 @@ fn do_not_die_when_active_is_ed() { // then assert_eq!( - Staking::ledger(&20).unwrap(), + Ledger::::get(&20).unwrap(), StakingLedger { stash: 21, total: ed, @@ -5509,7 +5517,7 @@ fn pre_bonding_era_cannot_be_claimed() { let claimed_rewards: BoundedVec<_, _> = (start_reward_era..=last_reward_era).collect::>().try_into().unwrap(); assert_eq!( - Staking::ledger(&4).unwrap(), + Ledger::::get(&4).unwrap(), StakingLedger { stash: 3, total: 1500, @@ -5537,7 +5545,7 @@ fn pre_bonding_era_cannot_be_claimed() { // decoding will fail now since Staking Ledger is in corrupt state HistoryDepth::set(history_depth - 1); - assert_eq!(Staking::ledger(&4), None); + assert_eq!(Ledger::::get(&4), None); // make sure stakers still cannot claim rewards that they are not meant to assert_noop!( @@ -5575,7 +5583,7 @@ fn reducing_history_depth_abrupt() { let claimed_rewards: BoundedVec<_, _> = (start_reward_era..=last_reward_era).collect::>().try_into().unwrap(); assert_eq!( - Staking::ledger(&4).unwrap(), + Ledger::::get(&4).unwrap(), StakingLedger { stash: 3, total: 1500, @@ -5614,7 +5622,7 @@ fn reducing_history_depth_abrupt() { let claimed_rewards: BoundedVec<_, _> = (start_reward_era..=last_reward_era).collect::>().try_into().unwrap(); assert_eq!( - Staking::ledger(&6).unwrap(), + Ledger::::get(&6).unwrap(), StakingLedger { stash: 5, total: 1200, @@ -5638,7 +5646,7 @@ fn reducing_max_unlocking_chunks_abrupt() { MaxUnlockingChunks::set(2); start_active_era(10); assert_ok!(Staking::bond(RuntimeOrigin::signed(3), 4, 300, RewardDestination::Staked)); - assert!(matches!(Staking::ledger(4), Some(_))); + assert!(matches!(Ledger::::get(4), Some(_))); // when staker unbonds assert_ok!(Staking::unbond(RuntimeOrigin::signed(4), 20)); @@ -5647,7 +5655,7 @@ fn reducing_max_unlocking_chunks_abrupt() { // => 10 + 3 = 13 let expected_unlocking: BoundedVec, MaxUnlockingChunks> = bounded_vec![UnlockChunk { value: 20 as Balance, era: 13 as EraIndex }]; - assert!(matches!(Staking::ledger(4), + assert!(matches!(Ledger::::get(4), Some(StakingLedger { unlocking, .. @@ -5659,7 +5667,7 @@ fn reducing_max_unlocking_chunks_abrupt() { // then another unlock chunk is added let expected_unlocking: BoundedVec, MaxUnlockingChunks> = bounded_vec![UnlockChunk { value: 20, era: 13 }, UnlockChunk { value: 50, era: 14 }]; - assert!(matches!(Staking::ledger(4), + assert!(matches!(Ledger::::get(4), Some(StakingLedger { unlocking, .. @@ -5787,13 +5795,13 @@ mod staking_interface { // without slash let _ = with_storage_layer::<(), _, _>(|| { // bond an account, can unstake - assert_eq!(Staking::bonded(&11), Some(10)); + assert_eq!(Bonded::::get(&11), Some(10)); assert_ok!(::force_unstake(11)); Err(DispatchError::from("revert")) }); // bond again and add a slash, still can unstake. - assert_eq!(Staking::bonded(&11), Some(10)); + assert_eq!(Bonded::::get(&11), Some(10)); add_slash(&11); assert_ok!(::force_unstake(11)); }); @@ -5804,20 +5812,21 @@ mod staking_interface { ExtBuilder::default().build_and_execute(|| { on_offence_now( &[OffenceDetails { - offender: (11, Staking::eras_stakers(active_era(), 11)), + offender: (11, ErasStakers::::get(active_era(), 11)), reporters: vec![], }], &[Perbill::from_percent(100)], ); - assert_eq!(Staking::bonded(&11), Some(10)); + assert_eq!(Bonded::::get(&11), Some(10)); assert_noop!( Staking::withdraw_unbonded(RuntimeOrigin::signed(10), 0), Error::::IncorrectSlashingSpans ); - let num_slashing_spans = Staking::slashing_spans(&11).map_or(0, |s| s.iter().count()); + let num_slashing_spans = + SlashingSpans::::get(&11).map_or(0, |s| s.iter().count()); assert_ok!(Staking::withdraw_unbonded( RuntimeOrigin::signed(10), num_slashing_spans as u32 diff --git a/frame/state-trie-migration/src/lib.rs b/frame/state-trie-migration/src/lib.rs index 23f73bb56b173..904bbe70e9a4d 100644 --- a/frame/state-trie-migration/src/lib.rs +++ b/frame/state-trie-migration/src/lib.rs @@ -593,8 +593,8 @@ pub mod pallet { ) -> DispatchResultWithPostInfo { let who = T::SignedFilter::ensure_origin(origin)?; - let max_limits = - Self::signed_migration_max_limits().ok_or(Error::::SignedMigrationNotAllowed)?; + let max_limits = SignedMigrationMaxLimits::::get() + .ok_or(Error::::SignedMigrationNotAllowed)?; ensure!( limits.size <= max_limits.size && limits.item <= max_limits.item, Error::::MaxSignedLimits, @@ -604,7 +604,7 @@ pub mod pallet { let deposit = T::SignedDepositPerItem::get().saturating_mul(limits.item.into()); ensure!(T::Currency::can_slash(&who, deposit), Error::::NotEnoughFunds); - let mut task = Self::migration_process(); + let mut task = MigrationProcess::::get(); ensure!( task == witness_task, DispatchErrorWithPostInfo { @@ -807,8 +807,8 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { fn on_initialize(_: BlockNumberFor) -> Weight { - if let Some(limits) = Self::auto_limits() { - let mut task = Self::migration_process(); + if let Some(limits) = AutoLimits::::get() { + let mut task = MigrationProcess::::get(); if let Err(e) = task.migrate_until_exhaustion(limits) { Self::halt(e); } @@ -911,9 +911,9 @@ mod benchmarks { let caller = frame_benchmarking::whitelisted_caller(); // Allow signed migrations. SignedMigrationMaxLimits::::put(MigrationLimits { size: 1024, item: 5 }); - }: _(frame_system::RawOrigin::Signed(caller), null, 0, StateTrieMigration::::migration_process()) + }: _(frame_system::RawOrigin::Signed(caller), null, 0, MigrationProcess::::get()) verify { - assert_eq!(StateTrieMigration::::migration_process(), Default::default()) + assert_eq!(MigrationProcess::::get(), Default::default()) } continue_migrate_wrong_witness { @@ -932,7 +932,7 @@ mod benchmarks { ) } verify { - assert_eq!(StateTrieMigration::::migration_process(), Default::default()) + assert_eq!(MigrationProcess::::get(), Default::default()) } migrate_custom_top_success { @@ -945,7 +945,7 @@ mod benchmarks { T::Currency::make_free_balance_be(&caller, stash); }: migrate_custom_top(frame_system::RawOrigin::Signed(caller.clone()), Default::default(), 0) verify { - assert_eq!(StateTrieMigration::::migration_process(), Default::default()); + assert_eq!(MigrationProcess::::get(), Default::default()); assert_eq!(T::Currency::free_balance(&caller), stash) } @@ -978,7 +978,7 @@ mod benchmarks { ); } verify { - assert_eq!(StateTrieMigration::::migration_process(), Default::default()); + assert_eq!(MigrationProcess::::get(), Default::default()); // must have gotten slashed assert!(T::Currency::free_balance(&caller) < stash) } @@ -997,7 +997,7 @@ mod benchmarks { 0 ) verify { - assert_eq!(StateTrieMigration::::migration_process(), Default::default()); + assert_eq!(MigrationProcess::::get(), Default::default()); assert_eq!(T::Currency::free_balance(&caller), stash); } @@ -1022,7 +1022,7 @@ mod benchmarks { ) } verify { - assert_eq!(StateTrieMigration::::migration_process(), Default::default()); + assert_eq!(MigrationProcess::::get(), Default::default()); // must have gotten slashed assert!(T::Currency::free_balance(&caller) < stash) } @@ -1312,10 +1312,9 @@ mod test { assert!(AutoLimits::::get().is_none()); // Calling `migrate_until_exhaustion` also fails. - let mut task = StateTrieMigration::migration_process(); - let result = task.migrate_until_exhaustion( - StateTrieMigration::signed_migration_max_limits().unwrap(), - ); + let mut task = MigrationProcess::::get(); + let result = + task.migrate_until_exhaustion(SignedMigrationMaxLimits::::get().unwrap()); assert!(result.is_err()); }); } @@ -1347,10 +1346,9 @@ mod test { assert!(AutoLimits::::get().is_none()); // Calling `migrate_until_exhaustion` also fails. - let mut task = StateTrieMigration::migration_process(); - let result = task.migrate_until_exhaustion( - StateTrieMigration::signed_migration_max_limits().unwrap(), - ); + let mut task = MigrationProcess::::get(); + let result = + task.migrate_until_exhaustion(SignedMigrationMaxLimits::::get().unwrap()); assert!(result.is_err()); }); } @@ -1366,7 +1364,7 @@ mod test { let root = run_to_block(30).0; // eventually everything is over. - assert!(StateTrieMigration::migration_process().finished()); + assert!(MigrationProcess::::get().finished()); root }); @@ -1390,7 +1388,7 @@ mod test { let root = run_to_block(30).0; // eventually everything is over. - assert!(StateTrieMigration::migration_process().finished()); + assert!(MigrationProcess::::get().finished()); root }); @@ -1422,7 +1420,7 @@ mod test { // eventually everything is over. assert!(matches!( - StateTrieMigration::migration_process(), + MigrationProcess::::get(), MigrationTask { progress_top: Progress::Complete, .. } )); root @@ -1499,15 +1497,14 @@ mod test { // migrate all keys in a series of submissions while !MigrationProcess::::get().finished() { // first we compute the task to get the accurate consumption. - let mut task = StateTrieMigration::migration_process(); - let result = task.migrate_until_exhaustion( - StateTrieMigration::signed_migration_max_limits().unwrap(), - ); + let mut task = MigrationProcess::::get(); + let result = + task.migrate_until_exhaustion(SignedMigrationMaxLimits::::get().unwrap()); assert!(result.is_ok()); frame_support::assert_ok!(StateTrieMigration::continue_migrate( RuntimeOrigin::signed(1), - StateTrieMigration::signed_migration_max_limits().unwrap(), + SignedMigrationMaxLimits::::get().unwrap(), task.dyn_size, MigrationProcess::::get() )); @@ -1517,7 +1514,7 @@ mod test { // and the task should be updated assert!(matches!( - StateTrieMigration::migration_process(), + MigrationProcess::::get(), MigrationTask { size: x, .. } if x > 0, )); } @@ -1610,7 +1607,9 @@ mod test { /// Exported set of tests to be called against different runtimes. #[cfg(feature = "remote-test")] pub(crate) mod remote_tests { - use crate::{AutoLimits, MigrationLimits, Pallet as StateTrieMigration, LOG_TARGET}; + use crate::{ + AutoLimits, MigrationLimits, MigrationProcess, Pallet as StateTrieMigration, LOG_TARGET, + }; use codec::Encode; use frame_support::{ traits::{Get, Hooks}, @@ -1691,7 +1690,7 @@ pub(crate) mod remote_tests { let last_state_root = ext.backend.root().clone(); let ((finished, weight), proof) = ext.execute_and_prove(|| { let weight = run_to_block::(now + One::one()).1; - if StateTrieMigration::::migration_process().finished() { + if MigrationProcess::::get().finished() { return (true, weight) } duration += One::one(); @@ -1728,7 +1727,7 @@ pub(crate) mod remote_tests { target: LOG_TARGET, "finished on_initialize migration in {} block, final state of the task: {:?}", duration, - StateTrieMigration::::migration_process(), + MigrationProcess::::get(), ) }); diff --git a/frame/sudo/src/extension.rs b/frame/sudo/src/extension.rs index 068fa2ed928d5..c6a671e37a912 100644 --- a/frame/sudo/src/extension.rs +++ b/frame/sudo/src/extension.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{Config, Pallet}; +use crate::{Config, Key}; use codec::{Decode, Encode}; use frame_support::{dispatch::DispatchInfo, ensure}; use scale_info::TypeInfo; @@ -86,7 +86,7 @@ where info: &DispatchInfoOf, _len: usize, ) -> TransactionValidity { - let sudo_key: T::AccountId = >::key().ok_or(UnknownTransaction::CannotLookup)?; + let sudo_key: T::AccountId = Key::::get().ok_or(UnknownTransaction::CannotLookup)?; ensure!(*who == sudo_key, InvalidTransaction::BadSigner); Ok(ValidTransaction { diff --git a/frame/sudo/src/lib.rs b/frame/sudo/src/lib.rs index 3a708b6d5d6b1..37bab8a95761d 100644 --- a/frame/sudo/src/lib.rs +++ b/frame/sudo/src/lib.rs @@ -155,7 +155,7 @@ pub mod pallet { ) -> DispatchResultWithPostInfo { // This is a public call, so we ensure that the origin is some signed account. let sender = ensure_signed(origin)?; - ensure!(Self::key().map_or(false, |k| sender == k), Error::::RequireSudo); + ensure!(Key::::get().map_or(false, |k| sender == k), Error::::RequireSudo); let res = call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()); Self::deposit_event(Event::Sudid { sudo_result: res.map(|_| ()).map_err(|e| e.error) }); @@ -180,7 +180,7 @@ pub mod pallet { ) -> DispatchResultWithPostInfo { // This is a public call, so we ensure that the origin is some signed account. let sender = ensure_signed(origin)?; - ensure!(Self::key().map_or(false, |k| sender == k), Error::::RequireSudo); + ensure!(Key::::get().map_or(false, |k| sender == k), Error::::RequireSudo); let res = call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()); Self::deposit_event(Event::Sudid { sudo_result: res.map(|_| ()).map_err(|e| e.error) }); @@ -203,7 +203,7 @@ pub mod pallet { ) -> DispatchResultWithPostInfo { // This is a public call, so we ensure that the origin is some signed account. let sender = ensure_signed(origin)?; - ensure!(Self::key().map_or(false, |k| sender == k), Error::::RequireSudo); + ensure!(Key::::get().map_or(false, |k| sender == k), Error::::RequireSudo); let new = T::Lookup::lookup(new)?; Self::deposit_event(Event::KeyChanged { old_sudoer: Key::::get() }); @@ -236,7 +236,7 @@ pub mod pallet { ) -> DispatchResultWithPostInfo { // This is a public call, so we ensure that the origin is some signed account. let sender = ensure_signed(origin)?; - ensure!(Self::key().map_or(false, |k| sender == k), Error::::RequireSudo); + ensure!(Key::::get().map_or(false, |k| sender == k), Error::::RequireSudo); let who = T::Lookup::lookup(who)?; diff --git a/frame/sudo/src/mock.rs b/frame/sudo/src/mock.rs index f8a03836f8f0f..011105da8ff2d 100644 --- a/frame/sudo/src/mock.rs +++ b/frame/sudo/src/mock.rs @@ -82,13 +82,11 @@ pub mod logger { } #[pallet::storage] - #[pallet::getter(fn account_log)] - pub(super) type AccountLog = + pub type AccountLog = StorageValue<_, BoundedVec>, ValueQuery>; #[pallet::storage] - #[pallet::getter(fn i32_log)] - pub(super) type I32Log = StorageValue<_, BoundedVec>, ValueQuery>; + pub type I32Log = StorageValue<_, BoundedVec>, ValueQuery>; } type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; diff --git a/frame/sudo/src/tests.rs b/frame/sudo/src/tests.rs index ae8f198736004..fcd9c5dcf58ba 100644 --- a/frame/sudo/src/tests.rs +++ b/frame/sudo/src/tests.rs @@ -20,7 +20,8 @@ use super::*; use frame_support::{assert_noop, assert_ok, weights::Weight}; use mock::{ - new_test_ext, Logger, LoggerCall, RuntimeCall, RuntimeEvent as TestEvent, RuntimeOrigin, Sudo, + logger::{AccountLog, I32Log}, + new_test_ext, LoggerCall, RuntimeCall, RuntimeEvent as TestEvent, RuntimeOrigin, Sudo, SudoCall, System, Test, }; @@ -28,9 +29,9 @@ use mock::{ fn test_setup_works() { // Environment setup, logger storage, and sudo `key` retrieval should work as expected. new_test_ext(1).execute_with(|| { - assert_eq!(Sudo::key(), Some(1u64)); - assert!(Logger::i32_log().is_empty()); - assert!(Logger::account_log().is_empty()); + assert_eq!(Key::::get(), Some(1u64)); + assert!(I32Log::::get().is_empty()); + assert!(AccountLog::::get().is_empty()); }); } @@ -44,7 +45,7 @@ fn sudo_basics() { weight: Weight::from_ref_time(1_000), })); assert_ok!(Sudo::sudo(RuntimeOrigin::signed(1), call)); - assert_eq!(Logger::i32_log(), vec![42i32]); + assert_eq!(I32Log::::get(), vec![42i32]); // A privileged function should not work when `sudo` is passed a non-root `key` as `origin`. let call = Box::new(RuntimeCall::Logger(LoggerCall::privileged_i32_log { @@ -84,7 +85,7 @@ fn sudo_unchecked_weight_basics() { call, Weight::from_ref_time(1_000) )); - assert_eq!(Logger::i32_log(), vec![42i32]); + assert_eq!(I32Log::::get(), vec![42i32]); // A privileged function should not work when called with a non-root `key`. let call = Box::new(RuntimeCall::Logger(LoggerCall::privileged_i32_log { @@ -100,7 +101,7 @@ fn sudo_unchecked_weight_basics() { Error::::RequireSudo, ); // `I32Log` is unchanged after unsuccessful call. - assert_eq!(Logger::i32_log(), vec![42i32]); + assert_eq!(I32Log::::get(), vec![42i32]); // Controls the dispatched weight. let call = Box::new(RuntimeCall::Logger(LoggerCall::privileged_i32_log { @@ -139,7 +140,7 @@ fn set_key_basics() { new_test_ext(1).execute_with(|| { // A root `key` can change the root `key` assert_ok!(Sudo::set_key(RuntimeOrigin::signed(1), 2)); - assert_eq!(Sudo::key(), Some(2u64)); + assert_eq!(Key::::get(), Some(2u64)); }); new_test_ext(1).execute_with(|| { @@ -173,8 +174,8 @@ fn sudo_as_basics() { weight: Weight::from_ref_time(1_000), })); assert_ok!(Sudo::sudo_as(RuntimeOrigin::signed(1), 2, call)); - assert!(Logger::i32_log().is_empty()); - assert!(Logger::account_log().is_empty()); + assert!(I32Log::::get().is_empty()); + assert!(AccountLog::::get().is_empty()); // A non-privileged function should not work when called with a non-root `key`. let call = Box::new(RuntimeCall::Logger(LoggerCall::non_privileged_log { @@ -189,9 +190,9 @@ fn sudo_as_basics() { weight: Weight::from_ref_time(1), })); assert_ok!(Sudo::sudo_as(RuntimeOrigin::signed(1), 2, call)); - assert_eq!(Logger::i32_log(), vec![42i32]); + assert_eq!(I32Log::::get(), vec![42i32]); // The correct user makes the call within `sudo_as`. - assert_eq!(Logger::account_log(), vec![2]); + assert_eq!(AccountLog::::get(), vec![2]); }); } diff --git a/frame/support/procedural/src/pallet/expand/storage.rs b/frame/support/procedural/src/pallet/expand/storage.rs index 0bb19ad6c29cd..edfc66c0135ad 100644 --- a/frame/support/procedural/src/pallet/expand/storage.rs +++ b/frame/support/procedural/src/pallet/expand/storage.rs @@ -381,6 +381,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { #(#cfg_attrs)* impl<#type_impl_gen> #pallet_ident<#type_use_gen> #completed_where_clause { #( #docs )* + #[deprecated = "#[pallet::getter] is deprecated and will be unavailable in future versions."] pub fn #getter() -> #query { < #full_ident as #frame_support::storage::StorageValue<#value> diff --git a/frame/support/test/tests/pallet.rs b/frame/support/test/tests/pallet.rs index 36150b28058a7..7218f6446b0a6 100644 --- a/frame/support/test/tests/pallet.rs +++ b/frame/support/test/tests/pallet.rs @@ -317,11 +317,9 @@ pub mod pallet { >; #[pallet::storage] - #[pallet::getter(fn nmap)] pub type NMap = StorageNMap<_, storage::Key, u32>; #[pallet::storage] - #[pallet::getter(fn nmap2)] pub type NMap2 = StorageNMap< Key = (NMapKey, NMapKey), Value = u64, @@ -329,7 +327,6 @@ pub mod pallet { >; #[pallet::storage] - #[pallet::getter(fn nmap3)] pub type NMap3 = StorageNMap< _, (NMapKey, NMapKey), @@ -338,31 +335,26 @@ pub mod pallet { >; #[pallet::storage] - #[pallet::getter(fn conditional_value)] #[cfg(feature = "frame-feature-testing")] pub type ConditionalValue = StorageValue<_, u32>; #[cfg(feature = "frame-feature-testing")] #[pallet::storage] - #[pallet::getter(fn conditional_map)] pub type ConditionalMap = StorageMap<_, Twox64Concat, u16, u32, OptionQuery, GetDefault, ConstU32<12>>; #[cfg(feature = "frame-feature-testing")] #[pallet::storage] - #[pallet::getter(fn conditional_double_map)] pub type ConditionalDoubleMap = StorageDoubleMap<_, Blake2_128Concat, u8, Twox64Concat, u16, u32>; #[cfg(feature = "frame-feature-testing")] #[pallet::storage] - #[pallet::getter(fn conditional_nmap)] pub type ConditionalNMap = StorageNMap<_, (storage::Key, storage::Key), u32>; #[pallet::storage] #[pallet::storage_prefix = "RenamedCountedMap"] - #[pallet::getter(fn counted_storage_map)] pub type SomeCountedStorageMap = CountedStorageMap; diff --git a/frame/support/test/tests/pallet_instance.rs b/frame/support/test/tests/pallet_instance.rs index 7fec0aa9d0e07..a608de44fba07 100644 --- a/frame/support/test/tests/pallet_instance.rs +++ b/frame/support/test/tests/pallet_instance.rs @@ -166,16 +166,13 @@ pub mod pallet { >; #[pallet::storage] - #[pallet::getter(fn nmap)] pub type NMap = StorageNMap<_, storage::Key, u32>; #[pallet::storage] - #[pallet::getter(fn nmap2)] pub type NMap2 = StorageNMap<_, (storage::Key, storage::Key), u64>; #[pallet::storage] - #[pallet::getter(fn nmap3)] pub type NMap3 = StorageNMap< _, (NMapKey, NMapKey), diff --git a/frame/support/test/tests/pallet_ui/storage_multiple_getters.rs b/frame/support/test/tests/pallet_ui/storage_multiple_getters.rs index 309b9b24136fa..245a5f774b3f7 100644 --- a/frame/support/test/tests/pallet_ui/storage_multiple_getters.rs +++ b/frame/support/test/tests/pallet_ui/storage_multiple_getters.rs @@ -21,5 +21,4 @@ mod pallet { type Foo = StorageValue<_, u8>; } -fn main() { -} +fn main() {} diff --git a/frame/system/src/extensions/check_genesis.rs b/frame/system/src/extensions/check_genesis.rs index f5811f306cfe3..0aab5fe37a272 100644 --- a/frame/system/src/extensions/check_genesis.rs +++ b/frame/system/src/extensions/check_genesis.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{Config, Pallet}; +use crate::{BlockHash, Config}; use codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_runtime::{ @@ -60,7 +60,7 @@ impl SignedExtension for CheckGenesis { const IDENTIFIER: &'static str = "CheckGenesis"; fn additional_signed(&self) -> Result { - Ok(>::block_hash(T::BlockNumber::zero())) + Ok(BlockHash::::get(T::BlockNumber::zero())) } fn pre_dispatch( diff --git a/frame/system/src/extensions/check_mortality.rs b/frame/system/src/extensions/check_mortality.rs index 635ab4ef1d9a9..9a2c8e1930d31 100644 --- a/frame/system/src/extensions/check_mortality.rs +++ b/frame/system/src/extensions/check_mortality.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{BlockHash, Config, Pallet}; +use crate::{BlockHash, Config, Number}; use codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_runtime::{ @@ -68,7 +68,7 @@ impl SignedExtension for CheckMortality { _info: &DispatchInfoOf, _len: usize, ) -> TransactionValidity { - let current_u64 = >::block_number().saturated_into::(); + let current_u64 = Number::::get().saturated_into::(); let valid_till = self.0.death(current_u64); Ok(ValidTransaction { longevity: valid_till.saturating_sub(current_u64), @@ -77,12 +77,12 @@ impl SignedExtension for CheckMortality { } fn additional_signed(&self) -> Result { - let current_u64 = >::block_number().saturated_into::(); + let current_u64 = Number::::get().saturated_into::(); let n = self.0.birth(current_u64).saturated_into::(); if !>::contains_key(n) { Err(InvalidTransaction::AncientBirthBlock.into()) } else { - Ok(>::block_hash(n)) + Ok(BlockHash::::get(n)) } } diff --git a/frame/system/src/extensions/check_weight.rs b/frame/system/src/extensions/check_weight.rs index 590d05474f91a..15381504b3770 100644 --- a/frame/system/src/extensions/check_weight.rs +++ b/frame/system/src/extensions/check_weight.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{limits::BlockWeights, Config, Pallet}; +use crate::{limits::BlockWeights, BlockWeight, Config, Pallet}; use codec::{Decode, Encode}; use frame_support::{ dispatch::{DispatchInfo, PostDispatchInfo}, @@ -63,7 +63,7 @@ where info: &DispatchInfoOf, ) -> Result { let maximum_weight = T::BlockWeights::get(); - let all_weight = Pallet::::block_weight(); + let all_weight = BlockWeight::::get(); calculate_consumed_weight::(maximum_weight, all_weight, info) } diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index c22a68296a159..d577118f9102e 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -545,7 +545,6 @@ pub mod pallet { /// The current weight for the block. #[pallet::storage] #[pallet::whitelist_storage] - #[pallet::getter(fn block_weight)] pub(super) type BlockWeight = StorageValue<_, ConsumedWeight, ValueQuery>; /// Total length (in bytes) for all extrinsics put together, for the current block. @@ -560,7 +559,6 @@ pub mod pallet { /// Extrinsics data for the current block (maps an extrinsic's index to its data). #[pallet::storage] - #[pallet::getter(fn extrinsic_data)] #[pallet::unbounded] pub(super) type ExtrinsicData = StorageMap<_, Twox64Concat, u32, Vec, ValueQuery>; @@ -568,18 +566,15 @@ pub mod pallet { /// The current block number being processed. Set by `execute_block`. #[pallet::storage] #[pallet::whitelist_storage] - #[pallet::getter(fn block_number)] pub(super) type Number = StorageValue<_, T::BlockNumber, ValueQuery>; /// Hash of the previous block. #[pallet::storage] - #[pallet::getter(fn parent_hash)] pub(super) type ParentHash = StorageValue<_, T::Hash, ValueQuery>; /// Digest of the current block, also part of the block header. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn digest)] pub(super) type Digest = StorageValue<_, generic::Digest, ValueQuery>; /// Events deposited for the current block. @@ -598,7 +593,6 @@ pub mod pallet { /// The number of events in the `Events` list. #[pallet::storage] #[pallet::whitelist_storage] - #[pallet::getter(fn event_count)] pub(super) type EventCount = StorageValue<_, EventIndex, ValueQuery>; /// Mapping between a topic (represented by T::Hash) and a vector of indexes @@ -613,7 +607,6 @@ pub mod pallet { /// no notification will be triggered thus the event might be lost. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn event_topics)] pub(super) type EventTopics = StorageMap<_, Blake2_128Concat, T::Hash, Vec<(T::BlockNumber, EventIndex)>, ValueQuery>; @@ -1002,6 +995,42 @@ impl Pallet { Account::::contains_key(who) } + /// The current weight for the block. + pub fn block_weight() -> ConsumedWeight { + BlockWeight::::get() + } + + /// Extrinsics data for the current block (maps an extrinsic's index to its data). + pub fn extrinsic_data(i: u32) -> Vec { + ExtrinsicData::::get(i) + } + + /// The current block number being processed. Set by `execute_block`. + pub fn block_number() -> T::BlockNumber { + Number::::get() + } + + /// Hash of the previous block. + pub fn parent_hash() -> T::Hash { + ParentHash::::get() + } + + /// Digest of the current block, also part of the block header. + pub fn digest() -> generic::Digest { + Digest::::get() + } + + /// The number of events in the `Events` list. + pub fn event_count() -> EventIndex { + EventCount::::get() + } + + /// Mapping between a topic (represented by T::Hash) and a vector of indexes + /// of events in the `>` list. + pub fn event_topics(topic: &T::Hash) -> Vec<(T::BlockNumber, EventIndex)> { + EventTopics::::get(topic) + } + /// Write code to the storage and emit related events and digest items. /// /// Note this function almost never should be used directly. It is exposed diff --git a/frame/timestamp/src/benchmarking.rs b/frame/timestamp/src/benchmarking.rs index 3a9297fda805e..53fbd3f17edbc 100644 --- a/frame/timestamp/src/benchmarking.rs +++ b/frame/timestamp/src/benchmarking.rs @@ -24,7 +24,7 @@ use frame_benchmarking::v1::{benchmarks, TrackedStorageKey}; use frame_support::{ensure, traits::OnFinalize}; use frame_system::RawOrigin; -use crate::Pallet as Timestamp; +use crate::{Now, Pallet as Timestamp}; const MAX_TIME: u32 = 100; @@ -41,7 +41,7 @@ benchmarks! { }); }: _(RawOrigin::None, t.into()) verify { - ensure!(Timestamp::::now() == t.into(), "Time was not set."); + ensure!(Now::::get() == t.into(), "Time was not set."); } on_finalize { diff --git a/frame/timestamp/src/lib.rs b/frame/timestamp/src/lib.rs index 61a46125a423b..c3e37c77cbba8 100644 --- a/frame/timestamp/src/lib.rs +++ b/frame/timestamp/src/lib.rs @@ -203,7 +203,7 @@ pub mod pallet { pub fn set(origin: OriginFor, #[pallet::compact] now: T::Moment) -> DispatchResult { ensure_none(origin)?; assert!(!DidUpdate::::exists(), "Timestamp must be updated only once in the block"); - let prev = Self::now(); + let prev = Now::::get(); assert!( prev.is_zero() || now >= prev + T::MinimumPeriod::get(), "Timestamp must increment by at least between sequential blocks" @@ -230,7 +230,7 @@ pub mod pallet { .expect("Timestamp inherent data must be provided"); let data = (*inherent_data).saturated_into::(); - let next_time = cmp::max(data, Self::now() + T::MinimumPeriod::get()); + let next_time = cmp::max(data, Now::::get() + T::MinimumPeriod::get()); Some(Call::set { now: next_time }) } @@ -251,7 +251,7 @@ pub mod pallet { .expect("Timestamp inherent data not correctly encoded") .expect("Timestamp inherent data must be provided"); - let minimum = (Self::now() + T::MinimumPeriod::get()).saturated_into::(); + let minimum = (Now::::get() + T::MinimumPeriod::get()).saturated_into::(); if t > *(data + MAX_TIMESTAMP_DRIFT_MILLIS) { Err(InherentError::TooFarInFuture) } else if t < minimum { @@ -273,7 +273,7 @@ impl Pallet { /// NOTE: if this function is called prior to setting the timestamp, /// it will return the timestamp of the previous block. pub fn get() -> T::Moment { - Self::now() + Now::::get() } /// Set the timestamp to something in particular. Only used for tests. @@ -290,7 +290,7 @@ impl Time for Pallet { /// Before the first set of now with inherent the value returned is zero. fn now() -> Self::Moment { - Self::now() + Now::::get() } } @@ -301,7 +301,7 @@ impl UnixTime for Pallet { fn now() -> core::time::Duration { // now is duration since unix epoch in millisecond as documented in // `sp_timestamp::InherentDataProvider`. - let now = Self::now(); + let now = Now::::get(); sp_std::if_std! { if now == T::Moment::zero() { log::error!( diff --git a/frame/timestamp/src/tests.rs b/frame/timestamp/src/tests.rs index 6a76fbc4820e6..43c6f55973533 100644 --- a/frame/timestamp/src/tests.rs +++ b/frame/timestamp/src/tests.rs @@ -17,7 +17,7 @@ //! Tests for the Timestamp module. -use crate::mock::*; +use crate::{mock::*, Now}; use frame_support::assert_ok; #[test] @@ -25,7 +25,7 @@ fn timestamp_works() { new_test_ext().execute_with(|| { crate::Now::::put(46); assert_ok!(Timestamp::set(RuntimeOrigin::none(), 69)); - assert_eq!(Timestamp::now(), 69); + assert_eq!(Now::::get(), 69); assert_eq!(Some(69), get_captured_moment()); }); } diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index fb4381c5242c6..c6c95516dd30c 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -595,7 +595,7 @@ where if pays_fee == Pays::Yes { // the adjustable part of the fee. let unadjusted_weight_fee = Self::weight_to_fee(weight); - let multiplier = Self::next_fee_multiplier(); + let multiplier = NextFeeMultiplier::::get(); // final adjusted weight fee. let adjusted_weight_fee = multiplier.saturating_mul_int(unadjusted_weight_fee); diff --git a/frame/treasury/src/benchmarking.rs b/frame/treasury/src/benchmarking.rs index 0947618a2b02f..d426f6d8b416b 100644 --- a/frame/treasury/src/benchmarking.rs +++ b/frame/treasury/src/benchmarking.rs @@ -124,7 +124,7 @@ benchmarks_instance_pallet! { value, beneficiary_lookup )?; - let proposal_id = Treasury::::proposal_count() - 1; + let proposal_id = ProposalCount::::get() - 1; Treasury::::approve_proposal(RawOrigin::Root.into(), proposal_id)?; let reject_origin = T::RejectOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; diff --git a/frame/treasury/src/lib.rs b/frame/treasury/src/lib.rs index f5ca0a984bc49..30417dbd1a5e4 100644 --- a/frame/treasury/src/lib.rs +++ b/frame/treasury/src/lib.rs @@ -209,7 +209,6 @@ pub mod pallet { /// Number of proposals that have been made. #[pallet::storage] - #[pallet::getter(fn proposal_count)] pub(crate) type ProposalCount = StorageValue<_, ProposalIndex, ValueQuery>; /// Proposals that have been made. @@ -361,7 +360,7 @@ pub mod pallet { T::Currency::reserve(&proposer, bond) .map_err(|_| Error::::InsufficientProposersBalance)?; - let c = Self::proposal_count(); + let c = ProposalCount::::get(); >::put(c + 1); >::insert(c, Proposal { proposer, value, beneficiary, bond }); @@ -436,7 +435,7 @@ pub mod pallet { let beneficiary = T::Lookup::lookup(beneficiary)?; ensure!(amount <= max_amount, Error::::InsufficientPermission); - let proposal_index = Self::proposal_count(); + let proposal_index = ProposalCount::::get(); Approvals::::try_append(proposal_index) .map_err(|_| Error::::TooManyApprovals)?; let proposal = Proposal { @@ -490,6 +489,11 @@ pub mod pallet { impl, I: 'static> Pallet { // Add public immutables and private mutables. + /// Number of proposals that have been made. + pub fn proposal_count() -> ProposalIndex { + ProposalCount::::get() + } + /// The account ID of the treasury pot. /// /// This actually does computation. If you need to keep using it, then make sure you cache the @@ -521,7 +525,7 @@ impl, I: 'static> Pallet { let proposals_approvals_len = v.len() as u32; v.retain(|&index| { // Should always be true, but shouldn't panic if false or we're screwed. - if let Some(p) = Self::proposals(index) { + if let Some(p) = Proposals::::get(index) { if p.value <= budget_remaining { budget_remaining -= p.value; >::remove(index); diff --git a/frame/treasury/src/tests.rs b/frame/treasury/src/tests.rs index e6a1ea0f543fe..c61730e5c3099 100644 --- a/frame/treasury/src/tests.rs +++ b/frame/treasury/src/tests.rs @@ -147,7 +147,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { fn genesis_config_works() { new_test_ext().execute_with(|| { assert_eq!(Treasury::pot(), 0); - assert_eq!(Treasury::proposal_count(), 0); + assert_eq!(ProposalCount::::get(), 0); }); } @@ -460,9 +460,9 @@ fn remove_already_removed_approval_fails() { assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3)); assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 0)); - assert_eq!(Treasury::approvals(), vec![0]); + assert_eq!(Approvals::::get(), vec![0]); assert_ok!(Treasury::remove_approval(RuntimeOrigin::root(), 0)); - assert_eq!(Treasury::approvals(), vec![]); + assert_eq!(Approvals::::get(), vec![]); assert_noop!( Treasury::remove_approval(RuntimeOrigin::root(), 0), diff --git a/frame/vesting/src/benchmarking.rs b/frame/vesting/src/benchmarking.rs index eb0d596b8a38b..bf4ad806a6920 100644 --- a/frame/vesting/src/benchmarking.rs +++ b/frame/vesting/src/benchmarking.rs @@ -25,7 +25,7 @@ use frame_system::{Pallet as System, RawOrigin}; use sp_runtime::traits::{Bounded, CheckedDiv, CheckedMul}; use super::*; -use crate::Pallet as Vesting; +use crate::{Pallet as Vesting, Vesting as VestingStorage}; const SEED: u32 = 0; @@ -284,7 +284,7 @@ benchmarks! { "Vesting balance should equal sum locked of all schedules", ); assert_eq!( - Vesting::::vesting(&caller).unwrap().len(), + VestingStorage::::get(&caller).unwrap().len(), s as usize, "There should be exactly max vesting schedules" ); @@ -297,7 +297,7 @@ benchmarks! { ); let expected_index = (s - 2) as usize; assert_eq!( - Vesting::::vesting(&caller).unwrap()[expected_index], + VestingStorage::::get(&caller).unwrap()[expected_index], expected_schedule ); assert_eq!( @@ -306,7 +306,7 @@ benchmarks! { "Vesting balance should equal total locked of all schedules", ); assert_eq!( - Vesting::::vesting(&caller).unwrap().len(), + VestingStorage::::get(&caller).unwrap().len(), (s - 1) as usize, "Schedule count should reduce by 1" ); @@ -336,7 +336,7 @@ benchmarks! { "Vesting balance should reflect that we are half way through all schedules duration", ); assert_eq!( - Vesting::::vesting(&caller).unwrap().len(), + VestingStorage::::get(&caller).unwrap().len(), s as usize, "There should be exactly max vesting schedules" ); @@ -351,12 +351,12 @@ benchmarks! { ); let expected_index = (s - 2) as usize; assert_eq!( - Vesting::::vesting(&caller).unwrap()[expected_index], + VestingStorage::::get(&caller).unwrap()[expected_index], expected_schedule, "New schedule is properly created and placed" ); assert_eq!( - Vesting::::vesting(&caller).unwrap()[expected_index], + VestingStorage::::get(&caller).unwrap()[expected_index], expected_schedule ); assert_eq!( @@ -365,7 +365,7 @@ benchmarks! { "Vesting balance should equal half total locked of all schedules", ); assert_eq!( - Vesting::::vesting(&caller).unwrap().len(), + VestingStorage::::get(&caller).unwrap().len(), (s - 1) as usize, "Schedule count should reduce by 1" ); diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index 6cde546f387b4..9a64a412571e2 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -422,7 +422,7 @@ pub mod pallet { let schedule1_index = schedule1_index as usize; let schedule2_index = schedule2_index as usize; - let schedules = Self::vesting(&who).ok_or(Error::::NotVesting)?; + let schedules = Vesting::::get(&who).ok_or(Error::::NotVesting)?; let merge_action = VestingAction::Merge { index1: schedule1_index, index2: schedule2_index }; @@ -595,7 +595,7 @@ impl Pallet { /// Unlock any vested funds of `who`. fn do_vest(who: T::AccountId) -> DispatchResult { - let schedules = Self::vesting(&who).ok_or(Error::::NotVesting)?; + let schedules = Vesting::::get(&who).ok_or(Error::::NotVesting)?; let (schedules, locked_now) = Self::exec_action(schedules.to_vec(), VestingAction::Passive)?; @@ -660,7 +660,7 @@ where /// Get the amount that is currently being vested and cannot be transferred out of this account. fn vesting_balance(who: &T::AccountId) -> Option> { - if let Some(v) = Self::vesting(who) { + if let Some(v) = Vesting::::get(who) { let now = >::block_number(); let total_locked_now = v.iter().fold(Zero::zero(), |total, schedule| { schedule.locked_at::(now).saturating_add(total) @@ -699,7 +699,7 @@ where return Err(Error::::InvalidScheduleParams.into()) }; - let mut schedules = Self::vesting(who).unwrap_or_default(); + let mut schedules = Vesting::::get(who).unwrap_or_default(); // NOTE: we must push the new schedule so that `exec_action` // will give the correct new locked amount. @@ -737,7 +737,7 @@ where /// Remove a vesting schedule for a given account. fn remove_vesting_schedule(who: &T::AccountId, schedule_index: u32) -> DispatchResult { - let schedules = Self::vesting(who).ok_or(Error::::NotVesting)?; + let schedules = Vesting::::get(who).ok_or(Error::::NotVesting)?; let remove_action = VestingAction::Remove { index: schedule_index as usize }; let (schedules, locked_now) = Self::exec_action(schedules.to_vec(), remove_action)?; diff --git a/frame/vesting/src/tests.rs b/frame/vesting/src/tests.rs index cbc2e09c83199..db9098c6afa96 100644 --- a/frame/vesting/src/tests.rs +++ b/frame/vesting/src/tests.rs @@ -61,9 +61,9 @@ fn check_vesting_status() { 64, // Vesting over 20 blocks 10, ); - assert_eq!(Vesting::vesting(&1).unwrap(), vec![user1_vesting_schedule]); // Account 1 has a vesting schedule - assert_eq!(Vesting::vesting(&2).unwrap(), vec![user2_vesting_schedule]); // Account 2 has a vesting schedule - assert_eq!(Vesting::vesting(&12).unwrap(), vec![user12_vesting_schedule]); // Account 12 has a vesting schedule + assert_eq!(VestingStorage::::get(&1).unwrap(), vec![user1_vesting_schedule]); // Account 1 has a vesting schedule + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![user2_vesting_schedule]); // Account 2 has a vesting schedule + assert_eq!(VestingStorage::::get(&12).unwrap(), vec![user12_vesting_schedule]); // Account 12 has a vesting schedule // Account 1 has only 128 units vested from their illiquid ED * 5 units at block 1 assert_eq!(Vesting::vesting_balance(&1), Some(128 * 9)); @@ -106,7 +106,7 @@ fn check_vesting_status_for_multi_schedule_account() { 10, ); // Account 2 already has a vesting schedule. - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0]); // Account 2's free balance is from sched0. let free_balance = Balances::free_balance(&2); @@ -124,7 +124,7 @@ fn check_vesting_status_for_multi_schedule_account() { let free_balance = Balances::free_balance(&2); assert_eq!(free_balance, ED * (10 + 20)); // The most recently added schedule exists. - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0, sched1]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0, sched1]); // sched1 has free funds at block #1, but nothing else. assert_eq!(Vesting::vesting_balance(&2), Some(free_balance - sched1.per_block())); @@ -167,7 +167,7 @@ fn check_vesting_status_for_multi_schedule_account() { assert_eq!(Vesting::vesting_balance(&2), Some(0)); // Since we have not called any extrinsics that would unlock funds the schedules // are still in storage, - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0, sched1, sched2]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0, sched1, sched2]); // but once we unlock the funds, they are removed from storage. vest_and_assert_no_vesting::(2); }); @@ -205,7 +205,7 @@ fn vested_balance_should_transfer_with_multi_sched() { let sched0 = VestingInfo::new(5 * ED, 128, 0); assert_ok!(Vesting::vested_transfer(Some(13).into(), 1, sched0)); // Total 10*ED locked for all the schedules. - assert_eq!(Vesting::vesting(&1).unwrap(), vec![sched0, sched0]); + assert_eq!(VestingStorage::::get(&1).unwrap(), vec![sched0, sched0]); let user1_free_balance = Balances::free_balance(&1); assert_eq!(user1_free_balance, 3840); // Account 1 has free balance @@ -243,7 +243,7 @@ fn vested_balance_should_transfer_using_vest_other_with_multi_sched() { let sched0 = VestingInfo::new(5 * ED, 128, 0); assert_ok!(Vesting::vested_transfer(Some(13).into(), 1, sched0)); // Total of 10*ED of locked for all the schedules. - assert_eq!(Vesting::vesting(&1).unwrap(), vec![sched0, sched0]); + assert_eq!(VestingStorage::::get(&1).unwrap(), vec![sched0, sched0]); let user1_free_balance = Balances::free_balance(&1); assert_eq!(user1_free_balance, 3840); // Account 1 has free balance @@ -302,7 +302,7 @@ fn liquid_funds_should_transfer_with_delayed_vesting() { 64, // Vesting over 20 blocks 10, ); - assert_eq!(Vesting::vesting(&12).unwrap(), vec![user12_vesting_schedule]); + assert_eq!(VestingStorage::::get(&12).unwrap(), vec![user12_vesting_schedule]); // Account 12 can still send liquid funds assert_ok!(Balances::transfer(Some(12).into(), 3, 256 * 5)); @@ -317,7 +317,7 @@ fn vested_transfer_works() { assert_eq!(user3_free_balance, 256 * 30); assert_eq!(user4_free_balance, 256 * 40); // Account 4 should not have any vesting yet. - assert_eq!(Vesting::vesting(&4), None); + assert_eq!(VestingStorage::::get(&4), None); // Make the schedule for the new transfer. let new_vesting_schedule = VestingInfo::new( 256 * 5, @@ -326,7 +326,7 @@ fn vested_transfer_works() { ); assert_ok!(Vesting::vested_transfer(Some(3).into(), 4, new_vesting_schedule)); // Now account 4 should have vesting. - assert_eq!(Vesting::vesting(&4).unwrap(), vec![new_vesting_schedule]); + assert_eq!(VestingStorage::::get(&4).unwrap(), vec![new_vesting_schedule]); // Ensure the transfer happened correctly. let user3_free_balance_updated = Balances::free_balance(&3); assert_eq!(user3_free_balance_updated, 256 * 25); @@ -365,7 +365,7 @@ fn vested_transfer_correctly_fails() { ED, // Vesting over 20 blocks 10, ); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![user2_vesting_schedule]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![user2_vesting_schedule]); // Fails due to too low transfer amount. let new_vesting_schedule_too_low = @@ -447,7 +447,7 @@ fn force_vested_transfer_works() { assert_eq!(user3_free_balance, ED * 30); assert_eq!(user4_free_balance, ED * 40); // Account 4 should not have any vesting yet. - assert_eq!(Vesting::vesting(&4), None); + assert_eq!(VestingStorage::::get(&4), None); // Make the schedule for the new transfer. let new_vesting_schedule = VestingInfo::new( ED * 5, @@ -466,8 +466,8 @@ fn force_vested_transfer_works() { new_vesting_schedule )); // Now account 4 should have vesting. - assert_eq!(Vesting::vesting(&4).unwrap()[0], new_vesting_schedule); - assert_eq!(Vesting::vesting(&4).unwrap().len(), 1); + assert_eq!(VestingStorage::::get(&4).unwrap()[0], new_vesting_schedule); + assert_eq!(VestingStorage::::get(&4).unwrap().len(), 1); // Ensure the transfer happened correctly. let user3_free_balance_updated = Balances::free_balance(&3); assert_eq!(user3_free_balance_updated, ED * 25); @@ -505,7 +505,7 @@ fn force_vested_transfer_correctly_fails() { ED, // Vesting over 20 blocks 10, ); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![user2_vesting_schedule]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![user2_vesting_schedule]); // Too low transfer amount. let new_vesting_schedule_too_low = @@ -591,12 +591,12 @@ fn merge_schedules_that_have_not_started() { ED, // Vest over 20 blocks. 10, ); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0]); assert_eq!(Balances::usable_balance(&2), 0); // Add a schedule that is identical to the one that already exists. assert_ok!(Vesting::vested_transfer(Some(3).into(), 2, sched0)); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0, sched0]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0, sched0]); assert_eq!(Balances::usable_balance(&2), 0); assert_ok!(Vesting::merge_schedules(Some(2).into(), 0, 1)); @@ -607,7 +607,7 @@ fn merge_schedules_that_have_not_started() { sched0.per_block() * 2, 10, // Starts at the block the schedules are merged/ ); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched1]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched1]); assert_eq!(Balances::usable_balance(&2), 0); }); @@ -623,7 +623,7 @@ fn merge_ongoing_schedules() { ED, // Vest over 20 blocks. 10, ); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0]); let sched1 = VestingInfo::new( ED * 10, @@ -631,7 +631,7 @@ fn merge_ongoing_schedules() { sched0.starting_block() + 5, // Start at block 15. ); assert_ok!(Vesting::vested_transfer(Some(4).into(), 2, sched1)); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0, sched1]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0, sched1]); // Got to half way through the second schedule where both schedules are actively vesting. let cur_block = 20; @@ -663,7 +663,7 @@ fn merge_ongoing_schedules() { let sched2_per_block = sched2_locked / sched2_duration; let sched2 = VestingInfo::new(sched2_locked, sched2_per_block, cur_block); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched2]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched2]); // And just to double check, we assert the new merged schedule we be cleaned up as expected. System::set_block_number(30); @@ -693,7 +693,7 @@ fn merging_shifts_other_schedules_index() { ); // Account 3 starts out with no schedules, - assert_eq!(Vesting::vesting(&3), None); + assert_eq!(VestingStorage::::get(&3), None); // and some usable balance. let usable_balance = Balances::usable_balance(&3); assert_eq!(usable_balance, 30 * ED); @@ -707,7 +707,7 @@ fn merging_shifts_other_schedules_index() { assert_ok!(Vesting::vested_transfer(Some(4).into(), 3, sched2)); // With no schedules vested or merged they are in the order they are created - assert_eq!(Vesting::vesting(&3).unwrap(), vec![sched0, sched1, sched2]); + assert_eq!(VestingStorage::::get(&3).unwrap(), vec![sched0, sched1, sched2]); // and the usable balance has not changed. assert_eq!(usable_balance, Balances::usable_balance(&3)); @@ -728,7 +728,7 @@ fn merging_shifts_other_schedules_index() { let sched3 = VestingInfo::new(sched3_locked, sched3_per_block, sched3_start); // The not touched schedule moves left and the new merged schedule is appended. - assert_eq!(Vesting::vesting(&3).unwrap(), vec![sched1, sched3]); + assert_eq!(VestingStorage::::get(&3).unwrap(), vec![sched1, sched3]); // The usable balance hasn't changed since none of the schedules have started. assert_eq!(Balances::usable_balance(&3), usable_balance); }); @@ -745,7 +745,7 @@ fn merge_ongoing_and_yet_to_be_started_schedules() { ED, // Vesting over 20 blocks 10, ); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0]); // Fast forward to half way through the life of sched1. let mut cur_block = @@ -797,7 +797,7 @@ fn merge_ongoing_and_yet_to_be_started_schedules() { let sched2_per_block = sched2_locked / sched2_duration; let sched2 = VestingInfo::new(sched2_locked, sched2_per_block, sched2_start); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched2]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched2]); }); } @@ -812,7 +812,7 @@ fn merge_finished_and_ongoing_schedules() { ED, // Vesting over 20 blocks. 10, ); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0]); let sched1 = VestingInfo::new( ED * 40, @@ -831,7 +831,7 @@ fn merge_finished_and_ongoing_schedules() { assert_ok!(Vesting::vested_transfer(Some(3).into(), 2, sched2)); // The schedules are in expected order prior to merging. - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0, sched1, sched2]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0, sched1, sched2]); // Fast forward to sched0's end block. let cur_block = sched0.ending_block_as_balance::(); @@ -846,7 +846,7 @@ fn merge_finished_and_ongoing_schedules() { // sched2 is now the first, since sched0 & sched1 get filtered out while "merging". // sched1 gets treated like the new merged schedule by getting pushed onto back // of the vesting schedules vec. Note: sched0 finished at the current block. - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched2, sched1]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched2, sched1]); // sched0 has finished, so its funds are fully unlocked. let sched0_unlocked_now = sched0.locked(); @@ -874,7 +874,7 @@ fn merge_finishing_schedules_does_not_create_a_new_one() { ED, // 20 block duration. 10, ); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0]); // Create sched1 and transfer it to account 2. let sched1 = VestingInfo::new( @@ -883,7 +883,7 @@ fn merge_finishing_schedules_does_not_create_a_new_one() { 10, ); assert_ok!(Vesting::vested_transfer(Some(3).into(), 2, sched1)); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0, sched1]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0, sched1]); let all_scheds_end = sched0 .ending_block_as_balance::() @@ -916,7 +916,7 @@ fn merge_finished_and_yet_to_be_started_schedules() { ED, // 20 block duration. 10, // Ends at block 30 ); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0]); let sched1 = VestingInfo::new( ED * 30, @@ -924,7 +924,7 @@ fn merge_finished_and_yet_to_be_started_schedules() { 35, ); assert_ok!(Vesting::vested_transfer(Some(13).into(), 2, sched1)); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0, sched1]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0, sched1]); let sched2 = VestingInfo::new( ED * 40, @@ -933,7 +933,7 @@ fn merge_finished_and_yet_to_be_started_schedules() { ); // Add a 3rd schedule to demonstrate how sched1 shifts. assert_ok!(Vesting::vested_transfer(Some(13).into(), 2, sched2)); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0, sched1, sched2]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0, sched1, sched2]); System::set_block_number(30); @@ -948,7 +948,7 @@ fn merge_finished_and_yet_to_be_started_schedules() { // sched0 is removed since it finished, and sched1 is removed and then pushed on the back // because it is treated as the merged schedule - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched2, sched1]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched2, sched1]); // The usable balance is updated because merging fully unlocked sched0. assert_eq!(Balances::usable_balance(&2), sched0.locked()); @@ -964,7 +964,7 @@ fn merge_schedules_throws_proper_errors() { ED, // 20 block duration. 10, ); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0]); // Account 2 only has 1 vesting schedule. assert_noop!( @@ -973,12 +973,12 @@ fn merge_schedules_throws_proper_errors() { ); // Account 4 has 0 vesting schedules. - assert_eq!(Vesting::vesting(&4), None); + assert_eq!(VestingStorage::::get(&4), None); assert_noop!(Vesting::merge_schedules(Some(4).into(), 0, 1), Error::::NotVesting); // There are enough schedules to merge but an index is non-existent. Vesting::vested_transfer(Some(3).into(), 2, sched0).unwrap(); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0, sched0]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![sched0, sched0]); assert_noop!( Vesting::merge_schedules(Some(2).into(), 0, 2), Error::::ScheduleIndexOutOfBounds @@ -1011,17 +1011,17 @@ fn generates_multiple_schedules_from_genesis_config() { .build() .execute_with(|| { let user1_sched1 = VestingInfo::new(5 * ED, 128, 0u64); - assert_eq!(Vesting::vesting(&1).unwrap(), vec![user1_sched1]); + assert_eq!(VestingStorage::::get(&1).unwrap(), vec![user1_sched1]); let user2_sched1 = VestingInfo::new(1 * ED, 12, 10u64); let user2_sched2 = VestingInfo::new(2 * ED, 25, 10u64); - assert_eq!(Vesting::vesting(&2).unwrap(), vec![user2_sched1, user2_sched2]); + assert_eq!(VestingStorage::::get(&2).unwrap(), vec![user2_sched1, user2_sched2]); let user12_sched1 = VestingInfo::new(1 * ED, 12, 10u64); let user12_sched2 = VestingInfo::new(2 * ED, 25, 10u64); let user12_sched3 = VestingInfo::new(3 * ED, 38, 10u64); assert_eq!( - Vesting::vesting(&12).unwrap(), + VestingStorage::::get(&12).unwrap(), vec![user12_sched1, user12_sched2, user12_sched3] ); }); diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index 35906107015c5..fd2cad1e845e8 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -25,10 +25,9 @@ pub mod system; use codec::{Decode, Encode, Error, Input, MaxEncodedLen}; use scale_info::TypeInfo; -use sp_std::{marker::PhantomData, prelude::*}; - use sp_application_crypto::{ecdsa, ed25519, sr25519, RuntimeAppPublic}; use sp_core::{offchain::KeyTypeId, OpaqueMetadata, RuntimeDebug}; +use sp_std::{marker::PhantomData, prelude::*}; use sp_trie::{ trie_types::{TrieDBBuilder, TrieDBMutBuilderV1}, PrefixedMemoryDB, StorageProof, @@ -892,7 +891,7 @@ cfg_if! { c: (3, 10), authorities: system::authorities() .into_iter().map(|x|(x, 1)).collect(), - randomness: >::randomness(), + randomness: >::get(), allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots, } } @@ -1188,7 +1187,7 @@ cfg_if! { c: (3, 10), authorities: system::authorities() .into_iter().map(|x|(x, 1)).collect(), - randomness: >::randomness(), + randomness: >::get(), allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots, } }