Files
pezkuwi-subxt/substrate/frame/staking/src/mock.rs
T
Zeke Mostov 247f33dc0b Nomination Pools (#10694)
* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>

* Add admin roles and make some calls permissionless

* Destroy pool in withdraw unbonded

* Add docs on pool admin

* Fixup tests

* Test unbond_other permissionless scenarios

* Test withdraw unbonded permissionless

* Test only can join open pools

* Move unsafe set state to mock

* Test: nominate_works

* Add bounds: MinJoinBond, MinCreateBond, MaxPools

* Test MinCreateBond, MinJoinBond, MaxPools

* Add post checks to tests

* Remove some TODOs

* Setup weight infrastructure

* Benchmark claim_payout

* Benchmark create

* Benchmark nominate

* Benchmark join

* Benchmark unbond_other

* Refactor join benchmark to use scenario setup

* Clean up and address warnings

* Basic withdraw unbonded benchmarks

* Refactor nominate benchmark

* Refactor claim payout

* Add feature sp-staking/runtime-benchmarks

* Get node runtime to compile

* Get node to run

* Make claim_payout bench work with node

* Make pool_withdraw_unbonded bench work with node

* Make withdraw_unbonded_other work with node runtime'

* Make create benchmark work with node

* Make nominate benchmark work with node runtime

* WiP new benchmark crate

* Implement initial mock for benchmarks

* Establish benchmark setup logic

* Get claim payout and nominate benchmarks working

* Remove pool bench utils; make struct fields pub insteaad

* Get more benchmarks to work; trim interface trait

* Some more top level docs

* Finish tranistion benchmarks to crate

* Hook up benchmark pallet to node runtime

* Get benches to work with node runtime

* cargo run --quiet --profile=production  --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_nomination_pools --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/nomination-pools/src/weights.rs --template=./.maintain/frame-weight-template.hbs

* Benchmark withdraw_unbonded_other_kill

* Delete old benchmarking files

* Refunds for withdraw_unbonded

* Remove some TODOs

* 'Don't return an option for the current_era'

* Streamline extrinsic docs

* small docs tweaks

* Refactor ledger::slash

* Add on_slash impl for nomination pools

* slash refactor wip

* WIP slash working

* DRY Ledger::stash

* Fix slash saturation

* Remove unused param from slash

* Docs and warnings

* Test ledger::slash

* save progress

* Introduce counter for delegators

* Add tests for max delegator errors

* Reproducible account ids

* Adapt tests to new account id format

* Simplify create_accounts api

* Fix staking tests

* Save PerBill slash impl before removing

* Rever ledger slash test

* Get node runtime to work

* Organize sub pools by unbond era, not curren era

* staking: Proportional ledger slashing

* Some comment cleanup

* Add more test post checks

* Update frame/staking/src/pallet/mod.rs

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>

* Tests: account for storing unbond era

* Improve docs for staking interface

* Add events Created, Destroyed

* withdraw_unbonded: Remove useless withdraw dust check

* Test: withdraw_unbonded_other_handles_faulty_sub_pool_accounting

* Add extrinsics: set_state_other, set_metadata

* Test: set_state_other_works

* Test: set_metadata_works

* Add benchmarks for set_state_other, set_metadata

* Fix benchmarks

* Add weight info for new extrinsics

* Some feedback

* duo feedback

* Incorporate some more feedback

* integrate more kian feedback

* integrate more kian feedback

* More improvements

* Add destroying_mul

* Make do_reward_payout take refs

* Remove some TODOs

* Add test for saturating

* feedback

* Fix join test

* use `inner` for nested types in nomination pools (#11030)

* Use nested inner type for pool

* make tests and benchmarks work

* remove feat

* all tests work now

* fix node-runtime

* nomination-pools: update benches for new account format (#11033)

* Update benches to new account format

* More sensible seeds

* bring back rward account sanity check

* Comment

* Add extrinsic set_configs (#11038)

* Better sanity checks for nomination pools  (#11042)

* new sanity checks, few other changes

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Zeke Mostov <z.mostov@gmail.com>

* nomination-pools: Fix state event regression + benches (#11045)

* new sanity checks, few other changes

* Fix benches, improve sanity check

* Remove useless clear storage in benchmarking

* Set state

* Save

* Doc

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: kianenigma <kian@parity.io>

* FMT

* Try fill in all staking configs

* Fix build

* More changes to nomination pools (#11050)

* new sanity checks, few other changes

* some last touches as a whole

* Apply suggestions from code review

* Remove redundant event

* Improve unbond_other error handling

* Remove comment

Co-authored-by: Zeke Mostov <z.mostov@gmail.com>
Co-authored-by: emostov <32168567+emostov@users.noreply.github.com>

* Remove sanity module and some TODOs

* round of feedback and imp from kian

* Add TODO for ED QoL at reward pool creation

* Make sure reward pool never gets dusted

* Improve error type

* demonstrate per_thing usage

* Update sanity check & fix create_works

* Improve test ext pool creation & fix some more tests

* Try revert

* Revert "Try revert"

This reverts commit c044c94730e1a370eecd8f5b2c4f632835913063.

* Revert "Improve test ext pool creation & fix some more tests"

This reverts commit 1e862a64a7423479260c6e5ad1bd4c8c95651f3a.

* Revert "Update sanity check & fix create_works"

This reverts commit 568a7b727687e4d585e2796afc638df97b83c632.

Roll back reward account funding

* Revert "Improve error type"

This reverts commit 4b993ee601a037e7a44e4a49bbfd60cf45b38b78.

* Revert "Make sure reward pool never gets dusted"

This reverts commit e7a3eb45bdfd156d3f6d94d194e988032ebbc593.

revert

* Update some tests

* FMT

* Test that era offset works correctly

* Update mocks

* Remove unnescary docs

* Doc updates

* Update calculate_delegator_payout_works_with_a_pool_of_1

* Fix test: claim_payout_works

* do_reward_payout_correctly_sets_pool_state_to_destroying

* Remove test do_reward_payout_errors_correctly

* Fix test: do_reward_payout_works

* Fix test: create_errors_correctly

* Fix test: create works

* Fix test: unbond_other_of_3_works

* Ensure that ED is transferred into reward pool upon creation

* WIP pool lifecycle test

* Fix benchmarks

* Add sanity check for ED + reward pools

* `bond_extra` for nomination pools (#11100)

* bond_extra for nomination pools

* Update frame/nomination-pools/src/lib.rs

* Update frame/nomination-pools/src/lib.rs

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Zeke Mostov <z.mostov@gmail.com>

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Zeke Mostov <z.mostov@gmail.com>

* add benchmarks

* remove the min logic of bond_extra

Co-authored-by: Zeke Mostov <z.mostov@gmail.com>

* FMT

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>

* make it compile end to end

* Update some type viz

* Update kick terminology

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>

* Update frame/nomination-pools/src/lib.rs

* Cache bonded account when creating pool

* Add bond extra weight stuff

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>

* Update docs for pool withdraw unbonded

* Update docs for unbond

* Improve Doc

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Update frame/nomination-pools/Cargo.toml

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Improve Docs

* Some docs improvements

* fmt

* Remove unlock_era

* Fix accidental frame-support regression

* Fix issue with transactions in tests

* Fix doc links

* Make sure result in test is used

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Fix can toggle state

* Account for new_funds in ok to be open

* Update docs: ok_to_withdraw_unbonded_other_with

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Remove some staking comments

* Rename SubPoolsWithEra to UnbondingPoolsWithEra

* Use validators length for benchmarks

* Use metadata length for benchmarks

* Remove debug assert eq

* docs

* Fix test: withdraw_unbonded_other_errors_correctly

* Fix check for having enough balance to create the pool

* Bond event for pool creation

* Ok to be open

* FMT

* Remove _other postfix

* Update frame/staking/src/lib.rs

* Adjust tests to account for only remove when < ED

* Remove stale TODOs

* Remove dupe test

* Fix build

* Make sure to convert to u256 so we don't saturate

* Refund depositor with reward pool fee

* FMT

* Remove reachable defensive

* Use compact encoding for relevant extrinsics

* Remove unnescary make_free_be for cleaning reward account

* Add not to maintainers for reward account accounting

* Remove note to maintainers from public doc

* Make sure all configs have currency balance

* Avoid saturation in balance_to_unbond

* Partial Unbonding for Nomination Pools (#11212)

* first draft of partial unbonding for pools

* remove option

* Add some more tests and fix issues

* Fix all tests

* simplify some tests

* Update frame/nomination-pools/src/mock.rs

* remove clone

* rename to delegator_unbonding_eras

* Update frame/nomination-pools/src/tests.rs

Co-authored-by: Zeke Mostov <z.mostov@gmail.com>

* Update frame/nomination-pools/src/tests.rs

Co-authored-by: Zeke Mostov <z.mostov@gmail.com>

* Update frame/nomination-pools/src/tests.rs

Co-authored-by: Zeke Mostov <z.mostov@gmail.com>

* remove pub

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Zeke Mostov <z.mostov@gmail.com>

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Zeke Mostov <z.mostov@gmail.com>

* undo

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Zeke Mostov <z.mostov@gmail.com>

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Zeke Mostov <z.mostov@gmail.com>

* leftovers

* fix invariant

* Fix the depositor assumption

* round of self-review

* little bit more cleanup

* Update frame/nomination-pools/src/mock.rs

* Apply suggestions from code review

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Zeke Mostov <z.mostov@gmail.com>

* Fix interpretation of MinCreateBond

* controvesial refactor

* rename

* make everything build

* add TODO about killing the reward account

* Update frame/nomination-pools/src/lib.rs

Co-authored-by: Zeke Mostov <z.mostov@gmail.com>

* Update frame/nomination-pools/src/lib.rs

* last self-review

Co-authored-by: Zeke Mostov <z.mostov@gmail.com>

* Update Cargo.lock

* Rename Delegator to PoolMember

* fmt

* Get runtime to build with runtime-benchmarks feature

* Update Cargo.lock

* Fix asserts to work in more scenarios

* gte not gt

* cargo run --quiet --profile=production  --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark pallet --chain=dev --steps=50 --repeat=20 --pallet=pallet_nomination_pools --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/nomination-pools/src/weights.rs --template=./.maintain/frame-weight-template.hbs

* Update frame/staking/src/mock.rs

* Update frame/nomination-pools/src/lib.rs

* Update frame/staking/src/slashing.rs

* Apply suggestions from code review

* fmt

* Fix some tests

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
Co-authored-by: Parity Bot <admin@parity.io>
Co-authored-by: kianenigma <kian@parity.io>
Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com>
2022-04-27 10:46:47 +00:00

890 lines
26 KiB
Rust

// This file is part of Substrate.
// Copyright (C) 2018-2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Test utilities
use crate::{self as pallet_staking, *};
use frame_election_provider_support::{
onchain, SequentialPhragmen, SortedListProvider, VoteWeight,
};
use frame_support::{
assert_ok, parameter_types,
traits::{
ConstU32, ConstU64, Currency, FindAuthor, GenesisBuild, Get, Hooks, Imbalance,
OnUnbalanced, OneSessionHandler,
},
weights::constants::RocksDbWeight,
};
use sp_core::H256;
use sp_io;
use sp_runtime::{
curve::PiecewiseLinear,
testing::{Header, TestXt, UintAuthorityId},
traits::{IdentityLookup, Zero},
};
use sp_staking::offence::{DisableStrategy, OffenceDetails, OnOffenceHandler};
use std::cell::RefCell;
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;
pub(crate) type AccountIndex = u64;
pub(crate) type BlockNumber = u64;
pub(crate) type Balance = u128;
/// Another session handler struct to test on_disabled.
pub struct OtherSessionHandler;
impl OneSessionHandler<AccountId> for OtherSessionHandler {
type Key = UintAuthorityId;
fn on_genesis_session<'a, I: 'a>(_: I)
where
I: Iterator<Item = (&'a AccountId, Self::Key)>,
AccountId: 'a,
{
}
fn on_new_session<'a, I: 'a>(_: bool, _: I, _: I)
where
I: Iterator<Item = (&'a AccountId, Self::Key)>,
AccountId: 'a,
{
}
fn on_disabled(_validator_index: u32) {}
}
impl sp_runtime::BoundToRuntimeAppPublic for OtherSessionHandler {
type Public = UintAuthorityId;
}
pub fn is_disabled(controller: AccountId) -> bool {
let stash = Staking::ledger(&controller).unwrap().stash;
let validator_index = match Session::validators().iter().position(|v| *v == stash) {
Some(index) => index as u32,
None => return false,
};
Session::disabled_validators().contains(&validator_index)
}
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
frame_support::construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
Authorship: pallet_authorship::{Pallet, Call, Storage, Inherent},
Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
Staking: pallet_staking::{Pallet, Call, Config<T>, Storage, Event<T>},
Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>},
Historical: pallet_session::historical::{Pallet, Storage},
BagsList: pallet_bags_list::{Pallet, Call, Storage, Event<T>},
}
);
/// Author of block is always 11
pub struct Author11;
impl FindAuthor<AccountId> for Author11 {
fn find_author<'a, I>(_digests: I) -> Option<AccountId>
where
I: 'a + IntoIterator<Item = (frame_support::ConsensusEngineId, &'a [u8])>,
{
Some(11)
}
}
parameter_types! {
pub BlockWeights: frame_system::limits::BlockWeights =
frame_system::limits::BlockWeights::simple_max(
frame_support::weights::constants::WEIGHT_PER_SECOND * 2
);
pub static SessionsPerEra: SessionIndex = 3;
pub static ExistentialDeposit: Balance = 1;
pub static SlashDeferDuration: EraIndex = 0;
pub static Period: BlockNumber = 5;
pub static Offset: BlockNumber = 0;
}
impl frame_system::Config for Test {
type BaseCallFilter = frame_support::traits::Everything;
type BlockWeights = ();
type BlockLength = ();
type DbWeight = RocksDbWeight;
type Origin = Origin;
type Index = AccountIndex;
type BlockNumber = BlockNumber;
type Call = Call;
type Hash = H256;
type Hashing = ::sp_runtime::traits::BlakeTwo256;
type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = Event;
type BlockHashCount = frame_support::traits::ConstU64<250>;
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<Balance>;
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
type MaxConsumers = frame_support::traits::ConstU32<16>;
}
impl pallet_balances::Config for Test {
type MaxLocks = frame_support::traits::ConstU32<1024>;
type MaxReserves = ();
type ReserveIdentifier = [u8; 8];
type Balance = Balance;
type Event = Event;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type WeightInfo = ();
}
sp_runtime::impl_opaque_keys! {
pub struct SessionKeys {
pub other: OtherSessionHandler,
}
}
impl pallet_session::Config for Test {
type SessionManager = pallet_session::historical::NoteHistoricalRoot<Test, Staking>;
type Keys = SessionKeys;
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
type SessionHandler = (OtherSessionHandler,);
type Event = Event;
type ValidatorId = AccountId;
type ValidatorIdOf = crate::StashOf<Test>;
type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
type WeightInfo = ();
}
impl pallet_session::historical::Config for Test {
type FullIdentification = crate::Exposure<AccountId, Balance>;
type FullIdentificationOf = crate::ExposureOf<Test>;
}
impl pallet_authorship::Config for Test {
type FindAuthor = Author11;
type UncleGenerations = ConstU64<0>;
type FilterUncle = ();
type EventHandler = Pallet<Test>;
}
impl pallet_timestamp::Config for Test {
type Moment = u64;
type OnTimestampSet = ();
type MinimumPeriod = ConstU64<5>;
type WeightInfo = ();
}
pallet_staking_reward_curve::build! {
const I_NPOS: PiecewiseLinear<'static> = curve!(
min_inflation: 0_025_000,
max_inflation: 0_100_000,
ideal_stake: 0_500_000,
falloff: 0_050_000,
max_piece_count: 40,
test_precision: 0_005_000,
);
}
parameter_types! {
pub const BondingDuration: EraIndex = 3;
pub const RewardCurve: &'static PiecewiseLinear<'static> = &I_NPOS;
pub const OffendingValidatorsThreshold: Perbill = Perbill::from_percent(75);
}
thread_local! {
pub static REWARD_REMAINDER_UNBALANCED: RefCell<u128> = RefCell::new(0);
}
pub struct RewardRemainderMock;
impl OnUnbalanced<NegativeImbalanceOf<Test>> for RewardRemainderMock {
fn on_nonzero_unbalanced(amount: NegativeImbalanceOf<Test>) {
REWARD_REMAINDER_UNBALANCED.with(|v| {
*v.borrow_mut() += amount.peek();
});
drop(amount);
}
}
const THRESHOLDS: [sp_npos_elections::VoteWeight; 9] =
[10, 20, 30, 40, 50, 60, 1_000, 2_000, 10_000];
parameter_types! {
pub static BagThresholds: &'static [sp_npos_elections::VoteWeight] = &THRESHOLDS;
pub static MaxNominations: u32 = 16;
pub static RewardOnUnbalanceWasCalled: bool = false;
pub static LedgerSlashPerEra: (BalanceOf<Test>, BTreeMap<EraIndex, BalanceOf<Test>>) = (Zero::zero(), BTreeMap::new());
}
impl pallet_bags_list::Config for Test {
type Event = Event;
type WeightInfo = ();
type ScoreProvider = Staking;
type BagThresholds = BagThresholds;
type Score = VoteWeight;
}
pub struct OnChainSeqPhragmen;
impl onchain::Config for OnChainSeqPhragmen {
type System = Test;
type Solver = SequentialPhragmen<AccountId, Perbill>;
type DataProvider = Staking;
type WeightInfo = ();
}
pub struct MockReward {}
impl OnUnbalanced<PositiveImbalanceOf<Test>> for MockReward {
fn on_unbalanced(_: PositiveImbalanceOf<Test>) {
RewardOnUnbalanceWasCalled::set(true);
}
}
pub struct OnStakerSlashMock<T: Config>(core::marker::PhantomData<T>);
impl<T: Config> sp_staking::OnStakerSlash<AccountId, Balance> for OnStakerSlashMock<T> {
fn on_slash(
_pool_account: &AccountId,
slashed_bonded: Balance,
slashed_chunks: &BTreeMap<EraIndex, Balance>,
) {
LedgerSlashPerEra::set((slashed_bonded, slashed_chunks.clone()));
}
}
impl crate::pallet::pallet::Config for Test {
type MaxNominations = MaxNominations;
type Currency = Balances;
type CurrencyBalance = <Self as pallet_balances::Config>::Balance;
type UnixTime = Timestamp;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type RewardRemainder = RewardRemainderMock;
type Event = Event;
type Slash = ();
type Reward = MockReward;
type SessionsPerEra = SessionsPerEra;
type SlashDeferDuration = SlashDeferDuration;
type SlashCancelOrigin = frame_system::EnsureRoot<Self::AccountId>;
type BondingDuration = BondingDuration;
type SessionInterface = Self;
type EraPayout = ConvertCurve<RewardCurve>;
type NextNewSession = Session;
type MaxNominatorRewardedPerValidator = ConstU32<64>;
type OffendingValidatorsThreshold = OffendingValidatorsThreshold;
type ElectionProvider = onchain::UnboundedExecution<OnChainSeqPhragmen>;
type GenesisElectionProvider = Self::ElectionProvider;
// NOTE: consider a macro and use `UseNominatorsAndValidatorsMap<Self>` as well.
type VoterList = BagsList;
type MaxUnlockingChunks = ConstU32<32>;
type OnStakerSlash = OnStakerSlashMock<Test>;
type BenchmarkingConfig = TestBenchmarkingConfig;
type WeightInfo = ();
}
impl<LocalCall> frame_system::offchain::SendTransactionTypes<LocalCall> for Test
where
Call: From<LocalCall>,
{
type OverarchingCall = Call;
type Extrinsic = Extrinsic;
}
pub type Extrinsic = TestXt<Call, ()>;
pub(crate) type StakingCall = crate::Call<Test>;
pub(crate) type TestRuntimeCall = <Test as frame_system::Config>::Call;
pub struct ExtBuilder {
nominate: bool,
validator_count: u32,
minimum_validator_count: u32,
invulnerables: Vec<AccountId>,
has_stakers: bool,
initialize_first_session: bool,
pub min_nominator_bond: Balance,
min_validator_bond: Balance,
balance_factor: Balance,
status: BTreeMap<AccountId, StakerStatus<AccountId>>,
stakes: BTreeMap<AccountId, Balance>,
stakers: Vec<(AccountId, AccountId, Balance, StakerStatus<AccountId>)>,
}
impl Default for ExtBuilder {
fn default() -> Self {
Self {
nominate: true,
validator_count: 2,
minimum_validator_count: 0,
balance_factor: 1,
invulnerables: vec![],
has_stakers: true,
initialize_first_session: true,
min_nominator_bond: ExistentialDeposit::get(),
min_validator_bond: ExistentialDeposit::get(),
status: Default::default(),
stakes: Default::default(),
stakers: Default::default(),
}
}
}
impl ExtBuilder {
pub fn existential_deposit(self, existential_deposit: Balance) -> Self {
EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = existential_deposit);
self
}
pub fn nominate(mut self, nominate: bool) -> Self {
self.nominate = nominate;
self
}
pub fn validator_count(mut self, count: u32) -> Self {
self.validator_count = count;
self
}
pub fn minimum_validator_count(mut self, count: u32) -> Self {
self.minimum_validator_count = count;
self
}
pub fn slash_defer_duration(self, eras: EraIndex) -> Self {
SLASH_DEFER_DURATION.with(|v| *v.borrow_mut() = eras);
self
}
pub fn invulnerables(mut self, invulnerables: Vec<AccountId>) -> Self {
self.invulnerables = invulnerables;
self
}
pub fn session_per_era(self, length: SessionIndex) -> Self {
SESSIONS_PER_ERA.with(|v| *v.borrow_mut() = length);
self
}
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 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 min_nominator_bond(mut self, amount: Balance) -> Self {
self.min_nominator_bond = amount;
self
}
pub fn min_validator_bond(mut self, amount: Balance) -> Self {
self.min_validator_bond = amount;
self
}
pub fn set_status(mut self, who: AccountId, status: StakerStatus<AccountId>) -> Self {
self.status.insert(who, status);
self
}
pub fn set_stake(mut self, who: AccountId, stake: Balance) -> Self {
self.stakes.insert(who, stake);
self
}
pub fn add_staker(
mut self,
stash: AccountId,
ctrl: AccountId,
stake: Balance,
status: StakerStatus<AccountId>,
) -> Self {
self.stakers.push((stash, ctrl, stake, status));
self
}
pub fn balance_factor(mut self, factor: Balance) -> Self {
self.balance_factor = factor;
self
}
fn build(self) -> sp_io::TestExternalities {
sp_tracing::try_init_simple();
let mut storage = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
let _ = pallet_balances::GenesisConfig::<Test> {
balances: vec![
(1, 10 * self.balance_factor),
(2, 20 * self.balance_factor),
(3, 300 * self.balance_factor),
(4, 400 * self.balance_factor),
// controllers
(10, self.balance_factor),
(20, self.balance_factor),
(30, self.balance_factor),
(40, self.balance_factor),
(50, self.balance_factor),
// stashes
(11, self.balance_factor * 1000),
(21, self.balance_factor * 2000),
(31, self.balance_factor * 2000),
(41, self.balance_factor * 2000),
(51, self.balance_factor * 2000),
// optional nominator
(100, self.balance_factor * 2000),
(101, self.balance_factor * 2000),
// aux accounts
(60, self.balance_factor),
(61, self.balance_factor * 2000),
(70, self.balance_factor),
(71, self.balance_factor * 2000),
(80, self.balance_factor),
(81, self.balance_factor * 2000),
// This allows us to have a total_payout different from 0.
(999, 1_000_000_000_000),
],
}
.assimilate_storage(&mut storage);
let mut stakers = vec![];
if self.has_stakers {
stakers = vec![
// (stash, ctrl, stake, status)
// these two will be elected in the default test where we elect 2.
(11, 10, self.balance_factor * 1000, StakerStatus::<AccountId>::Validator),
(21, 20, self.balance_factor * 1000, StakerStatus::<AccountId>::Validator),
// a loser validator
(31, 30, self.balance_factor * 500, StakerStatus::<AccountId>::Validator),
// an idle validator
(41, 40, self.balance_factor * 1000, StakerStatus::<AccountId>::Idle),
];
// optionally add a nominator
if self.nominate {
stakers.push((
101,
100,
self.balance_factor * 500,
StakerStatus::<AccountId>::Nominator(vec![11, 21]),
))
}
// replace any of the status if needed.
self.status.into_iter().for_each(|(stash, status)| {
let (_, _, _, ref mut prev_status) = stakers
.iter_mut()
.find(|s| s.0 == stash)
.expect("set_status staker should exist; qed");
*prev_status = status;
});
// replaced any of the stakes if needed.
self.stakes.into_iter().for_each(|(stash, stake)| {
let (_, _, ref mut prev_stake, _) = stakers
.iter_mut()
.find(|s| s.0 == stash)
.expect("set_stake staker should exits; qed.");
*prev_stake = stake;
});
// extend stakers if needed.
stakers.extend(self.stakers)
}
let _ = pallet_staking::GenesisConfig::<Test> {
stakers: stakers.clone(),
validator_count: self.validator_count,
minimum_validator_count: self.minimum_validator_count,
invulnerables: self.invulnerables,
slash_reward_fraction: Perbill::from_percent(10),
min_nominator_bond: self.min_nominator_bond,
min_validator_bond: self.min_validator_bond,
..Default::default()
}
.assimilate_storage(&mut storage);
let _ = pallet_session::GenesisConfig::<Test> {
keys: if self.has_stakers {
// set the keys for the first session.
stakers
.into_iter()
.map(|(id, ..)| (id, id, SessionKeys { other: id.into() }))
.collect()
} else {
// set some dummy validators in genesis.
(0..self.validator_count as u64)
.map(|id| (id, id, SessionKeys { other: id.into() }))
.collect()
},
}
.assimilate_storage(&mut storage);
let mut ext = sp_io::TestExternalities::from(storage);
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 as Hooks<u64>>::on_initialize(1);
Timestamp::set_timestamp(INIT_TIMESTAMP);
});
}
ext
}
pub fn build_and_execute(self, test: impl FnOnce() -> ()) {
let mut ext = self.build();
ext.execute_with(test);
ext.execute_with(post_conditions);
}
}
fn post_conditions() {
check_nominators();
check_exposures();
check_ledgers();
check_count();
}
fn check_count() {
let nominator_count = Nominators::<Test>::iter_keys().count() as u32;
let validator_count = Validators::<Test>::iter().count() as u32;
assert_eq!(nominator_count, Nominators::<Test>::count());
assert_eq!(validator_count, Validators::<Test>::count());
// the voters that the `VoterList` list is storing for us.
let external_voters = <Test as Config>::VoterList::count();
assert_eq!(external_voters, nominator_count + validator_count);
}
fn check_ledgers() {
// check the ledger of all stakers.
Bonded::<Test>::iter().for_each(|(_, ctrl)| assert_ledger_consistent(ctrl))
}
fn check_exposures() {
// a check per validator to ensure the exposure struct is always sane.
let era = active_era();
ErasStakers::<Test>::iter_prefix_values(era).for_each(|expo| {
assert_eq!(
expo.total as u128,
expo.own as u128 + expo.others.iter().map(|e| e.value as u128).sum::<u128>(),
"wrong total exposure.",
);
})
}
fn check_nominators() {
// a check per nominator to ensure their entire stake is correctly distributed. Will only kick-
// in if the nomination was submitted before the current era.
let era = active_era();
<Nominators<Test>>::iter()
.filter_map(
|(nominator, nomination)| {
if nomination.submitted_in > era {
Some(nominator)
} else {
None
}
},
)
.for_each(|nominator| {
// must be bonded.
assert_is_stash(nominator);
let mut sum = 0;
Session::validators()
.iter()
.map(|v| Staking::eras_stakers(era, v))
.for_each(|e| {
let individual =
e.others.iter().filter(|e| e.who == nominator).collect::<Vec<_>>();
let len = individual.len();
match len {
0 => { /* not supporting this validator at all. */ },
1 => sum += individual[0].value,
_ => panic!("nominator cannot back a validator more than once."),
};
});
let nominator_stake = Staking::slashable_balance_of(&nominator);
// a nominator cannot over-spend.
assert!(
nominator_stake >= sum,
"failed: Nominator({}) stake({}) >= sum divided({})",
nominator,
nominator_stake,
sum,
);
let diff = nominator_stake - sum;
assert!(diff < 100);
});
}
fn assert_is_stash(acc: AccountId) {
assert!(Staking::bonded(&acc).is_some(), "Not a stash.");
}
fn assert_ledger_consistent(ctrl: AccountId) {
// ensures ledger.total == ledger.active + sum(ledger.unlocking).
let ledger = Staking::ledger(ctrl).expect("Not a controller.");
let real_total: Balance = ledger.unlocking.iter().fold(ledger.active, |a, c| a + c.value);
assert_eq!(real_total, ledger.total);
assert!(
ledger.active >= Balances::minimum_balance() || ledger.active == 0,
"{}: active ledger amount ({}) must be greater than ED {}",
ctrl,
ledger.active,
Balances::minimum_balance()
);
}
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(stash: AccountId, ctrl: AccountId, val: Balance) {
let _ = Balances::make_free_balance_be(&stash, val);
let _ = Balances::make_free_balance_be(&ctrl, val);
assert_ok!(Staking::bond(Origin::signed(stash), ctrl, val, RewardDestination::Controller));
}
pub(crate) fn bond_validator(stash: AccountId, ctrl: AccountId, val: Balance) {
bond(stash, ctrl, val);
assert_ok!(Staking::validate(Origin::signed(ctrl), ValidatorPrefs::default()));
assert_ok!(Session::set_keys(Origin::signed(ctrl), SessionKeys { other: ctrl.into() }, vec![]));
}
pub(crate) fn bond_nominator(
stash: AccountId,
ctrl: AccountId,
val: Balance,
target: Vec<AccountId>,
) {
bond(stash, ctrl, val);
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 {
System::set_block_number(b);
Session::on_initialize(b);
<Staking as Hooks<u64>>::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);
}
/// Progress until the given era.
pub(crate) fn start_active_era(era_index: EraIndex) {
start_session((era_index * <SessionsPerEra as Get<u32>>::get()).into());
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 (payout, _rest) = <Test as Config>::EraPayout::era_payout(
Staking::eras_total_stake(active_era()),
Balances::total_issuance(),
duration,
);
assert!(payout > 0);
payout
}
pub(crate) fn maximum_payout_for_duration(duration: u64) -> Balance {
let (payout, rest) = <Test as Config>::EraPayout::era_payout(
Staking::eras_total_stake(active_era()),
Balances::total_issuance(),
duration,
);
payout + rest
}
/// 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() {
let rewards = <Test as Config>::SessionInterface::validators().into_iter().map(|v| (v, 1));
<Pallet<Test>>::reward_by_ids(rewards)
}
pub(crate) fn validator_controllers() -> Vec<AccountId> {
Session::validators()
.into_iter()
.map(|s| Staking::bonded(&s).expect("no controller for validator"))
.collect()
}
pub(crate) fn on_offence_in_era(
offenders: &[OffenceDetails<
AccountId,
pallet_session::historical::IdentificationTuple<Test>,
>],
slash_fraction: &[Perbill],
era: EraIndex,
disable_strategy: DisableStrategy,
) {
let bonded_eras = crate::BondedEras::<Test>::get();
for &(bonded_era, start_session) in bonded_eras.iter() {
if bonded_era == era {
let _ = Staking::on_offence(offenders, slash_fraction, start_session, disable_strategy);
return
} else if bonded_era > era {
break
}
}
if Staking::active_era().unwrap().index == era {
let _ = Staking::on_offence(
offenders,
slash_fraction,
Staking::eras_start_session_index(era).unwrap(),
disable_strategy,
);
} else {
panic!("cannot slash in era {}", era);
}
}
pub(crate) fn on_offence_now(
offenders: &[OffenceDetails<
AccountId,
pallet_session::historical::IdentificationTuple<Test>,
>],
slash_fraction: &[Perbill],
) {
let now = Staking::active_era().unwrap().index;
on_offence_in_era(offenders, slash_fraction, now, DisableStrategy::WhenSlashed)
}
pub(crate) fn add_slash(who: &AccountId) {
on_offence_now(
&[OffenceDetails {
offender: (who.clone(), Staking::eras_stakers(active_era(), who.clone())),
reporters: vec![],
}],
&[Perbill::from_percent(10)],
);
}
/// Make all validator and nominator request their payment
pub(crate) fn make_all_reward_payment(era: EraIndex) {
let validators_with_reward = ErasRewardPoints::<Test>::get(era)
.individual
.keys()
.cloned()
.collect::<Vec<_>>();
// reward validators
for validator_controller in validators_with_reward.iter().filter_map(Staking::bonded) {
let ledger = <Ledger<Test>>::get(&validator_controller).unwrap();
assert_ok!(Staking::payout_stakers(Origin::signed(1337), ledger.stash, era));
}
}
#[macro_export]
macro_rules! assert_session_era {
($session:expr, $era:expr) => {
assert_eq!(
Session::current_index(),
$session,
"wrong session {} != {}",
Session::current_index(),
$session,
);
assert_eq!(
Staking::current_era().unwrap(),
$era,
"wrong current era {} != {}",
Staking::current_era().unwrap(),
$era,
);
};
}
pub(crate) fn staking_events() -> Vec<crate::Event<Test>> {
System::events()
.into_iter()
.map(|r| r.event)
.filter_map(|e| if let Event::Staking(inner) = e { Some(inner) } else { None })
.collect()
}
pub(crate) fn balances(who: &AccountId) -> (Balance, Balance) {
(Balances::free_balance(who), Balances::reserved_balance(who))
}