Implement pallet-bags-list and its interfaces with pallet-staking (#9507)

* remove extra whitespace

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

* only emit rebag event on success

* add doc explaining the term voter

* revamp/simplify rebag test

* ensure genesis accounts are placed into the correct nodes/bags

* bond_extra implicitly rebags

* types at top; doc public type

* start sketching out adjustable thresholds

* add integrity test for voter bag threshold requirements

* get rid of BagIdx

This reorganizes bag storage such that bags are always referred to
by their upper threshold. This in turn means that adding and removing
bags is cheaper; you only need to migrate certain voters, not all of them.

* implement migration logic for when the threshold list changes

* start sketching out threshold proc macros

* further refine macro signatures

* WIP: implement make_ratio macro

* start rethinking the process of producing threshold lists

The macro approach seems to be a non-starter; that only really works
if we're throwing around numeric literals everywhere, and that's just
not nice in this case.

Instead, let's write helper functions and make it really easy to
generate the tables in separate, permanent files, which humans
can then edit.

* write helper functions to emit voter bags module

* WIP: demo generating voter bags for a realistic runtime

This isn't yet done, becuase it seems to take a Very Long Time to run,
and it really shouldn't. Need to look into that.

Still, it's a lot closer than it was this morning.

* rm unnecessary arg_enum

* fix voter bags math

Turns out that when you're working in exponential space, you need
to divide, not subtract, in order to keep the math working properly.

Also neaten up the output a little bit to make it easier to read.

* add computed voter bags thresholds to node

* fixup some docs

* iter from large bags to small, fulfuilling the contract

* make tests compile

* add VoterBagThresholds to some configs

* ensure that iteration covers all voters even with implied final bag

* use sp_std::boxed::Box;

* fix unused import

* add some more voter bags tests

* file_header.txt

* integrity test to ensure min bag exceeds existential weight

* add more debug assertions about node list length

* rm unused imports

* Kian enters

* Update frame/election-provider-support/src/onchain.rs

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

* Suggestions for #9081 (Store voters in unsorted bags) (#9328)

* Add some debug asserts to node::get and remove_node

* Improve the debug asserts in remove_node

* improve debug asserts

* Space

* Remove bad assertions

* Tests: WIP take_works

* Take test

* Doc comment

* Apply suggestions from code review

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

* Test storage is cleaned up;

* formatting

* Switch to simpler thresholds

* Update the storage cleanup test

* Remove hardcoded values from benchmark to make it more robust

* Fix tests to acces bags properly

* Sanity check WIP; tests failing

* Update sanity checks to be more correct

* Improve storage cleanup tests

* WIP remote_ext_tests

* Some notes on next steps

* Remove some stuff that was for remote-ext tests

* Some more cleanup to reduce diff

* More :clean:

* Mo cleanin

* small fix

* A lot of changes from kian

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

* merge fallout

* Run cargo +nightly fmt

* Fix a bunch of stuff, remove not needed runtime arg of make-bags

* add logs

* Glue the new staking bags to the election snapshot (#9415)

* Glue the new staking bags to the election snapshot

* add CheckedRem (#9412)

* add CheckedRem

* fix

* Run fmt

* Test comment

Co-authored-by: Xiliang Chen <xlchen1291@gmail.com>
Co-authored-by: emostov <32168567+emostov@users.noreply.github.com>

* Update node runtime with VoterSnapshotPerBlock

* Unit test for pallet-staking unsorted bags feature (targets #9081) (#9422)

* impl notional_bag_for_works

* Add tests: insert_as_works & insert_works

* Impl test: remove_works

* Trivial cleaning

* Add test: update_position_for_works

* Write out edge case; probably can delete later

* Add test: bags::get_works

* Add test: remove_node_happy_path_works

* Add test: remove_node_bad_paths_documented

* WIP: voting_data_works

* done

* Improve test voting_data_works

* Add comment

* Fill out test basic_setup_works

* Update: iteration_is_semi_sorted

* Improve remove_works

* Update update_position_for_works; create set_ledger_and_free_balance

* Improve get_works

* Improve storage clean up checks in remove test

* Test: impl rebag_works + insert_and_remove_works

* forgot file -  Test: impl rebag_works + insert_and_remove_works

* Small tweak

* Update voter_bags test to reflect unused bags are removed

* Unbond & Rebond: do_rebag

* Prevent infinite loops with duplicate tail insert

* Check iter.count on voter list in pre-migrate

* undo strang fmt comment stuff

* Add in todo

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

* Try prepare for master merge

* Reduce diff

* Add comment for test to add

* Add in code TODO for update_position efficiency updates

* Initial impl compiles

* impl StakingVoterListStub

* Sample impl<T: Config> VoterListProvider<T> for VoterList<T>

* impl VoterListProvider for voter-bags

* WIP integrate pallet-voter-bags to staking mock

* the trait `pallet_staking::pallet::pallet::Config` is not implemented for `mock::Test`

* random

* pushing my stuff

* Mock working

* WIP voter list tests

* Add bag insert, remove tests

* Add test for bag insert and remove

* Add remaining tests for VoterList

* Add tests for node

* Add rebag works

* Add rebag extrinsic tests

* Rename to bags-list and name the list .. list!

* Rename VoterBagThresholds => BagThresholds

* Add test count_works

* Test on_update_works

* test sanity check

* a round of test fixes

* push a lot of changes

* my last changes

* all bags-list test work; fmt

* Beautify some tests

* Doc comment for bags-list

* Add insert warnings

* Setup initial benchmark

* Wire up WeightInfo

* is_terminal wip; everything broken!

* Is terminal working

* add TODOs for remove_node

* clean up remoe_node

* Fix all staking tests

* retire VoterBagFor

* commit

* bring in stashed changes

* save

* bench pipeline works now, but I can't run stuff

* sabe

* benchmarks now run, but we have a failure

* WIP: Wire up make_bags

* bags-thresholds compiles

* Fix most build issues

* This will fix all the tests

* move bag thresholds to bags-list

* Move bag-thresholds bin to within pallet-bags

* Remove some unnescary TODOs

* Impl tets wrong_rebag_is_noop

* assert remove is a noop with bad data

* Assert integrity test panics

* Return an error when inserting duplicates

* Update to handle error in staking pallet when inserting to list

* Test contains and on_insert error

* Test re-nominate does not mess up list or count

* Everything builds and works, only the benchmark...

* fuck yeah benchmarks

* more cleanup, more hardening.

* use the bags list again

* fix benhc

* Some questions and changs for List::migration

* Fix migration removed_bags and new_bags usage

* Some trivial aesthetic changes

* Some more trivial changes

* tiny changes/

* mega rename

* fix all tests and ci build

* nit

* Test and fix migration

* nit

* fmt

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

* fmt

* remove unused

* make a few things pub

* make node also pub.. for remote-ext test

* Fix all tests again

* Force bag changes in relevant benchmarks (targets #9507) (#9529)

* force rebag for unbond, rebond, and bond_extra

* nit

* Improve utils

* fmt

* nits

* Move generate_bags to its own pallet

* Get runtime-benchmarks feature setup with prepare_on_update_benchmark

* Withdraw unbonded kill working

* Nominate bench working

* some cleanup

* WIP

* update to check head pre & post conditions

* Add some post condition verification stuff for on_remove

* Update nominate

* fmt

* Improvements

* Fix build

* fix build with polkadot companion

* Update frame/bags-list/src/list/tests.rs

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

* move generate-bag from frame to utils

* wip

* refactor WIP

* WIP save

* Refactor working

* some variable renaming

* WIP: prepare to remove head checks

* Finish MvP refactor

* Some cleanup

* Soem more cleanup

* save

* fix a lot of stuff

* Update client/db/src/bench.rs

Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com>

* Apply suggestions from code review

* Apply suggestions from code review

* Fix some issues that came from trying to merge comments on github

* some small changes

* simplify it

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
Co-authored-by: kianenigma <kian@parity.io>
Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com>

* Build works

* Apply suggestions from code review

Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>

* Apply suggestions from code review

Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>

* Remove commented out debug assert

* Remove some unused deps and some unused benchmarking stuff

* Fix stakings ElectionDataProvider clear

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

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

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

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

* Improving staking pallet-bags-list migration

* fix build and some comments;

* comment

* Reduce visibility in bags list components

* make node.bag_upper only accesible to benchmarks

* Address some feedback; comments updates

* use nominator map comment

* fix vec capacity debug assert

* Apply suggestions from code review

Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>

* clarify VoterSnapshotPerBlock

* Reduce diff on create_validators by wrapping with_seed

* Some small improvements to staking benches

* Soem comment updates

* fix vec capacity debug assert ... for real this time

* Reduce ListBags viz

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

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

* Remove supports_eq_unordered & Support eq_unordered

* Update utils/frame/generate-bags/src/lib.rs

Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>

* Make total-issuance & minimium-balance CLI args; Dont use emptry ext

* Improve docs for generate bags CLI args

* Apply suggestions from code review

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

* Apply suggestions from code review

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

* Don't use default bags weight in node runtime

* Feature gating sanity_check not working

* Feature gate sanity check by creating duplicate fns

* Fix line wrapping

* Document VoteWeightProvider

* Make bags ext-builder not a module

* Apply suggestions from code review

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

* use pallet_bags_list instead of crate in mock

* Make get_bags test helper fn live in List

* use remove_from_storage_unchecked for node removal

* Remove count of ids removed in remove_many

* Add node sanity check, improve list sanity check

* Do a list sanity check after on_update

* List::migrate: clean up debug assert, exit early when no change in thresholds

* Improve public doc comments for pallet_bags_list::list::List

* Improve public doc comments for pallet_bags_list::list::List

* Update generate bags docs

* Fix grammar in bags-list benchmark

* Add benchmark case for `rebag` extrinsic

* Add count parameter to List::clear; WIP adding MaxEncodedLen to list'

* MaxEncodeLen + generate_storage_info not working for Bag or Node

* Get MaxEncodeLen derive to work

* Try to correctly feature gate SortedListProvider::clear

* Use u32::MAX, not u32::max_value

* Get up to nominators_quota noms

* SortedListProvider::clear takes an Option

* Eplicitly ignore SortedListProvider return value

* Fix doc comment

* Update node-runtime voter snapshot per block

* Add test get_max_len_voters_even_if_some_nominators_are_slashed

* Add test only_iterates_max_2_times_nominators_quota

* Fix generate bags cargo.toml

* use sp_std vec

* Remove v8 migration hooks from pallet-staking

* Update npos trait

* Try respect line width

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

* Update frame/bags-list/src/benchmarks.rs

* Unwrap try-runtime error; remove sortedlistprovider pre upgrade len  check

* trigger ci

* restore

* trigger ci

* restore

* trigger ci

* revert

* trigger ci

* revert

Co-authored-by: Peter Goodspeed-Niklaus <coriolinus@users.noreply.github.com>
Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
Co-authored-by: Peter Goodspeed-Niklaus <peter.r.goodspeedniklaus@gmail.com>
Co-authored-by: kianenigma <kian@parity.io>
Co-authored-by: Xiliang Chen <xlchen1291@gmail.com>
Co-authored-by: Parity Benchmarking Bot <admin@parity.io>
Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com>
Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>
This commit is contained in:
Zeke Mostov
2021-09-16 19:25:21 -07:00
committed by GitHub
parent 867cf27bbd
commit 669972a171
36 changed files with 4601 additions and 339 deletions
+281 -46
View File
@@ -21,9 +21,10 @@ use super::*;
use crate::Pallet as Staking;
use testing_utils::*;
use frame_election_provider_support::SortedListProvider;
use frame_support::{
pallet_prelude::*,
traits::{Currency, Get, Imbalance},
traits::{Currency, CurrencyToVote, Get, Imbalance},
};
use sp_runtime::{
traits::{StaticLookup, Zero},
@@ -110,6 +111,8 @@ pub fn create_validator_with_nominators<T: Config>(
assert_eq!(new_validators.len(), 1);
assert_eq!(new_validators[0], v_stash, "Our validator was not selected!");
assert_ne!(CounterForValidators::<T>::get(), 0);
assert_ne!(CounterForNominators::<T>::get(), 0);
// Give Era Points
let reward = EraRewardPoints::<T::AccountId> {
@@ -129,13 +132,91 @@ pub fn create_validator_with_nominators<T: Config>(
Ok((v_stash, nominators))
}
struct ListScenario<T: Config> {
/// Stash that is expected to be moved.
origin_stash1: T::AccountId,
/// Controller of the Stash that is expected to be moved.
origin_controller1: T::AccountId,
dest_weight: BalanceOf<T>,
}
impl<T: Config> ListScenario<T> {
/// An expensive scenario for bags-list implementation:
///
/// - the node to be updated (r) is the head of a bag that has at least one other node. The bag
/// itself will need to be read and written to update its head. The node pointed to by r.next
/// will need to be read and written as it will need to have its prev pointer updated. Note
/// that there are two other worst case scenarios for bag removal: 1) the node is a tail and
/// 2) the node is a middle node with prev and next; all scenarios end up with the same number
/// of storage reads and writes.
///
/// - the destination bag has at least one node, which will need its next pointer updated.
///
/// NOTE: while this scenario specifically targets a worst case for the bags-list, it should
/// also elicit a worst case for other known `SortedListProvider` implementations; although
/// this may not be true against unknown `SortedListProvider` implementations.
fn new(origin_weight: BalanceOf<T>, is_increase: bool) -> Result<Self, &'static str> {
ensure!(!origin_weight.is_zero(), "origin weight must be greater than 0");
// burn the entire issuance.
let i = T::Currency::burn(T::Currency::total_issuance());
sp_std::mem::forget(i);
// create accounts with the origin weight
let (origin_stash1, origin_controller1) = create_stash_controller_with_balance::<T>(
USER_SEED + 2,
origin_weight,
Default::default(),
)?;
Staking::<T>::nominate(
RawOrigin::Signed(origin_controller1.clone()).into(),
// NOTE: these don't really need to be validators.
vec![T::Lookup::unlookup(account("random_validator", 0, SEED))],
)?;
let (_origin_stash2, origin_controller2) = create_stash_controller_with_balance::<T>(
USER_SEED + 3,
origin_weight,
Default::default(),
)?;
Staking::<T>::nominate(
RawOrigin::Signed(origin_controller2.clone()).into(),
vec![T::Lookup::unlookup(account("random_validator", 0, SEED))].clone(),
)?;
// find a destination weight that will trigger the worst case scenario
let dest_weight_as_vote =
T::SortedListProvider::weight_update_worst_case(&origin_stash1, is_increase);
let total_issuance = T::Currency::total_issuance();
let dest_weight =
T::CurrencyToVote::to_currency(dest_weight_as_vote as u128, total_issuance);
// create an account with the worst case destination weight
let (_dest_stash1, dest_controller1) = create_stash_controller_with_balance::<T>(
USER_SEED + 1,
dest_weight,
Default::default(),
)?;
Staking::<T>::nominate(
RawOrigin::Signed(dest_controller1).into(),
vec![T::Lookup::unlookup(account("random_validator", 0, SEED))],
)?;
Ok(ListScenario { origin_stash1, origin_controller1, dest_weight })
}
}
const USER_SEED: u32 = 999666;
benchmarks! {
bond {
let stash = create_funded_user::<T>("stash", USER_SEED, 100);
let controller = create_funded_user::<T>("controller", USER_SEED, 100);
let controller_lookup: <T::Lookup as StaticLookup>::Source = T::Lookup::unlookup(controller.clone());
let controller_lookup: <T::Lookup as StaticLookup>::Source
= T::Lookup::unlookup(controller.clone());
let reward_destination = RewardDestination::Staked;
let amount = T::Currency::minimum_balance() * 10u32.into();
whitelist_account!(stash);
@@ -146,10 +227,25 @@ benchmarks! {
}
bond_extra {
let (stash, controller) = create_stash_controller::<T>(USER_SEED, 100, Default::default())?;
let max_additional = T::Currency::minimum_balance() * 10u32.into();
let ledger = Ledger::<T>::get(&controller).ok_or("ledger not created before")?;
let original_bonded: BalanceOf<T> = ledger.active;
// clean up any existing state.
clear_validators_and_nominators::<T>();
let origin_weight = MinNominatorBond::<T>::get().max(T::Currency::minimum_balance());
// setup the worst case list scenario.
// the weight the nominator will start at.
let scenario = ListScenario::<T>::new(origin_weight, true)?;
let max_additional = scenario.dest_weight.clone() - origin_weight;
let stash = scenario.origin_stash1.clone();
let controller = scenario.origin_controller1.clone();
let original_bonded: BalanceOf<T>
= Ledger::<T>::get(&controller).map(|l| l.active).ok_or("ledger not created after")?;
T::Currency::deposit_into_existing(&stash, max_additional).unwrap();
whitelist_account!(stash);
}: _(RawOrigin::Signed(stash), max_additional)
verify {
@@ -159,10 +255,25 @@ benchmarks! {
}
unbond {
let (_, controller) = create_stash_controller::<T>(USER_SEED, 100, Default::default())?;
let amount = T::Currency::minimum_balance() * 10u32.into();
use sp_std::convert::TryFrom;
// clean up any existing state.
clear_validators_and_nominators::<T>();
// setup the worst case list scenario.
let total_issuance = T::Currency::total_issuance();
// the weight the nominator will start at. The value used here is expected to be
// significantly higher than the first position in a list (e.g. the first bag threshold).
let origin_weight = BalanceOf::<T>::try_from(952_994_955_240_703u128)
.map_err(|_| "balance expected to be a u128")
.unwrap();
let scenario = ListScenario::<T>::new(origin_weight, false)?;
let stash = scenario.origin_stash1.clone();
let controller = scenario.origin_controller1.clone();
let amount = origin_weight - scenario.dest_weight.clone();
let ledger = Ledger::<T>::get(&controller).ok_or("ledger not created before")?;
let original_bonded: BalanceOf<T> = ledger.active;
whitelist_account!(controller);
}: _(RawOrigin::Signed(controller.clone()), amount)
verify {
@@ -194,26 +305,50 @@ benchmarks! {
withdraw_unbonded_kill {
// Slashing Spans
let s in 0 .. MAX_SPANS;
let (stash, controller) = create_stash_controller::<T>(0, 100, Default::default())?;
add_slashing_spans::<T>(&stash, s);
let amount = T::Currency::minimum_balance() * 10u32.into();
Staking::<T>::unbond(RawOrigin::Signed(controller.clone()).into(), amount)?;
// clean up any existing state.
clear_validators_and_nominators::<T>();
let origin_weight = MinNominatorBond::<T>::get().max(T::Currency::minimum_balance());
// setup a worst case list scenario. Note that we don't care about the setup of the
// destination position because we are doing a removal from the list but no insert.
let scenario = ListScenario::<T>::new(origin_weight, true)?;
let controller = scenario.origin_controller1.clone();
let stash = scenario.origin_stash1.clone();
assert!(T::SortedListProvider::contains(&stash));
let ed = T::Currency::minimum_balance();
let mut ledger = Ledger::<T>::get(&controller).unwrap();
ledger.active = ed - One::one();
Ledger::<T>::insert(&controller, ledger);
CurrentEra::<T>::put(EraIndex::max_value());
let ledger = Ledger::<T>::get(&controller).ok_or("ledger not created before")?;
let original_total: BalanceOf<T> = ledger.total;
whitelist_account!(controller);
}: withdraw_unbonded(RawOrigin::Signed(controller.clone()), s)
verify {
assert!(!Ledger::<T>::contains_key(controller));
assert!(!T::SortedListProvider::contains(&stash));
}
validate {
let (stash, controller) = create_stash_controller::<T>(USER_SEED, 100, Default::default())?;
// clean up any existing state.
clear_validators_and_nominators::<T>();
let origin_weight = MinNominatorBond::<T>::get().max(T::Currency::minimum_balance());
// setup a worst case scenario where the user calling validate was formerly a nominator so
// they must be removed from the list.
let scenario = ListScenario::<T>::new(origin_weight, true)?;
let controller = scenario.origin_controller1.clone();
let stash = scenario.origin_stash1.clone();
assert!(T::SortedListProvider::contains(&stash));
let prefs = ValidatorPrefs::default();
whitelist_account!(controller);
}: _(RawOrigin::Signed(controller), prefs)
verify {
assert!(Validators::<T>::contains_key(stash));
assert!(Validators::<T>::contains_key(&stash));
assert!(!T::SortedListProvider::contains(&stash));
}
kick {
@@ -225,7 +360,7 @@ benchmarks! {
// these are the other validators; there are `T::MAX_NOMINATIONS - 1` of them, so
// there are a total of `T::MAX_NOMINATIONS` validators in the system.
let rest_of_validators = create_validators::<T>(T::MAX_NOMINATIONS - 1, 100)?;
let rest_of_validators = create_validators_with_seed::<T>(T::MAX_NOMINATIONS - 1, 100, 415)?;
// this is the validator that will be kicking.
let (stash, controller) = create_stash_controller::<T>(
@@ -282,18 +417,50 @@ benchmarks! {
// Worst case scenario, T::MAX_NOMINATIONS
nominate {
let n in 1 .. T::MAX_NOMINATIONS;
let (stash, controller) = create_stash_controller::<T>(n + 1, 100, Default::default())?;
let validators = create_validators::<T>(n, 100)?;
// clean up any existing state.
clear_validators_and_nominators::<T>();
let origin_weight = MinNominatorBond::<T>::get().max(T::Currency::minimum_balance());
// setup a worst case list scenario. Note we don't care about the destination position, because
// we are just doing an insert into the origin position.
let scenario = ListScenario::<T>::new(origin_weight, true)?;
let (stash, controller) = create_stash_controller_with_balance::<T>(
SEED + T::MAX_NOMINATIONS + 1, // make sure the account does not conflict with others
origin_weight,
Default::default(),
).unwrap();
assert!(!Nominators::<T>::contains_key(&stash));
assert!(!T::SortedListProvider::contains(&stash));
let validators = create_validators::<T>(n, 100).unwrap();
whitelist_account!(controller);
}: _(RawOrigin::Signed(controller), validators)
verify {
assert!(Nominators::<T>::contains_key(stash));
assert!(Nominators::<T>::contains_key(&stash));
assert!(T::SortedListProvider::contains(&stash))
}
chill {
let (_, controller) = create_stash_controller::<T>(USER_SEED, 100, Default::default())?;
// clean up any existing state.
clear_validators_and_nominators::<T>();
let origin_weight = MinNominatorBond::<T>::get().max(T::Currency::minimum_balance());
// setup a worst case list scenario. Note that we don't care about the setup of the
// destination position because we are doing a removal from the list but no insert.
let scenario = ListScenario::<T>::new(origin_weight, true)?;
let controller = scenario.origin_controller1.clone();
let stash = scenario.origin_stash1.clone();
assert!(T::SortedListProvider::contains(&stash));
whitelist_account!(controller);
}: _(RawOrigin::Signed(controller))
verify {
assert!(!T::SortedListProvider::contains(&stash));
}
set_payee {
let (stash, controller) = create_stash_controller::<T>(USER_SEED, 100, Default::default())?;
@@ -345,11 +512,23 @@ benchmarks! {
force_unstake {
// Slashing Spans
let s in 0 .. MAX_SPANS;
let (stash, controller) = create_stash_controller::<T>(0, 100, Default::default())?;
// Clean up any existing state.
clear_validators_and_nominators::<T>();
let origin_weight = MinNominatorBond::<T>::get().max(T::Currency::minimum_balance());
// setup a worst case list scenario. Note that we don't care about the setup of the
// destination position because we are doing a removal from the list but no insert.
let scenario = ListScenario::<T>::new(origin_weight, true)?;
let controller = scenario.origin_controller1.clone();
let stash = scenario.origin_stash1.clone();
assert!(T::SortedListProvider::contains(&stash));
add_slashing_spans::<T>(&stash, s);
}: _(RawOrigin::Root, stash, s)
}: _(RawOrigin::Root, stash.clone(), s)
verify {
assert!(!Ledger::<T>::contains_key(&controller));
assert!(!T::SortedListProvider::contains(&stash));
}
cancel_deferred_slash {
@@ -438,19 +617,46 @@ benchmarks! {
rebond {
let l in 1 .. MAX_UNLOCKING_CHUNKS as u32;
let (_, controller) = create_stash_controller::<T>(USER_SEED, 100, Default::default())?;
let mut staking_ledger = Ledger::<T>::get(controller.clone()).unwrap();
// clean up any existing state.
clear_validators_and_nominators::<T>();
let origin_weight = MinNominatorBond::<T>::get()
.max(T::Currency::minimum_balance())
// we use 100 to play friendly with the list threshold values in the mock
.max(100u32.into());
// setup a worst case list scenario.
let scenario = ListScenario::<T>::new(origin_weight, true)?;
let dest_weight = scenario.dest_weight.clone();
// rebond an amount that will give the user dest_weight
let rebond_amount = dest_weight - origin_weight;
// spread that amount to rebond across `l` unlocking chunks,
let value = rebond_amount / l.into();
// if `value` is zero, we need a greater delta between dest <=> origin weight
assert_ne!(value, Zero::zero());
// so the sum of unlocking chunks puts voter into the dest bag.
assert!(value * l.into() + origin_weight > origin_weight);
assert!(value * l.into() + origin_weight <= dest_weight);
let unlock_chunk = UnlockChunk::<BalanceOf<T>> {
value: 1u32.into(),
value,
era: EraIndex::zero(),
};
let stash = scenario.origin_stash1.clone();
let controller = scenario.origin_controller1.clone();
let mut staking_ledger = Ledger::<T>::get(controller.clone()).unwrap();
for _ in 0 .. l {
staking_ledger.unlocking.push(unlock_chunk.clone())
}
Ledger::<T>::insert(controller.clone(), staking_ledger.clone());
let original_bonded: BalanceOf<T> = staking_ledger.active;
whitelist_account!(controller);
}: _(RawOrigin::Signed(controller.clone()), (l + 100).into())
}: _(RawOrigin::Signed(controller.clone()), rebond_amount)
verify {
let ledger = Ledger::<T>::get(&controller).ok_or("ledger not created after")?;
let new_bonded: BalanceOf<T> = ledger.active;
@@ -477,19 +683,28 @@ benchmarks! {
reap_stash {
let s in 1 .. MAX_SPANS;
let (stash, controller) = create_stash_controller::<T>(0, 100, Default::default())?;
Staking::<T>::validate(RawOrigin::Signed(controller.clone()).into(), ValidatorPrefs::default())?;
// clean up any existing state.
clear_validators_and_nominators::<T>();
let origin_weight = MinNominatorBond::<T>::get().max(T::Currency::minimum_balance());
// setup a worst case list scenario. Note that we don't care about the setup of the
// destination position because we are doing a removal from the list but no insert.
let scenario = ListScenario::<T>::new(origin_weight, true)?;
let controller = scenario.origin_controller1.clone();
let stash = scenario.origin_stash1.clone();
add_slashing_spans::<T>(&stash, s);
T::Currency::make_free_balance_be(&stash, T::Currency::minimum_balance());
whitelist_account!(controller);
assert!(Bonded::<T>::contains_key(&stash));
assert!(Validators::<T>::contains_key(&stash));
assert!(T::SortedListProvider::contains(&stash));
whitelist_account!(controller);
}: _(RawOrigin::Signed(controller), stash.clone(), s)
verify {
assert!(!Bonded::<T>::contains_key(&stash));
assert!(!Validators::<T>::contains_key(&stash));
assert!(!T::SortedListProvider::contains(&stash));
}
new_era {
@@ -590,17 +805,21 @@ benchmarks! {
// total number of slashing spans. Assigned to validators randomly.
let s in 1 .. 20;
let validators = create_validators_with_nominators_for_era::<T>(v, n, T::MAX_NOMINATIONS as usize, false, None)?
.into_iter()
.map(|v| T::Lookup::lookup(v).unwrap())
.collect::<Vec<_>>();
let validators = create_validators_with_nominators_for_era::<T>(
v, n, T::MAX_NOMINATIONS as usize, false, None
)?
.into_iter()
.map(|v| T::Lookup::lookup(v).unwrap())
.collect::<Vec<_>>();
(0..s).for_each(|index| {
add_slashing_spans::<T>(&validators[index as usize], 10);
});
let num_voters = (v + n) as usize;
}: {
let voters = <Staking<T>>::get_npos_voters();
assert_eq!(voters.len() as u32, v + n);
let voters = <Staking<T>>::get_npos_voters(None);
assert_eq!(voters.len(), num_voters);
}
get_npos_targets {
@@ -609,7 +828,9 @@ benchmarks! {
// number of nominator intention.
let n = MAX_NOMINATORS;
let _ = create_validators_with_nominators_for_era::<T>(v, n, T::MAX_NOMINATIONS as usize, false, None)?;
let _ = create_validators_with_nominators_for_era::<T>(
v, n, T::MAX_NOMINATIONS as usize, false, None
)?;
}: {
let targets = <Staking<T>>::get_npos_targets();
assert_eq!(targets.len() as u32, v);
@@ -633,8 +854,18 @@ benchmarks! {
}
chill_other {
let (_, controller) = create_stash_controller::<T>(USER_SEED, 100, Default::default())?;
Staking::<T>::validate(RawOrigin::Signed(controller.clone()).into(), ValidatorPrefs::default())?;
// clean up any existing state.
clear_validators_and_nominators::<T>();
let origin_weight = MinNominatorBond::<T>::get().max(T::Currency::minimum_balance());
// setup a worst case list scenario. Note that we don't care about the setup of the
// destination position because we are doing a removal from the list but no insert.
let scenario = ListScenario::<T>::new(origin_weight, true)?;
let controller = scenario.origin_controller1.clone();
let stash = scenario.origin_stash1.clone();
assert!(T::SortedListProvider::contains(&stash));
Staking::<T>::set_staking_limits(
RawOrigin::Root.into(),
BalanceOf::<T>::max_value(),
@@ -643,10 +874,11 @@ benchmarks! {
Some(0),
Some(Percent::from_percent(0))
)?;
let caller = whitelisted_caller();
}: _(RawOrigin::Signed(caller), controller.clone())
verify {
assert!(!Validators::<T>::contains_key(controller));
assert!(!T::SortedListProvider::contains(&stash));
}
}
@@ -658,7 +890,7 @@ mod tests {
#[test]
fn create_validators_with_nominators_for_era_works() {
ExtBuilder::default().has_stakers(true).build_and_execute(|| {
ExtBuilder::default().build_and_execute(|| {
let v = 10;
let n = 100;
@@ -674,6 +906,9 @@ mod tests {
let count_validators = Validators::<Test>::iter().count();
let count_nominators = Nominators::<Test>::iter().count();
assert_eq!(count_validators, CounterForValidators::<Test>::get() as usize);
assert_eq!(count_nominators, CounterForNominators::<Test>::get() as usize);
assert_eq!(count_validators, v as usize);
assert_eq!(count_nominators, n as usize);
});
@@ -681,7 +916,7 @@ mod tests {
#[test]
fn create_validator_with_nominators_works() {
ExtBuilder::default().has_stakers(true).build_and_execute(|| {
ExtBuilder::default().build_and_execute(|| {
let n = 10;
let (validator_stash, nominators) = create_validator_with_nominators::<Test>(
@@ -706,7 +941,7 @@ mod tests {
#[test]
fn add_slashing_spans_works() {
ExtBuilder::default().has_stakers(true).build_and_execute(|| {
ExtBuilder::default().build_and_execute(|| {
let n = 10;
let (validator_stash, _nominators) = create_validator_with_nominators::<Test>(
@@ -738,7 +973,7 @@ mod tests {
#[test]
fn test_payout_all() {
ExtBuilder::default().has_stakers(true).build_and_execute(|| {
ExtBuilder::default().build_and_execute(|| {
let v = 10;
let n = 100;
+13 -4
View File
@@ -100,6 +100,13 @@
//!
//! An account can become a nominator via the [`nominate`](Call::nominate) call.
//!
//! #### Voting
//!
//! Staking is closely related to elections; actual validators are chosen from among all potential
//! validators via election by the potential validators and nominators. To reduce use of the phrase
//! "potential validators and nominators", we often use the term **voters**, who are simply
//! the union of potential validators and nominators.
//!
//! #### Rewards and Slash
//!
//! The **reward and slashing** procedure is the core of the Staking pallet, attempting to _embrace
@@ -264,15 +271,15 @@
//! - [Session](../pallet_session/index.html): Used to manage sessions. Also, a list of new
//! validators is stored in the Session pallet's `Validators` at the end of each era.
#![recursion_limit = "128"]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
#[cfg(test)]
mod mock;
#[cfg(any(feature = "runtime-benchmarks", test))]
pub mod testing_utils;
#[cfg(test)]
pub(crate) mod mock;
#[cfg(test)]
mod tests;
@@ -420,6 +427,7 @@ pub struct UnlockChunk<Balance: HasCompact> {
}
/// The ledger of a (bonded) stash.
#[cfg_attr(feature = "runtime-benchmarks", derive(Default))]
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
pub struct StakingLedger<AccountId, Balance: HasCompact> {
/// The stash account whose balance is actually locked and at stake.
@@ -727,11 +735,12 @@ enum Releases {
V5_0_0, // blockable validators.
V6_0_0, // removal of all storage associated with offchain phragmen.
V7_0_0, // keep track of number of nominators / validators in map
V8_0_0, // populate `SortedListProvider`.
}
impl Default for Releases {
fn default() -> Self {
Releases::V7_0_0
Releases::V8_0_0
}
}
+50
View File
@@ -18,6 +18,56 @@
use super::*;
pub mod v8 {
use frame_election_provider_support::SortedListProvider;
use frame_support::traits::Get;
use crate::{Config, Nominators, Pallet, StorageVersion, Weight};
#[cfg(feature = "try-runtime")]
pub fn pre_migrate<T: Config>() -> Result<(), &'static str> {
frame_support::ensure!(
StorageVersion::<T>::get() == crate::Releases::V7_0_0,
"must upgrade linearly"
);
crate::log!(info, "👜 staking bags-list migration passes PRE migrate checks ✅",);
Ok(())
}
/// Migration to sorted [`SortedListProvider`].
pub fn migrate<T: Config>() -> Weight {
if StorageVersion::<T>::get() == crate::Releases::V7_0_0 {
crate::log!(info, "migrating staking to Releases::V8_0_0");
let migrated = T::SortedListProvider::regenerate(
Nominators::<T>::iter().map(|(id, _)| id),
Pallet::<T>::weight_of_fn(),
);
debug_assert_eq!(T::SortedListProvider::sanity_check(), Ok(()));
StorageVersion::<T>::put(crate::Releases::V8_0_0);
crate::log!(
info,
"👜 completed staking migration to Releases::V8_0_0 with {} voters migrated",
migrated,
);
T::BlockWeights::get().max_block
} else {
T::DbWeight::get().reads(1)
}
}
#[cfg(feature = "try-runtime")]
pub fn post_migrate<T: Config>() -> Result<(), &'static str> {
T::SortedListProvider::sanity_check()
.map_err(|_| "SortedListProvider is not in a sane state.")?;
crate::log!(info, "👜 staking bags-list migration passes POST migrate checks ✅",);
Ok(())
}
}
pub mod v7 {
use super::*;
+33 -11
View File
@@ -17,9 +17,8 @@
//! Test utilities
use crate as staking;
use crate::*;
use frame_election_provider_support::onchain;
use crate::{self as pallet_staking, *};
use frame_election_provider_support::{onchain, SortedListProvider};
use frame_support::{
assert_ok, parameter_types,
traits::{
@@ -104,8 +103,9 @@ frame_support::construct_runtime!(
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: staking::{Pallet, Call, Config<T>, Storage, Event<T>},
Staking: pallet_staking::{Pallet, Call, Config<T>, Storage, Event<T>},
Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>},
BagsList: pallet_bags_list::{Pallet, Call, Storage, Event<T>},
}
);
@@ -242,12 +242,26 @@ impl OnUnbalanced<NegativeImbalanceOf<Test>> for RewardRemainderMock {
}
}
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;
}
impl pallet_bags_list::Config for Test {
type Event = Event;
type WeightInfo = ();
type VoteWeightProvider = Staking;
type BagThresholds = BagThresholds;
}
impl onchain::Config for Test {
type Accuracy = Perbill;
type DataProvider = Staking;
}
impl Config for Test {
impl crate::pallet::pallet::Config for Test {
const MAX_NOMINATIONS: u32 = 16;
type Currency = Balances;
type UnixTime = Timestamp;
@@ -267,6 +281,8 @@ impl Config for Test {
type ElectionProvider = onchain::OnChainSequentialPhragmen<Self>;
type GenesisElectionProvider = Self::ElectionProvider;
type WeightInfo = ();
// NOTE: consider a macro and use `UseNominatorsMap<Self>` as well.
type SortedListProvider = BagsList;
}
impl<LocalCall> frame_system::offchain::SendTransactionTypes<LocalCall> for Test
@@ -469,7 +485,7 @@ impl ExtBuilder {
stakers.extend(self.stakers)
}
let _ = staking::GenesisConfig::<Test> {
let _ = pallet_staking::GenesisConfig::<Test> {
stakers,
validator_count: self.validator_count,
minimum_validator_count: self.minimum_validator_count,
@@ -533,6 +549,10 @@ fn check_count() {
let validator_count = Validators::<Test>::iter().count() as u32;
assert_eq!(nominator_count, CounterForNominators::<Test>::get());
assert_eq!(validator_count, CounterForValidators::<Test>::get());
// the voters that the `SortedListProvider` list is storing for us.
let external_voters = <Test as Config>::SortedListProvider::count();
assert_eq!(external_voters, nominator_count);
}
fn check_ledgers() {
@@ -625,10 +645,14 @@ pub(crate) fn current_era() -> EraIndex {
Staking::current_era().unwrap()
}
pub(crate) fn bond_validator(stash: AccountId, ctrl: AccountId, val: Balance) {
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()));
}
@@ -638,9 +662,7 @@ pub(crate) fn bond_nominator(
val: Balance,
target: Vec<AccountId>,
) {
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));
bond(stash, ctrl, val);
assert_ok!(Staking::nominate(Origin::signed(ctrl), target));
}
@@ -833,7 +855,7 @@ macro_rules! assert_session_era {
};
}
pub(crate) fn staking_events() -> Vec<staking::Event<Test>> {
pub(crate) fn staking_events() -> Vec<crate::Event<Test>> {
System::events()
.into_iter()
.map(|r| r.event)
+201 -52
View File
@@ -17,7 +17,10 @@
//! Implementations for the Staking FRAME Pallet.
use frame_election_provider_support::{data_provider, ElectionProvider, Supports, VoteWeight};
use frame_election_provider_support::{
data_provider, ElectionDataProvider, ElectionProvider, SortedListProvider, Supports,
VoteWeight, VoteWeightProvider,
};
use frame_support::{
pallet_prelude::*,
traits::{
@@ -26,6 +29,7 @@ use frame_support::{
},
weights::{Weight, WithPostDispatchInfo},
};
use frame_system::pallet_prelude::BlockNumberFor;
use pallet_session::historical;
use sp_runtime::{
traits::{Bounded, Convert, SaturatedConversion, Saturating, Zero},
@@ -64,7 +68,7 @@ impl<T: Config> Pallet<T> {
///
/// This prevents call sites from repeatedly requesting `total_issuance` from backend. But it is
/// important to be only used while the total issuance is not changing.
pub fn slashable_balance_of_fn() -> Box<dyn Fn(&T::AccountId) -> VoteWeight> {
pub fn weight_of_fn() -> Box<dyn Fn(&T::AccountId) -> VoteWeight> {
// NOTE: changing this to unboxed `impl Fn(..)` return type and the pallet will still
// compile, while some types in mock fail to resolve.
let issuance = T::Currency::total_issuance();
@@ -73,6 +77,12 @@ impl<T: Config> Pallet<T> {
})
}
/// Same as `weight_of_fn`, but made for one time use.
pub fn weight_of(who: &T::AccountId) -> VoteWeight {
let issuance = T::Currency::total_issuance();
Self::slashable_balance_of_vote_weight(who, issuance)
}
pub(super) fn do_payout_stakers(
validator_stash: T::AccountId,
era: EraIndex,
@@ -629,54 +639,92 @@ impl<T: Config> Pallet<T> {
/// Get all of the voters that are eligible for the npos election.
///
/// This will use all on-chain nominators, and all the validators will inject a self vote.
/// `maybe_max_len` can imposes a cap on the number of voters returned; First all the validator
/// are included in no particular order, then remainder is taken from the nominators, as
/// returned by [`Config::SortedListProvider`].
///
/// This will use nominators, and all the validators will inject a self vote.
///
/// This function is self-weighing as [`DispatchClass::Mandatory`].
///
/// ### Slashing
///
/// All nominations that have been submitted before the last non-zero slash of the validator are
/// auto-chilled.
pub fn get_npos_voters() -> Vec<(T::AccountId, VoteWeight, Vec<T::AccountId>)> {
let weight_of = Self::slashable_balance_of_fn();
let mut all_voters = Vec::new();
/// auto-chilled, but still count towards the limit imposed by `maybe_max_len`.
pub fn get_npos_voters(
maybe_max_len: Option<usize>,
) -> Vec<(T::AccountId, VoteWeight, Vec<T::AccountId>)> {
let max_allowed_len = {
let nominator_count = CounterForNominators::<T>::get() as usize;
let validator_count = CounterForValidators::<T>::get() as usize;
let all_voter_count = validator_count.saturating_add(nominator_count);
maybe_max_len.unwrap_or(all_voter_count).min(all_voter_count)
};
let mut validator_count = 0u32;
for (validator, _) in <Validators<T>>::iter() {
let mut all_voters = Vec::<_>::with_capacity(max_allowed_len);
// first, grab all validators in no particular order, capped by the maximum allowed length.
let mut validators_taken = 0u32;
for (validator, _) in <Validators<T>>::iter().take(max_allowed_len) {
// Append self vote.
let self_vote = (validator.clone(), weight_of(&validator), vec![validator.clone()]);
let self_vote =
(validator.clone(), Self::weight_of(&validator), vec![validator.clone()]);
all_voters.push(self_vote);
validator_count.saturating_inc();
validators_taken.saturating_inc();
}
// Collect all slashing spans into a BTreeMap for further queries.
// .. and grab whatever we have left from nominators.
let nominators_quota = (max_allowed_len as u32).saturating_sub(validators_taken);
let slashing_spans = <SlashingSpans<T>>::iter().collect::<BTreeMap<_, _>>();
let mut nominator_count = 0u32;
for (nominator, nominations) in Nominators::<T>::iter() {
let Nominations { submitted_in, mut targets, suppressed: _ } = nominations;
// track the count of nominators added to `all_voters
let mut nominators_taken = 0u32;
// track every nominator iterated over, but not necessarily added to `all_voters`
let mut nominators_seen = 0u32;
// Filter out nomination targets which were nominated before the most recent
// slashing span.
targets.retain(|stash| {
slashing_spans
.get(stash)
.map_or(true, |spans| submitted_in >= spans.last_nonzero_slash())
});
let mut nominators_iter = T::SortedListProvider::iter();
while nominators_taken < nominators_quota && nominators_seen < nominators_quota * 2 {
let nominator = match nominators_iter.next() {
Some(nominator) => {
nominators_seen.saturating_inc();
nominator
},
None => break,
};
if !targets.is_empty() {
let vote_weight = weight_of(&nominator);
all_voters.push((nominator, vote_weight, targets));
nominator_count.saturating_inc();
if let Some(Nominations { submitted_in, mut targets, suppressed: _ }) =
<Nominators<T>>::get(&nominator)
{
targets.retain(|stash| {
slashing_spans
.get(stash)
.map_or(true, |spans| submitted_in >= spans.last_nonzero_slash())
});
if !targets.len().is_zero() {
all_voters.push((nominator.clone(), Self::weight_of(&nominator), targets));
nominators_taken.saturating_inc();
}
} else {
log!(error, "invalid item in `SortedListProvider`: {:?}", nominator)
}
}
// all_voters should have not re-allocated.
debug_assert!(all_voters.capacity() == max_allowed_len);
Self::register_weight(T::WeightInfo::get_npos_voters(
validator_count,
nominator_count,
validators_taken,
nominators_taken,
slashing_spans.len() as u32,
));
log!(
info,
"generated {} npos voters, {} from validators and {} nominators",
all_voters.len(),
validators_taken,
nominators_taken
);
all_voters
}
@@ -698,34 +746,59 @@ impl<T: Config> Pallet<T> {
}
/// This function will add a nominator to the `Nominators` storage map,
/// and keep track of the `CounterForNominators`.
/// [`SortedListProvider`] and keep track of the `CounterForNominators`.
///
/// If the nominator already exists, their nominations will be updated.
///
/// NOTE: you must ALWAYS use this function to add nominator or update their targets. Any access
/// to `Nominators`, its counter, or `VoterList` outside of this function is almost certainly
/// wrong.
pub fn do_add_nominator(who: &T::AccountId, nominations: Nominations<T::AccountId>) {
if !Nominators::<T>::contains_key(who) {
CounterForNominators::<T>::mutate(|x| x.saturating_inc())
// maybe update the counter.
CounterForNominators::<T>::mutate(|x| x.saturating_inc());
// maybe update sorted list. Error checking is defensive-only - this should never fail.
if T::SortedListProvider::on_insert(who.clone(), Self::weight_of(who)).is_err() {
log!(warn, "attempt to insert duplicate nominator ({:#?})", who);
debug_assert!(false, "attempt to insert duplicate nominator");
};
debug_assert_eq!(T::SortedListProvider::sanity_check(), Ok(()));
}
Nominators::<T>::insert(who, nominations);
}
/// This function will remove a nominator from the `Nominators` storage map,
/// and keep track of the `CounterForNominators`.
/// [`SortedListProvider`] and keep track of the `CounterForNominators`.
///
/// Returns true if `who` was removed from `Nominators`, otherwise false.
///
/// NOTE: you must ALWAYS use this function to remove a nominator from the system. Any access to
/// `Nominators`, its counter, or `VoterList` outside of this function is almost certainly
/// wrong.
pub fn do_remove_nominator(who: &T::AccountId) -> bool {
if Nominators::<T>::contains_key(who) {
Nominators::<T>::remove(who);
CounterForNominators::<T>::mutate(|x| x.saturating_dec());
T::SortedListProvider::on_remove(who);
debug_assert_eq!(T::SortedListProvider::sanity_check(), Ok(()));
debug_assert_eq!(CounterForNominators::<T>::get(), T::SortedListProvider::count());
true
} else {
false
}
}
/// This function will add a validator to the `Validators` storage map,
/// and keep track of the `CounterForValidators`.
/// This function will add a validator to the `Validators` storage map, and keep track of the
/// `CounterForValidators`.
///
/// If the validator already exists, their preferences will be updated.
///
/// NOTE: you must ALWAYS use this function to add a validator to the system. Any access to
/// `Validators`, its counter, or `VoterList` outside of this function is almost certainly
/// wrong.
pub fn do_add_validator(who: &T::AccountId, prefs: ValidatorPrefs) {
if !Validators::<T>::contains_key(who) {
CounterForValidators::<T>::mutate(|x| x.saturating_inc())
@@ -737,6 +810,10 @@ impl<T: Config> Pallet<T> {
/// and keep track of the `CounterForValidators`.
///
/// Returns true if `who` was removed from `Validators`, otherwise false.
///
/// NOTE: you must ALWAYS use this function to remove a validator from the system. Any access to
/// `Validators`, its counter, or `VoterList` outside of this function is almost certainly
/// wrong.
pub fn do_remove_validator(who: &T::AccountId) -> bool {
if Validators::<T>::contains_key(who) {
Validators::<T>::remove(who);
@@ -758,10 +835,9 @@ impl<T: Config> Pallet<T> {
}
}
impl<T: Config> frame_election_provider_support::ElectionDataProvider<T::AccountId, T::BlockNumber>
for Pallet<T>
{
impl<T: Config> ElectionDataProvider<T::AccountId, BlockNumberFor<T>> for Pallet<T> {
const MAXIMUM_VOTES_PER_VOTER: u32 = T::MAX_NOMINATIONS;
fn desired_targets() -> data_provider::Result<u32> {
Self::register_weight(T::DbWeight::get().reads(1));
Ok(Self::validator_count())
@@ -770,30 +846,26 @@ impl<T: Config> frame_election_provider_support::ElectionDataProvider<T::Account
fn voters(
maybe_max_len: Option<usize>,
) -> data_provider::Result<Vec<(T::AccountId, VoteWeight, Vec<T::AccountId>)>> {
let nominator_count = CounterForNominators::<T>::get();
let validator_count = CounterForValidators::<T>::get();
let voter_count = nominator_count.saturating_add(validator_count) as usize;
debug_assert!(<Nominators<T>>::iter().count() as u32 == CounterForNominators::<T>::get());
debug_assert!(<Validators<T>>::iter().count() as u32 == CounterForValidators::<T>::get());
debug_assert_eq!(
CounterForNominators::<T>::get(),
T::SortedListProvider::count(),
"voter_count must be accurate",
);
// register the extra 2 reads
Self::register_weight(T::DbWeight::get().reads(2));
// This can never fail -- if `maybe_max_len` is `Some(_)` we handle it.
let voters = Self::get_npos_voters(maybe_max_len);
debug_assert!(maybe_max_len.map_or(true, |max| voters.len() <= max));
if maybe_max_len.map_or(false, |max_len| voter_count > max_len) {
return Err("Voter snapshot too big")
}
Ok(Self::get_npos_voters())
Ok(voters)
}
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<T::AccountId>> {
let target_count = CounterForValidators::<T>::get() as usize;
let target_count = CounterForValidators::<T>::get();
// register the extra 1 read
Self::register_weight(T::DbWeight::get().reads(1));
if maybe_max_len.map_or(false, |max_len| target_count > max_len) {
// We can't handle this case yet -- return an error.
if maybe_max_len.map_or(false, |max_len| target_count > max_len as u32) {
return Err("Target snapshot too big")
}
@@ -879,6 +951,9 @@ impl<T: Config> frame_election_provider_support::ElectionDataProvider<T::Account
<Ledger<T>>::remove_all(None);
<Validators<T>>::remove_all(None);
<Nominators<T>>::remove_all(None);
<CounterForNominators<T>>::kill();
<CounterForValidators<T>>::kill();
let _ = T::SortedListProvider::clear(None);
}
#[cfg(feature = "runtime-benchmarks")]
@@ -1152,3 +1227,77 @@ where
consumed_weight
}
}
impl<T: Config> VoteWeightProvider<T::AccountId> for Pallet<T> {
fn vote_weight(who: &T::AccountId) -> VoteWeight {
Self::weight_of(who)
}
#[cfg(feature = "runtime-benchmarks")]
fn set_vote_weight_of(who: &T::AccountId, weight: VoteWeight) {
// this will clearly results in an inconsistent state, but it should not matter for a
// benchmark.
use sp_std::convert::TryInto;
let active: BalanceOf<T> = weight.try_into().map_err(|_| ()).unwrap();
let mut ledger = Self::ledger(who).unwrap_or_default();
ledger.active = active;
<Ledger<T>>::insert(who, ledger);
<Bonded<T>>::insert(who, who);
// also, we play a trick to make sure that a issuance based-`CurrencyToVote` behaves well:
// This will make sure that total issuance is zero, thus the currency to vote will be a 1-1
// conversion.
let imbalance = T::Currency::burn(T::Currency::total_issuance());
// kinda ugly, but gets the job done. The fact that this works here is a HUGE exception.
// Don't try this pattern in other places.
sp_std::mem::forget(imbalance);
}
}
/// A simple voter list implementation that does not require any additional pallets. Note, this
/// does not provided nominators in sorted ordered. If you desire nominators in a sorted order take
/// a look at [`pallet-bags-list].
pub struct UseNominatorsMap<T>(sp_std::marker::PhantomData<T>);
impl<T: Config> SortedListProvider<T::AccountId> for UseNominatorsMap<T> {
type Error = ();
/// Returns iterator over voter list, which can have `take` called on it.
fn iter() -> Box<dyn Iterator<Item = T::AccountId>> {
Box::new(Nominators::<T>::iter().map(|(n, _)| n))
}
fn count() -> u32 {
CounterForNominators::<T>::get()
}
fn contains(id: &T::AccountId) -> bool {
Nominators::<T>::contains_key(id)
}
fn on_insert(_: T::AccountId, _weight: VoteWeight) -> Result<(), Self::Error> {
// nothing to do on insert.
Ok(())
}
fn on_update(_: &T::AccountId, _weight: VoteWeight) {
// nothing to do on update.
}
fn on_remove(_: &T::AccountId) {
// nothing to do on remove.
}
fn regenerate(
_: impl IntoIterator<Item = T::AccountId>,
_: Box<dyn Fn(&T::AccountId) -> VoteWeight>,
) -> u32 {
// nothing to do upon regenerate.
0
}
fn sanity_check() -> Result<(), &'static str> {
Ok(())
}
fn clear(maybe_count: Option<u32>) -> u32 {
Nominators::<T>::remove_all(maybe_count);
if let Some(count) = maybe_count {
CounterForNominators::<T>::mutate(|noms| *noms - count);
count
} else {
CounterForNominators::<T>::take()
}
}
}
+41 -4
View File
@@ -17,6 +17,7 @@
//! Staking FRAME Pallet.
use frame_election_provider_support::SortedListProvider;
use frame_support::{
pallet_prelude::*,
traits::{
@@ -38,7 +39,7 @@ mod impls;
pub use impls::*;
use crate::{
migrations, slashing, weights::WeightInfo, ActiveEraInfo, BalanceOf, EraIndex, EraPayout,
log, migrations, slashing, weights::WeightInfo, ActiveEraInfo, BalanceOf, EraIndex, EraPayout,
EraRewardPoints, Exposure, Forcing, NegativeImbalanceOf, Nominations, PositiveImbalanceOf,
Releases, RewardDestination, SessionInterface, StakingLedger, UnappliedSlash, UnlockChunk,
ValidatorPrefs,
@@ -140,6 +141,11 @@ pub mod pallet {
#[pallet::constant]
type MaxNominatorRewardedPerValidator: Get<u32>;
/// Something that can provide a sorted list of voters in a somewhat sorted way. The
/// original use case for this was designed with [`pallet_bags_list::Pallet`] in mind. If
/// the bags-list is not desired, [`impls::UseNominatorsMap`] is likely the desired option.
type SortedListProvider: SortedListProvider<Self::AccountId>;
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
}
@@ -492,6 +498,13 @@ pub mod pallet {
MinValidatorBond::<T>::put(self.min_validator_bond);
for &(ref stash, ref controller, balance, ref status) in &self.stakers {
log!(
trace,
"inserting genesis staker: {:?} => {:?} => {:?}",
stash,
balance,
status
);
assert!(
T::Currency::free_balance(&stash) >= balance,
"Stash does not have enough balance to bond."
@@ -514,6 +527,13 @@ pub mod pallet {
_ => Ok(()),
});
}
// all voters are reported to the `SortedListProvider`.
assert_eq!(
T::SortedListProvider::count(),
CounterForNominators::<T>::get(),
"not all genesis stakers were inserted into sorted list provider, something is wrong."
);
}
}
@@ -763,8 +783,15 @@ pub mod pallet {
Error::<T>::InsufficientBond
);
Self::deposit_event(Event::<T>::Bonded(stash, extra));
// NOTE: ledger must be updated prior to calling `Self::weight_of`.
Self::update_ledger(&controller, &ledger);
// update this staker in the sorted list, if they exist in it.
if T::SortedListProvider::contains(&stash) {
T::SortedListProvider::on_update(&stash, Self::weight_of(&ledger.stash));
debug_assert_eq!(T::SortedListProvider::sanity_check(), Ok(()));
}
Self::deposit_event(Event::<T>::Bonded(stash.clone(), extra));
}
Ok(())
}
@@ -823,7 +850,14 @@ pub mod pallet {
// Note: in case there is no current era it is fine to bond one era more.
let era = Self::current_era().unwrap_or(0) + T::BondingDuration::get();
ledger.unlocking.push(UnlockChunk { value, era });
// NOTE: ledger must be updated prior to calling `Self::weight_of`.
Self::update_ledger(&controller, &ledger);
// update this staker in the sorted list, if they exist in it.
if T::SortedListProvider::contains(&ledger.stash) {
T::SortedListProvider::on_update(&ledger.stash, Self::weight_of(&ledger.stash));
}
Self::deposit_event(Event::<T>::Unbonded(ledger.stash, value));
}
Ok(())
@@ -1319,7 +1353,12 @@ pub mod pallet {
ensure!(ledger.active >= T::Currency::minimum_balance(), Error::<T>::InsufficientBond);
Self::deposit_event(Event::<T>::Bonded(ledger.stash.clone(), value));
// NOTE: ledger must be updated prior to calling `Self::weight_of`.
Self::update_ledger(&controller, &ledger);
if T::SortedListProvider::contains(&ledger.stash) {
T::SortedListProvider::on_update(&ledger.stash, Self::weight_of(&ledger.stash));
}
let removed_chunks = 1u32 // for the case where the last iterated chunk is not removed
.saturating_add(initial_unlocking)
@@ -1492,8 +1531,6 @@ pub mod pallet {
///
/// This can be helpful if bond requirements are updated, and we need to remove old users
/// who do not satisfy these requirements.
// TODO: Maybe we can deprecate `chill` in the future.
// https://github.com/paritytech/substrate/issues/9111
#[pallet::weight(T::WeightInfo::chill_other())]
pub fn chill_other(origin: OriginFor<T>, controller: T::AccountId) -> DispatchResult {
// Anyone can call this function.
+46 -4
View File
@@ -27,6 +27,7 @@ use rand_chacha::{
};
use sp_io::hashing::blake2_256;
use frame_election_provider_support::SortedListProvider;
use frame_support::{pallet_prelude::*, traits::Currency};
use sp_runtime::{traits::StaticLookup, Perbill};
use sp_std::prelude::*;
@@ -37,8 +38,11 @@ const SEED: u32 = 0;
pub fn clear_validators_and_nominators<T: Config>() {
Validators::<T>::remove_all(None);
CounterForValidators::<T>::kill();
// whenever we touch nominators counter we should update `T::SortedListProvider` as well.
Nominators::<T>::remove_all(None);
CounterForNominators::<T>::kill();
let _ = T::SortedListProvider::clear(None);
}
/// Grab a funded user.
@@ -49,9 +53,18 @@ pub fn create_funded_user<T: Config>(
) -> T::AccountId {
let user = account(string, n, SEED);
let balance = T::Currency::minimum_balance() * balance_factor.into();
T::Currency::make_free_balance_be(&user, balance);
// ensure T::CurrencyToVote will work correctly.
T::Currency::issue(balance);
let _ = T::Currency::make_free_balance_be(&user, balance);
user
}
/// Grab a funded user with max Balance.
pub fn create_funded_user_with_balance<T: Config>(
string: &'static str,
n: u32,
balance: BalanceOf<T>,
) -> T::AccountId {
let user = account(string, n, SEED);
let _ = T::Currency::make_free_balance_be(&user, balance);
user
}
@@ -75,6 +88,26 @@ pub fn create_stash_controller<T: Config>(
return Ok((stash, controller))
}
/// Create a stash and controller pair with fixed balance.
pub fn create_stash_controller_with_balance<T: Config>(
n: u32,
balance: crate::BalanceOf<T>,
destination: RewardDestination<T::AccountId>,
) -> Result<(T::AccountId, T::AccountId), &'static str> {
let stash = create_funded_user_with_balance::<T>("stash", n, balance);
let controller = create_funded_user_with_balance::<T>("controller", n, balance);
let controller_lookup: <T::Lookup as StaticLookup>::Source =
T::Lookup::unlookup(controller.clone());
Staking::<T>::bond(
RawOrigin::Signed(stash.clone()).into(),
controller_lookup,
balance,
destination,
)?;
Ok((stash, controller))
}
/// Create a stash and controller pair, where the controller is dead, and payouts go to controller.
/// This is used to test worst case payout scenarios.
pub fn create_stash_and_dead_controller<T: Config>(
@@ -101,11 +134,20 @@ pub fn create_stash_and_dead_controller<T: Config>(
pub fn create_validators<T: Config>(
max: u32,
balance_factor: u32,
) -> Result<Vec<<T::Lookup as StaticLookup>::Source>, &'static str> {
create_validators_with_seed::<T>(max, balance_factor, 0)
}
/// create `max` validators, with a seed to help unintentional prevent account collisions.
pub fn create_validators_with_seed<T: Config>(
max: u32,
balance_factor: u32,
seed: u32,
) -> Result<Vec<<T::Lookup as StaticLookup>::Source>, &'static str> {
let mut validators: Vec<<T::Lookup as StaticLookup>::Source> = Vec::with_capacity(max as usize);
for i in 0..max {
let (stash, controller) =
create_stash_controller::<T>(i, balance_factor, RewardDestination::Staked)?;
create_stash_controller::<T>(i + seed, balance_factor, RewardDestination::Staked)?;
let validator_prefs =
ValidatorPrefs { commission: Perbill::from_percent(50), ..Default::default() };
Staking::<T>::validate(RawOrigin::Signed(controller).into(), validator_prefs)?;
+162 -11
View File
@@ -18,7 +18,7 @@
//! Tests for the module.
use super::{Event, *};
use frame_election_provider_support::{ElectionProvider, Support};
use frame_election_provider_support::{ElectionProvider, SortedListProvider, Support};
use frame_support::{
assert_noop, assert_ok,
dispatch::WithPostDispatchInfo,
@@ -542,8 +542,8 @@ fn nominating_and_rewards_should_work() {
total: 1000 + 800,
own: 1000,
others: vec![
IndividualExposure { who: 3, value: 400 },
IndividualExposure { who: 1, value: 400 },
IndividualExposure { who: 3, value: 400 },
]
},
);
@@ -553,8 +553,8 @@ fn nominating_and_rewards_should_work() {
total: 1000 + 1200,
own: 1000,
others: vec![
IndividualExposure { who: 3, value: 600 },
IndividualExposure { who: 1, value: 600 },
IndividualExposure { who: 3, value: 600 },
]
},
);
@@ -1907,8 +1907,8 @@ fn bond_with_duplicate_vote_should_be_ignored_by_election_provider() {
assert_eq!(
supports,
vec![
(21, Support { total: 1800, voters: vec![(21, 1000), (3, 400), (1, 400)] }),
(31, Support { total: 2200, voters: vec![(31, 1000), (3, 600), (1, 600)] })
(21, Support { total: 1800, voters: vec![(21, 1000), (1, 400), (3, 400)] }),
(31, Support { total: 2200, voters: vec![(31, 1000), (1, 600), (3, 600)] })
],
);
});
@@ -1952,7 +1952,7 @@ fn bond_with_duplicate_vote_should_be_ignored_by_election_provider_elected() {
supports,
vec![
(11, Support { total: 1500, voters: vec![(11, 1000), (1, 500)] }),
(21, Support { total: 2500, voters: vec![(21, 1000), (3, 1000), (1, 500)] })
(21, Support { total: 2500, voters: vec![(21, 1000), (1, 500), (3, 1000)] })
],
);
});
@@ -3881,11 +3881,137 @@ mod election_data_provider {
}
#[test]
fn respects_len_limits() {
ExtBuilder::default().build_and_execute(|| {
assert_eq!(Staking::voters(Some(1)).unwrap_err(), "Voter snapshot too big");
assert_eq!(Staking::targets(Some(1)).unwrap_err(), "Target snapshot too big");
});
fn respects_snapshot_len_limits() {
ExtBuilder::default()
.set_status(41, StakerStatus::Validator)
.build_and_execute(|| {
// sum of all nominators who'd be voters (1), plus the self-votes (4).
assert_eq!(
<Test as Config>::SortedListProvider::count() +
<Validators<Test>>::iter().count() as u32,
5
);
// if limits is less..
assert_eq!(Staking::voters(Some(1)).unwrap().len(), 1);
// if limit is equal..
assert_eq!(Staking::voters(Some(5)).unwrap().len(), 5);
// if limit is more.
assert_eq!(Staking::voters(Some(55)).unwrap().len(), 5);
// if target limit is more..
assert_eq!(Staking::targets(Some(6)).unwrap().len(), 4);
assert_eq!(Staking::targets(Some(4)).unwrap().len(), 4);
// if target limit is less, then we return an error.
assert_eq!(Staking::targets(Some(1)).unwrap_err(), "Target snapshot too big");
});
}
#[test]
fn only_iterates_max_2_times_nominators_quota() {
ExtBuilder::default()
.nominate(true) // add nominator 101, who nominates [11, 21]
// the other nominators only nominate 21
.add_staker(61, 60, 2_000, StakerStatus::<AccountId>::Nominator(vec![21]))
.add_staker(71, 70, 2_000, StakerStatus::<AccountId>::Nominator(vec![21]))
.add_staker(81, 80, 2_000, StakerStatus::<AccountId>::Nominator(vec![21]))
.build_and_execute(|| {
// given our nominators ordered by stake,
assert_eq!(
<Test as Config>::SortedListProvider::iter().collect::<Vec<_>>(),
vec![61, 71, 81, 101]
);
// and total voters
assert_eq!(
<Test as Config>::SortedListProvider::count() +
<Validators<Test>>::iter().count() as u32,
7
);
// roll to session 5
run_to_block(25);
// slash 21, the only validator nominated by our first 3 nominators
add_slash(&21);
// we take 4 voters: 2 validators and 2 nominators (so nominators quota = 2)
assert_eq!(
Staking::voters(Some(3))
.unwrap()
.iter()
.map(|(stash, _, _)| stash)
.copied()
.collect::<Vec<_>>(),
vec![31, 11], // 2 validators, but no nominators because we hit the quota
);
});
}
// Even if some of the higher staked nominators are slashed, we still get up to max len voters
// by adding more lower staked nominators. In other words, we assert that we keep on adding
// valid nominators until we reach max len voters; which is opposed to simply stopping after we
// have iterated max len voters, but not adding all of them to voters due to some nominators not
// having valid targets.
#[test]
fn get_max_len_voters_even_if_some_nominators_are_slashed() {
ExtBuilder::default()
.nominate(true) // add nominator 101, who nominates [11, 21]
.add_staker(61, 60, 20, StakerStatus::<AccountId>::Nominator(vec![21]))
// 61 only nominates validator 21 ^^
.add_staker(71, 70, 10, StakerStatus::<AccountId>::Nominator(vec![11, 21]))
.build_and_execute(|| {
// given our nominators ordered by stake,
assert_eq!(
<Test as Config>::SortedListProvider::iter().collect::<Vec<_>>(),
vec![101, 61, 71]
);
// and total voters
assert_eq!(
<Test as Config>::SortedListProvider::count() +
<Validators<Test>>::iter().count() as u32,
6
);
// we take 5 voters
assert_eq!(
Staking::voters(Some(5))
.unwrap()
.iter()
.map(|(stash, _, _)| stash)
.copied()
.collect::<Vec<_>>(),
// then
vec![
31, 21, 11, // 3 nominators
101, 61 // 2 validators, and 71 is excluded
],
);
// roll to session 5
run_to_block(25);
// slash 21, the only validator nominated by 61
add_slash(&21);
// we take 4 voters
assert_eq!(
Staking::voters(Some(4))
.unwrap()
.iter()
.map(|(stash, _, _)| stash)
.copied()
.collect::<Vec<_>>(),
vec![
31, 11, // 2 validators (21 was slashed)
101, 71 // 2 nominators, excluding 61
],
);
});
}
#[test]
@@ -4232,3 +4358,28 @@ fn capped_stakers_works() {
assert_ok!(Staking::validate(Origin::signed(last_validator), ValidatorPrefs::default()));
})
}
mod sorted_list_provider {
use super::*;
use frame_election_provider_support::SortedListProvider;
#[test]
fn re_nominate_does_not_change_counters_or_list() {
ExtBuilder::default().nominate(true).build_and_execute(|| {
// given
let pre_insert_nominator_count = Nominators::<Test>::iter().count() as u32;
assert_eq!(<Test as Config>::SortedListProvider::count(), pre_insert_nominator_count);
assert!(Nominators::<Test>::contains_key(101));
assert_eq!(<Test as Config>::SortedListProvider::iter().collect::<Vec<_>>(), vec![101]);
// when account 101 renominates
assert_ok!(Staking::nominate(Origin::signed(100), vec![41]));
// then counts don't change
assert_eq!(<Test as Config>::SortedListProvider::count(), pre_insert_nominator_count);
assert_eq!(Nominators::<Test>::iter().count() as u32, pre_insert_nominator_count);
// and the list is the same
assert_eq!(<Test as Config>::SortedListProvider::iter().collect::<Vec<_>>(), vec![101]);
});
}
}
+271 -197
View File
@@ -18,7 +18,7 @@
//! Autogenerated weights for pallet_staking
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2021-08-18, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! DATE: 2021-09-04, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128
// Executed Command:
@@ -85,37 +85,42 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Balances Locks (r:1 w:1)
// Storage: Staking Payee (r:0 w:1)
fn bond() -> Weight {
(73_523_000 as Weight)
(73_865_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
// Storage: Staking Bonded (r:1 w:0)
// Storage: Staking Ledger (r:1 w:1)
// Storage: Balances Locks (r:1 w:1)
// Storage: BagsList ListNodes (r:3 w:3)
// Storage: BagsList ListBags (r:2 w:2)
fn bond_extra() -> Weight {
(58_129_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
(114_296_000 as Weight)
.saturating_add(T::DbWeight::get().reads(8 as Weight))
.saturating_add(T::DbWeight::get().writes(7 as Weight))
}
// Storage: Staking Ledger (r:1 w:1)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking Validators (r:1 w:0)
// Storage: Staking MinNominatorBond (r:1 w:0)
// Storage: Staking CurrentEra (r:1 w:0)
// Storage: Balances Locks (r:1 w:1)
// Storage: System Account (r:1 w:1)
// Storage: BagsList ListNodes (r:3 w:3)
// Storage: Staking Bonded (r:1 w:0)
// Storage: BagsList ListBags (r:2 w:2)
fn unbond() -> Weight {
(61_542_000 as Weight)
.saturating_add(T::DbWeight::get().reads(6 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
(121_737_000 as Weight)
.saturating_add(T::DbWeight::get().reads(12 as Weight))
.saturating_add(T::DbWeight::get().writes(8 as Weight))
}
// Storage: Staking Ledger (r:1 w:1)
// Storage: Staking CurrentEra (r:1 w:0)
// Storage: Balances Locks (r:1 w:1)
// Storage: System Account (r:1 w:1)
fn withdraw_unbonded_update(s: u32, ) -> Weight {
(53_160_000 as Weight)
(51_631_000 as Weight)
// Standard Error: 0
.saturating_add((53_000 as Weight).saturating_mul(s as Weight))
.saturating_add((55_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
@@ -124,36 +129,40 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking Bonded (r:1 w:1)
// Storage: Staking SlashingSpans (r:1 w:0)
// Storage: Staking Validators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:1)
// Storage: Staking CounterForNominators (r:1 w:1)
// Storage: BagsList ListNodes (r:2 w:2)
// Storage: BagsList ListBags (r:1 w:1)
// Storage: BagsList CounterForListNodes (r:1 w:1)
// Storage: System Account (r:1 w:1)
// Storage: Balances Locks (r:1 w:1)
// Storage: Staking Payee (r:0 w:1)
// Storage: Staking SpanSlash (r:0 w:2)
fn withdraw_unbonded_kill(s: u32, ) -> Weight {
(85_826_000 as Weight)
// Standard Error: 2_000
.saturating_add((2_453_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(8 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
fn withdraw_unbonded_kill(_s: u32, ) -> Weight {
(101_870_000 as Weight)
.saturating_add(T::DbWeight::get().reads(13 as Weight))
.saturating_add(T::DbWeight::get().writes(11 as Weight))
}
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking MinValidatorBond (r:1 w:0)
// Storage: Staking Validators (r:1 w:1)
// Storage: Staking MaxValidatorsCount (r:1 w:0)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:1)
// Storage: Staking CounterForNominators (r:1 w:1)
// Storage: BagsList ListNodes (r:2 w:2)
// Storage: BagsList ListBags (r:1 w:1)
// Storage: BagsList CounterForListNodes (r:1 w:1)
// Storage: Staking CounterForValidators (r:1 w:1)
fn validate() -> Weight {
(34_936_000 as Weight)
.saturating_add(T::DbWeight::get().reads(6 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
(69_092_000 as Weight)
.saturating_add(T::DbWeight::get().reads(11 as Weight))
.saturating_add(T::DbWeight::get().writes(8 as Weight))
}
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking Nominators (r:1 w:1)
fn kick(k: u32, ) -> Weight {
(23_493_000 as Weight)
// Standard Error: 17_000
.saturating_add((16_632_000 as Weight).saturating_mul(k as Weight))
(21_468_000 as Weight)
// Standard Error: 19_000
.saturating_add((16_415_000 as Weight).saturating_mul(k as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(k as Weight)))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(k as Weight)))
@@ -165,84 +174,97 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking Validators (r:2 w:0)
// Storage: Staking CurrentEra (r:1 w:0)
// Storage: Staking CounterForNominators (r:1 w:1)
// Storage: Staking Bonded (r:1 w:0)
// Storage: BagsList ListNodes (r:2 w:2)
// Storage: BagsList ListBags (r:1 w:1)
// Storage: BagsList CounterForListNodes (r:1 w:1)
fn nominate(n: u32, ) -> Weight {
(41_733_000 as Weight)
// Standard Error: 11_000
.saturating_add((5_840_000 as Weight).saturating_mul(n as Weight))
.saturating_add(T::DbWeight::get().reads(7 as Weight))
(82_389_000 as Weight)
// Standard Error: 14_000
.saturating_add((5_597_000 as Weight).saturating_mul(n as Weight))
.saturating_add(T::DbWeight::get().reads(12 as Weight))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(n as Weight)))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking Validators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:1)
// Storage: Staking CounterForNominators (r:1 w:1)
// Storage: BagsList ListNodes (r:2 w:2)
// Storage: BagsList ListBags (r:1 w:1)
// Storage: BagsList CounterForListNodes (r:1 w:1)
fn chill() -> Weight {
(17_901_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
(69_655_000 as Weight)
.saturating_add(T::DbWeight::get().reads(8 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking Payee (r:0 w:1)
fn set_payee() -> Weight {
(13_760_000 as Weight)
(12_770_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Staking Bonded (r:1 w:1)
// Storage: Staking Ledger (r:2 w:2)
fn set_controller() -> Weight {
(28_388_000 as Weight)
(27_756_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
// Storage: Staking ValidatorCount (r:0 w:1)
fn set_validator_count() -> Weight {
(2_537_000 as Weight)
(2_446_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Staking ForceEra (r:0 w:1)
fn force_no_eras() -> Weight {
(2_749_000 as Weight)
(2_720_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Staking ForceEra (r:0 w:1)
fn force_new_era() -> Weight {
(2_834_000 as Weight)
(2_711_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Staking ForceEra (r:0 w:1)
fn force_new_era_always() -> Weight {
(2_800_000 as Weight)
(2_796_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Staking Invulnerables (r:0 w:1)
fn set_invulnerables(v: u32, ) -> Weight {
(3_429_000 as Weight)
(3_141_000 as Weight)
// Standard Error: 0
.saturating_add((56_000 as Weight).saturating_mul(v as Weight))
.saturating_add((53_000 as Weight).saturating_mul(v as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Staking Bonded (r:1 w:1)
// Storage: Staking SlashingSpans (r:1 w:0)
// Storage: Staking Validators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:1)
// Storage: Staking CounterForNominators (r:1 w:1)
// Storage: BagsList ListNodes (r:2 w:2)
// Storage: BagsList ListBags (r:1 w:1)
// Storage: BagsList CounterForListNodes (r:1 w:1)
// Storage: System Account (r:1 w:1)
// Storage: Balances Locks (r:1 w:1)
// Storage: Staking Ledger (r:0 w:1)
// Storage: Staking Payee (r:0 w:1)
// Storage: Staking SpanSlash (r:0 w:2)
fn force_unstake(s: u32, ) -> Weight {
(61_799_000 as Weight)
(97_394_000 as Weight)
// Standard Error: 2_000
.saturating_add((2_451_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(6 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
.saturating_add((2_370_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(11 as Weight))
.saturating_add(T::DbWeight::get().writes(12 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
// Storage: Staking UnappliedSlashes (r:1 w:1)
fn cancel_deferred_slash(s: u32, ) -> Weight {
(3_383_988_000 as Weight)
// Standard Error: 223_000
.saturating_add((19_981_000 as Weight).saturating_mul(s as Weight))
(2_783_746_000 as Weight)
// Standard Error: 182_000
.saturating_add((16_223_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
@@ -257,9 +279,9 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking Payee (r:2 w:0)
// Storage: System Account (r:2 w:2)
fn payout_stakers_dead_controller(n: u32, ) -> Weight {
(124_714_000 as Weight)
// Standard Error: 23_000
.saturating_add((47_575_000 as Weight).saturating_mul(n as Weight))
(109_233_000 as Weight)
// Standard Error: 17_000
.saturating_add((47_612_000 as Weight).saturating_mul(n as Weight))
.saturating_add(T::DbWeight::get().reads(10 as Weight))
.saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(n as Weight)))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
@@ -277,9 +299,9 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: System Account (r:2 w:2)
// Storage: Balances Locks (r:2 w:2)
fn payout_stakers_alive_staked(n: u32, ) -> Weight {
(160_203_000 as Weight)
// Standard Error: 24_000
.saturating_add((61_321_000 as Weight).saturating_mul(n as Weight))
(177_392_000 as Weight)
// Standard Error: 20_000
.saturating_add((60_771_000 as Weight).saturating_mul(n as Weight))
.saturating_add(T::DbWeight::get().reads(11 as Weight))
.saturating_add(T::DbWeight::get().reads((5 as Weight).saturating_mul(n as Weight)))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
@@ -288,12 +310,15 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking Ledger (r:1 w:1)
// Storage: Balances Locks (r:1 w:1)
// Storage: System Account (r:1 w:1)
// Storage: BagsList ListNodes (r:3 w:3)
// Storage: Staking Bonded (r:1 w:0)
// Storage: BagsList ListBags (r:2 w:2)
fn rebond(l: u32, ) -> Weight {
(49_593_000 as Weight)
// Standard Error: 3_000
.saturating_add((78_000 as Weight).saturating_mul(l as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
(111_858_000 as Weight)
// Standard Error: 4_000
.saturating_add((36_000 as Weight).saturating_mul(l as Weight))
.saturating_add(T::DbWeight::get().reads(9 as Weight))
.saturating_add(T::DbWeight::get().writes(8 as Weight))
}
// Storage: Staking CurrentEra (r:1 w:0)
// Storage: Staking HistoryDepth (r:1 w:1)
@@ -306,8 +331,8 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking ErasStartSessionIndex (r:0 w:1)
fn set_history_depth(e: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 71_000
.saturating_add((35_237_000 as Weight).saturating_mul(e as Weight))
// Standard Error: 68_000
.saturating_add((33_495_000 as Weight).saturating_mul(e as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
.saturating_add(T::DbWeight::get().writes((7 as Weight).saturating_mul(e as Weight)))
@@ -315,19 +340,22 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: System Account (r:1 w:1)
// Storage: Staking Bonded (r:1 w:1)
// Storage: Staking SlashingSpans (r:1 w:1)
// Storage: Staking Validators (r:1 w:1)
// Storage: Staking CounterForValidators (r:1 w:1)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking Validators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:1)
// Storage: Staking CounterForNominators (r:1 w:1)
// Storage: BagsList ListNodes (r:2 w:2)
// Storage: BagsList ListBags (r:1 w:1)
// Storage: BagsList CounterForListNodes (r:1 w:1)
// Storage: Balances Locks (r:1 w:1)
// Storage: Staking Ledger (r:0 w:1)
// Storage: Staking Payee (r:0 w:1)
// Storage: Staking SpanSlash (r:0 w:1)
fn reap_stash(s: u32, ) -> Weight {
(72_484_000 as Weight)
// Standard Error: 2_000
.saturating_add((2_452_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(7 as Weight))
.saturating_add(T::DbWeight::get().writes(8 as Weight))
(100_178_000 as Weight)
// Standard Error: 1_000
.saturating_add((2_358_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(11 as Weight))
.saturating_add(T::DbWeight::get().writes(12 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
// Storage: Staking CounterForNominators (r:1 w:0)
@@ -336,7 +364,9 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking Bonded (r:101 w:0)
// Storage: Staking Ledger (r:101 w:0)
// Storage: Staking SlashingSpans (r:1 w:0)
// Storage: Staking Nominators (r:101 w:0)
// Storage: BagsList ListBags (r:200 w:0)
// Storage: BagsList ListNodes (r:100 w:0)
// Storage: Staking Nominators (r:100 w:0)
// Storage: Staking ValidatorCount (r:1 w:0)
// Storage: Staking MinimumValidatorCount (r:1 w:0)
// Storage: Staking CurrentEra (r:1 w:1)
@@ -348,39 +378,43 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking ErasStartSessionIndex (r:0 w:1)
fn new_era(v: u32, n: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 856_000
.saturating_add((305_057_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 860_000
.saturating_add((298_721_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 43_000
.saturating_add((47_890_000 as Weight).saturating_mul(n as Weight))
.saturating_add(T::DbWeight::get().reads(9 as Weight))
.saturating_add((49_427_000 as Weight).saturating_mul(n as Weight))
.saturating_add(T::DbWeight::get().reads(208 as Weight))
.saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(v as Weight)))
.saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(n as Weight)))
.saturating_add(T::DbWeight::get().reads((4 as Weight).saturating_mul(n as Weight)))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
.saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(v as Weight)))
}
// Storage: Staking CounterForNominators (r:1 w:0)
// Storage: Staking CounterForValidators (r:1 w:0)
// Storage: Staking Validators (r:501 w:0)
// Storage: Staking Bonded (r:1500 w:0)
// Storage: Staking Ledger (r:1500 w:0)
// Storage: Staking SlashingSpans (r:21 w:0)
// Storage: Staking Nominators (r:1001 w:0)
// Storage: BagsList ListBags (r:200 w:0)
// Storage: BagsList ListNodes (r:1000 w:0)
// Storage: Staking Nominators (r:1000 w:0)
fn get_npos_voters(v: u32, n: u32, s: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 98_000
.saturating_add((25_610_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 98_000
.saturating_add((28_064_000 as Weight).saturating_mul(n as Weight))
// Standard Error: 3_346_000
.saturating_add((18_123_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
// Standard Error: 91_000
.saturating_add((26_605_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 91_000
.saturating_add((31_481_000 as Weight).saturating_mul(n as Weight))
// Standard Error: 3_122_000
.saturating_add((16_672_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(204 as Weight))
.saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(v as Weight)))
.saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(n as Weight)))
.saturating_add(T::DbWeight::get().reads((4 as Weight).saturating_mul(n as Weight)))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
}
// Storage: Staking Validators (r:501 w:0)
fn get_npos_targets(v: u32, ) -> Weight {
(30_422_000 as Weight)
// Standard Error: 33_000
.saturating_add((11_252_000 as Weight).saturating_mul(v as Weight))
(0 as Weight)
// Standard Error: 34_000
.saturating_add((10_558_000 as Weight).saturating_mul(v as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(v as Weight)))
}
@@ -390,20 +424,23 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking MaxNominatorsCount (r:0 w:1)
// Storage: Staking MinNominatorBond (r:0 w:1)
fn set_staking_limits() -> Weight {
(6_486_000 as Weight)
(6_353_000 as Weight)
.saturating_add(T::DbWeight::get().writes(5 as Weight))
}
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking ChillThreshold (r:1 w:0)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking Validators (r:1 w:1)
// Storage: Staking MaxValidatorsCount (r:1 w:0)
// Storage: Staking CounterForValidators (r:1 w:1)
// Storage: Staking MinValidatorBond (r:1 w:0)
// Storage: Staking Nominators (r:1 w:1)
// Storage: Staking MaxNominatorsCount (r:1 w:0)
// Storage: Staking CounterForNominators (r:1 w:1)
// Storage: Staking MinNominatorBond (r:1 w:0)
// Storage: Staking Validators (r:1 w:0)
// Storage: BagsList ListNodes (r:2 w:2)
// Storage: BagsList ListBags (r:1 w:1)
// Storage: BagsList CounterForListNodes (r:1 w:1)
fn chill_other() -> Weight {
(58_222_000 as Weight)
.saturating_add(T::DbWeight::get().reads(7 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
(83_389_000 as Weight)
.saturating_add(T::DbWeight::get().reads(11 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
}
@@ -416,37 +453,42 @@ impl WeightInfo for () {
// Storage: Balances Locks (r:1 w:1)
// Storage: Staking Payee (r:0 w:1)
fn bond() -> Weight {
(73_523_000 as Weight)
(73_865_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
// Storage: Staking Bonded (r:1 w:0)
// Storage: Staking Ledger (r:1 w:1)
// Storage: Balances Locks (r:1 w:1)
// Storage: BagsList ListNodes (r:3 w:3)
// Storage: BagsList ListBags (r:2 w:2)
fn bond_extra() -> Weight {
(58_129_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
(114_296_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(8 as Weight))
.saturating_add(RocksDbWeight::get().writes(7 as Weight))
}
// Storage: Staking Ledger (r:1 w:1)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking Validators (r:1 w:0)
// Storage: Staking MinNominatorBond (r:1 w:0)
// Storage: Staking CurrentEra (r:1 w:0)
// Storage: Balances Locks (r:1 w:1)
// Storage: System Account (r:1 w:1)
// Storage: BagsList ListNodes (r:3 w:3)
// Storage: Staking Bonded (r:1 w:0)
// Storage: BagsList ListBags (r:2 w:2)
fn unbond() -> Weight {
(61_542_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(6 as Weight))
.saturating_add(RocksDbWeight::get().writes(3 as Weight))
(121_737_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(12 as Weight))
.saturating_add(RocksDbWeight::get().writes(8 as Weight))
}
// Storage: Staking Ledger (r:1 w:1)
// Storage: Staking CurrentEra (r:1 w:0)
// Storage: Balances Locks (r:1 w:1)
// Storage: System Account (r:1 w:1)
fn withdraw_unbonded_update(s: u32, ) -> Weight {
(53_160_000 as Weight)
(51_631_000 as Weight)
// Standard Error: 0
.saturating_add((53_000 as Weight).saturating_mul(s as Weight))
.saturating_add((55_000 as Weight).saturating_mul(s as Weight))
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(3 as Weight))
}
@@ -455,36 +497,40 @@ impl WeightInfo for () {
// Storage: Staking Bonded (r:1 w:1)
// Storage: Staking SlashingSpans (r:1 w:0)
// Storage: Staking Validators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:1)
// Storage: Staking CounterForNominators (r:1 w:1)
// Storage: BagsList ListNodes (r:2 w:2)
// Storage: BagsList ListBags (r:1 w:1)
// Storage: BagsList CounterForListNodes (r:1 w:1)
// Storage: System Account (r:1 w:1)
// Storage: Balances Locks (r:1 w:1)
// Storage: Staking Payee (r:0 w:1)
// Storage: Staking SpanSlash (r:0 w:2)
fn withdraw_unbonded_kill(s: u32, ) -> Weight {
(85_826_000 as Weight)
// Standard Error: 2_000
.saturating_add((2_453_000 as Weight).saturating_mul(s as Weight))
.saturating_add(RocksDbWeight::get().reads(8 as Weight))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
fn withdraw_unbonded_kill(_s: u32, ) -> Weight {
(101_870_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(13 as Weight))
.saturating_add(RocksDbWeight::get().writes(11 as Weight))
}
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking MinValidatorBond (r:1 w:0)
// Storage: Staking Validators (r:1 w:1)
// Storage: Staking MaxValidatorsCount (r:1 w:0)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:1)
// Storage: Staking CounterForNominators (r:1 w:1)
// Storage: BagsList ListNodes (r:2 w:2)
// Storage: BagsList ListBags (r:1 w:1)
// Storage: BagsList CounterForListNodes (r:1 w:1)
// Storage: Staking CounterForValidators (r:1 w:1)
fn validate() -> Weight {
(34_936_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(6 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
(69_092_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(11 as Weight))
.saturating_add(RocksDbWeight::get().writes(8 as Weight))
}
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking Nominators (r:1 w:1)
fn kick(k: u32, ) -> Weight {
(23_493_000 as Weight)
// Standard Error: 17_000
.saturating_add((16_632_000 as Weight).saturating_mul(k as Weight))
(21_468_000 as Weight)
// Standard Error: 19_000
.saturating_add((16_415_000 as Weight).saturating_mul(k as Weight))
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(k as Weight)))
.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(k as Weight)))
@@ -496,84 +542,97 @@ impl WeightInfo for () {
// Storage: Staking Validators (r:2 w:0)
// Storage: Staking CurrentEra (r:1 w:0)
// Storage: Staking CounterForNominators (r:1 w:1)
// Storage: Staking Bonded (r:1 w:0)
// Storage: BagsList ListNodes (r:2 w:2)
// Storage: BagsList ListBags (r:1 w:1)
// Storage: BagsList CounterForListNodes (r:1 w:1)
fn nominate(n: u32, ) -> Weight {
(41_733_000 as Weight)
// Standard Error: 11_000
.saturating_add((5_840_000 as Weight).saturating_mul(n as Weight))
.saturating_add(RocksDbWeight::get().reads(7 as Weight))
(82_389_000 as Weight)
// Standard Error: 14_000
.saturating_add((5_597_000 as Weight).saturating_mul(n as Weight))
.saturating_add(RocksDbWeight::get().reads(12 as Weight))
.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(n as Weight)))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
}
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking Validators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:1)
// Storage: Staking CounterForNominators (r:1 w:1)
// Storage: BagsList ListNodes (r:2 w:2)
// Storage: BagsList ListBags (r:1 w:1)
// Storage: BagsList CounterForListNodes (r:1 w:1)
fn chill() -> Weight {
(17_901_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
(69_655_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(8 as Weight))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
}
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking Payee (r:0 w:1)
fn set_payee() -> Weight {
(13_760_000 as Weight)
(12_770_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Staking Bonded (r:1 w:1)
// Storage: Staking Ledger (r:2 w:2)
fn set_controller() -> Weight {
(28_388_000 as Weight)
(27_756_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
.saturating_add(RocksDbWeight::get().writes(3 as Weight))
}
// Storage: Staking ValidatorCount (r:0 w:1)
fn set_validator_count() -> Weight {
(2_537_000 as Weight)
(2_446_000 as Weight)
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Staking ForceEra (r:0 w:1)
fn force_no_eras() -> Weight {
(2_749_000 as Weight)
(2_720_000 as Weight)
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Staking ForceEra (r:0 w:1)
fn force_new_era() -> Weight {
(2_834_000 as Weight)
(2_711_000 as Weight)
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Staking ForceEra (r:0 w:1)
fn force_new_era_always() -> Weight {
(2_800_000 as Weight)
(2_796_000 as Weight)
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Staking Invulnerables (r:0 w:1)
fn set_invulnerables(v: u32, ) -> Weight {
(3_429_000 as Weight)
(3_141_000 as Weight)
// Standard Error: 0
.saturating_add((56_000 as Weight).saturating_mul(v as Weight))
.saturating_add((53_000 as Weight).saturating_mul(v as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Staking Bonded (r:1 w:1)
// Storage: Staking SlashingSpans (r:1 w:0)
// Storage: Staking Validators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:1)
// Storage: Staking CounterForNominators (r:1 w:1)
// Storage: BagsList ListNodes (r:2 w:2)
// Storage: BagsList ListBags (r:1 w:1)
// Storage: BagsList CounterForListNodes (r:1 w:1)
// Storage: System Account (r:1 w:1)
// Storage: Balances Locks (r:1 w:1)
// Storage: Staking Ledger (r:0 w:1)
// Storage: Staking Payee (r:0 w:1)
// Storage: Staking SpanSlash (r:0 w:2)
fn force_unstake(s: u32, ) -> Weight {
(61_799_000 as Weight)
(97_394_000 as Weight)
// Standard Error: 2_000
.saturating_add((2_451_000 as Weight).saturating_mul(s as Weight))
.saturating_add(RocksDbWeight::get().reads(6 as Weight))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
.saturating_add((2_370_000 as Weight).saturating_mul(s as Weight))
.saturating_add(RocksDbWeight::get().reads(11 as Weight))
.saturating_add(RocksDbWeight::get().writes(12 as Weight))
.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
// Storage: Staking UnappliedSlashes (r:1 w:1)
fn cancel_deferred_slash(s: u32, ) -> Weight {
(3_383_988_000 as Weight)
// Standard Error: 223_000
.saturating_add((19_981_000 as Weight).saturating_mul(s as Weight))
(2_783_746_000 as Weight)
// Standard Error: 182_000
.saturating_add((16_223_000 as Weight).saturating_mul(s as Weight))
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
@@ -588,9 +647,9 @@ impl WeightInfo for () {
// Storage: Staking Payee (r:2 w:0)
// Storage: System Account (r:2 w:2)
fn payout_stakers_dead_controller(n: u32, ) -> Weight {
(124_714_000 as Weight)
// Standard Error: 23_000
.saturating_add((47_575_000 as Weight).saturating_mul(n as Weight))
(109_233_000 as Weight)
// Standard Error: 17_000
.saturating_add((47_612_000 as Weight).saturating_mul(n as Weight))
.saturating_add(RocksDbWeight::get().reads(10 as Weight))
.saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(n as Weight)))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
@@ -608,9 +667,9 @@ impl WeightInfo for () {
// Storage: System Account (r:2 w:2)
// Storage: Balances Locks (r:2 w:2)
fn payout_stakers_alive_staked(n: u32, ) -> Weight {
(160_203_000 as Weight)
// Standard Error: 24_000
.saturating_add((61_321_000 as Weight).saturating_mul(n as Weight))
(177_392_000 as Weight)
// Standard Error: 20_000
.saturating_add((60_771_000 as Weight).saturating_mul(n as Weight))
.saturating_add(RocksDbWeight::get().reads(11 as Weight))
.saturating_add(RocksDbWeight::get().reads((5 as Weight).saturating_mul(n as Weight)))
.saturating_add(RocksDbWeight::get().writes(3 as Weight))
@@ -619,12 +678,15 @@ impl WeightInfo for () {
// Storage: Staking Ledger (r:1 w:1)
// Storage: Balances Locks (r:1 w:1)
// Storage: System Account (r:1 w:1)
// Storage: BagsList ListNodes (r:3 w:3)
// Storage: Staking Bonded (r:1 w:0)
// Storage: BagsList ListBags (r:2 w:2)
fn rebond(l: u32, ) -> Weight {
(49_593_000 as Weight)
// Standard Error: 3_000
.saturating_add((78_000 as Weight).saturating_mul(l as Weight))
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
.saturating_add(RocksDbWeight::get().writes(3 as Weight))
(111_858_000 as Weight)
// Standard Error: 4_000
.saturating_add((36_000 as Weight).saturating_mul(l as Weight))
.saturating_add(RocksDbWeight::get().reads(9 as Weight))
.saturating_add(RocksDbWeight::get().writes(8 as Weight))
}
// Storage: Staking CurrentEra (r:1 w:0)
// Storage: Staking HistoryDepth (r:1 w:1)
@@ -637,8 +699,8 @@ impl WeightInfo for () {
// Storage: Staking ErasStartSessionIndex (r:0 w:1)
fn set_history_depth(e: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 71_000
.saturating_add((35_237_000 as Weight).saturating_mul(e as Weight))
// Standard Error: 68_000
.saturating_add((33_495_000 as Weight).saturating_mul(e as Weight))
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
.saturating_add(RocksDbWeight::get().writes((7 as Weight).saturating_mul(e as Weight)))
@@ -646,19 +708,22 @@ impl WeightInfo for () {
// Storage: System Account (r:1 w:1)
// Storage: Staking Bonded (r:1 w:1)
// Storage: Staking SlashingSpans (r:1 w:1)
// Storage: Staking Validators (r:1 w:1)
// Storage: Staking CounterForValidators (r:1 w:1)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking Validators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:1)
// Storage: Staking CounterForNominators (r:1 w:1)
// Storage: BagsList ListNodes (r:2 w:2)
// Storage: BagsList ListBags (r:1 w:1)
// Storage: BagsList CounterForListNodes (r:1 w:1)
// Storage: Balances Locks (r:1 w:1)
// Storage: Staking Ledger (r:0 w:1)
// Storage: Staking Payee (r:0 w:1)
// Storage: Staking SpanSlash (r:0 w:1)
fn reap_stash(s: u32, ) -> Weight {
(72_484_000 as Weight)
// Standard Error: 2_000
.saturating_add((2_452_000 as Weight).saturating_mul(s as Weight))
.saturating_add(RocksDbWeight::get().reads(7 as Weight))
.saturating_add(RocksDbWeight::get().writes(8 as Weight))
(100_178_000 as Weight)
// Standard Error: 1_000
.saturating_add((2_358_000 as Weight).saturating_mul(s as Weight))
.saturating_add(RocksDbWeight::get().reads(11 as Weight))
.saturating_add(RocksDbWeight::get().writes(12 as Weight))
.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
// Storage: Staking CounterForNominators (r:1 w:0)
@@ -667,7 +732,9 @@ impl WeightInfo for () {
// Storage: Staking Bonded (r:101 w:0)
// Storage: Staking Ledger (r:101 w:0)
// Storage: Staking SlashingSpans (r:1 w:0)
// Storage: Staking Nominators (r:101 w:0)
// Storage: BagsList ListBags (r:200 w:0)
// Storage: BagsList ListNodes (r:100 w:0)
// Storage: Staking Nominators (r:100 w:0)
// Storage: Staking ValidatorCount (r:1 w:0)
// Storage: Staking MinimumValidatorCount (r:1 w:0)
// Storage: Staking CurrentEra (r:1 w:1)
@@ -679,39 +746,43 @@ impl WeightInfo for () {
// Storage: Staking ErasStartSessionIndex (r:0 w:1)
fn new_era(v: u32, n: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 856_000
.saturating_add((305_057_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 860_000
.saturating_add((298_721_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 43_000
.saturating_add((47_890_000 as Weight).saturating_mul(n as Weight))
.saturating_add(RocksDbWeight::get().reads(9 as Weight))
.saturating_add((49_427_000 as Weight).saturating_mul(n as Weight))
.saturating_add(RocksDbWeight::get().reads(208 as Weight))
.saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(v as Weight)))
.saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(n as Weight)))
.saturating_add(RocksDbWeight::get().reads((4 as Weight).saturating_mul(n as Weight)))
.saturating_add(RocksDbWeight::get().writes(3 as Weight))
.saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(v as Weight)))
}
// Storage: Staking CounterForNominators (r:1 w:0)
// Storage: Staking CounterForValidators (r:1 w:0)
// Storage: Staking Validators (r:501 w:0)
// Storage: Staking Bonded (r:1500 w:0)
// Storage: Staking Ledger (r:1500 w:0)
// Storage: Staking SlashingSpans (r:21 w:0)
// Storage: Staking Nominators (r:1001 w:0)
// Storage: BagsList ListBags (r:200 w:0)
// Storage: BagsList ListNodes (r:1000 w:0)
// Storage: Staking Nominators (r:1000 w:0)
fn get_npos_voters(v: u32, n: u32, s: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 98_000
.saturating_add((25_610_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 98_000
.saturating_add((28_064_000 as Weight).saturating_mul(n as Weight))
// Standard Error: 3_346_000
.saturating_add((18_123_000 as Weight).saturating_mul(s as Weight))
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
// Standard Error: 91_000
.saturating_add((26_605_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 91_000
.saturating_add((31_481_000 as Weight).saturating_mul(n as Weight))
// Standard Error: 3_122_000
.saturating_add((16_672_000 as Weight).saturating_mul(s as Weight))
.saturating_add(RocksDbWeight::get().reads(204 as Weight))
.saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(v as Weight)))
.saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(n as Weight)))
.saturating_add(RocksDbWeight::get().reads((4 as Weight).saturating_mul(n as Weight)))
.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
}
// Storage: Staking Validators (r:501 w:0)
fn get_npos_targets(v: u32, ) -> Weight {
(30_422_000 as Weight)
// Standard Error: 33_000
.saturating_add((11_252_000 as Weight).saturating_mul(v as Weight))
(0 as Weight)
// Standard Error: 34_000
.saturating_add((10_558_000 as Weight).saturating_mul(v as Weight))
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(v as Weight)))
}
@@ -721,19 +792,22 @@ impl WeightInfo for () {
// Storage: Staking MaxNominatorsCount (r:0 w:1)
// Storage: Staking MinNominatorBond (r:0 w:1)
fn set_staking_limits() -> Weight {
(6_486_000 as Weight)
(6_353_000 as Weight)
.saturating_add(RocksDbWeight::get().writes(5 as Weight))
}
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking ChillThreshold (r:1 w:0)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking Validators (r:1 w:1)
// Storage: Staking MaxValidatorsCount (r:1 w:0)
// Storage: Staking CounterForValidators (r:1 w:1)
// Storage: Staking MinValidatorBond (r:1 w:0)
// Storage: Staking Nominators (r:1 w:1)
// Storage: Staking MaxNominatorsCount (r:1 w:0)
// Storage: Staking CounterForNominators (r:1 w:1)
// Storage: Staking MinNominatorBond (r:1 w:0)
// Storage: Staking Validators (r:1 w:0)
// Storage: BagsList ListNodes (r:2 w:2)
// Storage: BagsList ListBags (r:1 w:1)
// Storage: BagsList CounterForListNodes (r:1 w:1)
fn chill_other() -> Weight {
(58_222_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(7 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
(83_389_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(11 as Weight))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
}
}