diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index dd176219aa7c1..cd02ddaac498a 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -17,8 +17,8 @@ //! # Session Module //! -//! The Session module allows validators to manage their session keys, provides a function for changing -//! the session length, and handles session rotation. +//! The Session module allows validators to manage their session keys, provides a function for +//! changing the session length, and handles session rotation. //! //! - [`session::Config`](./trait.Config.html) //! - [`Call`](./enum.Call.html) @@ -29,34 +29,39 @@ //! ### Terminology //! //! -//! - **Session:** A session is a period of time that has a constant set of validators. Validators can only join -//! or exit the validator set at a session change. It is measured in block numbers. The block where a session is -//! ended is determined by the `ShouldEndSession` trait. When the session is ending, a new validator set -//! can be chosen by `OnSessionEnding` implementations. -//! - **Session key:** A session key is actually several keys kept together that provide the various signing -//! functions required by network authorities/validators in pursuit of their duties. -//! - **Validator ID:** Every account has an associated validator ID. For some simple staking systems, this -//! may just be the same as the account ID. For staking systems using a stash/controller model, -//! the validator ID would be the stash account ID of the controller. +//! - **Session:** A session is a period of time that has a constant set of validators. Validators +//! can only join or exit the validator set at a session change. It is measured in block numbers. +//! The block where a session is ended is determined by the `ShouldEndSession` trait. When the +//! session is ending, a new validator set can be chosen by `OnSessionEnding` implementations. +//! +//! - **Session key:** A session key is actually several keys kept together that provide the various +//! signing functions required by network authorities/validators in pursuit of their duties. +//! - **Validator ID:** Every account has an associated validator ID. For some simple staking +//! systems, this may just be the same as the account ID. For staking systems using a +//! stash/controller model, the validator ID would be the stash account ID of the controller. +//! //! - **Session key configuration process:** Session keys are set using `set_keys` for use not in -//! the next session, but the session after next. They are stored in `NextKeys`, a mapping between -//! the caller's `ValidatorId` and the session keys provided. `set_keys` allows users to set their -//! session key prior to being selected as validator. -//! It is a public call since it uses `ensure_signed`, which checks that the origin is a signed account. -//! As such, the account ID of the origin stored in `NextKeys` may not necessarily be associated with -//! a block author or a validator. The session keys of accounts are removed once their account balance is zero. +//! the next session, but the session after next. They are stored in `NextKeys`, a mapping between +//! the caller's `ValidatorId` and the session keys provided. `set_keys` allows users to set their +//! session key prior to being selected as validator. It is a public call since it uses +//! `ensure_signed`, which checks that the origin is a signed account. As such, the account ID of +//! the origin stored in `NextKeys` may not necessarily be associated with a block author or a +//! validator. The session keys of accounts are removed once their account balance is zero. +//! //! - **Session length:** This pallet does not assume anything about the length of each session. -//! Rather, it relies on an implementation of `ShouldEndSession` to dictate a new session's start. -//! This pallet provides the `PeriodicSessions` struct for simple periodic sessions. -//! - **Session rotation configuration:** Configure as either a 'normal' (rewardable session where rewards are -//! applied) or 'exceptional' (slashable) session rotation. +//! Rather, it relies on an implementation of `ShouldEndSession` to dictate a new session's start. +//! This pallet provides the `PeriodicSessions` struct for simple periodic sessions. +//! +//! - **Session rotation configuration:** Configure as either a 'normal' (rewardable session where +//! rewards are applied) or 'exceptional' (slashable) session rotation. +//! //! - **Session rotation process:** At the beginning of each block, the `on_initialize` function -//! queries the provided implementation of `ShouldEndSession`. If the session is to end the newly -//! activated validator IDs and session keys are taken from storage and passed to the -//! `SessionHandler`. The validator set supplied by `SessionManager::new_session` and the corresponding session -//! keys, which may have been registered via `set_keys` during the previous session, are written -//! to storage where they will wait one session before being passed to the `SessionHandler` -//! themselves. +//! queries the provided implementation of `ShouldEndSession`. If the session is to end the newly +//! activated validator IDs and session keys are taken from storage and passed to the +//! `SessionHandler`. The validator set supplied by `SessionManager::new_session` and the +//! corresponding session keys, which may have been registered via `set_keys` during the previous +//! session, are written to storage where they will wait one session before being passed to the +//! `SessionHandler` themselves. //! //! ### Goals //! @@ -75,7 +80,7 @@ //! ### Public Functions //! //! - `rotate_session` - Change to the next session. Register the new authority set. Queue changes -//! for next session rotation. +//! for next session rotation. //! - `disable_index` - Disable a validator by index. //! - `disable` - Disable a validator by Validator ID //! @@ -83,13 +88,14 @@ //! //! ### Example from the FRAME //! -//! The [Staking pallet](../pallet_staking/index.html) uses the Session pallet to get the validator set. +//! The [Staking pallet](../pallet_staking/index.html) uses the Session pallet to get the validator +//! set. //! //! ``` //! use pallet_session as session; //! //! fn validators() -> Vec<::ValidatorId> { -//! >::validators() +//! >::validators() //! } //! # fn main(){} //! ``` @@ -166,7 +172,7 @@ impl< period.saturating_sub(block_after_last_session) ) } else { - Zero::zero() + now } } else { offset @@ -174,10 +180,10 @@ impl< } fn weight(_now: BlockNumber) -> Weight { - // Weight note: `estimate_next_session_rotation` has no storage reads and trivial computational overhead. - // There should be no risk to the chain having this weight value be zero for now. - // However, this value of zero was not properly calculated, and so it would be reasonable - // to come back here and properly calculate the weight of this function. + // Weight note: `estimate_next_session_rotation` has no storage reads and trivial + // computational overhead. There should be no risk to the chain having this weight value be + // zero for now. However, this value of zero was not properly calculated, and so it would be + // reasonable to come back here and properly calculate the weight of this function. 0 } } @@ -186,17 +192,17 @@ impl< pub trait SessionManager { /// Plan a new session, and optionally provide the new validator set. /// - /// Even if the validator-set is the same as before, if any underlying economic - /// conditions have changed (i.e. stake-weights), the new validator set must be returned. - /// This is necessary for consensus engines making use of the session module to - /// issue a validator-set change so misbehavior can be provably associated with the new - /// economic conditions as opposed to the old. - /// The returned validator set, if any, will not be applied until `new_index`. - /// `new_index` is strictly greater than from previous call. + /// Even if the validator-set is the same as before, if any underlying economic conditions have + /// changed (i.e. stake-weights), the new validator set must be returned. This is necessary for + /// consensus engines making use of the session module to issue a validator-set change so + /// misbehavior can be provably associated with the new economic conditions as opposed to the + /// old. The returned validator set, if any, will not be applied until `new_index`. `new_index` + /// is strictly greater than from previous call. /// /// The first session start at index 0. /// - /// `new_session(session)` is guaranteed to be called before `end_session(session-1)`. + /// `new_session(session)` is guaranteed to be called before `end_session(session-1)`. In other + /// words, a new session must always be planned before an ongoing one can be finished. fn new_session(new_index: SessionIndex) -> Option>; /// End the session. /// @@ -205,7 +211,7 @@ pub trait SessionManager { fn end_session(end_index: SessionIndex); /// Start the session. /// - /// The session start to be used for validation + /// The session start to be used for validation. fn start_session(start_index: SessionIndex); } @@ -242,7 +248,7 @@ pub trait SessionHandler { /// A notification for end of the session. /// - /// Note it is triggered before any `SessionManager::end_session` handlers, + /// Note it is triggered before any [`SessionManager::end_session`] handlers, /// so we can still affect the validator set. fn on_before_session_ending() {} diff --git a/frame/session/src/tests.rs b/frame/session/src/tests.rs index 7a33aa5296bc8..3da5d16caad51 100644 --- a/frame/session/src/tests.rs +++ b/frame/session/src/tests.rs @@ -252,31 +252,32 @@ fn session_changed_flag_works() { #[test] fn periodic_session_works() { - struct Period; - struct Offset; - impl Get for Period { - fn get() -> u64 { 10 } + frame_support::parameter_types! { + const Period: u64 = 10; + const Offset: u64 = 3; } - impl Get for Offset { - fn get() -> u64 { 3 } - } - - type P = PeriodicSessions; - for i in 0..3 { + for i in 0u64..3 { assert!(!P::should_end_session(i)); + assert_eq!(P::estimate_next_session_rotation(i).unwrap(), 3); } - assert!(P::should_end_session(3)); + assert!(P::should_end_session(3u64)); + assert_eq!(P::estimate_next_session_rotation(3u64).unwrap(), 3); - for i in (1..10).map(|i| 3 + i) { + for i in (1u64..10).map(|i| 3 + i) { assert!(!P::should_end_session(i)); + assert_eq!(P::estimate_next_session_rotation(i).unwrap(), 13); } - assert!(P::should_end_session(13)); + assert!(P::should_end_session(13u64)); + assert_eq!(P::estimate_next_session_rotation(13u64).unwrap(), 13); + + assert!(!P::should_end_session(14u64)); + assert_eq!(P::estimate_next_session_rotation(14u64).unwrap(), 23); } #[test] diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index af326e27c62a8..f70a76cb1acc0 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -952,11 +952,14 @@ decl_storage! { /// The active era information, it holds index and start. /// - /// The active era is the era currently rewarded. - /// Validator set of this era must be equal to `SessionInterface::validators`. + /// The active era is the era being currently rewarded. Validator set of this era must be + /// equal to [`SessionInterface::validators`]. pub ActiveEra get(fn active_era): Option; /// The session index at which the era start for the last `HISTORY_DEPTH` eras. + /// + /// Note: This tracks the starting session (i.e. session index when era start being active) + /// for the eras in `[CurrentEra - HISTORY_DEPTH, CurrentEra]`. pub ErasStartSessionIndex get(fn eras_start_session_index): map hasher(twox_64_concat) EraIndex => Option; @@ -2630,14 +2633,17 @@ impl Module { /// 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); + // 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) { if next_active_era_start_session_index == start_session { Self::start_era(start_session); } else if next_active_era_start_session_index < start_session { - // This arm should never happen, but better handle it than to stall the - // staking pallet. + // This arm should never happen, but better handle it than to stall the staking + // pallet. frame_support::print("Warning: A session appears to have been skipped."); Self::start_era(start_session); } @@ -2893,9 +2899,11 @@ impl Module { /// Self votes are added and nominations before the most recent slashing span are ignored. /// /// No storage item is updated. - pub fn do_phragmen(iterations: usize) - -> Option> - where ExtendedBalance: From> + pub fn do_phragmen( + iterations: usize, + ) -> Option> + where + ExtendedBalance: From>, { let weight_of = Self::slashable_balance_of_fn(); let mut all_nominators: Vec<(T::AccountId, VoteWeight, Vec)> = Vec::new(); @@ -2928,7 +2936,11 @@ impl Module { if all_validators.len() < Self::minimum_validator_count().max(1) as usize { // If we don't have enough candidates, nothing to do. - log!(error, "💸 Chain does not have enough staking candidates to operate. Era {:?}.", Self::current_era()); + log!( + warn, + "💸 Chain does not have enough staking candidates to operate. Era {:?}.", + Self::current_era() + ); None } else { seq_phragmen::<_, Accuracy>( @@ -3090,12 +3102,30 @@ impl Module { /// some session can lag in between the newest session planned and the latest session started. impl pallet_session::SessionManager for Module { fn new_session(new_index: SessionIndex) -> Option> { + frame_support::debug::native::trace!( + target: LOG_TARGET, + "[{}] planning new_session({})", + >::block_number(), + new_index + ); Self::new_session(new_index) } fn start_session(start_index: SessionIndex) { + frame_support::debug::native::trace!( + target: LOG_TARGET, + "[{}] starting start_session({})", + >::block_number(), + start_index + ); Self::start_session(start_index) } fn end_session(end_index: SessionIndex) { + frame_support::debug::native::trace!( + target: LOG_TARGET, + "[{}] ending end_session({})", + >::block_number(), + end_index + ); Self::end_session(end_index) } } diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index 76689503f65ab..f3c6d50d4cf56 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -38,6 +38,7 @@ use sp_staking::offence::{OffenceDetails, OnOffenceHandler}; use std::{cell::RefCell, collections::HashSet}; pub const INIT_TIMESTAMP: u64 = 30_000; +pub const BLOCK_TIME: u64 = 1000; /// The AccountId alias in this test module. pub(crate) type AccountId = u64; @@ -135,10 +136,11 @@ parameter_types! { ); pub const MaxLocks: u32 = 1024; pub static SessionsPerEra: SessionIndex = 3; - pub static ExistentialDeposit: Balance = 0; + pub static ExistentialDeposit: Balance = 1; pub static SlashDeferDuration: EraIndex = 0; pub static ElectionLookahead: BlockNumber = 0; - pub static Period: BlockNumber = 1; + pub static Period: BlockNumber = 5; + pub static Offset: BlockNumber = 0; pub static MaxIterations: u32 = 0; } @@ -175,7 +177,6 @@ impl pallet_balances::Config for Test { type WeightInfo = (); } parameter_types! { - pub const Offset: BlockNumber = 0; pub const UncleGenerations: u64 = 0; pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(25); } @@ -286,46 +287,36 @@ where pub type Extrinsic = TestXt; pub struct ExtBuilder { - session_length: BlockNumber, - election_lookahead: BlockNumber, - session_per_era: SessionIndex, - existential_deposit: Balance, validator_pool: bool, nominate: bool, validator_count: u32, minimum_validator_count: u32, - slash_defer_duration: EraIndex, fair: bool, num_validators: Option, invulnerables: Vec, has_stakers: bool, - max_offchain_iterations: u32, + initialize_first_session: bool, } impl Default for ExtBuilder { fn default() -> Self { Self { - session_length: 1, - election_lookahead: 0, - session_per_era: 3, - existential_deposit: 1, validator_pool: false, nominate: true, validator_count: 2, minimum_validator_count: 0, - slash_defer_duration: 0, fair: true, num_validators: None, invulnerables: vec![], has_stakers: true, - max_offchain_iterations: 0, + initialize_first_session: true, } } } impl ExtBuilder { - pub fn existential_deposit(mut self, existential_deposit: Balance) -> Self { - self.existential_deposit = existential_deposit; + pub fn existential_deposit(self, existential_deposit: Balance) -> Self { + EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = existential_deposit); self } pub fn validator_pool(mut self, validator_pool: bool) -> Self { @@ -344,8 +335,8 @@ impl ExtBuilder { self.minimum_validator_count = count; self } - pub fn slash_defer_duration(mut self, eras: EraIndex) -> Self { - self.slash_defer_duration = eras; + pub fn slash_defer_duration(self, eras: EraIndex) -> Self { + SLASH_DEFER_DURATION.with(|v| *v.borrow_mut() = eras); self } pub fn fair(mut self, is_fair: bool) -> Self { @@ -360,46 +351,43 @@ impl ExtBuilder { self.invulnerables = invulnerables; self } - pub fn session_per_era(mut self, length: SessionIndex) -> Self { - self.session_per_era = length; + pub fn session_per_era(self, length: SessionIndex) -> Self { + SESSIONS_PER_ERA.with(|v| *v.borrow_mut() = length); self } - pub fn election_lookahead(mut self, look: BlockNumber) -> Self { - self.election_lookahead = look; + pub fn election_lookahead(self, look: BlockNumber) -> Self { + ELECTION_LOOKAHEAD.with(|v| *v.borrow_mut() = look); self } - pub fn session_length(mut self, length: BlockNumber) -> Self { - self.session_length = length; + pub fn period(self, length: BlockNumber) -> Self { + PERIOD.with(|v| *v.borrow_mut() = length); self } pub fn has_stakers(mut self, has: bool) -> Self { self.has_stakers = has; self } - pub fn max_offchain_iterations(mut self, iterations: u32) -> Self { - self.max_offchain_iterations = iterations; + pub fn max_offchain_iterations(self, iterations: u32) -> Self { + MAX_ITERATIONS.with(|v| *v.borrow_mut() = iterations); self } pub fn offchain_election_ext(self) -> Self { - self.session_per_era(4) - .session_length(5) - .election_lookahead(3) - } - pub fn set_associated_constants(&self) { - EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit); - SLASH_DEFER_DURATION.with(|v| *v.borrow_mut() = self.slash_defer_duration); - SESSIONS_PER_ERA.with(|v| *v.borrow_mut() = self.session_per_era); - ELECTION_LOOKAHEAD.with(|v| *v.borrow_mut() = self.election_lookahead); - PERIOD.with(|v| *v.borrow_mut() = self.session_length); - MAX_ITERATIONS.with(|v| *v.borrow_mut() = self.max_offchain_iterations); + self.session_per_era(4).period(5).election_lookahead(3) + } + pub fn initialize_first_session(mut self, init: bool) -> Self { + self.initialize_first_session = init; + self + } + pub fn offset(self, offset: BlockNumber) -> Self { + OFFSET.with(|v| *v.borrow_mut() = offset); + self } pub fn build(self) -> sp_io::TestExternalities { sp_tracing::try_init_simple(); - self.set_associated_constants(); let mut storage = frame_system::GenesisConfig::default() .build_storage::() .unwrap(); - let balance_factor = if self.existential_deposit > 1 { + let balance_factor = if ExistentialDeposit::get() > 1 { 256 } else { 1 @@ -475,13 +463,17 @@ impl ExtBuilder { SESSION.with(|x| *x.borrow_mut() = (validators.clone(), HashSet::new())); }); - // We consider all test to start after timestamp is initialized - // This must be ensured by having `timestamp::on_initialize` called before - // `staking::on_initialize` - ext.execute_with(|| { - System::set_block_number(1); - Timestamp::set_timestamp(INIT_TIMESTAMP); - }); + if self.initialize_first_session { + // We consider all test to start after timestamp is initialized This must be ensured by + // having `timestamp::on_initialize` called before `staking::on_initialize`. Also, if + // session length is 1, then it is already triggered. + ext.execute_with(|| { + System::set_block_number(1); + Session::on_initialize(1); + Staking::on_initialize(1); + Timestamp::set_timestamp(INIT_TIMESTAMP); + }); + } ext } @@ -498,20 +490,12 @@ pub type Session = pallet_session::Module; pub type Timestamp = pallet_timestamp::Module; pub type Staking = Module; -pub(crate) fn current_era() -> EraIndex { - Staking::current_era().unwrap() -} - fn post_conditions() { check_nominators(); check_exposures(); check_ledgers(); } -pub(crate) fn active_era() -> EraIndex { - Staking::active_era().unwrap().index -} - fn check_ledgers() { // check the ledger of all stakers. Bonded::::iter().for_each(|(_, ctrl)| assert_ledger_consistent(ctrl)) @@ -593,6 +577,14 @@ fn assert_ledger_consistent(ctrl: AccountId) { ); } +pub(crate) fn active_era() -> EraIndex { + Staking::active_era().unwrap().index +} + +pub(crate) fn current_era() -> EraIndex { + Staking::current_era().unwrap() +} + pub(crate) fn bond_validator(stash: AccountId, ctrl: AccountId, val: Balance) { let _ = Balances::make_free_balance_be(&stash, val); let _ = Balances::make_free_balance_be(&ctrl, val); @@ -625,52 +617,98 @@ pub(crate) fn bond_nominator( assert_ok!(Staking::nominate(Origin::signed(ctrl), target)); } +/// Progress to the given block, triggering session and era changes as we progress. +/// +/// This will finalize the previous block, initialize up to the given block, essentially simulating +/// a block import/propose process where we first initialize the block, then execute some stuff (not +/// in the function), and then finalize the block. pub(crate) fn run_to_block(n: BlockNumber) { Staking::on_finalize(System::block_number()); - for b in System::block_number() + 1..=n { + for b in (System::block_number() + 1)..=n { System::set_block_number(b); Session::on_initialize(b); Staking::on_initialize(b); + Timestamp::set_timestamp(System::block_number() * BLOCK_TIME + INIT_TIMESTAMP); if b != n { Staking::on_finalize(System::block_number()); } } } +/// Progresses from the current block number (whatever that may be) to the `P * session_index + 1`. +pub(crate) fn start_session(session_index: SessionIndex) { + let end: u64 = if Offset::get().is_zero() { + (session_index as u64) * Period::get() + } else { + Offset::get() + (session_index.saturating_sub(1) as u64) * Period::get() + }; + run_to_block(end); + // session must have progressed properly. + assert_eq!( + Session::current_index(), + session_index, + "current session index = {}, expected = {}", + Session::current_index(), + session_index, + ); +} + +/// Go one session forward. pub(crate) fn advance_session() { let current_index = Session::current_index(); start_session(current_index + 1); } -pub(crate) fn start_session(session_index: SessionIndex) { - assert_eq!(>::get(), 1, "start_session can only be used with session length 1."); - for i in Session::current_index()..session_index { - Staking::on_finalize(System::block_number()); - System::set_block_number((i + 1).into()); - Timestamp::set_timestamp(System::block_number() * 1000 + INIT_TIMESTAMP); - Session::on_initialize(System::block_number()); - Staking::on_initialize(System::block_number()); - } - - assert_eq!(Session::current_index(), session_index); -} - -// This start and activate the era given. -// Because the mock use pallet-session which delays session by one, this will be one session after -// the election happened, not the first session after the election has happened. -pub(crate) fn start_era(era_index: EraIndex) { +/// Progress until the given era. +pub(crate) fn start_active_era(era_index: EraIndex) { start_session((era_index * >::get()).into()); - assert_eq!(Staking::current_era().unwrap(), era_index); - assert_eq!(Staking::active_era().unwrap().index, era_index); + assert_eq!(active_era(), era_index); + // One way or another, current_era must have changed before the active era, so they must match + // at this point. + assert_eq!(current_era(), active_era()); } pub(crate) fn current_total_payout_for_duration(duration: u64) -> Balance { + let reward = inflation::compute_total_payout( + ::RewardCurve::get(), + Staking::eras_total_stake(active_era()), + Balances::total_issuance(), + duration, + ) + .0; + assert!(reward > 0); + reward +} + +pub(crate) fn maximum_payout_for_duration(duration: u64) -> Balance { inflation::compute_total_payout( ::RewardCurve::get(), - Staking::eras_total_stake(Staking::active_era().unwrap().index), + 0, Balances::total_issuance(), duration, - ).0 + ) + .1 +} + +/// Time it takes to finish a session. +/// +/// Note, if you see `time_per_session() - BLOCK_TIME`, it is fine. This is because we set the +/// timestamp after on_initialize, so the timestamp is always one block old. +pub(crate) fn time_per_session() -> u64 { + Period::get() * BLOCK_TIME +} + +/// Time it takes to finish an era. +/// +/// Note, if you see `time_per_era() - BLOCK_TIME`, it is fine. This is because we set the +/// timestamp after on_initialize, so the timestamp is always one block old. +pub(crate) fn time_per_era() -> u64 { + time_per_session() * SessionsPerEra::get() as u64 +} + +/// Time that will be calculated for the reward per era. +pub(crate) fn reward_time_per_era() -> u64 { + time_per_era() - BLOCK_TIME } pub(crate) fn reward_all_elected() { @@ -939,8 +977,11 @@ pub(crate) fn make_all_reward_payment(era: EraIndex) { // reward validators for validator_controller in validators_with_reward.iter().filter_map(Staking::bonded) { let ledger = >::get(&validator_controller).unwrap(); - - assert_ok!(Staking::payout_stakers(Origin::signed(1337), ledger.stash, era)); + assert_ok!(Staking::payout_stakers( + Origin::signed(1337), + ledger.stash, + era + )); } } diff --git a/frame/staking/src/tests.rs b/frame/staking/src/tests.rs index 79edc012cd3f2..86186af7d3e79 100644 --- a/frame/staking/src/tests.rs +++ b/frame/staking/src/tests.rs @@ -158,7 +158,7 @@ fn change_controller_works() { // change controller assert_ok!(Staking::set_controller(Origin::signed(11), 5)); assert_eq!(Staking::bonded(&11), Some(5)); - mock::start_era(1); + mock::start_active_era(1); // 10 is no longer in control. assert_noop!( @@ -171,12 +171,7 @@ fn change_controller_works() { #[test] fn rewards_should_work() { - // should check that: - // * rewards get recorded per session - // * rewards get paid per Era - // * `RewardRemainder::on_unbalanced` is called - // * Check that nominators are also rewarded - ExtBuilder::default().nominate(true).build_and_execute(|| { + ExtBuilder::default().nominate(true).session_per_era(3).build_and_execute(|| { let init_balance_10 = Balances::total_balance(&10); let init_balance_11 = Balances::total_balance(&11); let init_balance_20 = Balances::total_balance(&20); @@ -184,7 +179,7 @@ fn rewards_should_work() { let init_balance_100 = Balances::total_balance(&100); let init_balance_101 = Balances::total_balance(&101); - // Check state + // Set payees Payee::::insert(11, RewardDestination::Controller); Payee::::insert(21, RewardDestination::Controller); Payee::::insert(101, RewardDestination::Controller); @@ -194,9 +189,9 @@ fn rewards_should_work() { // This is the second validator of the current elected set. >::reward_by_ids(vec![(21, 50)]); - // Compute total payout now for whole duration as other parameter won't change - let total_payout_0 = current_total_payout_for_duration(3 * 1000); - assert!(total_payout_0 > 10); // Test is meaningful if reward something + // Compute total payout now for whole duration of the session. + let total_payout_0 = current_total_payout_for_duration(reward_time_per_era()); + let maximum_payout = maximum_payout_for_duration(reward_time_per_era()); start_session(1); @@ -207,10 +202,13 @@ fn rewards_should_work() { assert_eq!(Balances::total_balance(&100), init_balance_100); assert_eq!(Balances::total_balance(&101), init_balance_101); assert_eq_uvec!(Session::validators(), vec![11, 21]); - assert_eq!(Staking::eras_reward_points(Staking::active_era().unwrap().index), EraRewardPoints { - total: 50*3, - individual: vec![(11, 100), (21, 50)].into_iter().collect(), - }); + assert_eq!( + Staking::eras_reward_points(Staking::active_era().unwrap().index), + EraRewardPoints { + total: 50 * 3, + individual: vec![(11, 100), (21, 50)].into_iter().collect(), + } + ); let part_for_10 = Perbill::from_rational_approximation::(1000, 1125); let part_for_20 = Perbill::from_rational_approximation::(1000, 1375); let part_for_100_from_10 = Perbill::from_rational_approximation::(125, 1125); @@ -220,14 +218,28 @@ fn rewards_should_work() { start_session(3); assert_eq!(Staking::active_era().unwrap().index, 1); - assert_eq!(mock::REWARD_REMAINDER_UNBALANCED.with(|v| *v.borrow()), 7050); - assert_eq!(*mock::staking_events().last().unwrap(), RawEvent::EraPayout(0, 2350, 7050)); + assert_eq!( + mock::REWARD_REMAINDER_UNBALANCED.with(|v| *v.borrow()), + maximum_payout - total_payout_0, + ); + assert_eq!( + *mock::staking_events().last().unwrap(), + RawEvent::EraPayout(0, total_payout_0, maximum_payout - total_payout_0) + ); mock::make_all_reward_payment(0); - assert_eq_error_rate!(Balances::total_balance(&10), init_balance_10 + part_for_10 * total_payout_0*2/3, 2); - assert_eq_error_rate!(Balances::total_balance(&11), init_balance_11, 2); - assert_eq_error_rate!(Balances::total_balance(&20), init_balance_20 + part_for_20 * total_payout_0*1/3, 2); - assert_eq_error_rate!(Balances::total_balance(&21), init_balance_21, 2); + assert_eq_error_rate!( + Balances::total_balance(&10), + init_balance_10 + part_for_10 * total_payout_0 * 2 / 3, + 2, + ); + assert_eq_error_rate!(Balances::total_balance(&11), init_balance_11, 2,); + assert_eq_error_rate!( + Balances::total_balance(&20), + init_balance_20 + part_for_20 * total_payout_0 * 1 / 3, + 2, + ); + assert_eq_error_rate!(Balances::total_balance(&21), init_balance_21, 2,); assert_eq_error_rate!( Balances::total_balance(&100), init_balance_100 @@ -241,18 +253,31 @@ fn rewards_should_work() { >::reward_by_ids(vec![(11, 1)]); // Compute total payout now for whole duration as other parameter won't change - let total_payout_1 = current_total_payout_for_duration(3 * 1000); - assert!(total_payout_1 > 10); // Test is meaningful if reward something + let total_payout_1 = current_total_payout_for_duration(reward_time_per_era()); - mock::start_era(2); - assert_eq!(mock::REWARD_REMAINDER_UNBALANCED.with(|v| *v.borrow()), 7050*2); - assert_eq!(*mock::staking_events().last().unwrap(), RawEvent::EraPayout(1, 2350, 7050)); + mock::start_active_era(2); + assert_eq!( + mock::REWARD_REMAINDER_UNBALANCED.with(|v| *v.borrow()), + maximum_payout * 2 - total_payout_0 - total_payout_1, + ); + assert_eq!( + *mock::staking_events().last().unwrap(), + RawEvent::EraPayout(1, total_payout_1, maximum_payout - total_payout_1) + ); mock::make_all_reward_payment(1); - assert_eq_error_rate!(Balances::total_balance(&10), init_balance_10 + part_for_10 * (total_payout_0 * 2/3 + total_payout_1), 2); - assert_eq_error_rate!(Balances::total_balance(&11), init_balance_11, 2); - assert_eq_error_rate!(Balances::total_balance(&20), init_balance_20 + part_for_20 * total_payout_0 * 1/3, 2); - assert_eq_error_rate!(Balances::total_balance(&21), init_balance_21, 2); + assert_eq_error_rate!( + Balances::total_balance(&10), + init_balance_10 + part_for_10 * (total_payout_0 * 2 / 3 + total_payout_1), + 2, + ); + assert_eq_error_rate!(Balances::total_balance(&11), init_balance_11, 2,); + assert_eq_error_rate!( + Balances::total_balance(&20), + init_balance_20 + part_for_20 * total_payout_0 * 1 / 3, + 2, + ); + assert_eq_error_rate!(Balances::total_balance(&21), init_balance_21, 2,); assert_eq_error_rate!( Balances::total_balance(&100), init_balance_100 @@ -266,18 +291,11 @@ fn rewards_should_work() { #[test] fn staking_should_work() { - // should test: - // * new validators can be added to the default set - // * new ones will be chosen per era - // * either one can unlock the stash and back-down from being a validator via `chill`ing. ExtBuilder::default() .nominate(false) .fair(false) // to give 20 more staked value .build() .execute_with(|| { - // --- Block 1: - start_session(1); - // remember + compare this along with the test. assert_eq_uvec!(validator_controllers(), vec![20, 10]); @@ -359,7 +377,7 @@ fn less_than_needed_candidates_works() { assert_eq!(Staking::minimum_validator_count(), 1); assert_eq_uvec!(validator_controllers(), vec![30, 20, 10]); - mock::start_era(1); + mock::start_active_era(1); // Previous set is selected. NO election algorithm is even executed. assert_eq_uvec!(validator_controllers(), vec![30, 20, 10]); @@ -395,7 +413,7 @@ fn no_candidate_emergency_condition() { let _ = Staking::chill(Origin::signed(10)); // trigger era - mock::start_era(1); + mock::start_active_era(1); // Previous ones are elected. chill is invalidates. TODO: #2494 assert_eq_uvec!(validator_controllers(), vec![10, 20, 30, 40]); @@ -435,12 +453,11 @@ fn nominating_and_rewards_should_work() { assert_ok!(Staking::nominate(Origin::signed(4), vec![11, 21, 41])); // the total reward for era 0 - let total_payout_0 = current_total_payout_for_duration(3000); - assert!(total_payout_0 > 100); // Test is meaningful if reward something + let total_payout_0 = current_total_payout_for_duration(reward_time_per_era()); >::reward_by_ids(vec![(41, 1)]); >::reward_by_ids(vec![(31, 1)]); - mock::start_era(1); + mock::start_active_era(1); // 10 and 20 have more votes, they will be chosen. assert_eq_uvec!(validator_controllers(), vec![20, 10]); @@ -478,12 +495,11 @@ fn nominating_and_rewards_should_work() { ); // the total reward for era 1 - let total_payout_1 = current_total_payout_for_duration(3000); - assert!(total_payout_1 > 100); // Test is meaningful if reward something + let total_payout_1 = current_total_payout_for_duration(reward_time_per_era()); >::reward_by_ids(vec![(21, 2)]); >::reward_by_ids(vec![(11, 1)]); - mock::start_era(2); + mock::start_active_era(2); // nothing else will happen, era ends and rewards are paid again, // it is expected that nominators will also be paid. See below @@ -495,26 +511,26 @@ fn nominating_and_rewards_should_work() { assert_eq_error_rate!( Balances::total_balance(&2), initial_balance + (2 * payout_for_10 / 9 + 3 * payout_for_20 / 11), - 1, + 2, ); // Nominator 4: has [400/1800 ~ 2/9 from 10] + [600/2200 ~ 3/11 from 20]'s reward. ==> 2/9 + 3/11 assert_eq_error_rate!( Balances::total_balance(&4), initial_balance + (2 * payout_for_10 / 9 + 3 * payout_for_20 / 11), - 1, + 2, ); // Validator 10: got 800 / 1800 external stake => 8/18 =? 4/9 => Validator's share = 5/9 assert_eq_error_rate!( Balances::total_balance(&10), initial_balance + 5 * payout_for_10 / 9, - 1, + 2, ); // Validator 20: got 1200 / 2200 external stake => 12/22 =? 6/11 => Validator's share = 5/11 assert_eq_error_rate!( Balances::total_balance(&20), initial_balance + 5 * payout_for_20 / 11, - 1, + 2, ); }); } @@ -522,7 +538,7 @@ fn nominating_and_rewards_should_work() { #[test] fn nominators_also_get_slashed_pro_rata() { ExtBuilder::default().build_and_execute(|| { - mock::start_era(1); + mock::start_active_era(1); let slash_percent = Perbill::from_percent(5); let initial_exposure = Staking::eras_stakers(active_era(), 11); // 101 is a nominator for 11 @@ -637,40 +653,87 @@ fn double_controlling_should_fail() { } #[test] -fn session_and_eras_work() { - ExtBuilder::default().build_and_execute(|| { - assert_eq!(Staking::active_era().unwrap().index, 0); - assert_eq!(Session::current_index(), 0); +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!(System::block_number(), 1); - // Session 1: No change. + // Session 1: this is basically a noop. This has already been started. start_session(1); assert_eq!(Session::current_index(), 1); - assert_eq!(Staking::active_era().unwrap().index, 0); + 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!(Staking::active_era().unwrap().index, 0); + 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!(Staking::active_era().unwrap().index, 1); + 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!(Staking::active_era().unwrap().index, 1); + 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!(Staking::active_era().unwrap().index, 1); + 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!(Staking::active_era().unwrap().index, 2); + assert_eq!(active_era(), 2); + assert_eq!(System::block_number(), 6); + }); +} + +#[test] +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!(System::block_number(), 1); + + start_session(1); + assert_eq!(Session::current_index(), 1); + assert_eq!(active_era(), 0); + assert_eq!(System::block_number(), 5); + + start_session(2); + assert_eq!(Session::current_index(), 2); + assert_eq!(active_era(), 0); + assert_eq!(System::block_number(), 10); + + start_session(3); + assert_eq!(Session::current_index(), 3); + assert_eq!(active_era(), 1); + assert_eq!(System::block_number(), 15); + + start_session(4); + assert_eq!(Session::current_index(), 4); + assert_eq!(active_era(), 1); + assert_eq!(System::block_number(), 20); + + start_session(5); + assert_eq!(Session::current_index(), 5); + assert_eq!(active_era(), 1); + assert_eq!(System::block_number(), 25); + + start_session(6); + assert_eq!(Session::current_index(), 6); + assert_eq!(active_era(), 2); + assert_eq!(System::block_number(), 30); }); } @@ -678,53 +741,62 @@ fn session_and_eras_work() { fn forcing_new_era_works() { ExtBuilder::default().build_and_execute(|| { // normal flow of session. - assert_eq!(Staking::active_era().unwrap().index, 0); - start_session(0); - assert_eq!(Staking::active_era().unwrap().index, 0); start_session(1); - assert_eq!(Staking::active_era().unwrap().index, 0); + assert_eq!(active_era(), 0); + start_session(2); - assert_eq!(Staking::active_era().unwrap().index, 0); + assert_eq!(active_era(), 0); + start_session(3); - assert_eq!(Staking::active_era().unwrap().index, 1); + assert_eq!(active_era(), 1); // no era change. ForceEra::put(Forcing::ForceNone); + start_session(4); - assert_eq!(Staking::active_era().unwrap().index, 1); + assert_eq!(active_era(), 1); + start_session(5); - assert_eq!(Staking::active_era().unwrap().index, 1); + assert_eq!(active_era(), 1); + start_session(6); - assert_eq!(Staking::active_era().unwrap().index, 1); + assert_eq!(active_era(), 1); + start_session(7); - assert_eq!(Staking::active_era().unwrap().index, 1); + assert_eq!(active_era(), 1); // back to normal. // this immediately starts a new session. ForceEra::put(Forcing::NotForcing); + start_session(8); - assert_eq!(Staking::active_era().unwrap().index, 1); // There is one session delay - start_session(9); - assert_eq!(Staking::active_era().unwrap().index, 2); + assert_eq!(active_era(), 1); + start_session(9); + assert_eq!(active_era(), 2); // forceful change ForceEra::put(Forcing::ForceAlways); + start_session(10); - assert_eq!(Staking::active_era().unwrap().index, 2); // There is one session delay + assert_eq!(active_era(), 2); + start_session(11); - assert_eq!(Staking::active_era().unwrap().index, 3); + assert_eq!(active_era(), 3); + start_session(12); - assert_eq!(Staking::active_era().unwrap().index, 4); + assert_eq!(active_era(), 4); // just one forceful change ForceEra::put(Forcing::ForceNew); start_session(13); - assert_eq!(Staking::active_era().unwrap().index, 5); + assert_eq!(active_era(), 5); assert_eq!(ForceEra::get(), Forcing::NotForcing); + start_session(14); - assert_eq!(Staking::active_era().unwrap().index, 6); + assert_eq!(active_era(), 6); + start_session(15); - assert_eq!(Staking::active_era().unwrap().index, 6); + assert_eq!(active_era(), 6); }); } @@ -738,7 +810,7 @@ fn cannot_transfer_staked_balance() { // 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(Staking::active_era().unwrap().index, 11).total, 1000); + assert_eq!(Staking::eras_stakers(active_era(), 11).total, 1000); // Confirm account 11 cannot transfer as a result assert_noop!( Balances::transfer(Origin::signed(11), 20, 1), @@ -816,11 +888,10 @@ fn reward_destination_works() { })); // Compute total payout now for whole duration as other parameter won't change - let total_payout_0 = current_total_payout_for_duration(3000); - assert!(total_payout_0 > 100); // Test is meaningful if reward something + let total_payout_0 = current_total_payout_for_duration(reward_time_per_era()); >::reward_by_ids(vec![(11, 1)]); - mock::start_era(1); + mock::start_active_era(1); mock::make_all_reward_payment(0); // Check that RewardDestination is Staked (default) @@ -840,11 +911,10 @@ fn reward_destination_works() { >::insert(&11, RewardDestination::Stash); // Compute total payout now for whole duration as other parameter won't change - let total_payout_1 = current_total_payout_for_duration(3000); - assert!(total_payout_1 > 100); // Test is meaningful if reward something + let total_payout_1 = current_total_payout_for_duration(reward_time_per_era()); >::reward_by_ids(vec![(11, 1)]); - mock::start_era(2); + mock::start_active_era(2); mock::make_all_reward_payment(1); // Check that RewardDestination is Stash @@ -869,11 +939,10 @@ fn reward_destination_works() { assert_eq!(Balances::free_balance(10), 1); // Compute total payout now for whole duration as other parameter won't change - let total_payout_2 = current_total_payout_for_duration(3000); - assert!(total_payout_2 > 100); // Test is meaningful if reward something + let total_payout_2 = current_total_payout_for_duration(reward_time_per_era()); >::reward_by_ids(vec![(11, 1)]); - mock::start_era(3); + mock::start_active_era(3); mock::make_all_reward_payment(2); // Check that RewardDestination is Controller @@ -908,19 +977,18 @@ fn validator_payment_prefs_work() { >::insert(&11, RewardDestination::Controller); >::insert(&101, RewardDestination::Controller); - mock::start_era(1); + mock::start_active_era(1); mock::make_all_reward_payment(0); let balance_era_1_10 = Balances::total_balance(&10); let balance_era_1_100 = Balances::total_balance(&100); // Compute total payout now for whole duration as other parameter won't change - let total_payout_1 = current_total_payout_for_duration(3000); - assert!(total_payout_1 > 100); // Test is meaningful if reward something + let total_payout_1 = current_total_payout_for_duration(reward_time_per_era()); let exposure_1 = Staking::eras_stakers(Staking::active_era().unwrap().index, 11); >::reward_by_ids(vec![(11, 1)]); - mock::start_era(2); + mock::start_active_era(2); mock::make_all_reward_payment(1); let taken_cut = commission * total_payout_1; @@ -995,13 +1063,12 @@ fn bond_extra_and_withdraw_unbonded_works() { // Initial config should be correct assert_eq!(Staking::active_era().unwrap().index, 0); - assert_eq!(Session::current_index(), 0); // check the balance of a validator accounts. assert_eq!(Balances::total_balance(&10), 1); // confirm that 10 is a normal validator and gets paid at the end of the era. - mock::start_era(1); + mock::start_active_era(1); // Initial state of 10 assert_eq!(Staking::ledger(&10), Some(StakingLedger { @@ -1033,7 +1100,7 @@ fn bond_extra_and_withdraw_unbonded_works() { ); // trigger next era. - mock::start_era(2); + mock::start_active_era(2); assert_eq!(Staking::active_era().unwrap().index, 2); // ledger should be the same. @@ -1077,7 +1144,7 @@ fn bond_extra_and_withdraw_unbonded_works() { ); // trigger next era. - mock::start_era(3); + mock::start_active_era(3); // nothing yet assert_ok!(Staking::withdraw_unbonded(Origin::signed(10), 0)); @@ -1093,7 +1160,7 @@ fn bond_extra_and_withdraw_unbonded_works() { ); // trigger next era. - mock::start_era(5); + mock::start_active_era(5); assert_ok!(Staking::withdraw_unbonded(Origin::signed(10), 0)); // Now the value is free and the staking ledger is updated. @@ -1118,14 +1185,14 @@ fn too_many_unbond_calls_should_not_work() { assert_ok!(Staking::unbond(Origin::signed(10), 1)); } - mock::start_era(1); + mock::start_active_era(1); // locked at era 1 until 4 assert_ok!(Staking::unbond(Origin::signed(10), 1)); // can't do more. assert_noop!(Staking::unbond(Origin::signed(10), 1), Error::::NoMoreChunks); - mock::start_era(3); + mock::start_active_era(3); assert_noop!(Staking::unbond(Origin::signed(10), 1), Error::::NoMoreChunks); // free up. @@ -1157,7 +1224,7 @@ fn rebond_works() { let _ = Balances::make_free_balance_be(&11, 1000000); // confirm that 10 is a normal validator and gets paid at the end of the era. - mock::start_era(1); + mock::start_active_era(1); // Initial state of 10 assert_eq!( @@ -1171,7 +1238,7 @@ fn rebond_works() { }) ); - mock::start_era(2); + mock::start_active_era(2); assert_eq!(Staking::active_era().unwrap().index, 2); // Try to rebond some funds. We get an error since no fund is unbonded. @@ -1302,7 +1369,7 @@ fn rebond_is_fifo() { let _ = Balances::make_free_balance_be(&11, 1000000); // confirm that 10 is a normal validator and gets paid at the end of the era. - mock::start_era(1); + mock::start_active_era(1); // Initial state of 10 assert_eq!( @@ -1316,7 +1383,7 @@ fn rebond_is_fifo() { }) ); - mock::start_era(2); + mock::start_active_era(2); // Unbond some of the funds in stash. Staking::unbond(Origin::signed(10), 400).unwrap(); @@ -1333,7 +1400,7 @@ fn rebond_is_fifo() { }) ); - mock::start_era(3); + mock::start_active_era(3); // Unbond more of the funds in stash. Staking::unbond(Origin::signed(10), 300).unwrap(); @@ -1351,7 +1418,7 @@ fn rebond_is_fifo() { }) ); - mock::start_era(4); + mock::start_active_era(4); // Unbond yet more of the funds in stash. Staking::unbond(Origin::signed(10), 200).unwrap(); @@ -1411,13 +1478,12 @@ fn reward_to_stake_works() { >::insert(&20, StakingLedger { stash: 21, total: 69, active: 69, unlocking: vec![], claimed_rewards: vec![] }); // Compute total payout now for whole duration as other parameter won't change - let total_payout_0 = current_total_payout_for_duration(3000); - assert!(total_payout_0 > 100); // Test is meaningful if reward something + let total_payout_0 = current_total_payout_for_duration(reward_time_per_era()); >::reward_by_ids(vec![(11, 1)]); >::reward_by_ids(vec![(21, 1)]); // New era --> rewards are paid --> stakes are changed - mock::start_era(1); + mock::start_active_era(1); mock::make_all_reward_payment(0); assert_eq!(Staking::eras_stakers(Staking::active_era().unwrap().index, 11).total, 1000); @@ -1427,7 +1493,7 @@ fn reward_to_stake_works() { assert_eq!(_11_balance, 1000 + total_payout_0 / 2); // Trigger another new era as the info are frozen before the era start. - mock::start_era(2); + mock::start_active_era(2); // -- new infos assert_eq!(Staking::eras_stakers(Staking::active_era().unwrap().index, 11).total, 1000 + total_payout_0 / 2); @@ -1568,7 +1634,7 @@ fn switching_roles() { assert_ok!(Staking::bond(Origin::signed(5), 6, 1000, RewardDestination::Controller)); assert_ok!(Staking::validate(Origin::signed(6), ValidatorPrefs::default())); - mock::start_era(1); + mock::start_active_era(1); // with current nominators 10 and 5 have the most stake assert_eq_uvec!(validator_controllers(), vec![6, 10]); @@ -1582,7 +1648,7 @@ fn switching_roles() { // 2 : 2000 self vote + 250 vote. // Winners: 20 and 2 - mock::start_era(2); + mock::start_active_era(2); assert_eq_uvec!(validator_controllers(), vec![2, 20]); }); @@ -1604,7 +1670,7 @@ fn wrong_vote_is_null() { ])); // new block - mock::start_era(1); + mock::start_active_era(1); assert_eq_uvec!(validator_controllers(), vec![20, 10]); }); @@ -1643,15 +1709,15 @@ fn bond_with_no_staked_value() { }) ); - mock::start_era(1); - mock::start_era(2); + mock::start_active_era(1); + mock::start_active_era(2); // not yet removed. assert_ok!(Staking::withdraw_unbonded(Origin::signed(2), 0)); assert!(Staking::ledger(2).is_some()); assert_eq!(Balances::locks(&1)[0].amount, 5); - mock::start_era(3); + mock::start_active_era(3); // poof. Account 1 is removed from the staking system. assert_ok!(Staking::withdraw_unbonded(Origin::signed(2), 0)); @@ -1662,8 +1728,6 @@ fn bond_with_no_staked_value() { #[test] fn bond_with_little_staked_value_bounded() { - // Behavior when someone bonds with little staked value. - // Particularly when she votes and the candidate is elected. ExtBuilder::default() .validator_count(3) .nominate(false) @@ -1680,37 +1744,38 @@ fn bond_with_little_staked_value_bounded() { assert_ok!(Staking::bond(Origin::signed(1), 2, 1, RewardDestination::Controller)); assert_ok!(Staking::validate(Origin::signed(2), ValidatorPrefs::default())); - // reward era 0 - let total_payout_0 = current_total_payout_for_duration(3000); - assert!(total_payout_0 > 100); // Test is meaningful if reward something + // 1 era worth of reward. BUT, we set the timestamp after on_initialize, so outdated by + // one block. + let total_payout_0 = current_total_payout_for_duration(reward_time_per_era()); + reward_all_elected(); - mock::start_era(1); + mock::start_active_era(1); mock::make_all_reward_payment(0); // 2 is elected. assert_eq_uvec!(validator_controllers(), vec![20, 10, 2]); - // And has minimal stake - assert_eq!(Staking::eras_stakers(Staking::active_era().unwrap().index, 2).total, 0); + assert_eq!(Staking::eras_stakers(active_era(), 2).total, 0); // Old ones are rewarded. - assert_eq!(Balances::free_balance(10), init_balance_10 + total_payout_0 / 3); + assert_eq_error_rate!(Balances::free_balance(10), init_balance_10 + total_payout_0 / 3, 1); // no rewards paid to 2. This was initial election. assert_eq!(Balances::free_balance(2), init_balance_2); - // reward era 1 - let total_payout_1 = current_total_payout_for_duration(3000); - assert!(total_payout_1 > 100); // Test is meaningful if reward something + // reward era 2 + let total_payout_1 = current_total_payout_for_duration(reward_time_per_era()); reward_all_elected(); - mock::start_era(2); + mock::start_active_era(2); mock::make_all_reward_payment(1); assert_eq_uvec!(validator_controllers(), vec![20, 10, 2]); - assert_eq!(Staking::eras_stakers(Staking::active_era().unwrap().index, 2).total, 0); + assert_eq!(Staking::eras_stakers(active_era(), 2).total, 0); - assert_eq!(Balances::free_balance(2), init_balance_2 + total_payout_1 / 3); - assert_eq!( + // 2 is now rewarded. + assert_eq_error_rate!(Balances::free_balance(2), init_balance_2 + total_payout_1 / 3, 1); + assert_eq_error_rate!( Balances::free_balance(&10), init_balance_10 + total_payout_0 / 3 + total_payout_1 / 3, + 2, ); }); } @@ -1842,7 +1907,7 @@ fn phragmen_should_not_overflow() { bond_nominator(7, 6, Votes::max_value() as Balance, vec![3, 5]); bond_nominator(9, 8, Votes::max_value() as Balance, vec![3, 5]); - mock::start_era(1); + mock::start_active_era(1); assert_eq_uvec!(validator_controllers(), vec![4, 2]); @@ -1983,10 +2048,10 @@ fn era_is_always_same_length() { ExtBuilder::default().build_and_execute(|| { let session_per_era = >::get(); - mock::start_era(1); + mock::start_active_era(1); assert_eq!(Staking::eras_start_session_index(current_era()).unwrap(), session_per_era); - mock::start_era(2); + mock::start_active_era(2); assert_eq!(Staking::eras_start_session_index(current_era()).unwrap(), session_per_era * 2u32); let session = Session::current_index(); @@ -1996,7 +2061,7 @@ fn era_is_always_same_length() { assert_eq!(current_era(), 3); assert_eq!(Staking::eras_start_session_index(current_era()).unwrap(), session + 2); - mock::start_era(4); + mock::start_active_era(4); assert_eq!(Staking::eras_start_session_index(current_era()).unwrap(), session + 2u32 + session_per_era); }); } @@ -2060,7 +2125,7 @@ fn offence_deselects_validator_even_when_slash_is_zero() { assert_eq!(Staking::force_era(), Forcing::ForceNew); assert!(!>::contains_key(11)); - mock::start_era(1); + mock::start_active_era(1); assert!(!Session::validators().contains(&11)); assert!(!>::contains_key(11)); @@ -2098,7 +2163,7 @@ fn slashing_performed_according_exposure() { #[test] fn slash_in_old_span_does_not_deselect() { ExtBuilder::default().build_and_execute(|| { - mock::start_era(1); + mock::start_active_era(1); assert!(>::contains_key(11)); assert!(Session::validators().contains(&11)); @@ -2117,14 +2182,14 @@ fn slash_in_old_span_does_not_deselect() { assert_eq!(Staking::force_era(), Forcing::ForceNew); assert!(!>::contains_key(11)); - mock::start_era(2); + mock::start_active_era(2); Staking::validate(Origin::signed(10), Default::default()).unwrap(); assert_eq!(Staking::force_era(), Forcing::NotForcing); assert!(>::contains_key(11)); assert!(!Session::validators().contains(&11)); - mock::start_era(3); + mock::start_active_era(3); // this staker is in a new slashing span now, having re-registered after // their prior slash. @@ -2409,7 +2474,7 @@ fn garbage_collection_on_window_pruning() { // ensures that `ValidatorSlashInEra` and `NominatorSlashInEra` are cleared after // `BondingDuration`. ExtBuilder::default().build_and_execute(|| { - mock::start_era(1); + mock::start_active_era(1); assert_eq!(Balances::free_balance(11), 1000); let now = Staking::active_era().unwrap().index; @@ -2439,7 +2504,7 @@ fn garbage_collection_on_window_pruning() { assert!(::ValidatorSlashInEra::get(&now, &11).is_some()); assert!(::NominatorSlashInEra::get(&now, &101).is_some()); - mock::start_era(era); + mock::start_active_era(era); } assert!(::ValidatorSlashInEra::get(&now, &11).is_none()); @@ -2450,9 +2515,9 @@ fn garbage_collection_on_window_pruning() { #[test] fn slashing_nominators_by_span_max() { ExtBuilder::default().build_and_execute(|| { - mock::start_era(1); - mock::start_era(2); - mock::start_era(3); + mock::start_active_era(1); + mock::start_active_era(2); + mock::start_active_era(3); assert_eq!(Balances::free_balance(11), 1000); assert_eq!(Balances::free_balance(21), 2000); @@ -2548,9 +2613,9 @@ fn slashing_nominators_by_span_max() { #[test] fn slashes_are_summed_across_spans() { ExtBuilder::default().build_and_execute(|| { - mock::start_era(1); - mock::start_era(2); - mock::start_era(3); + mock::start_active_era(1); + mock::start_active_era(2); + mock::start_active_era(3); assert_eq!(Balances::free_balance(21), 2000); assert_eq!(Staking::slashable_balance_of(&21), 1000); @@ -2578,7 +2643,7 @@ fn slashes_are_summed_across_spans() { // 21 has been force-chilled. re-signal intent to validate. Staking::validate(Origin::signed(20), Default::default()).unwrap(); - mock::start_era(4); + mock::start_active_era(4); assert_eq!(Staking::slashable_balance_of(&21), 900); @@ -2605,16 +2670,18 @@ fn slashes_are_summed_across_spans() { #[test] fn deferred_slashes_are_deferred() { - ExtBuilder::default().slash_defer_duration(2).build_and_execute(|| { - mock::start_era(1); + ExtBuilder::default() + .slash_defer_duration(2) + .build_and_execute(|| { + mock::start_active_era(1); - assert_eq!(Balances::free_balance(11), 1000); + assert_eq!(Balances::free_balance(11), 1000); - let exposure = Staking::eras_stakers(Staking::active_era().unwrap().index, 11); - assert_eq!(Balances::free_balance(101), 2000); - let nominated_value = exposure.others.iter().find(|o| o.who == 101).unwrap().value; + let exposure = Staking::eras_stakers(Staking::active_era().unwrap().index, 11); + assert_eq!(Balances::free_balance(101), 2000); + let nominated_value = exposure.others.iter().find(|o| o.who == 101).unwrap().value; - on_offence_now( + on_offence_now( &[ OffenceDetails { offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), @@ -2624,40 +2691,42 @@ fn deferred_slashes_are_deferred() { &[Perbill::from_percent(10)], ); - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(101), 2000); + assert_eq!(Balances::free_balance(11), 1000); + assert_eq!(Balances::free_balance(101), 2000); - mock::start_era(2); + mock::start_active_era(2); - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(101), 2000); + assert_eq!(Balances::free_balance(11), 1000); + assert_eq!(Balances::free_balance(101), 2000); - mock::start_era(3); + mock::start_active_era(3); - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(101), 2000); + assert_eq!(Balances::free_balance(11), 1000); + assert_eq!(Balances::free_balance(101), 2000); - // at the start of era 4, slashes from era 1 are processed, - // after being deferred for at least 2 full eras. - mock::start_era(4); + // at the start of era 4, slashes from era 1 are processed, + // after being deferred for at least 2 full eras. + mock::start_active_era(4); - assert_eq!(Balances::free_balance(11), 900); - assert_eq!(Balances::free_balance(101), 2000 - (nominated_value / 10)); - }) + assert_eq!(Balances::free_balance(11), 900); + assert_eq!(Balances::free_balance(101), 2000 - (nominated_value / 10)); + }) } #[test] fn remove_deferred() { - ExtBuilder::default().slash_defer_duration(2).build_and_execute(|| { - mock::start_era(1); + ExtBuilder::default() + .slash_defer_duration(2) + .build_and_execute(|| { + mock::start_active_era(1); - assert_eq!(Balances::free_balance(11), 1000); + assert_eq!(Balances::free_balance(11), 1000); - let exposure = Staking::eras_stakers(Staking::active_era().unwrap().index, 11); - assert_eq!(Balances::free_balance(101), 2000); - let nominated_value = exposure.others.iter().find(|o| o.who == 101).unwrap().value; + let exposure = Staking::eras_stakers(Staking::active_era().unwrap().index, 11); + assert_eq!(Balances::free_balance(101), 2000); + let nominated_value = exposure.others.iter().find(|o| o.who == 101).unwrap().value; - on_offence_now( + on_offence_now( &[ OffenceDetails { offender: (11, exposure.clone()), @@ -2667,12 +2736,12 @@ fn remove_deferred() { &[Perbill::from_percent(10)], ); - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(101), 2000); + assert_eq!(Balances::free_balance(11), 1000); + assert_eq!(Balances::free_balance(101), 2000); - mock::start_era(2); + mock::start_active_era(2); - on_offence_in_era( + on_offence_in_era( &[ OffenceDetails { offender: (11, exposure.clone()), @@ -2689,32 +2758,32 @@ fn remove_deferred() { Error::::EmptyTargets ); - assert_ok!(Staking::cancel_deferred_slash(Origin::root(), 1, vec![0])); + assert_ok!(Staking::cancel_deferred_slash(Origin::root(), 1, vec![0])); - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(101), 2000); + assert_eq!(Balances::free_balance(11), 1000); + assert_eq!(Balances::free_balance(101), 2000); - mock::start_era(3); + mock::start_active_era(3); - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(101), 2000); + assert_eq!(Balances::free_balance(11), 1000); + assert_eq!(Balances::free_balance(101), 2000); - // at the start of era 4, slashes from era 1 are processed, - // after being deferred for at least 2 full eras. - mock::start_era(4); + // at the start of era 4, slashes from era 1 are processed, + // after being deferred for at least 2 full eras. + mock::start_active_era(4); - // the first slash for 10% was cancelled, so no effect. - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(101), 2000); + // the first slash for 10% was cancelled, so no effect. + assert_eq!(Balances::free_balance(11), 1000); + assert_eq!(Balances::free_balance(101), 2000); - mock::start_era(5); + mock::start_active_era(5); - let slash_10 = Perbill::from_percent(10); - let slash_15 = Perbill::from_percent(15); - let initial_slash = slash_10 * nominated_value; + let slash_10 = Perbill::from_percent(10); + let slash_15 = Perbill::from_percent(15); + let initial_slash = slash_10 * nominated_value; - let total_slash = slash_15 * nominated_value; - let actual_slash = total_slash - initial_slash; + let total_slash = slash_15 * nominated_value; + let actual_slash = total_slash - initial_slash; // 5% slash (15 - 10) processed now. assert_eq!(Balances::free_balance(11), 950); @@ -2724,15 +2793,17 @@ fn remove_deferred() { #[test] fn remove_multi_deferred() { - ExtBuilder::default().slash_defer_duration(2).build_and_execute(|| { - mock::start_era(1); + ExtBuilder::default() + .slash_defer_duration(2) + .build_and_execute(|| { + mock::start_active_era(1); - assert_eq!(Balances::free_balance(11), 1000); + assert_eq!(Balances::free_balance(11), 1000); - let exposure = Staking::eras_stakers(Staking::active_era().unwrap().index, 11); - assert_eq!(Balances::free_balance(101), 2000); + let exposure = Staking::eras_stakers(Staking::active_era().unwrap().index, 11); + assert_eq!(Balances::free_balance(101), 2000); - on_offence_now( + on_offence_now( &[ OffenceDetails { offender: (11, exposure.clone()), @@ -2899,7 +2970,7 @@ mod offchain_election { .session_per_era(3) .build() .execute_with(|| { - mock::start_era(1); + mock::start_active_era(1); assert_eq!(Session::current_index(), 3); assert_eq!(Staking::current_era(), Some(1)); assert_eq!(Staking::is_current_session_final(), false); @@ -2921,7 +2992,7 @@ mod offchain_election { fn offchain_window_is_triggered() { ExtBuilder::default() .session_per_era(5) - .session_length(10) + .period(10) .election_lookahead(3) .build() .execute_with(|| { @@ -2981,7 +3052,7 @@ mod offchain_election { fn offchain_window_is_triggered_when_forcing() { ExtBuilder::default() .session_per_era(5) - .session_length(10) + .period(10) .election_lookahead(3) .build() .execute_with(|| { @@ -3002,11 +3073,10 @@ mod offchain_election { fn offchain_window_is_triggered_when_force_always() { ExtBuilder::default() .session_per_era(5) - .session_length(10) + .period(10) .election_lookahead(3) .build() .execute_with(|| { - ForceEra::put(Forcing::ForceAlways); run_to_block(16); assert_eq!(Staking::era_election_status(), ElectionStatus::Closed); @@ -3029,7 +3099,7 @@ mod offchain_election { fn offchain_window_closes_when_forcenone() { ExtBuilder::default() .session_per_era(5) - .session_length(10) + .period(10) .election_lookahead(3) .build() .execute_with(|| { @@ -4101,7 +4171,7 @@ mod offchain_election { #[test] fn slash_kicks_validators_not_nominators_and_disables_nominator_for_kicked_validator() { ExtBuilder::default().build_and_execute(|| { - mock::start_era(1); + mock::start_active_era(1); assert_eq_uvec!(Session::validators(), vec![11, 21]); // pre-slash balance @@ -4149,7 +4219,7 @@ fn slash_kicks_validators_not_nominators_and_disables_nominator_for_kicked_valid // actually re-bond the slashed validator assert_ok!(Staking::validate(Origin::signed(10), Default::default())); - mock::start_era(2); + mock::start_active_era(2); let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11); let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21); @@ -4180,31 +4250,28 @@ fn claim_reward_at_the_last_era_and_no_double_claim_and_invalid_claim() { >::reward_by_ids(vec![(11, 1)]); // Compute total payout now for whole duration as other parameter won't change - let total_payout_0 = current_total_payout_for_duration(3000); - assert!(total_payout_0 > 10); // Test is meaningful if reward something + let total_payout_0 = current_total_payout_for_duration(reward_time_per_era()); - mock::start_era(1); + mock::start_active_era(1); >::reward_by_ids(vec![(11, 1)]); // Change total issuance in order to modify total payout let _ = Balances::deposit_creating(&999, 1_000_000_000); // Compute total payout now for whole duration as other parameter won't change - let total_payout_1 = current_total_payout_for_duration(3000); - assert!(total_payout_1 > 10); // Test is meaningful if reward something + let total_payout_1 = current_total_payout_for_duration(reward_time_per_era()); assert!(total_payout_1 != total_payout_0); - mock::start_era(2); + mock::start_active_era(2); >::reward_by_ids(vec![(11, 1)]); // Change total issuance in order to modify total payout let _ = Balances::deposit_creating(&999, 1_000_000_000); // Compute total payout now for whole duration as other parameter won't change - let total_payout_2 = current_total_payout_for_duration(3000); - assert!(total_payout_2 > 10); // Test is meaningful if reward something + let total_payout_2 = current_total_payout_for_duration(reward_time_per_era()); assert!(total_payout_2 != total_payout_0); assert!(total_payout_2 != total_payout_1); - mock::start_era(Staking::history_depth() + 1); + mock::start_active_era(Staking::history_depth() + 1); let active_era = Staking::active_era().unwrap().index; @@ -4248,7 +4315,7 @@ fn claim_reward_at_the_last_era_and_no_double_claim_and_invalid_claim() { #[test] fn zero_slash_keeps_nominators() { ExtBuilder::default().build_and_execute(|| { - mock::start_era(1); + mock::start_active_era(1); assert_eq!(Balances::free_balance(11), 1000); @@ -4285,12 +4352,13 @@ fn zero_slash_keeps_nominators() { #[test] fn six_session_delay() { - ExtBuilder::default().build_and_execute(|| { + 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 init_active_era = Staking::active_era().unwrap().index; + // pallet-session is delaying session by one, thus the next session to plan is +2. assert_eq!(>::new_session(init_session + 2), None); assert_eq!(>::new_session(init_session + 3), Some(val_set.clone())); @@ -4300,10 +4368,11 @@ fn six_session_delay() { >::end_session(init_session); >::start_session(init_session + 1); - assert_eq!(Staking::active_era().unwrap().index, init_active_era); + assert_eq!(active_era(), init_active_era); + >::end_session(init_session + 1); >::start_session(init_session + 2); - assert_eq!(Staking::active_era().unwrap().index, init_active_era); + assert_eq!(active_era(), init_active_era); // Reward current era Staking::reward_by_ids(vec![(11, 1)]); @@ -4311,13 +4380,15 @@ fn six_session_delay() { // New active era is triggered here. >::end_session(init_session + 2); >::start_session(init_session + 3); - assert_eq!(Staking::active_era().unwrap().index, init_active_era + 1); + assert_eq!(active_era(), init_active_era + 1); + >::end_session(init_session + 3); >::start_session(init_session + 4); - assert_eq!(Staking::active_era().unwrap().index, init_active_era + 1); + assert_eq!(active_era(), init_active_era + 1); + >::end_session(init_session + 4); >::start_session(init_session + 5); - assert_eq!(Staking::active_era().unwrap().index, init_active_era + 1); + assert_eq!(active_era(), init_active_era + 1); // Reward current era Staking::reward_by_ids(vec![(21, 2)]); @@ -4325,7 +4396,7 @@ fn six_session_delay() { // New active era is triggered here. >::end_session(init_session + 5); >::start_session(init_session + 6); - assert_eq!(Staking::active_era().unwrap().index, init_active_era + 2); + assert_eq!(active_era(), init_active_era + 2); // That reward are correct assert_eq!(Staking::eras_reward_points(init_active_era).total, 1); @@ -4335,10 +4406,6 @@ fn six_session_delay() { #[test] fn test_max_nominator_rewarded_per_validator_and_cant_steal_someone_else_reward() { - // Test: - // * If nominator nomination is below the $MaxNominatorRewardedPerValidator other nominator - // then the nominator can't claim its reward - // * A nominator can't claim another nominator reward ExtBuilder::default().build_and_execute(|| { for i in 0..=::MaxNominatorRewardedPerValidator::get() { let stash = 10_000 + i as AccountId; @@ -4355,14 +4422,13 @@ fn test_max_nominator_rewarded_per_validator_and_cant_steal_someone_else_reward( ); assert_ok!(Staking::nominate(Origin::signed(controller), vec![11])); } - mock::start_era(1); + mock::start_active_era(1); >::reward_by_ids(vec![(11, 1)]); - // Compute total payout now for whole duration as other parameter won't change - let total_payout_0 = current_total_payout_for_duration(3 * 1000); - assert!(total_payout_0 > 100); // Test is meaningful if reward something + // compute and ensure the reward amount is greater than zero. + let _ = current_total_payout_for_duration(reward_time_per_era()); - mock::start_era(2); + mock::start_active_era(2); mock::make_all_reward_payment(1); // Assert only nominators from 1 to Max are rewarded @@ -4381,7 +4447,7 @@ fn test_max_nominator_rewarded_per_validator_and_cant_steal_someone_else_reward( #[test] fn set_history_depth_works() { ExtBuilder::default().build_and_execute(|| { - mock::start_era(10); + mock::start_active_era(10); Staking::set_history_depth(Origin::root(), 20, 0).unwrap(); assert!(::ErasTotalStake::contains_key(10 - 4)); assert!(::ErasTotalStake::contains_key(10 - 5)); @@ -4411,12 +4477,13 @@ fn test_payout_stakers() { bond_nominator(1000 + i, 100 + i, balance + i as Balance, vec![11]); } - mock::start_era(1); + mock::start_active_era(1); Staking::reward_by_ids(vec![(11, 1)]); - // Compute total payout now for whole duration as other parameter won't change - let total_payout_0 = current_total_payout_for_duration(3 * 1000); - assert!(total_payout_0 > 100); // Test is meaningful if reward something - mock::start_era(2); + + // compute and ensure the reward amount is greater than zero. + let _ = current_total_payout_for_duration(reward_time_per_era()); + + mock::start_active_era(2); assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 1)); // Top 64 nominators of validator 11 automatically paid out, including the validator @@ -4438,10 +4505,11 @@ fn test_payout_stakers() { for i in 3..16 { Staking::reward_by_ids(vec![(11, 1)]); - // Compute total payout now for whole duration as other parameter won't change - let total_payout_0 = current_total_payout_for_duration(3 * 1000); - assert!(total_payout_0 > 100); // Test is meaningful if reward something - mock::start_era(i); + + // compute and ensure the reward amount is greater than zero. + let _ = current_total_payout_for_duration(reward_time_per_era()); + + mock::start_active_era(i); assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, i - 1)); } @@ -4453,10 +4521,9 @@ fn test_payout_stakers() { for i in 16..100 { Staking::reward_by_ids(vec![(11, 1)]); - // Compute total payout now for whole duration as other parameter won't change - let total_payout_0 = current_total_payout_for_duration(3 * 1000); - assert!(total_payout_0 > 100); // Test is meaningful if reward something - mock::start_era(i); + // compute and ensure the reward amount is greater than zero. + let _ = current_total_payout_for_duration(reward_time_per_era()); + mock::start_active_era(i); } // We clean it up as history passes @@ -4491,12 +4558,13 @@ fn payout_stakers_handles_basic_errors() { bond_nominator(1000 + i, 100 + i, balance + i as Balance, vec![11]); } - mock::start_era(1); + mock::start_active_era(1); Staking::reward_by_ids(vec![(11, 1)]); - // Compute total payout now for whole duration as other parameter won't change - let total_payout_0 = current_total_payout_for_duration(3 * 1000); - assert!(total_payout_0 > 100); // Test is meaningful if reward something - mock::start_era(2); + + // compute and ensure the reward amount is greater than zero. + let _ = current_total_payout_for_duration(reward_time_per_era()); + + mock::start_active_era(2); // Wrong Era, too big assert_noop!(Staking::payout_stakers(Origin::signed(1337), 11, 2), Error::::InvalidEraToReward); @@ -4505,10 +4573,9 @@ fn payout_stakers_handles_basic_errors() { for i in 3..100 { Staking::reward_by_ids(vec![(11, 1)]); - // Compute total payout now for whole duration as other parameter won't change - let total_payout_0 = current_total_payout_for_duration(3 * 1000); - assert!(total_payout_0 > 100); // Test is meaningful if reward something - mock::start_era(i); + // compute and ensure the reward amount is greater than zero. + let _ = current_total_payout_for_duration(reward_time_per_era()); + mock::start_active_era(i); } // We are at era 99, with history depth of 84 // We should be able to payout era 15 through 98 (84 total eras), but not 14 or 99. @@ -4538,7 +4605,7 @@ fn bond_during_era_correctly_populates_claimed_rewards() { claimed_rewards: vec![], }) ); - mock::start_era(5); + mock::start_active_era(5); bond_validator(11, 10, 1000); assert_eq!( Staking::ledger(&10), @@ -4550,7 +4617,7 @@ fn bond_during_era_correctly_populates_claimed_rewards() { claimed_rewards: (0..5).collect(), }) ); - mock::start_era(99); + mock::start_active_era(99); bond_validator(13, 12, 1000); assert_eq!( Staking::ledger(&12), @@ -4655,12 +4722,11 @@ fn payout_creates_controller() { assert_ok!(Balances::transfer(Origin::signed(1337), 1234, 100)); assert_eq!(Balances::free_balance(1337), 0); - mock::start_era(1); + mock::start_active_era(1); Staking::reward_by_ids(vec![(11, 1)]); - // Compute total payout now for whole duration as other parameter won't change - let total_payout_0 = current_total_payout_for_duration(3 * 1000); - assert!(total_payout_0 > 100); // Test is meaningful if reward something - mock::start_era(2); + // compute and ensure the reward amount is greater than zero. + let _ = current_total_payout_for_duration(reward_time_per_era()); + mock::start_active_era(2); assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 1)); // Controller is created @@ -4684,12 +4750,11 @@ fn payout_to_any_account_works() { // Reward Destination account doesn't exist assert_eq!(Balances::free_balance(42), 0); - mock::start_era(1); + mock::start_active_era(1); Staking::reward_by_ids(vec![(11, 1)]); - // Compute total payout now for whole duration as other parameter won't change - let total_payout_0 = current_total_payout_for_duration(3 * 1000); - assert!(total_payout_0 > 100); // Test is meaningful if reward something - mock::start_era(2); + // compute and ensure the reward amount is greater than zero. + let _ = current_total_payout_for_duration(reward_time_per_era()); + mock::start_active_era(2); assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 1)); // Payment is successful @@ -4698,7 +4763,111 @@ fn payout_to_any_account_works() { } #[test] -fn cannot_bond_extra_to_lower_than_ed() { +fn session_buffering_with_offset() { + // similar to live-chains, have some offset for the first session + ExtBuilder::default() + .offset(2) + .period(5) + .session_per_era(5) + .build_and_execute(|| { + assert_eq!(current_era(), 0); + assert_eq!(active_era(), 0); + assert_eq!(Session::current_index(), 0); + + start_session(1); + assert_eq!(current_era(), 0); + assert_eq!(active_era(), 0); + assert_eq!(Session::current_index(), 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!(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!(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!(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!(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); + + }); +} + +#[test] +fn session_buffering_no_offset() { + // no offset, first session starts immediately + ExtBuilder::default() + .offset(0) + .period(5) + .session_per_era(5) + .build_and_execute(|| { + assert_eq!(current_era(), 0); + assert_eq!(active_era(), 0); + assert_eq!(Session::current_index(), 0); + + start_session(1); + assert_eq!(current_era(), 0); + assert_eq!(active_era(), 0); + assert_eq!(Session::current_index(), 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!(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!(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!(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!(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); + + }); +} + +#[test] +fn cannot_rebond_to_lower_than_ed() { ExtBuilder::default() .existential_deposit(10) .build_and_execute(|| { @@ -4732,14 +4901,14 @@ fn cannot_bond_extra_to_lower_than_ed() { // now bond a wee bit more assert_noop!( - Staking::bond_extra(Origin::signed(21), 5), + Staking::rebond(Origin::signed(20), 5), Error::::InsufficientValue, ); }) } #[test] -fn cannot_rebond_to_lower_than_ed() { +fn cannot_bond_extra_to_lower_than_ed() { ExtBuilder::default() .existential_deposit(10) .build_and_execute(|| { @@ -4766,14 +4935,17 @@ fn cannot_rebond_to_lower_than_ed() { stash: 21, total: 1000, active: 0, - unlocking: vec![UnlockChunk { value: 1000, era: 3 }], + unlocking: vec![UnlockChunk { + value: 1000, + era: 3 + }], claimed_rewards: vec![] } ); // now bond a wee bit more assert_noop!( - Staking::rebond(Origin::signed(20), 5), + Staking::bond_extra(Origin::signed(21), 5), Error::::InsufficientValue, ); })