From 535010888274864d3a690b6f50e3cead75013723 Mon Sep 17 00:00:00 2001 From: Shannon Wells Date: Fri, 12 Jul 2024 13:16:23 -0700 Subject: [PATCH] Refactor reward era (#2069) # Goal The goal of this PR is primarily to pull RewardEra out of the Capacity Config and make it the same type everywhere. Other changes in this PR that were incidental to this refactor * I renamed staking_events in testing_utils, because it captures all the events from the pallet. * I pulled out RewardEraLength into constants so it could be different for different environments. Related to #1970 --- common/primitives/src/capacity.rs | 3 + e2e/capacity/change_staking_target.test.ts | 14 +++-- pallets/capacity/src/benchmarking.rs | 9 +-- pallets/capacity/src/lib.rs | 55 +++++++------------ .../src/migration/provider_boost_init.rs | 3 +- .../src/tests/change_staking_target_tests.rs | 15 +++-- pallets/capacity/src/tests/eras_tests.rs | 9 ++- pallets/capacity/src/tests/mock.rs | 3 +- .../src/tests/provider_boost_history_tests.rs | 5 +- .../src/tests/provider_boost_tests.rs | 2 +- .../capacity/src/tests/reward_pool_tests.rs | 3 +- .../src/tests/rewards_provider_tests.rs | 9 ++- .../src/tests/stake_and_deposit_tests.rs | 6 +- pallets/capacity/src/tests/testing_utils.rs | 2 +- pallets/capacity/src/tests/unstaking_tests.rs | 4 +- .../capacity/src/tests/withdrawal_tests.rs | 2 +- pallets/capacity/src/types.rs | 43 +++++++++------ .../frequency-tx-payment/src/tests/mock.rs | 1 - runtime/common/src/constants.rs | 5 ++ runtime/frequency/src/lib.rs | 12 ++-- 20 files changed, 106 insertions(+), 99 deletions(-) diff --git a/common/primitives/src/capacity.rs b/common/primitives/src/capacity.rs index 58fb44b490..6200a1b9d6 100644 --- a/common/primitives/src/capacity.rs +++ b/common/primitives/src/capacity.rs @@ -2,6 +2,9 @@ use crate::msa::MessageSourceId; use frame_support::traits::tokens::Balance; use sp_runtime::DispatchError; +/// The type of a Reward Era +pub type RewardEra = u32; + /// A trait for checking that a target MSA can be staked to. pub trait TargetValidator { /// Checks if an MSA is a valid target. diff --git a/e2e/capacity/change_staking_target.test.ts b/e2e/capacity/change_staking_target.test.ts index 99fb4a454b..acbfa737ab 100644 --- a/e2e/capacity/change_staking_target.test.ts +++ b/e2e/capacity/change_staking_target.test.ts @@ -33,9 +33,15 @@ describe("Capacity: change_staking_target", function() { const stakeKeys = createKeys("staker"); const oldProvider = await createMsaAndProvider(fundingSource, stakeKeys, "Provider2", providerBalance); - await assert.doesNotReject(stakeToProvider(fundingSource, stakeKeys, oldProvider, tokenMinStake*3n)); - const notAProvider = 3; - const call = ExtrinsicHelper.changeStakingTarget(stakeKeys, oldProvider, notAProvider, tokenMinStake); - await assert.rejects(call.signAndSend(), {name: "InvalidTarget"}) + await assert.doesNotReject(stakeToProvider(fundingSource, stakeKeys, oldProvider, tokenMinStake*6n)); + const notAProvider = 9999; + const call = ExtrinsicHelper.changeStakingTarget(stakeKeys, oldProvider, notAProvider, tokenMinStake*2n); + await assert.rejects(call.signAndSend(), + (err) => { + assert. strictEqual(err?.name, 'InvalidTarget', `expected InvalidTarget, got ${err?.name}`); + // // {name: "InvalidTarget"} + // assert. strictEqual(err?.message, `Wrong value: expected`); + return true; + }); }); }); diff --git a/pallets/capacity/src/benchmarking.rs b/pallets/capacity/src/benchmarking.rs index b5d9686597..9b1182c649 100644 --- a/pallets/capacity/src/benchmarking.rs +++ b/pallets/capacity/src/benchmarking.rs @@ -1,9 +1,10 @@ use super::*; use crate::Pallet as Capacity; +use crate::StakingType::*; use frame_benchmarking::{account, benchmarks, whitelist_account}; use frame_support::{assert_ok, BoundedVec}; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use parity_scale_codec::alloc::vec::Vec; const SEED: u32 = 0; @@ -38,11 +39,11 @@ pub fn set_up_epoch(current_block: BlockNumberFor, current_epoch: } pub fn set_era_and_reward_pool_at_block( - era_index: T::RewardEra, + era_index: RewardEra, started_at: BlockNumberFor, total_staked_token: BalanceOf, ) { - let era_info: RewardEraInfo> = + let era_info: RewardEraInfo> = RewardEraInfo { era_index, started_at }; CurrentEraInfo::::set(era_info); CurrentEraProviderBoostTotal::::set(total_staked_token) @@ -149,7 +150,7 @@ benchmarks! { let total_staked_token: BalanceOf = 5_000u32.into(); let started_at: BlockNumberFor = current_block.saturating_sub(::EraLength::get().into()); - let current_era: T::RewardEra = (history_limit + 1u32).into(); + let current_era: RewardEra = (history_limit + 1u32).into(); CurrentEraInfo::::set(RewardEraInfo{ era_index: current_era, started_at }); fill_reward_pool_chunks::(); }: { diff --git a/pallets/capacity/src/lib.rs b/pallets/capacity/src/lib.rs index 1778d6cb02..6446bf5291 100644 --- a/pallets/capacity/src/lib.rs +++ b/pallets/capacity/src/lib.rs @@ -36,7 +36,7 @@ use frame_support::{ }, weights::{constants::RocksDbWeight, Weight}, }; - +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::{ traits::{CheckedAdd, CheckedDiv, One, Saturating, Zero}, ArithmeticError, BoundedVec, DispatchError, Perbill, Permill, @@ -50,7 +50,6 @@ pub use common_primitives::{ #[cfg(feature = "runtime-benchmarks")] use common_primitives::benchmarks::RegisterProviderBenchmarkHelper; - pub use pallet::*; pub use types::*; pub use weights::*; @@ -66,18 +65,23 @@ mod tests; /// storage migrations pub mod migration; pub mod weights; -pub(crate) type BalanceOf = +type BalanceOf = <::Currency as InspectFungible<::AccountId>>::Balance; -use crate::StakingType::{MaximumCapacity, ProviderBoost}; +use crate::StakingType::ProviderBoost; +use common_primitives::capacity::RewardEra; use frame_system::pallet_prelude::*; #[frame_support::pallet] pub mod pallet { use super::*; - use frame_support::{pallet_prelude::*, Twox64Concat}; - use parity_scale_codec::EncodeLike; + use crate::StakingType::MaximumCapacity; + use common_primitives::capacity::RewardEra; + use frame_support::{ + pallet_prelude::{StorageVersion, *}, + Twox64Concat, + }; use sp_runtime::traits::{AtLeast32BitUnsigned, MaybeDisplay}; /// A reason for freezing funds. @@ -153,24 +157,6 @@ pub mod pallet { #[pallet::constant] type CapacityPerToken: Get; - /// A period of `EraLength` blocks in which a Staking Pool applies and - /// when Provider Boost Rewards may be earned. - type RewardEra: Parameter - + Member - + MaybeSerializeDeserialize - + MaybeDisplay - + AtLeast32BitUnsigned - + Default - + Copy - + sp_std::hash::Hash - + MaxEncodedLen - + EncodeLike - + Into> - + Into> - + Into - + EncodeLike - + TypeInfo; - /// The number of blocks in a RewardEra #[pallet::constant] type EraLength: Get; @@ -272,7 +258,7 @@ pub mod pallet { #[pallet::whitelist_storage] #[pallet::getter(fn get_current_era)] pub type CurrentEraInfo = - StorageValue<_, RewardEraInfo>, ValueQuery>; + StorageValue<_, RewardEraInfo>, ValueQuery>; /// Reward Pool history is divided into chunks of size RewardPoolChunkLength. /// ProviderBoostHistoryLimit is the total number of items, the key is the @@ -949,8 +935,7 @@ impl Pallet { } fn start_new_reward_era_if_needed(current_block: BlockNumberFor) -> Weight { - let current_era_info: RewardEraInfo> = - Self::get_current_era(); // 1r + let current_era_info: RewardEraInfo> = Self::get_current_era(); // 1r if current_block.saturating_sub(current_era_info.started_at) >= T::EraLength::get().into() { // 1r @@ -976,7 +961,7 @@ impl Pallet { /// Returns: /// Error::MaxRetargetsExceeded if they try to retarget too many times in one era. fn update_retarget_record(staker: &T::AccountId) -> Result<(), DispatchError> { - let current_era: T::RewardEra = Self::get_current_era().era_index; + let current_era: RewardEra = Self::get_current_era().era_index; let mut retargets = Self::get_retargets_for(staker).unwrap_or_default(); ensure!(retargets.update(current_era).is_some(), Error::::MaxRetargetsExceeded); Retargets::::set(staker, Some(retargets)); @@ -1014,7 +999,7 @@ impl Pallet { /// pass 'false' for a decrease (unstake) pub(crate) fn upsert_boost_history( account: &T::AccountId, - current_era: T::RewardEra, + current_era: RewardEra, boost_amount: BalanceOf, add: bool, ) -> Result<(), DispatchError> { @@ -1113,7 +1098,7 @@ impl Pallet { // Returns the block number for the end of the provided era. Assumes `era` is at least this // era or in the future - pub(crate) fn block_at_end_of_era(era: T::RewardEra) -> BlockNumberFor { + pub(crate) fn block_at_end_of_era(era: RewardEra) -> BlockNumberFor { let current_era_info = Self::get_current_era(); let era_length: BlockNumberFor = T::EraLength::get().into(); @@ -1127,8 +1112,8 @@ impl Pallet { // Figure out the history chunk that a given era is in and pull out the total stake for that era. pub(crate) fn get_total_stake_for_past_era( - reward_era: T::RewardEra, - current_era: T::RewardEra, + reward_era: RewardEra, + current_era: RewardEra, ) -> Result, DispatchError> { // Make sure that the past era is not too old let era_range = current_era.saturating_sub(reward_era); @@ -1153,7 +1138,7 @@ impl Pallet { /// - The second step is which chunk to add to: /// - Divide the cycle by the chunk length and take the floor /// - Floor(5 / 3) = 1 - pub(crate) fn get_chunk_index_for_era(era: T::RewardEra) -> u32 { + pub(crate) fn get_chunk_index_for_era(era: RewardEra) -> u32 { let history_limit: u32 = T::ProviderBoostHistoryLimit::get(); let chunk_len = T::RewardPoolChunkLength::get(); // Remove one because eras are 1 indexed @@ -1170,7 +1155,7 @@ impl Pallet { // - [6], [2,3], [4,5] // - [6,7], [2,3], [4,5] // - [6,7], [8], [4,5] - pub(crate) fn update_provider_boost_reward_pool(era: T::RewardEra, boost_total: BalanceOf) { + pub(crate) fn update_provider_boost_reward_pool(era: RewardEra, boost_total: BalanceOf) { // Current era is this era let chunk_idx: u32 = Self::get_chunk_index_for_era(era); let mut new_chunk = @@ -1268,7 +1253,7 @@ impl Replenishable for Pallet { impl ProviderBoostRewardsProvider for Pallet { type AccountId = T::AccountId; - type RewardEra = T::RewardEra; + type RewardEra = common_primitives::capacity::RewardEra; type Hash = T::Hash; type Balance = BalanceOf; diff --git a/pallets/capacity/src/migration/provider_boost_init.rs b/pallets/capacity/src/migration/provider_boost_init.rs index 23239e9877..a5934a07bc 100644 --- a/pallets/capacity/src/migration/provider_boost_init.rs +++ b/pallets/capacity/src/migration/provider_boost_init.rs @@ -4,6 +4,7 @@ use frame_support::{ traits::{Get, OnRuntimeUpgrade}, }; +use common_primitives::capacity::RewardEra; #[cfg(feature = "try-runtime")] use sp_std::vec::Vec; @@ -15,7 +16,7 @@ impl OnRuntimeUpgrade for ProviderBoostInit { let current_era_info = CurrentEraInfo::::get(); // 1r if current_era_info.eq(&RewardEraInfo::default()) { let current_block = frame_system::Pallet::::block_number(); // Whitelisted - let era_index: T::RewardEra = 1u32.into(); + let era_index: RewardEra = 1u32.into(); CurrentEraInfo::::set(RewardEraInfo { era_index, started_at: current_block }); // 1w CurrentEraProviderBoostTotal::::set(0u32.into()); // 1w T::DbWeight::get().reads_writes(2, 1) diff --git a/pallets/capacity/src/tests/change_staking_target_tests.rs b/pallets/capacity/src/tests/change_staking_target_tests.rs index 805018d221..bc84219cbf 100644 --- a/pallets/capacity/src/tests/change_staking_target_tests.rs +++ b/pallets/capacity/src/tests/change_staking_target_tests.rs @@ -1,8 +1,8 @@ use super::{ mock::*, - testing_utils::{setup_provider, staking_events}, + testing_utils::{capacity_events, setup_provider}, }; -use crate::*; +use crate::{StakingType::*, *}; use common_primitives::msa::MessageSourceId; use frame_support::{assert_noop, assert_ok, traits::Get}; @@ -229,7 +229,7 @@ fn change_staking_starget_emits_event_on_success() { to_msa, to_amount )); - let events = staking_events(); + let events = capacity_events(); assert_eq!( events.last().unwrap(), @@ -425,7 +425,7 @@ fn impl_retarget_info_errors_when_attempt_to_update_past_bounded_max() { TestCase { era: 1u32, retargets: 5u32, last_retarget: 1, expected: None }, ] { let mut retarget_info: RetargetInfo = - RetargetInfo { retarget_count: tc.retargets, last_retarget_at: tc.last_retarget }; + RetargetInfo::new(tc.retargets, tc.last_retarget); assert_eq!(retarget_info.update(tc.era), tc.expected); } }) @@ -448,7 +448,7 @@ fn impl_retarget_info_updates_values_correctly() { TestCase { era: 1, retargets: 5, last_retarget: 1, expected_retargets: 5 }, ] { let mut retarget_info: RetargetInfo = - RetargetInfo { retarget_count: tc.retargets, last_retarget_at: tc.last_retarget }; + RetargetInfo::new(tc.retargets, tc.last_retarget); retarget_info.update(tc.era); assert_eq!(retarget_info.retarget_count, tc.expected_retargets); } @@ -459,10 +459,9 @@ fn impl_retarget_info_updates_values_correctly() { fn impl_retarget_chunks_cleanup_when_new_reward_era() { new_test_ext().execute_with(|| { let current_era = 2u32; - let mut retarget_info: RetargetInfo = - RetargetInfo { retarget_count: 5, last_retarget_at: 1 }; + let mut retarget_info: RetargetInfo = RetargetInfo::new(5, 1); assert!(retarget_info.update(current_era).is_some()); - let expected: RetargetInfo = RetargetInfo { retarget_count: 1, last_retarget_at: 2 }; + let expected: RetargetInfo = RetargetInfo::new(1, 2); assert_eq!(retarget_info, expected); }); } diff --git a/pallets/capacity/src/tests/eras_tests.rs b/pallets/capacity/src/tests/eras_tests.rs index 2c5548d128..f30b17c464 100644 --- a/pallets/capacity/src/tests/eras_tests.rs +++ b/pallets/capacity/src/tests/eras_tests.rs @@ -1,9 +1,8 @@ use super::mock::*; use crate::{ - tests::testing_utils::*, BalanceOf, Config, CurrentEraInfo, CurrentEraProviderBoostTotal, - RewardEraInfo, + tests::testing_utils::*, BalanceOf, CurrentEraInfo, CurrentEraProviderBoostTotal, RewardEraInfo, }; -use common_primitives::msa::MessageSourceId; +use common_primitives::{capacity::RewardEra, msa::MessageSourceId}; use frame_support::assert_ok; pub fn boost_provider_and_run_to_end_of_era( @@ -44,7 +43,7 @@ fn start_new_era_if_needed_updates_era_info() { fn assert_chunk_is_full_and_has_earliest_era_total( chunk_index: u32, is_full: bool, - era: ::RewardEra, + era: RewardEra, total: BalanceOf, ) { let chunk = Capacity::get_reward_pool_chunk(chunk_index).unwrap(); @@ -55,7 +54,7 @@ fn assert_chunk_is_full_and_has_earliest_era_total( // gets the last (i.e. latest non-current) stored reward pool era, which is in chunk 0. // asserts that it is the same as `era`, and that it has amount `total` -fn assert_last_era_total(era: ::RewardEra, total: BalanceOf) { +fn assert_last_era_total(era: RewardEra, total: BalanceOf) { let chunk_idx = Capacity::get_chunk_index_for_era(era); let chunk_opt = Capacity::get_reward_pool_chunk(chunk_idx); assert!(chunk_opt.is_some(), "No pool for Era: {:?} with chunk index: {:?}", era, chunk_idx); diff --git a/pallets/capacity/src/tests/mock.rs b/pallets/capacity/src/tests/mock.rs index ace151d2e4..e023897bab 100644 --- a/pallets/capacity/src/tests/mock.rs +++ b/pallets/capacity/src/tests/mock.rs @@ -152,7 +152,7 @@ impl ProviderBoostRewardsProvider for TestRewardsProvider { } fn staking_reward_totals( - account_id: Self::AccountId, + _account_id: Self::AccountId, ) -> Result< BoundedVec, ::ProviderBoostHistoryLimit>, DispatchError, @@ -197,7 +197,6 @@ impl pallet_capacity::Config for Test { type MaxEpochLength = ConstU32<100>; type EpochNumber = u32; type CapacityPerToken = TestCapacityPerToken; - type RewardEra = TestRewardEra; type EraLength = ConstU32<10>; type ProviderBoostHistoryLimit = ConstU32<12>; type RewardsProvider = Capacity; diff --git a/pallets/capacity/src/tests/provider_boost_history_tests.rs b/pallets/capacity/src/tests/provider_boost_history_tests.rs index 15d0fb768a..c8961f4c73 100644 --- a/pallets/capacity/src/tests/provider_boost_history_tests.rs +++ b/pallets/capacity/src/tests/provider_boost_history_tests.rs @@ -6,6 +6,7 @@ use crate::{ Config, ProviderBoostHistory, StakingType::{MaximumCapacity, ProviderBoost}, }; +use common_primitives::capacity::RewardEra; use frame_support::assert_ok; use sp_runtime::traits::{Get, Zero}; @@ -71,12 +72,12 @@ fn provider_boost_history_add_era_balance_adds_entries_and_deletes_old_if_full() } assert_eq!(pbh.count(), bound as usize); - let new_era: ::RewardEra = 99; + let new_era: RewardEra = 99; pbh.add_era_balance(&new_era, &1000u64); assert_eq!(pbh.count(), bound as usize); assert!(pbh.get_entry_for_era(&new_era).is_some()); - let first_era: ::RewardEra = 1; + let first_era: RewardEra = 1; assert!(pbh.get_entry_for_era(&first_era).is_none()); } diff --git a/pallets/capacity/src/tests/provider_boost_tests.rs b/pallets/capacity/src/tests/provider_boost_tests.rs index f231570703..6ed5b4a359 100644 --- a/pallets/capacity/src/tests/provider_boost_tests.rs +++ b/pallets/capacity/src/tests/provider_boost_tests.rs @@ -27,7 +27,7 @@ fn provider_boost_works() { let capacity_details = Capacity::get_capacity_for(target).unwrap(); assert_eq!(capacity_details.total_capacity_issued, capacity); - let events = staking_events(); + let events = capacity_events(); assert_eq!( events.first().unwrap(), &Event::ProviderBoosted { account, target, amount, capacity } diff --git a/pallets/capacity/src/tests/reward_pool_tests.rs b/pallets/capacity/src/tests/reward_pool_tests.rs index c79c1de569..2f5347d705 100644 --- a/pallets/capacity/src/tests/reward_pool_tests.rs +++ b/pallets/capacity/src/tests/reward_pool_tests.rs @@ -2,6 +2,7 @@ use crate::{ tests::{mock::*, testing_utils::set_era_and_reward_pool}, BalanceOf, Config, ProviderBoostRewardPools, RewardPoolHistoryChunk, }; +use common_primitives::capacity::RewardEra; use frame_support::{assert_ok, traits::Get}; use std::ops::Add; @@ -9,7 +10,7 @@ use std::ops::Add; // runtime. fn fill_reward_pool_history_chunk( chunk_index: u32, - starting_era: ::RewardEra, + starting_era: RewardEra, number_of_items: u32, starting_total_stake: BalanceOf, ) { diff --git a/pallets/capacity/src/tests/rewards_provider_tests.rs b/pallets/capacity/src/tests/rewards_provider_tests.rs index d4cd909082..947cd46b60 100644 --- a/pallets/capacity/src/tests/rewards_provider_tests.rs +++ b/pallets/capacity/src/tests/rewards_provider_tests.rs @@ -1,16 +1,15 @@ use super::mock::*; use crate::{ - Config, CurrentEraInfo, Error, ProviderBoostHistories, ProviderBoostHistory, - ProviderBoostRewardsProvider, RewardEraInfo, StakingDetails, StakingType::*, - UnclaimedRewardInfo, + Config, ProviderBoostHistories, ProviderBoostHistory, ProviderBoostRewardsProvider, + StakingType::*, UnclaimedRewardInfo, }; -use frame_support::{assert_err, assert_ok, traits::Len}; +use frame_support::{assert_ok, traits::Len}; use crate::tests::testing_utils::{ run_to_block, set_era_and_reward_pool, setup_provider, system_run_to_block, }; use common_primitives::msa::MessageSourceId; -use sp_core::{Get, H256}; +use sp_core::Get; // This tests Capacity implementation of the trait, but uses the mock's constants, // to ensure that it's correctly specified in the pallet. diff --git a/pallets/capacity/src/tests/stake_and_deposit_tests.rs b/pallets/capacity/src/tests/stake_and_deposit_tests.rs index 47e67e8018..c4dcf1c0e3 100644 --- a/pallets/capacity/src/tests/stake_and_deposit_tests.rs +++ b/pallets/capacity/src/tests/stake_and_deposit_tests.rs @@ -37,7 +37,7 @@ fn stake_works() { capacity_details ); - let events = staking_events(); + let events = capacity_events(); assert_eq!(events.first().unwrap(), &Event::Staked { account, target, amount, capacity }); assert_eq!( @@ -101,7 +101,7 @@ fn stake_increase_stake_amount_works() { // First Stake assert_ok!(Capacity::stake(RuntimeOrigin::signed(account), target, initial_amount)); - let events = staking_events(); + let events = capacity_events(); assert_eq!( events.first().unwrap(), &Event::Staked { account, target, amount: initial_amount, capacity } @@ -136,7 +136,7 @@ fn stake_increase_stake_amount_works() { assert_eq!(Capacity::get_capacity_for(target).unwrap().total_capacity_issued, 15); assert_eq!(Capacity::get_capacity_for(target).unwrap().last_replenished_epoch, 0); - let events = staking_events(); + let events = capacity_events(); assert_eq!( events.last().unwrap(), &Event::Staked { account, target, amount: additional_amount, capacity } diff --git a/pallets/capacity/src/tests/testing_utils.rs b/pallets/capacity/src/tests/testing_utils.rs index c45f777b26..0f4a2969ea 100644 --- a/pallets/capacity/src/tests/testing_utils.rs +++ b/pallets/capacity/src/tests/testing_utils.rs @@ -10,7 +10,7 @@ use crate::{ }; use common_primitives::msa::MessageSourceId; -pub fn staking_events() -> Vec> { +pub fn capacity_events() -> Vec> { let result = System::events() .into_iter() .map(|r| r.event) diff --git a/pallets/capacity/src/tests/unstaking_tests.rs b/pallets/capacity/src/tests/unstaking_tests.rs index 9a7943af28..ac17532f38 100644 --- a/pallets/capacity/src/tests/unstaking_tests.rs +++ b/pallets/capacity/src/tests/unstaking_tests.rs @@ -73,7 +73,7 @@ fn unstake_happy_path() { } ); - let events = staking_events(); + let events = capacity_events(); assert_eq!( events.last().unwrap(), &Event::UnStaked { @@ -285,7 +285,7 @@ fn unstake_when_not_staking_to_target_errors() { } #[test] -fn unstake_provider_boosted_target_adjusts_reward_pool_total() { +fn unstake_provider_boosted_target_in_same_era_adjusts_reward_pool_total() { new_test_ext().execute_with(|| { // two accounts staking to the same target let account1 = 600; diff --git a/pallets/capacity/src/tests/withdrawal_tests.rs b/pallets/capacity/src/tests/withdrawal_tests.rs index 46f6fe443a..8f4f6930d7 100644 --- a/pallets/capacity/src/tests/withdrawal_tests.rs +++ b/pallets/capacity/src/tests/withdrawal_tests.rs @@ -17,7 +17,7 @@ fn impl_withdraw_is_successful() { ); assert_ok!(Capacity::deduct(target_msa_id, 5u32.into())); - let events = staking_events(); + let events = capacity_events(); assert_eq!( events.last().unwrap(), diff --git a/pallets/capacity/src/types.rs b/pallets/capacity/src/types.rs index e7f1158673..08aaf7b594 100644 --- a/pallets/capacity/src/types.rs +++ b/pallets/capacity/src/types.rs @@ -1,6 +1,10 @@ //! Types for the Capacity Pallet use super::*; -use frame_support::{BoundedVec, EqNoBound, PartialEqNoBound, RuntimeDebugNoBound}; +use common_primitives::capacity::RewardEra; +use frame_support::{ + pallet_prelude::PhantomData, BoundedVec, EqNoBound, PartialEqNoBound, RuntimeDebugNoBound, +}; +use frame_system::pallet_prelude::BlockNumberFor; use parity_scale_codec::{Decode, Encode, EncodeLike, MaxEncodedLen}; use scale_info::TypeInfo; use sp_runtime::{ @@ -276,7 +280,7 @@ where #[derive(PartialEq, Eq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)] #[scale_info(skip_type_params(T))] pub struct RewardPoolHistoryChunk( - BoundedBTreeMap, T::RewardPoolChunkLength>, + BoundedBTreeMap, T::RewardPoolChunkLength>, ); impl Default for RewardPoolHistoryChunk { fn default() -> Self { @@ -298,14 +302,14 @@ impl RewardPoolHistoryChunk { /// A wrapper for retrieving how much was provider_boosted in the given era /// from the BoundedBTreeMap - pub fn total_for_era(&self, reward_era: &T::RewardEra) -> Option<&BalanceOf> { + pub fn total_for_era(&self, reward_era: &RewardEra) -> Option<&BalanceOf> { self.0.get(reward_era) } /// returns the range of eras in this chunk /// Used in testing - pub fn era_range(&self) -> (T::RewardEra, T::RewardEra) { - let zero_reward_era: T::RewardEra = Zero::zero(); + pub fn era_range(&self) -> (RewardEra, RewardEra) { + let zero_reward_era: RewardEra = Zero::zero(); let zero_balance: BalanceOf = Zero::zero(); let (first, _vf) = self.0.first_key_value().unwrap_or((&zero_reward_era, &zero_balance)); let (last, _vl) = self.0.last_key_value().unwrap_or((&zero_reward_era, &zero_balance)); @@ -315,15 +319,15 @@ impl RewardPoolHistoryChunk { /// A wrapper for adding a new reward_era_entry to the BoundedBTreeMap pub fn try_insert( &mut self, - reward_era: T::RewardEra, + reward_era: RewardEra, total: BalanceOf, - ) -> Result>, (T::RewardEra, BalanceOf)> { + ) -> Result>, (RewardEra, BalanceOf)> { self.0.try_insert(reward_era, total) } /// Get the earliest reward era stored in this BoundedBTreeMap /// Used only in testing. - pub fn earliest_era(&self) -> Option<&T::RewardEra> { + pub fn earliest_era(&self) -> Option<&RewardEra> { if let Some((first_era, _first_total)) = self.0.first_key_value() { return Some(first_era); } @@ -340,7 +344,7 @@ impl RewardPoolHistoryChunk { #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)] #[scale_info(skip_type_params(T))] pub struct ProviderBoostHistory( - BoundedBTreeMap, T::ProviderBoostHistoryLimit>, + BoundedBTreeMap, T::ProviderBoostHistoryLimit>, ); impl Default for ProviderBoostHistory { @@ -360,7 +364,7 @@ impl ProviderBoostHistory { /// returns the total number of history items pub fn add_era_balance( &mut self, - reward_era: &T::RewardEra, + reward_era: &RewardEra, add_amount: &BalanceOf, ) -> Option { if let Some(entry) = self.0.get_mut(&reward_era) { @@ -388,7 +392,7 @@ impl ProviderBoostHistory { /// Otherwise returns Some(history_count) pub fn subtract_era_balance( &mut self, - reward_era: &T::RewardEra, + reward_era: &RewardEra, subtract_amount: &BalanceOf, ) -> Option { if self.count().is_zero() { @@ -419,7 +423,7 @@ impl ProviderBoostHistory { } /// A wrapper for the key/value retrieval of the BoundedBTreeMap. - pub(crate) fn get_entry_for_era(&self, reward_era: &T::RewardEra) -> Option<&BalanceOf> { + pub(crate) fn get_entry_for_era(&self, reward_era: &RewardEra) -> Option<&BalanceOf> { self.0.get(reward_era) } @@ -428,7 +432,7 @@ impl ProviderBoostHistory { /// /// Note there is no sense of what the current era is; subsequent calls could return a different result /// if 'reward_era' is the current era and there has been a boost or unstake. - pub(crate) fn get_amount_staked_for_era(&self, reward_era: &T::RewardEra) -> BalanceOf { + pub(crate) fn get_amount_staked_for_era(&self, reward_era: &RewardEra) -> BalanceOf { // this gives an ordered-by-key Iterator let mut bmap_iter = self.0.iter(); let mut eligible_amount: BalanceOf = Zero::zero(); @@ -479,19 +483,24 @@ pub struct RetargetInfo { /// How many times the account has retargeted this RewardEra pub retarget_count: u32, /// The last RewardEra they retargeted - pub last_retarget_at: T::RewardEra, + pub last_retarget_at: RewardEra, + _marker: PhantomData, } impl Default for RetargetInfo { fn default() -> Self { - Self { retarget_count: 0u32, last_retarget_at: Zero::zero() } + Self { retarget_count: 0u32, last_retarget_at: Zero::zero(), _marker: Default::default() } } } impl RetargetInfo { + /// Constructor + pub fn new(retarget_count: u32, last_retarget_at: RewardEra) -> Self { + Self { retarget_count, last_retarget_at, _marker: Default::default() } + } /// Increment retarget count and return Some() or /// If there are too many, return None - pub fn update(&mut self, current_era: T::RewardEra) -> Option<()> { + pub fn update(&mut self, current_era: RewardEra) -> Option<()> { let max_retargets = T::MaxRetargetsPerRewardEra::get(); if self.retarget_count.ge(&max_retargets) && self.last_retarget_at.eq(¤t_era) { return None; @@ -548,7 +557,7 @@ pub trait ProviderBoostRewardsProvider { #[scale_info(skip_type_params(T))] pub struct UnclaimedRewardInfo { /// The Reward Era for which this reward was earned - pub reward_era: T::RewardEra, + pub reward_era: RewardEra, /// When this reward expires, i.e. can no longer be claimed pub expires_at_block: BlockNumberFor, /// The amount staked in this era that is eligible for rewards. Does not count additional amounts diff --git a/pallets/frequency-tx-payment/src/tests/mock.rs b/pallets/frequency-tx-payment/src/tests/mock.rs index 89e9eecbdd..ebddca77ea 100644 --- a/pallets/frequency-tx-payment/src/tests/mock.rs +++ b/pallets/frequency-tx-payment/src/tests/mock.rs @@ -219,7 +219,6 @@ impl pallet_capacity::Config for Test { type EpochNumber = u32; type CapacityPerToken = TestCapacityPerToken; type RuntimeFreezeReason = RuntimeFreezeReason; - type RewardEra = u32; type EraLength = ConstU32<5>; type ProviderBoostHistoryLimit = ConstU32<6>; type RewardsProvider = Capacity; diff --git a/runtime/common/src/constants.rs b/runtime/common/src/constants.rs index 6042c18569..80588dc222 100644 --- a/runtime/common/src/constants.rs +++ b/runtime/common/src/constants.rs @@ -397,4 +397,9 @@ parameter_types! { pub const CapacityPerToken: Perbill = Perbill::from_percent(2); pub const CapacityRewardCap: Permill = Permill::from_parts(3_800); // 0.38% or 0.0038 per RewardEra } +pub type CapacityRewardEraLength = + ConstU32<{ prod_or_testnet_or_local!(14 * DAYS, 1 * HOURS, 50) }>; + +pub type CapacityChangeStakingTargetThawEras = ConstU32<5>; + // -end- Capacity Pallet --- diff --git a/runtime/frequency/src/lib.rs b/runtime/frequency/src/lib.rs index 76742711c6..c791805f60 100644 --- a/runtime/frequency/src/lib.rs +++ b/runtime/frequency/src/lib.rs @@ -322,9 +322,10 @@ pub type Executive = frame_executive::Executive< frame_system::ChainContext, Runtime, AllPalletsWithSystem, - (pallet_schemas::migration::v4::MigrateToV4, - pallet_capacity::migration::provider_boost_init::ProviderBoostInit, - ), + ( + pallet_schemas::migration::v4::MigrateToV4, + pallet_capacity::migration::provider_boost_init::ProviderBoostInit, + ), >; /// Opaque types. These are used by the CLI to instantiate machinery that don't need to know @@ -520,8 +521,7 @@ impl pallet_capacity::Config for Runtime { type EpochNumber = u32; type CapacityPerToken = CapacityPerToken; type RuntimeFreezeReason = RuntimeFreezeReason; - type RewardEra = u32; - type EraLength = ConstU32<{ 14 * DAYS }>; + type EraLength = CapacityRewardEraLength; type ProviderBoostHistoryLimit = ConstU32<30u32>; type RewardsProvider = Capacity; type MaxRetargetsPerRewardEra = ConstU32<16>; @@ -714,7 +714,7 @@ impl pallet_democracy::Config for Runtime { type EnactmentPeriod = EnactmentPeriod; type RuntimeEvent = RuntimeEvent; type FastTrackVotingPeriod = FastTrackVotingPeriod; - type InstantAllowed = frame_support::traits::ConstBool; + type InstantAllowed = ConstBool; type LaunchPeriod = LaunchPeriod; type MaxProposals = DemocracyMaxProposals; type MaxVotes = DemocracyMaxVotes;