remove the uselsss weight return type from election provider API (#9569)

* remove the uselsss weight return type from election provider API

* fix everything, should be ready for final benchmark

* simplify on_init a bit furhter

* cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_election_provider_multi_phase --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/election-provider-multi-phase/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 unwraps

* fmt

* Update lock file

* whitelist block weight

* cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_election_provider_multi_phase --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/election-provider-multi-phase/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

* fix warning

Co-authored-by: Parity Benchmarking Bot <admin@parity.io>
This commit is contained in:
Kian Paimani
2021-08-19 08:45:54 +01:00
committed by GitHub
parent 354b77fb88
commit 7a32c3504d
22 changed files with 552 additions and 556 deletions
+22 -2
View File
@@ -5015,6 +5015,8 @@ dependencies = [
"sp-std",
"sp-tracing",
"static_assertions",
"strum 0.21.0",
"strum_macros 0.21.1",
]
[[package]]
@@ -9036,7 +9038,7 @@ dependencies = [
"lazy_static",
"sp-core",
"sp-runtime",
"strum",
"strum 0.20.0",
]
[[package]]
@@ -9521,9 +9523,15 @@ version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7318c509b5ba57f18533982607f24070a55d353e90d4cae30c467cdb2ad5ac5c"
dependencies = [
"strum_macros",
"strum_macros 0.20.1",
]
[[package]]
name = "strum"
version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aaf86bbcfd1fa9670b7a129f64fc0c9fcbbfe4f1bc4210e9e98fe71ffc12cde2"
[[package]]
name = "strum_macros"
version = "0.20.1"
@@ -9536,6 +9544,18 @@ dependencies = [
"syn",
]
[[package]]
name = "strum_macros"
version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d06aaeeee809dbc59eb4556183dd927df67db1540de5be8d3ec0b6636358a5ec"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "subkey"
version = "2.0.1"
+2
View File
@@ -1618,6 +1618,8 @@ impl_runtime_apis! {
hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),
// System Events
hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),
// System BlockWeight
hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef734abf5cb34d6244378cddbf18e849d96").to_vec().into(),
// Treasury Account
hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da95ecffd7b6c0f78751baa9d281e0bfa3a6d6f646c70792f74727372790000000000000000000000000000000000000000").to_vec().into(),
];
-1
View File
@@ -194,7 +194,6 @@ parameter_types! {
impl onchain::Config for Test {
type AccountId = <Self as frame_system::Config>::AccountId;
type BlockNumber = <Self as frame_system::Config>::BlockNumber;
type BlockWeights = ();
type Accuracy = Perbill;
type DataProvider = Staking;
}
@@ -36,6 +36,8 @@ rand = { version = "0.7.3", default-features = false, optional = true, features
"alloc",
"small_rng",
] }
strum = { optional = true, version = "0.21.0" }
strum_macros = { optional = true, version = "0.21.1" }
[dev-dependencies]
parking_lot = "0.11.0"
@@ -45,7 +47,6 @@ sp-io = { version = "4.0.0-dev", path = "../../primitives/io" }
sp-npos-elections = { version = "4.0.0-dev", default-features = false, path = "../../primitives/npos-elections" }
sp-tracing = { version = "4.0.0-dev", path = "../../primitives/tracing" }
frame-election-provider-support = { version = "4.0.0-dev", features = [
"runtime-benchmarks",
], path = "../election-provider-support" }
pallet-balances = { version = "4.0.0-dev", path = "../balances" }
frame-benchmarking = { version = "4.0.0-dev", path = "../benchmarking" }
@@ -68,5 +69,11 @@ std = [
"frame-election-provider-support/std",
"log/std",
]
runtime-benchmarks = ["frame-benchmarking", "rand"]
runtime-benchmarks = [
"frame-benchmarking",
"frame-election-provider-support/runtime-benchmarks",
"rand",
"strum",
"strum_macros",
]
try-runtime = ["frame-support/try-runtime"]
@@ -151,8 +151,6 @@ fn solution_with_size<T: Config>(
}
fn set_up_data_provider<T: Config>(v: u32, t: u32) {
// number of votes in snapshot.
T::DataProvider::clear();
log!(
info,
@@ -192,37 +190,22 @@ frame_benchmarking::benchmarks! {
}
on_initialize_open_signed {
// NOTE: this benchmark currently doesn't have any components because the length of a db
// read/write is not captured. Otherwise, it is quite influenced by how much data
// `T::ElectionDataProvider` is reading and passing on.
assert!(<MultiPhase<T>>::snapshot().is_none());
assert!(<MultiPhase<T>>::current_phase().is_off());
}: {
<MultiPhase<T>>::on_initialize_open_signed().unwrap();
<MultiPhase<T>>::on_initialize_open_signed();
} verify {
assert!(<MultiPhase<T>>::snapshot().is_some());
assert!(<MultiPhase<T>>::snapshot().is_none());
assert!(<MultiPhase<T>>::current_phase().is_signed());
}
on_initialize_open_unsigned_with_snapshot {
on_initialize_open_unsigned {
assert!(<MultiPhase<T>>::snapshot().is_none());
assert!(<MultiPhase<T>>::current_phase().is_off());
}: {
<MultiPhase<T>>::on_initialize_open_unsigned(true, true, 1u32.into()).unwrap();
<MultiPhase<T>>::on_initialize_open_unsigned(true, 1u32.into())
} verify {
assert!(<MultiPhase<T>>::snapshot().is_some());
assert!(<MultiPhase<T>>::current_phase().is_unsigned());
}
on_initialize_open_unsigned_without_snapshot {
// need to assume signed phase was open before
<MultiPhase<T>>::on_initialize_open_signed().unwrap();
assert!(<MultiPhase<T>>::snapshot().is_some());
assert!(<MultiPhase<T>>::current_phase().is_signed());
}: {
<MultiPhase<T>>::on_initialize_open_unsigned(false, true, 1u32.into()).unwrap();
} verify {
assert!(<MultiPhase<T>>::snapshot().is_some());
assert!(<MultiPhase<T>>::snapshot().is_none());
assert!(<MultiPhase<T>>::current_phase().is_unsigned());
}
@@ -259,30 +242,51 @@ frame_benchmarking::benchmarks! {
assert_eq!(T::Currency::reserved_balance(&receiver), 0u32.into());
}
create_snapshot_internal {
// number of votes in snapshot. Fixed to maximum.
let v = T::BenchmarkingConfig::SNAPSHOT_MAXIMUM_VOTERS;
// number of targets in snapshot. Fixed to maximum.
let t = T::BenchmarkingConfig::MAXIMUM_TARGETS;
// we don't directly need the data-provider to be populated, but it is just easy to use it.
set_up_data_provider::<T>(v, t);
let targets = T::DataProvider::targets(None)?;
let voters = T::DataProvider::voters(None)?;
let desired_targets = T::DataProvider::desired_targets()?;
assert!(<MultiPhase<T>>::snapshot().is_none());
}: {
<MultiPhase::<T>>::create_snapshot_internal(targets, voters, desired_targets)
} verify {
assert!(<MultiPhase<T>>::snapshot().is_some());
assert_eq!(<MultiPhase<T>>::snapshot_metadata().ok_or("metadata missing")?.voters, v + t);
assert_eq!(<MultiPhase<T>>::snapshot_metadata().ok_or("metadata missing")?.targets, t);
}
// a call to `<Pallet as ElectionProvider>::elect` where we only return the queued solution.
elect_queued {
// number of votes in snapshot.
let v in (T::BenchmarkingConfig::VOTERS[0]) .. T::BenchmarkingConfig::VOTERS[1];
// number of targets in snapshot.
let t in (T::BenchmarkingConfig::TARGETS[0]) .. T::BenchmarkingConfig::TARGETS[1];
// number of assignments, i.e. solution.len(). This means the active nominators, thus must be
// a subset of `v` component.
// a subset of `v`.
let a in (T::BenchmarkingConfig::ACTIVE_VOTERS[0]) .. T::BenchmarkingConfig::ACTIVE_VOTERS[1];
// number of desired targets. Must be a subset of `t` component.
// number of desired targets. Must be a subset of `t`.
let d in (T::BenchmarkingConfig::DESIRED_TARGETS[0]) .. T::BenchmarkingConfig::DESIRED_TARGETS[1];
// number of votes in snapshot. Not dominant.
let v = T::BenchmarkingConfig::VOTERS[1];
// number of targets in snapshot. Not dominant.
let t = T::BenchmarkingConfig::TARGETS[1];
let witness = SolutionOrSnapshotSize { voters: v, targets: t };
let raw_solution = solution_with_size::<T>(witness, a, d)?;
let ready_solution =
<MultiPhase<T>>::feasibility_check(raw_solution, ElectionCompute::Signed).unwrap();
<MultiPhase<T>>::feasibility_check(raw_solution, ElectionCompute::Signed)?;
<CurrentPhase<T>>::put(Phase::Signed);
// assume a queued solution is stored, regardless of where it comes from.
<QueuedSolution<T>>::put(ready_solution);
// these are set by the `solution_with_size` function.
assert!(<DesiredTargets<T>>::get().is_some());
assert!(<Snapshot<T>>::get().is_some());
assert!(<SnapshotMetadata<T>>::get().is_some());
<CurrentPhase<T>>::put(Phase::Signed);
// assume a queued solution is stored, regardless of where it comes from.
<QueuedSolution<T>>::put(ready_solution);
}: {
assert_ok!(<MultiPhase<T> as ElectionProvider<T::AccountId, T::BlockNumber>>::elect());
} verify {
@@ -303,7 +307,8 @@ frame_benchmarking::benchmarks! {
..Default::default()
};
MultiPhase::<T>::on_initialize_open_signed().expect("should be ok to start signed phase");
<MultiPhase<T>>::create_snapshot()?;
MultiPhase::<T>::on_initialize_open_signed();
<Round<T>>::put(1);
let mut signed_submissions = SignedSubmissions::<T>::get();
@@ -346,7 +351,7 @@ frame_benchmarking::benchmarks! {
<CurrentPhase<T>>::put(Phase::Unsigned((true, 1u32.into())));
// encode the most significant storage item that needs to be decoded in the dispatch.
let encoded_snapshot = <MultiPhase<T>>::snapshot().unwrap().encode();
let encoded_snapshot = <MultiPhase<T>>::snapshot().ok_or("missing snapshot")?.encode();
let encoded_call = <Call<T>>::submit_unsigned(Box::new(raw_solution.clone()), witness).encode();
}: {
assert_ok!(
@@ -357,8 +362,8 @@ frame_benchmarking::benchmarks! {
)
);
let _decoded_snap = <RoundSnapshot<T::AccountId> as Decode>::decode(&mut &*encoded_snapshot)
.unwrap();
let _decoded_call = <Call<T> as Decode>::decode(&mut &*encoded_call).unwrap();
.expect("decoding should not fail; qed.");
let _decoded_call = <Call<T> as Decode>::decode(&mut &*encoded_call).expect("decoding should not fail; qed.");
} verify {
assert!(<MultiPhase<T>>::queued_solution().is_some());
}
@@ -382,10 +387,11 @@ frame_benchmarking::benchmarks! {
assert_eq!(raw_solution.solution.unique_targets().len() as u32, d);
// encode the most significant storage item that needs to be decoded in the dispatch.
let encoded_snapshot = <MultiPhase<T>>::snapshot().unwrap().encode();
let encoded_snapshot = <MultiPhase<T>>::snapshot().ok_or("snapshot missing")?.encode();
}: {
assert_ok!(<MultiPhase<T>>::feasibility_check(raw_solution, ElectionCompute::Unsigned));
let _decoded_snap = <RoundSnapshot<T::AccountId> as Decode>::decode(&mut &*encoded_snapshot).unwrap();
let _decoded_snap = <RoundSnapshot<T::AccountId> as Decode>::decode(&mut &*encoded_snapshot)
.expect("decoding should not fail; qed.");
}
// NOTE: this weight is not used anywhere, but the fact that it should succeed when execution in
@@ -405,9 +411,8 @@ frame_benchmarking::benchmarks! {
// number of votes in snapshot. Fixed to maximum.
let v = T::BenchmarkingConfig::MINER_MAXIMUM_VOTERS;
// number of targets in snapshot. Fixed to maximum.
let t = T::BenchmarkingConfig::MAXIMUM_TARGETS;
let t = T::BenchmarkingConfig::MAXIMUM_TARGETS;
T::DataProvider::clear();
set_up_data_provider::<T>(v, t);
let now = frame_system::Pallet::<T>::block_number();
<CurrentPhase<T>>::put(Phase::Unsigned((true, now)));
@@ -428,17 +433,16 @@ frame_benchmarking::benchmarks! {
// number of votes in snapshot. Fixed to maximum.
let v = T::BenchmarkingConfig::SNAPSHOT_MAXIMUM_VOTERS;
// number of targets in snapshot. Fixed to maximum.
let t = T::BenchmarkingConfig::MAXIMUM_TARGETS;
let t = T::BenchmarkingConfig::MAXIMUM_TARGETS;
T::DataProvider::clear();
set_up_data_provider::<T>(v, t);
assert!(<MultiPhase<T>>::snapshot().is_none());
}: {
<MultiPhase::<T>>::create_snapshot().unwrap()
<MultiPhase::<T>>::create_snapshot()?
} verify {
assert!(<MultiPhase<T>>::snapshot().is_some());
assert_eq!(<MultiPhase<T>>::snapshot_metadata().unwrap().voters, v + t);
assert_eq!(<MultiPhase<T>>::snapshot_metadata().unwrap().targets, t);
assert_eq!(<MultiPhase<T>>::snapshot_metadata().ok_or("snapshot missing")?.voters, v + t);
assert_eq!(<MultiPhase<T>>::snapshot_metadata().ok_or("snapshot missing")?.targets, t);
}
#[extra]
@@ -462,10 +466,10 @@ frame_benchmarking::benchmarks! {
// assignments
let witness = SolutionOrSnapshotSize { voters: v, targets: t };
let RawSolution { solution, .. } = solution_with_size::<T>(witness, a, d)?;
let RoundSnapshot { voters, targets } = MultiPhase::<T>::snapshot().unwrap();
let RoundSnapshot { voters, targets } = MultiPhase::<T>::snapshot().ok_or("snapshot missing")?;
let voter_at = helpers::voter_at_fn::<T>(&voters);
let target_at = helpers::target_at_fn::<T>(&targets);
let mut assignments = solution.into_assignment(voter_at, target_at).unwrap();
let mut assignments = solution.into_assignment(voter_at, target_at).expect("solution generated by `solution_with_size` must be valid.");
// make a voter cache and some helper functions for access
let cache = helpers::generate_voter_cache::<T>(&voters);
@@ -233,7 +233,7 @@ use frame_support::{
dispatch::DispatchResultWithPostInfo,
ensure,
traits::{Currency, Get, OnUnbalanced, ReservableCurrency},
weights::Weight,
weights::{DispatchClass, Weight},
};
use frame_system::{ensure_none, offchain::SendTransactionTypes};
use sp_arithmetic::{
@@ -254,7 +254,7 @@ use sp_runtime::{
};
use sp_std::{convert::TryInto, prelude::*};
#[cfg(any(feature = "runtime-benchmarks", test))]
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
#[cfg(test)]
mod mock;
@@ -266,12 +266,12 @@ const LOG_TARGET: &'static str = "runtime::election-provider";
pub mod signed;
pub mod unsigned;
pub mod weights;
pub use weights::WeightInfo;
pub use signed::{
BalanceOf, NegativeImbalanceOf, PositiveImbalanceOf, SignedSubmission, SignedSubmissionOf,
SignedSubmissions, SubmissionIndicesOf,
};
pub use weights::WeightInfo;
/// The solution type used by this crate.
pub type SolutionOf<T> = <T as Config>::Solution;
@@ -290,7 +290,6 @@ pub struct OnChainConfig<T: Config>(sp_std::marker::PhantomData<T>);
impl<T: Config> onchain::Config for OnChainConfig<T> {
type AccountId = T::AccountId;
type BlockNumber = T::BlockNumber;
type BlockWeights = T::BlockWeights;
type Accuracy = T::OnChainAccuracy;
type DataProvider = T::DataProvider;
}
@@ -487,6 +486,7 @@ pub struct SolutionOrSnapshotSize {
///
/// Note that this is different from [`pallet::Error`].
#[derive(Debug, Eq, PartialEq)]
#[cfg_attr(feature = "runtime-benchmarks", derive(strum_macros::IntoStaticStr))]
pub enum ElectionError {
/// An error happened in the feasibility check sub-system.
Feasibility(FeasibilityError),
@@ -520,6 +520,7 @@ impl From<unsigned::MinerError> for ElectionError {
/// Errors that can happen in the feasibility check.
#[derive(Debug, Eq, PartialEq)]
#[cfg_attr(feature = "runtime-benchmarks", derive(strum_macros::IntoStaticStr))]
pub enum FeasibilityError {
/// Wrong number of winners presented.
WrongWinnerCount,
@@ -699,17 +700,15 @@ pub mod pallet {
match current_phase {
Phase::Off if remaining <= signed_deadline && remaining > unsigned_deadline => {
// NOTE: if signed-phase length is zero, second part of the if-condition fails.
match Self::on_initialize_open_signed() {
Ok(snap_weight) => {
log!(info, "Starting signed phase round {}.", Self::round());
T::WeightInfo::on_initialize_open_signed().saturating_add(snap_weight)
match Self::create_snapshot() {
Ok(_) => {
Self::on_initialize_open_signed();
T::WeightInfo::on_initialize_open_signed()
},
Err(why) => {
// Not much we can do about this at this point.
log!(warn, "failed to open signed phase due to {:?}", why);
T::WeightInfo::on_initialize_nothing()
// NOTE: ^^ The trait specifies that this is a noop in terms of weight
// in case of error.
},
}
},
@@ -718,8 +717,7 @@ pub mod pallet {
{
// our needs vary according to whether or not the unsigned phase follows a
// signed phase
let (need_snapshot, enabled, signed_weight) = if current_phase == Phase::Signed
{
let (need_snapshot, enabled) = if current_phase == Phase::Signed {
// there was previously a signed phase: close the signed phase, no need for
// snapshot.
//
@@ -729,35 +727,31 @@ pub mod pallet {
// is a guard against the case that `elect` is called prematurely. This
// adds a small amount of overhead, but that is unfortunately
// unavoidable.
let (_success, weight) = Self::finalize_signed_phase();
let _ = Self::finalize_signed_phase();
// In the future we can consider disabling the unsigned phase if the signed
// phase completes successfully, but for now we're enabling it
// unconditionally as a defensive measure.
(false, true, weight)
(false, true)
} else {
// No signed phase: create a new snapshot, definitely `enable` the unsigned
// phase.
(true, true, Weight::zero())
(true, true)
};
match Self::on_initialize_open_unsigned(need_snapshot, enabled, now) {
Ok(snap_weight) => {
log!(info, "Starting unsigned phase({}).", enabled);
let base_weight = if need_snapshot {
T::WeightInfo::on_initialize_open_unsigned_with_snapshot()
} else {
T::WeightInfo::on_initialize_open_unsigned_without_snapshot()
};
base_weight.saturating_add(snap_weight).saturating_add(signed_weight)
},
Err(why) => {
// Not much we can do about this at this point.
log!(warn, "failed to open unsigned phase due to {:?}", why);
T::WeightInfo::on_initialize_nothing()
// NOTE: ^^ The trait specifies that this is a noop in terms of weight
// in case of error.
},
if need_snapshot {
match Self::create_snapshot() {
Ok(_) => {
Self::on_initialize_open_unsigned(enabled, now);
T::WeightInfo::on_initialize_open_unsigned()
},
Err(why) => {
log!(warn, "failed to open unsigned phase due to {:?}", why);
T::WeightInfo::on_initialize_nothing()
},
}
} else {
Self::on_initialize_open_unsigned(enabled, now);
T::WeightInfo::on_initialize_open_unsigned()
}
}
_ => T::WeightInfo::on_initialize_nothing(),
@@ -1255,70 +1249,31 @@ impl<T: Config> Pallet<T> {
}
/// Logic for [`<Pallet as Hooks>::on_initialize`] when signed phase is being opened.
///
/// This is decoupled for easy weight calculation.
///
/// Returns `Ok(snapshot_weight)` if success, where `snapshot_weight` is the weight that
/// needs to recorded for the creation of snapshot.
pub fn on_initialize_open_signed() -> Result<Weight, ElectionError> {
let weight = Self::create_snapshot()?;
pub fn on_initialize_open_signed() {
log!(info, "Starting signed phase round {}.", Self::round());
<CurrentPhase<T>>::put(Phase::Signed);
Self::deposit_event(Event::SignedPhaseStarted(Self::round()));
Ok(weight.saturating_add(T::DbWeight::get().writes(1)))
}
/// Logic for [`<Pallet as Hooks<T>>::on_initialize`] when unsigned phase is being opened.
///
/// This is decoupled for easy weight calculation.
///
/// Returns `Ok(snapshot_weight)` if success, where `snapshot_weight` is the weight that
/// needs to recorded for the creation of snapshot.
pub fn on_initialize_open_unsigned(
need_snapshot: bool,
enabled: bool,
now: T::BlockNumber,
) -> Result<Weight, ElectionError> {
let weight = if need_snapshot {
// If not being followed by a signed phase, then create the snapshots.
debug_assert!(Self::snapshot().is_none());
Self::create_snapshot()?
} else {
0
};
pub fn on_initialize_open_unsigned(enabled: bool, now: T::BlockNumber) {
let round = Self::round();
log!(info, "Starting unsigned phase round {} enabled {}.", round, enabled);
<CurrentPhase<T>>::put(Phase::Unsigned((enabled, now)));
Self::deposit_event(Event::UnsignedPhaseStarted(Self::round()));
Ok(weight.saturating_add(T::DbWeight::get().writes(1)))
Self::deposit_event(Event::UnsignedPhaseStarted(round));
}
/// Creates the snapshot. Writes new data to:
/// Parts of [`create_snapshot`] that happen inside of this pallet.
///
/// 1. [`SnapshotMetadata`]
/// 2. [`RoundSnapshot`]
/// 3. [`DesiredTargets`]
///
/// Returns `Ok(consumed_weight)` if operation is okay.
pub fn create_snapshot() -> Result<Weight, ElectionError> {
let target_limit = <SolutionTargetIndexOf<T>>::max_value().saturated_into::<usize>();
let voter_limit = <SolutionVoterIndexOf<T>>::max_value().saturated_into::<usize>();
let (targets, w1) =
T::DataProvider::targets(Some(target_limit)).map_err(ElectionError::DataProvider)?;
let (voters, w2) =
T::DataProvider::voters(Some(voter_limit)).map_err(ElectionError::DataProvider)?;
let (desired_targets, w3) =
T::DataProvider::desired_targets().map_err(ElectionError::DataProvider)?;
// Defensive-only.
if targets.len() > target_limit || voters.len() > voter_limit {
debug_assert!(false, "Snapshot limit has not been respected.");
return Err(ElectionError::DataProvider("Snapshot too big for submission."))
}
// Only write snapshot if all existed.
/// Extracted for easier weight calculation.
fn create_snapshot_internal(
targets: Vec<T::AccountId>,
voters: Vec<crate::unsigned::Voter<T>>,
desired_targets: u32,
) {
let metadata =
SolutionOrSnapshotSize { voters: voters.len() as u32, targets: targets.len() as u32 };
log!(debug, "creating a snapshot with metadata {:?}", metadata);
log!(info, "creating a snapshot with metadata {:?}", metadata);
<SnapshotMetadata<T>>::put(metadata);
<DesiredTargets<T>>::put(desired_targets);
@@ -1328,7 +1283,7 @@ impl<T: Config> Pallet<T> {
// allocation.
let snapshot = RoundSnapshot { voters, targets };
let size = snapshot.encoded_size();
log!(info, "snapshot pre-calculated size {:?}", size);
log!(debug, "snapshot pre-calculated size {:?}", size);
let mut buffer = Vec::with_capacity(size);
snapshot.encode_to(&mut buffer);
@@ -1338,10 +1293,60 @@ impl<T: Config> Pallet<T> {
debug_assert!(buffer.len() == size && size == buffer.capacity());
sp_io::storage::set(&<Snapshot<T>>::hashed_key(), &buffer);
Ok(w1
.saturating_add(w2)
.saturating_add(w3)
.saturating_add(T::DbWeight::get().writes(3)))
}
/// Parts of [`create_snapshot`] that happen outside of this pallet.
///
/// Extracted for easier weight calculation.
fn create_snapshot_external(
) -> Result<(Vec<T::AccountId>, Vec<crate::unsigned::Voter<T>>, u32), ElectionError> {
let target_limit = <SolutionTargetIndexOf<T>>::max_value().saturated_into::<usize>();
let voter_limit = <SolutionVoterIndexOf<T>>::max_value().saturated_into::<usize>();
let targets =
T::DataProvider::targets(Some(target_limit)).map_err(ElectionError::DataProvider)?;
let voters =
T::DataProvider::voters(Some(voter_limit)).map_err(ElectionError::DataProvider)?;
let desired_targets =
T::DataProvider::desired_targets().map_err(ElectionError::DataProvider)?;
// Defensive-only.
if targets.len() > target_limit || voters.len() > voter_limit {
debug_assert!(false, "Snapshot limit has not been respected.");
return Err(ElectionError::DataProvider("Snapshot too big for submission."))
}
Ok((targets, voters, desired_targets))
}
/// Creates the snapshot. Writes new data to:
///
/// 1. [`SnapshotMetadata`]
/// 2. [`RoundSnapshot`]
/// 3. [`DesiredTargets`]
///
/// Returns `Ok(())` if operation is okay.
///
/// This is a *self-weighing* function, it will register its own extra weight as
/// [`DispatchClass::Mandatory`] with the system pallet.
pub fn create_snapshot() -> Result<(), ElectionError> {
// this is self-weighing itself..
let (targets, voters, desired_targets) = Self::create_snapshot_external()?;
// ..therefore we only measure the weight of this and add it.
Self::create_snapshot_internal(targets, voters, desired_targets);
Self::register_weight(T::WeightInfo::create_snapshot_internal());
Ok(())
}
/// Register some amount of weight directly with the system pallet.
///
/// This is always mandatory weight.
fn register_weight(weight: Weight) {
<frame_system::Pallet<T>>::register_extra_weight_unchecked(
weight,
DispatchClass::Mandatory,
);
}
/// Kill everything created by [`Pallet::create_snapshot`].
@@ -1467,7 +1472,7 @@ impl<T: Config> Pallet<T> {
}
/// On-chain fallback of election.
fn onchain_fallback() -> Result<(Supports<T::AccountId>, Weight), ElectionError> {
fn onchain_fallback() -> Result<Supports<T::AccountId>, ElectionError> {
<onchain::OnChainSequentialPhragmen<OnChainConfig<T>> as ElectionProvider<
T::AccountId,
T::BlockNumber,
@@ -1475,7 +1480,7 @@ impl<T: Config> Pallet<T> {
.map_err(Into::into)
}
fn do_elect() -> Result<(Supports<T::AccountId>, Weight), ElectionError> {
fn do_elect() -> Result<Supports<T::AccountId>, ElectionError> {
// We have to unconditionally try finalizing the signed phase here. There are only two
// possibilities:
//
@@ -1483,41 +1488,27 @@ impl<T: Config> Pallet<T> {
// system
// - signed phase was complete or not started, in which case finalization is idempotent and
// inexpensive (1 read of an empty vector).
let (_, signed_finalize_weight) = Self::finalize_signed_phase();
let _ = Self::finalize_signed_phase();
<QueuedSolution<T>>::take()
.map_or_else(
|| match T::Fallback::get() {
FallbackStrategy::OnChain => Self::onchain_fallback()
.map(|(s, w)| (s, w, ElectionCompute::OnChain))
.map(|s| {
// onchain election incurs maximum block weight
Self::register_weight(T::BlockWeights::get().max_block);
(s, ElectionCompute::OnChain)
})
.map_err(Into::into),
FallbackStrategy::Nothing => Err(ElectionError::NoFallbackConfigured),
},
|ReadySolution { supports, compute, .. }| {
// defensive-only: snapshot must always exist by this point.
let metadata = Self::snapshot_metadata().unwrap_or_default();
let desired = supports.len() as u32;
let active_voters = supports
.iter()
.map(|(_, x)| x)
.fold(Zero::zero(), |acc, next| acc + next.voters.len() as u32);
Ok((
supports,
T::WeightInfo::elect_queued(
metadata.voters,
metadata.targets,
active_voters,
desired,
),
compute,
))
},
|ReadySolution { supports, compute, .. }| Ok((supports, compute)),
)
.map(|(supports, weight, compute)| {
.map(|(supports, compute)| {
Self::deposit_event(Event::ElectionFinalized(Some(compute)));
if Self::round() != 1 {
log!(info, "Finalized election round with compute {:?}.", compute);
}
(supports, weight.saturating_add(signed_finalize_weight))
supports
})
.map_err(|err| {
Self::deposit_event(Event::ElectionFinalized(None));
@@ -1527,18 +1518,29 @@ impl<T: Config> Pallet<T> {
err
})
}
/// record the weight of the given `supports`.
fn weigh_supports(supports: &Supports<T::AccountId>) {
let active_voters = supports
.iter()
.map(|(_, x)| x)
.fold(Zero::zero(), |acc, next| acc + next.voters.len() as u32);
let desired_targets = supports.len() as u32;
Self::register_weight(T::WeightInfo::elect_queued(active_voters, desired_targets));
}
}
impl<T: Config> ElectionProvider<T::AccountId, T::BlockNumber> for Pallet<T> {
type Error = ElectionError;
type DataProvider = T::DataProvider;
fn elect() -> Result<(Supports<T::AccountId>, Weight), Self::Error> {
fn elect() -> Result<Supports<T::AccountId>, Self::Error> {
match Self::do_elect() {
Ok((supports, weight)) => {
// All went okay, put sign to be Off, clean snapshot, etc.
Ok(supports) => {
// All went okay, record the weight, put sign to be Off, clean snapshot, etc.
Self::weigh_supports(&supports);
Self::rotate_round();
Ok((supports, weight))
Ok(supports)
},
Err(why) => {
log!(error, "Entering emergency mode: {:?}", why);
@@ -1796,7 +1798,7 @@ mod tests {
assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, 25)));
assert!(MultiPhase::snapshot().is_some());
MultiPhase::elect().unwrap();
assert_ok!(MultiPhase::elect());
assert!(MultiPhase::current_phase().is_off());
assert!(MultiPhase::snapshot().is_none());
@@ -1829,7 +1831,7 @@ mod tests {
roll_to(30);
assert!(MultiPhase::current_phase().is_unsigned_open_at(20));
MultiPhase::elect().unwrap();
assert_ok!(MultiPhase::elect());
assert!(MultiPhase::current_phase().is_off());
assert!(MultiPhase::snapshot().is_none());
@@ -1896,7 +1898,7 @@ mod tests {
// An unexpected call to elect.
roll_to(20);
MultiPhase::elect().unwrap();
assert_ok!(MultiPhase::elect());
// We surely can't have any feasible solutions. This will cause an on-chain election.
assert_eq!(
@@ -1941,7 +1943,7 @@ mod tests {
// an unexpected call to elect.
roll_to(20);
assert!(MultiPhase::elect().is_ok());
assert_ok!(MultiPhase::elect());
// all storage items must be cleared.
assert_eq!(MultiPhase::round(), 2);
@@ -1963,7 +1965,7 @@ mod tests {
assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, 25)));
// Zilch solutions thus far.
let (supports, _) = MultiPhase::elect().unwrap();
let supports = MultiPhase::elect().unwrap();
assert_eq!(
supports,
@@ -2001,7 +2003,7 @@ mod tests {
// On-chain backup works though.
roll_to(29);
let (supports, _) = MultiPhase::elect().unwrap();
let supports = MultiPhase::elect().unwrap();
assert!(supports.len() > 0);
})
}
@@ -283,6 +283,13 @@ impl multi_phase::weights::WeightInfo for DualMockWeightInfo {
<() as multi_phase::weights::WeightInfo>::on_initialize_nothing()
}
}
fn create_snapshot_internal() -> Weight {
if MockWeightInfo::get() {
Zero::zero()
} else {
<() as multi_phase::weights::WeightInfo>::create_snapshot_internal()
}
}
fn on_initialize_open_signed() -> Weight {
if MockWeightInfo::get() {
Zero::zero()
@@ -290,18 +297,18 @@ impl multi_phase::weights::WeightInfo for DualMockWeightInfo {
<() as multi_phase::weights::WeightInfo>::on_initialize_open_signed()
}
}
fn on_initialize_open_unsigned_with_snapshot() -> Weight {
fn on_initialize_open_unsigned() -> Weight {
if MockWeightInfo::get() {
Zero::zero()
} else {
<() as multi_phase::weights::WeightInfo>::on_initialize_open_unsigned_with_snapshot()
<() as multi_phase::weights::WeightInfo>::on_initialize_open_unsigned()
}
}
fn on_initialize_open_unsigned_without_snapshot() -> Weight {
fn elect_queued(a: u32, d: u32) -> Weight {
if MockWeightInfo::get() {
Zero::zero()
} else {
<() as multi_phase::weights::WeightInfo>::on_initialize_open_unsigned_without_snapshot()
<() as multi_phase::weights::WeightInfo>::elect_queued(a, d)
}
}
fn finalize_signed_phase_accept_solution() -> Weight {
@@ -325,13 +332,6 @@ impl multi_phase::weights::WeightInfo for DualMockWeightInfo {
<() as multi_phase::weights::WeightInfo>::submit(c)
}
}
fn elect_queued(v: u32, t: u32, a: u32, d: u32) -> Weight {
if MockWeightInfo::get() {
Zero::zero()
} else {
<() as multi_phase::weights::WeightInfo>::elect_queued(v, t, a, d)
}
}
fn submit_unsigned(v: u32, t: u32, a: u32, d: u32) -> Weight {
if MockWeightInfo::get() {
// 10 base
@@ -397,35 +397,36 @@ pub struct ExtBuilder {}
pub struct StakingMock;
impl ElectionDataProvider<AccountId, u64> for StakingMock {
const MAXIMUM_VOTES_PER_VOTER: u32 = <TestNposSolution as NposSolution>::LIMIT as u32;
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<(Vec<AccountId>, Weight)> {
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
let targets = Targets::get();
if maybe_max_len.map_or(false, |max_len| targets.len() > max_len) {
return Err("Targets too big")
}
Ok((targets, 0))
Ok(targets)
}
fn voters(
maybe_max_len: Option<usize>,
) -> data_provider::Result<(Vec<(AccountId, VoteWeight, Vec<AccountId>)>, Weight)> {
) -> data_provider::Result<Vec<(AccountId, VoteWeight, Vec<AccountId>)>> {
let voters = Voters::get();
if maybe_max_len.map_or(false, |max_len| voters.len() > max_len) {
return Err("Voters too big")
}
Ok((voters, 0))
Ok(voters)
}
fn desired_targets() -> data_provider::Result<(u32, Weight)> {
Ok((DesiredTargets::get(), 0))
fn desired_targets() -> data_provider::Result<u32> {
Ok(DesiredTargets::get())
}
fn next_election_prediction(now: u64) -> u64 {
now + EpochLength::get() - now % EpochLength::get()
}
#[cfg(any(feature = "runtime-benchmarks", test))]
#[cfg(feature = "runtime-benchmarks")]
fn put_snapshot(
voters: Vec<(AccountId, VoteWeight, Vec<AccountId>)>,
targets: Vec<AccountId>,
@@ -435,20 +436,20 @@ impl ElectionDataProvider<AccountId, u64> for StakingMock {
Voters::set(voters);
}
#[cfg(any(feature = "runtime-benchmarks", test))]
#[cfg(feature = "runtime-benchmarks")]
fn clear() {
Targets::set(vec![]);
Voters::set(vec![]);
}
#[cfg(any(feature = "runtime-benchmarks", test))]
#[cfg(feature = "runtime-benchmarks")]
fn add_voter(voter: AccountId, weight: VoteWeight, targets: Vec<AccountId>) {
let mut current = Voters::get();
current.push((voter, weight, targets));
Voters::set(current);
}
#[cfg(any(feature = "runtime-benchmarks", test))]
#[cfg(feature = "runtime-benchmarks")]
fn add_target(target: AccountId) {
let mut current = Targets::get();
current.push(target);
@@ -343,7 +343,17 @@ impl<T: Config> Pallet<T> {
///
/// This drains the [`SignedSubmissions`], potentially storing the best valid one in
/// [`QueuedSolution`].
pub fn finalize_signed_phase() -> (bool, Weight) {
///
/// This is a *self-weighing* function, it automatically registers its weight internally when
/// being called.
pub fn finalize_signed_phase() -> bool {
let (weight, found_solution) = Self::finalize_signed_phase_internal();
Self::register_weight(weight);
found_solution
}
/// The guts of [`finalized_signed_phase`], that does everything except registering its weight.
pub(crate) fn finalize_signed_phase_internal() -> (Weight, bool) {
let mut all_submissions = Self::signed_submissions();
let mut found_solution = false;
let mut weight = T::DbWeight::get().reads(1);
@@ -402,9 +412,9 @@ impl<T: Config> Pallet<T> {
found_solution,
discarded
);
(found_solution, weight)
}
(weight, found_solution)
}
/// Helper function for the case where a solution is accepted in the signed phase.
///
/// Extracted to facilitate with weight calculation.
@@ -568,7 +578,7 @@ mod tests {
assert_ok!(submit_with_witness(Origin::signed(99), solution));
assert_eq!(balances(&99), (95, 5));
assert!(MultiPhase::finalize_signed_phase().0);
assert!(MultiPhase::finalize_signed_phase());
assert_eq!(balances(&99), (100 + 7 + 8, 0));
})
}
@@ -589,7 +599,7 @@ mod tests {
assert_eq!(balances(&99), (95, 5));
// no good solution was stored.
assert!(!MultiPhase::finalize_signed_phase().0);
assert!(!MultiPhase::finalize_signed_phase());
// and the bond is gone.
assert_eq!(balances(&99), (95, 0));
})
@@ -615,7 +625,7 @@ mod tests {
assert_eq!(balances(&999), (95, 5));
// _some_ good solution was stored.
assert!(MultiPhase::finalize_signed_phase().0);
assert!(MultiPhase::finalize_signed_phase());
// 99 is rewarded.
assert_eq!(balances(&99), (100 + 7 + 8, 0));
@@ -806,7 +816,7 @@ mod tests {
);
// _some_ good solution was stored.
assert!(MultiPhase::finalize_signed_phase().0);
assert!(MultiPhase::finalize_signed_phase());
// 99 is rewarded.
assert_eq!(balances(&99), (100 + 7 + 8, 0));
@@ -906,7 +916,7 @@ mod tests {
roll_to(block_number);
assert_eq!(SignedSubmissions::<Runtime>::decode_len().unwrap_or_default(), 0);
assert_storage_noop!(MultiPhase::finalize_signed_phase());
assert_storage_noop!(MultiPhase::finalize_signed_phase_internal());
}
})
}
@@ -923,7 +933,7 @@ mod tests {
assert_ok!(submit_with_witness(Origin::signed(99), solution.clone()));
// _some_ good solution was stored.
assert!(MultiPhase::finalize_signed_phase().0);
assert!(MultiPhase::finalize_signed_phase());
// calling it again doesn't change anything
assert_storage_noop!(MultiPhase::finalize_signed_phase());
@@ -662,19 +662,19 @@ mod max_weight {
struct TestWeight;
impl crate::weights::WeightInfo for TestWeight {
fn elect_queued(a: u32, d: u32) -> Weight {
unreachable!()
}
fn create_snapshot_internal() -> Weight {
unreachable!()
}
fn on_initialize_nothing() -> Weight {
unreachable!()
}
fn on_initialize_open_signed() -> Weight {
unreachable!()
}
fn on_initialize_open_unsigned_with_snapshot() -> Weight {
unreachable!()
}
fn elect_queued(_v: u32, _t: u32, _a: u32, _d: u32) -> Weight {
0
}
fn on_initialize_open_unsigned_without_snapshot() -> Weight {
fn on_initialize_open_unsigned() -> Weight {
unreachable!()
}
fn finalize_signed_phase_accept_solution() -> Weight {
@@ -18,7 +18,7 @@
//! Autogenerated weights for pallet_election_provider_multi_phase
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! DATE: 2021-08-18, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128
// Executed Command:
@@ -47,11 +47,11 @@ use sp_std::marker::PhantomData;
pub trait WeightInfo {
fn on_initialize_nothing() -> Weight;
fn on_initialize_open_signed() -> Weight;
fn on_initialize_open_unsigned_with_snapshot() -> Weight;
fn on_initialize_open_unsigned_without_snapshot() -> Weight;
fn on_initialize_open_unsigned() -> Weight;
fn finalize_signed_phase_accept_solution() -> Weight;
fn finalize_signed_phase_reject_solution() -> Weight;
fn elect_queued(v: u32, t: u32, a: u32, d: u32, ) -> Weight;
fn create_snapshot_internal() -> Weight;
fn elect_queued(a: u32, d: u32, ) -> Weight;
fn submit(c: u32, ) -> Weight;
fn submit_unsigned(v: u32, t: u32, a: u32, d: u32, ) -> Weight;
fn feasibility_check(v: u32, t: u32, a: u32, d: u32, ) -> Weight;
@@ -69,65 +69,43 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking ForceEra (r:1 w:0)
// Storage: ElectionProviderMultiPhase CurrentPhase (r:1 w:0)
fn on_initialize_nothing() -> Weight {
(22_589_000 as Weight)
(23_878_000 as Weight)
.saturating_add(T::DbWeight::get().reads(8 as Weight))
}
// Storage: Staking CounterForValidators (r:1 w:0)
// Storage: Staking Validators (r:2 w:0)
// Storage: Staking CounterForNominators (r:1 w:0)
// Storage: Staking SlashingSpans (r:1 w:0)
// Storage: Staking Bonded (r:1 w:0)
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking ValidatorCount (r:1 w:0)
// Storage: ElectionProviderMultiPhase Round (r:1 w:0)
// Storage: ElectionProviderMultiPhase SnapshotMetadata (r:0 w:1)
// Storage: ElectionProviderMultiPhase DesiredTargets (r:0 w:1)
// Storage: ElectionProviderMultiPhase Snapshot (r:0 w:1)
// Storage: ElectionProviderMultiPhase CurrentPhase (r:0 w:1)
fn on_initialize_open_signed() -> Weight {
(107_551_000 as Weight)
.saturating_add(T::DbWeight::get().reads(10 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
// Storage: Staking CounterForValidators (r:1 w:0)
// Storage: Staking Validators (r:2 w:0)
// Storage: Staking CounterForNominators (r:1 w:0)
// Storage: Staking SlashingSpans (r:1 w:0)
// Storage: Staking Bonded (r:1 w:0)
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking ValidatorCount (r:1 w:0)
// Storage: ElectionProviderMultiPhase Round (r:1 w:0)
// Storage: ElectionProviderMultiPhase SnapshotMetadata (r:0 w:1)
// Storage: ElectionProviderMultiPhase DesiredTargets (r:0 w:1)
// Storage: ElectionProviderMultiPhase Snapshot (r:0 w:1)
// Storage: ElectionProviderMultiPhase CurrentPhase (r:0 w:1)
fn on_initialize_open_unsigned_with_snapshot() -> Weight {
(96_899_000 as Weight)
.saturating_add(T::DbWeight::get().reads(10 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
(34_547_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: ElectionProviderMultiPhase Round (r:1 w:0)
// Storage: ElectionProviderMultiPhase CurrentPhase (r:0 w:1)
fn on_initialize_open_unsigned_without_snapshot() -> Weight {
(18_549_000 as Weight)
fn on_initialize_open_unsigned() -> Weight {
(33_568_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: System Account (r:1 w:1)
// Storage: ElectionProviderMultiPhase QueuedSolution (r:0 w:1)
fn finalize_signed_phase_accept_solution() -> Weight {
(48_349_000 as Weight)
(50_596_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
// Storage: System Account (r:1 w:1)
fn finalize_signed_phase_reject_solution() -> Weight {
(32_014_000 as Weight)
(33_389_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: ElectionProviderMultiPhase SnapshotMetadata (r:0 w:1)
// Storage: ElectionProviderMultiPhase DesiredTargets (r:0 w:1)
// Storage: ElectionProviderMultiPhase Snapshot (r:0 w:1)
fn create_snapshot_internal() -> Weight {
(8_835_233_000 as Weight)
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
// Storage: ElectionProviderMultiPhase SignedSubmissionIndices (r:1 w:1)
// Storage: ElectionProviderMultiPhase SignedSubmissionNextIndex (r:1 w:1)
// Storage: ElectionProviderMultiPhase SnapshotMetadata (r:1 w:1)
@@ -137,16 +115,12 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: ElectionProviderMultiPhase DesiredTargets (r:0 w:1)
// Storage: ElectionProviderMultiPhase Snapshot (r:0 w:1)
// Storage: ElectionProviderMultiPhase CurrentPhase (r:0 w:1)
fn elect_queued(v: u32, t: u32, a: u32, d: u32, ) -> Weight {
(0 as Weight)
fn elect_queued(a: u32, d: u32, ) -> Weight {
(82_395_000 as Weight)
// Standard Error: 1_000
.saturating_add((43_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 6_000
.saturating_add((189_000 as Weight).saturating_mul(t as Weight))
// Standard Error: 2_000
.saturating_add((1_667_000 as Weight).saturating_mul(a as Weight))
// Standard Error: 15_000
.saturating_add((129_000 as Weight).saturating_mul(d as Weight))
.saturating_add((1_769_000 as Weight).saturating_mul(a as Weight))
// Standard Error: 13_000
.saturating_add((320_000 as Weight).saturating_mul(d as Weight))
.saturating_add(T::DbWeight::get().reads(6 as Weight))
.saturating_add(T::DbWeight::get().writes(8 as Weight))
}
@@ -157,9 +131,9 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: ElectionProviderMultiPhase SignedSubmissionNextIndex (r:1 w:1)
// Storage: ElectionProviderMultiPhase SignedSubmissionsMap (r:0 w:1)
fn submit(c: u32, ) -> Weight {
(72_163_000 as Weight)
// Standard Error: 30_000
.saturating_add((254_000 as Weight).saturating_mul(c as Weight))
(77_368_000 as Weight)
// Standard Error: 9_000
.saturating_add((369_000 as Weight).saturating_mul(c as Weight))
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
@@ -173,13 +147,13 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
fn submit_unsigned(v: u32, t: u32, a: u32, d: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 4_000
.saturating_add((3_512_000 as Weight).saturating_mul(v as Weight))
.saturating_add((3_553_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 23_000
.saturating_add((49_000 as Weight).saturating_mul(t as Weight))
.saturating_add((35_000 as Weight).saturating_mul(t as Weight))
// Standard Error: 7_000
.saturating_add((10_295_000 as Weight).saturating_mul(a as Weight))
.saturating_add((10_600_000 as Weight).saturating_mul(a as Weight))
// Standard Error: 59_000
.saturating_add((6_008_000 as Weight).saturating_mul(d as Weight))
.saturating_add((6_128_000 as Weight).saturating_mul(d as Weight))
.saturating_add(T::DbWeight::get().reads(7 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
@@ -187,16 +161,14 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: ElectionProviderMultiPhase DesiredTargets (r:1 w:0)
// Storage: ElectionProviderMultiPhase MinimumUntrustedScore (r:1 w:0)
// Storage: ElectionProviderMultiPhase Snapshot (r:1 w:0)
fn feasibility_check(v: u32, t: u32, a: u32, d: u32, ) -> Weight {
fn feasibility_check(v: u32, _t: u32, a: u32, d: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 8_000
.saturating_add((3_508_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 40_000
.saturating_add((302_000 as Weight).saturating_mul(t as Weight))
// Standard Error: 13_000
.saturating_add((8_658_000 as Weight).saturating_mul(a as Weight))
// Standard Error: 100_000
.saturating_add((4_816_000 as Weight).saturating_mul(d as Weight))
// Standard Error: 3_000
.saturating_add((3_478_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 6_000
.saturating_add((8_930_000 as Weight).saturating_mul(a as Weight))
// Standard Error: 47_000
.saturating_add((5_199_000 as Weight).saturating_mul(d as Weight))
.saturating_add(T::DbWeight::get().reads(4 as Weight))
}
}
@@ -212,65 +184,43 @@ impl WeightInfo for () {
// Storage: Staking ForceEra (r:1 w:0)
// Storage: ElectionProviderMultiPhase CurrentPhase (r:1 w:0)
fn on_initialize_nothing() -> Weight {
(22_589_000 as Weight)
(23_878_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(8 as Weight))
}
// Storage: Staking CounterForValidators (r:1 w:0)
// Storage: Staking Validators (r:2 w:0)
// Storage: Staking CounterForNominators (r:1 w:0)
// Storage: Staking SlashingSpans (r:1 w:0)
// Storage: Staking Bonded (r:1 w:0)
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking ValidatorCount (r:1 w:0)
// Storage: ElectionProviderMultiPhase Round (r:1 w:0)
// Storage: ElectionProviderMultiPhase SnapshotMetadata (r:0 w:1)
// Storage: ElectionProviderMultiPhase DesiredTargets (r:0 w:1)
// Storage: ElectionProviderMultiPhase Snapshot (r:0 w:1)
// Storage: ElectionProviderMultiPhase CurrentPhase (r:0 w:1)
fn on_initialize_open_signed() -> Weight {
(107_551_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(10 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
// Storage: Staking CounterForValidators (r:1 w:0)
// Storage: Staking Validators (r:2 w:0)
// Storage: Staking CounterForNominators (r:1 w:0)
// Storage: Staking SlashingSpans (r:1 w:0)
// Storage: Staking Bonded (r:1 w:0)
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking ValidatorCount (r:1 w:0)
// Storage: ElectionProviderMultiPhase Round (r:1 w:0)
// Storage: ElectionProviderMultiPhase SnapshotMetadata (r:0 w:1)
// Storage: ElectionProviderMultiPhase DesiredTargets (r:0 w:1)
// Storage: ElectionProviderMultiPhase Snapshot (r:0 w:1)
// Storage: ElectionProviderMultiPhase CurrentPhase (r:0 w:1)
fn on_initialize_open_unsigned_with_snapshot() -> Weight {
(96_899_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(10 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
(34_547_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: ElectionProviderMultiPhase Round (r:1 w:0)
// Storage: ElectionProviderMultiPhase CurrentPhase (r:0 w:1)
fn on_initialize_open_unsigned_without_snapshot() -> Weight {
(18_549_000 as Weight)
fn on_initialize_open_unsigned() -> Weight {
(33_568_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: System Account (r:1 w:1)
// Storage: ElectionProviderMultiPhase QueuedSolution (r:0 w:1)
fn finalize_signed_phase_accept_solution() -> Weight {
(48_349_000 as Weight)
(50_596_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
}
// Storage: System Account (r:1 w:1)
fn finalize_signed_phase_reject_solution() -> Weight {
(32_014_000 as Weight)
(33_389_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: ElectionProviderMultiPhase SnapshotMetadata (r:0 w:1)
// Storage: ElectionProviderMultiPhase DesiredTargets (r:0 w:1)
// Storage: ElectionProviderMultiPhase Snapshot (r:0 w:1)
fn create_snapshot_internal() -> Weight {
(8_835_233_000 as Weight)
.saturating_add(RocksDbWeight::get().writes(3 as Weight))
}
// Storage: ElectionProviderMultiPhase SignedSubmissionIndices (r:1 w:1)
// Storage: ElectionProviderMultiPhase SignedSubmissionNextIndex (r:1 w:1)
// Storage: ElectionProviderMultiPhase SnapshotMetadata (r:1 w:1)
@@ -280,16 +230,12 @@ impl WeightInfo for () {
// Storage: ElectionProviderMultiPhase DesiredTargets (r:0 w:1)
// Storage: ElectionProviderMultiPhase Snapshot (r:0 w:1)
// Storage: ElectionProviderMultiPhase CurrentPhase (r:0 w:1)
fn elect_queued(v: u32, t: u32, a: u32, d: u32, ) -> Weight {
(0 as Weight)
fn elect_queued(a: u32, d: u32, ) -> Weight {
(82_395_000 as Weight)
// Standard Error: 1_000
.saturating_add((43_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 6_000
.saturating_add((189_000 as Weight).saturating_mul(t as Weight))
// Standard Error: 2_000
.saturating_add((1_667_000 as Weight).saturating_mul(a as Weight))
// Standard Error: 15_000
.saturating_add((129_000 as Weight).saturating_mul(d as Weight))
.saturating_add((1_769_000 as Weight).saturating_mul(a as Weight))
// Standard Error: 13_000
.saturating_add((320_000 as Weight).saturating_mul(d as Weight))
.saturating_add(RocksDbWeight::get().reads(6 as Weight))
.saturating_add(RocksDbWeight::get().writes(8 as Weight))
}
@@ -300,9 +246,9 @@ impl WeightInfo for () {
// Storage: ElectionProviderMultiPhase SignedSubmissionNextIndex (r:1 w:1)
// Storage: ElectionProviderMultiPhase SignedSubmissionsMap (r:0 w:1)
fn submit(c: u32, ) -> Weight {
(72_163_000 as Weight)
// Standard Error: 30_000
.saturating_add((254_000 as Weight).saturating_mul(c as Weight))
(77_368_000 as Weight)
// Standard Error: 9_000
.saturating_add((369_000 as Weight).saturating_mul(c as Weight))
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
.saturating_add(RocksDbWeight::get().writes(3 as Weight))
}
@@ -316,13 +262,13 @@ impl WeightInfo for () {
fn submit_unsigned(v: u32, t: u32, a: u32, d: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 4_000
.saturating_add((3_512_000 as Weight).saturating_mul(v as Weight))
.saturating_add((3_553_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 23_000
.saturating_add((49_000 as Weight).saturating_mul(t as Weight))
.saturating_add((35_000 as Weight).saturating_mul(t as Weight))
// Standard Error: 7_000
.saturating_add((10_295_000 as Weight).saturating_mul(a as Weight))
.saturating_add((10_600_000 as Weight).saturating_mul(a as Weight))
// Standard Error: 59_000
.saturating_add((6_008_000 as Weight).saturating_mul(d as Weight))
.saturating_add((6_128_000 as Weight).saturating_mul(d as Weight))
.saturating_add(RocksDbWeight::get().reads(7 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
@@ -330,16 +276,14 @@ impl WeightInfo for () {
// Storage: ElectionProviderMultiPhase DesiredTargets (r:1 w:0)
// Storage: ElectionProviderMultiPhase MinimumUntrustedScore (r:1 w:0)
// Storage: ElectionProviderMultiPhase Snapshot (r:1 w:0)
fn feasibility_check(v: u32, t: u32, a: u32, d: u32, ) -> Weight {
fn feasibility_check(v: u32, _t: u32, a: u32, d: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 8_000
.saturating_add((3_508_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 40_000
.saturating_add((302_000 as Weight).saturating_mul(t as Weight))
// Standard Error: 13_000
.saturating_add((8_658_000 as Weight).saturating_mul(a as Weight))
// Standard Error: 100_000
.saturating_add((4_816_000 as Weight).saturating_mul(d as Weight))
// Standard Error: 3_000
.saturating_add((3_478_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 6_000
.saturating_add((8_930_000 as Weight).saturating_mul(a as Weight))
// Standard Error: 47_000
.saturating_add((5_199_000 as Weight).saturating_mul(d as Weight))
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
}
}
@@ -80,7 +80,6 @@
//! ```rust
//! # use frame_election_provider_support::{*, data_provider};
//! # use sp_npos_elections::{Support, Assignment};
//! # use frame_support::weights::Weight;
//!
//! type AccountId = u64;
//! type Balance = u64;
@@ -101,16 +100,16 @@
//!
//! impl<T: Config> ElectionDataProvider<AccountId, BlockNumber> for Module<T> {
//! const MAXIMUM_VOTES_PER_VOTER: u32 = 1;
//! fn desired_targets() -> data_provider::Result<(u32, Weight)> {
//! Ok((1, 0))
//! fn desired_targets() -> data_provider::Result<u32> {
//! Ok(1)
//! }
//! fn voters(maybe_max_len: Option<usize>)
//! -> data_provider::Result<(Vec<(AccountId, VoteWeight, Vec<AccountId>)>, Weight)>
//! -> data_provider::Result<Vec<(AccountId, VoteWeight, Vec<AccountId>)>>
//! {
//! Ok((Default::default(), 0))
//! Ok(Default::default())
//! }
//! fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<(Vec<AccountId>, Weight)> {
//! Ok((vec![10, 20, 30], 0))
//! fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
//! Ok(vec![10, 20, 30])
//! }
//! fn next_election_prediction(now: BlockNumber) -> BlockNumber {
//! 0
@@ -132,12 +131,10 @@
//! type Error = &'static str;
//! type DataProvider = T::DataProvider;
//!
//! fn elect() -> Result<(Supports<AccountId>, Weight), Self::Error> {
//! fn elect() -> Result<Supports<AccountId>, Self::Error> {
//! Self::DataProvider::targets(None)
//! .map_err(|_| "failed to elect")
//! .map(|(t, weight)| {
//! (vec![(t[0], Support::default())], weight)
//! })
//! .map(|t| vec![(t[0], Support::default())])
//! }
//! }
//! }
@@ -164,7 +161,6 @@
#![cfg_attr(not(feature = "std"), no_std)]
pub mod onchain;
use frame_support::weights::Weight;
use sp_std::{fmt::Debug, prelude::*};
/// Re-export some type as they are used in the interface.
@@ -189,9 +185,9 @@ pub trait ElectionDataProvider<AccountId, BlockNumber> {
/// If `maybe_max_len` is `Some(v)` then the resulting vector MUST NOT be longer than `v` items
/// long.
///
/// It is assumed that this function will only consume a notable amount of weight, when it
/// returns `Ok(_)`.
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<(Vec<AccountId>, Weight)>;
/// This should be implemented as a self-weighing function. The implementor should register its
/// appropriate weight at the end of execution with the system pallet directly.
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>>;
/// All possible voters for the election.
///
@@ -200,14 +196,17 @@ pub trait ElectionDataProvider<AccountId, BlockNumber> {
/// If `maybe_max_len` is `Some(v)` then the resulting vector MUST NOT be longer than `v` items
/// long.
///
/// It is assumed that this function will only consume a notable amount of weight, when it
/// returns `Ok(_)`.
/// This should be implemented as a self-weighing function. The implementor should register its
/// appropriate weight at the end of execution with the system pallet directly.
fn voters(
maybe_max_len: Option<usize>,
) -> data_provider::Result<(Vec<(AccountId, VoteWeight, Vec<AccountId>)>, Weight)>;
) -> data_provider::Result<Vec<(AccountId, VoteWeight, Vec<AccountId>)>>;
/// The number of targets to elect.
fn desired_targets() -> data_provider::Result<(u32, Weight)>;
///
/// This should be implemented as a self-weighing function. The implementor should register its
/// appropriate weight at the end of execution with the system pallet directly.
fn desired_targets() -> data_provider::Result<u32>;
/// Provide a best effort prediction about when the next election is about to happen.
///
@@ -249,15 +248,15 @@ pub trait ElectionDataProvider<AccountId, BlockNumber> {
#[cfg(feature = "std")]
impl<AccountId, BlockNumber> ElectionDataProvider<AccountId, BlockNumber> for () {
const MAXIMUM_VOTES_PER_VOTER: u32 = 0;
fn targets(_maybe_max_len: Option<usize>) -> data_provider::Result<(Vec<AccountId>, Weight)> {
fn targets(_maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
Ok(Default::default())
}
fn voters(
_maybe_max_len: Option<usize>,
) -> data_provider::Result<(Vec<(AccountId, VoteWeight, Vec<AccountId>)>, Weight)> {
) -> data_provider::Result<Vec<(AccountId, VoteWeight, Vec<AccountId>)>> {
Ok(Default::default())
}
fn desired_targets() -> data_provider::Result<(u32, Weight)> {
fn desired_targets() -> data_provider::Result<u32> {
Ok(Default::default())
}
fn next_election_prediction(now: BlockNumber) -> BlockNumber {
@@ -280,7 +279,10 @@ pub trait ElectionProvider<AccountId, BlockNumber> {
/// Elect a new set of winners.
///
/// The result is returned in a target major format, namely as vector of supports.
fn elect() -> Result<(Supports<AccountId>, Weight), Self::Error>;
///
/// This should be implemented as a self-weighing function. The implementor should register its
/// appropriate weight at the end of execution with the system pallet directly.
fn elect() -> Result<Supports<AccountId>, Self::Error>;
}
#[cfg(feature = "std")]
@@ -288,7 +290,7 @@ impl<AccountId, BlockNumber> ElectionProvider<AccountId, BlockNumber> for () {
type Error = &'static str;
type DataProvider = ();
fn elect() -> Result<(Supports<AccountId>, Weight), Self::Error> {
fn elect() -> Result<Supports<AccountId>, Self::Error> {
Err("<() as ElectionProvider> cannot do anything.")
}
}
@@ -18,7 +18,6 @@
//! An implementation of [`ElectionProvider`] that does an on-chain sequential phragmen.
use crate::{ElectionDataProvider, ElectionProvider};
use frame_support::{traits::Get, weights::Weight};
use sp_npos_elections::*;
use sp_std::{collections::btree_map::BTreeMap, marker::PhantomData, prelude::*};
@@ -55,8 +54,6 @@ pub struct OnChainSequentialPhragmen<T: Config>(PhantomData<T>);
///
/// Note that this is similar to a pallet traits, but [`OnChainSequentialPhragmen`] is not a pallet.
pub trait Config {
/// The block limits.
type BlockWeights: Get<frame_system::limits::BlockWeights>;
/// The account identifier type.
type AccountId: IdentifierT;
/// The block number type.
@@ -71,11 +68,10 @@ impl<T: Config> ElectionProvider<T::AccountId, T::BlockNumber> for OnChainSequen
type Error = Error;
type DataProvider = T::DataProvider;
fn elect() -> Result<(Supports<T::AccountId>, Weight), Self::Error> {
let (voters, _) = Self::DataProvider::voters(None).map_err(Error::DataProvider)?;
let (targets, _) = Self::DataProvider::targets(None).map_err(Error::DataProvider)?;
let (desired_targets, _) =
Self::DataProvider::desired_targets().map_err(Error::DataProvider)?;
fn elect() -> Result<Supports<T::AccountId>, Self::Error> {
let voters = Self::DataProvider::voters(None).map_err(Error::DataProvider)?;
let targets = Self::DataProvider::targets(None).map_err(Error::DataProvider)?;
let desired_targets = Self::DataProvider::desired_targets().map_err(Error::DataProvider)?;
let mut stake_map: BTreeMap<T::AccountId, VoteWeight> = BTreeMap::new();
@@ -93,16 +89,13 @@ impl<T: Config> ElectionProvider<T::AccountId, T::BlockNumber> for OnChainSequen
let staked = assignment_ratio_to_staked_normalized(assignments, &stake_of)?;
let winners = to_without_backing(winners);
to_supports(&winners, &staked)
.map_err(Error::from)
.map(|s| (s, T::BlockWeights::get().max_block))
to_supports(&winners, &staked).map_err(Error::from)
}
}
#[cfg(test)]
mod tests {
use super::*;
use frame_support::weights::Weight;
use sp_npos_elections::Support;
use sp_runtime::Perbill;
@@ -110,7 +103,6 @@ mod tests {
type BlockNumber = u32;
struct Runtime;
impl Config for Runtime {
type BlockWeights = ();
type AccountId = AccountId;
type BlockNumber = BlockNumber;
type Accuracy = Perbill;
@@ -124,21 +116,20 @@ mod tests {
use crate::data_provider;
pub struct DataProvider;
impl ElectionDataProvider<AccountId, BlockNumber> for DataProvider {
const MAXIMUM_VOTES_PER_VOTER: u32 = 2;
fn voters(
_: Option<usize>,
) -> data_provider::Result<(Vec<(AccountId, VoteWeight, Vec<AccountId>)>, Weight)> {
Ok((vec![(1, 10, vec![10, 20]), (2, 20, vec![30, 20]), (3, 30, vec![10, 30])], 0))
) -> data_provider::Result<Vec<(AccountId, VoteWeight, Vec<AccountId>)>> {
Ok(vec![(1, 10, vec![10, 20]), (2, 20, vec![30, 20]), (3, 30, vec![10, 30])])
}
fn targets(_: Option<usize>) -> data_provider::Result<(Vec<AccountId>, Weight)> {
Ok((vec![10, 20, 30], 0))
fn targets(_: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
Ok(vec![10, 20, 30])
}
fn desired_targets() -> data_provider::Result<(u32, Weight)> {
Ok((2, 0))
fn desired_targets() -> data_provider::Result<u32> {
Ok(2)
}
fn next_election_prediction(_: BlockNumber) -> BlockNumber {
@@ -150,7 +141,7 @@ mod tests {
#[test]
fn onchain_seq_phragmen_works() {
assert_eq!(
OnChainPhragmen::elect().unwrap().0,
OnChainPhragmen::elect().unwrap(),
vec![
(10, Support { total: 25, voters: vec![(1, 10), (3, 15)] }),
(30, Support { total: 35, voters: vec![(2, 20), (3, 15)] })
-1
View File
@@ -196,7 +196,6 @@ parameter_types! {
impl onchain::Config for Test {
type AccountId = <Self as frame_system::Config>::AccountId;
type BlockNumber = <Self as frame_system::Config>::BlockNumber;
type BlockWeights = ();
type Accuracy = Perbill;
type DataProvider = Staking;
}
@@ -153,7 +153,6 @@ pub type Extrinsic = sp_runtime::testing::TestXt<Call, ()>;
impl onchain::Config for Test {
type AccountId = AccountId;
type BlockNumber = BlockNumber;
type BlockWeights = ();
type Accuracy = Perbill;
type DataProvider = Staking;
}
@@ -161,7 +161,6 @@ where
impl onchain::Config for Test {
type AccountId = AccountId;
type BlockNumber = BlockNumber;
type BlockWeights = ();
type Accuracy = sp_runtime::Perbill;
type DataProvider = Staking;
}
+1 -3
View File
@@ -43,9 +43,7 @@ pallet-timestamp = { version = "4.0.0-dev", path = "../timestamp" }
pallet-staking-reward-curve = { version = "4.0.0-dev", path = "../staking/reward-curve" }
substrate-test-utils = { version = "4.0.0-dev", path = "../../test-utils" }
frame-benchmarking = { version = "4.0.0-dev", path = "../benchmarking" }
frame-election-provider-support = { version = "4.0.0-dev", features = [
"runtime-benchmarks",
], path = "../election-provider-support" }
frame-election-provider-support = { version = "4.0.0-dev", path = "../election-provider-support" }
rand_chacha = { version = "0.2" }
[features]
+1 -1
View File
@@ -267,7 +267,7 @@
#![recursion_limit = "128"]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(any(feature = "runtime-benchmarks", test))]
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
#[cfg(test)]
mod mock;
-1
View File
@@ -245,7 +245,6 @@ impl OnUnbalanced<NegativeImbalanceOf<Test>> for RewardRemainderMock {
impl onchain::Config for Test {
type AccountId = AccountId;
type BlockNumber = BlockNumber;
type BlockWeights = BlockWeights;
type Accuracy = Perbill;
type DataProvider = Staking;
}
+56 -30
View File
@@ -405,7 +405,7 @@ impl<T: Config> Pallet<T> {
start_session_index: SessionIndex,
is_genesis: bool,
) -> Option<Vec<T::AccountId>> {
let (election_result, weight) = if is_genesis {
let election_result = if is_genesis {
T::GenesisElectionProvider::elect().map_err(|e| {
log!(warn, "genesis election provider failed due to {:?}", e);
Self::deposit_event(Event::StakingElectionFailed);
@@ -418,13 +418,7 @@ impl<T: Config> Pallet<T> {
}
.ok()?;
<frame_system::Pallet<T>>::register_extra_weight_unchecked(
weight,
frame_support::weights::DispatchClass::Mandatory,
);
let exposures = Self::collect_exposures(election_result);
if (exposures.len() as u32) < Self::minimum_validator_count().max(1) {
// Session will panic if we ever return an empty validator set, thus max(1) ^^.
match CurrentEra::<T>::get() {
@@ -637,25 +631,28 @@ impl<T: Config> Pallet<T> {
///
/// This will use all on-chain 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.
///
/// Note that this is VERY expensive. Use with care.
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();
let mut validator_count = 0u32;
for (validator, _) in <Validators<T>>::iter() {
// Append self vote.
let self_vote = (validator.clone(), weight_of(&validator), vec![validator.clone()]);
all_voters.push(self_vote);
validator_count.saturating_inc();
}
// Collect all slashing spans into a BTreeMap for further queries.
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;
@@ -669,17 +666,35 @@ impl<T: Config> Pallet<T> {
if !targets.is_empty() {
let vote_weight = weight_of(&nominator);
all_voters.push((nominator, vote_weight, targets))
all_voters.push((nominator, vote_weight, targets));
nominator_count.saturating_inc();
}
}
Self::register_weight(T::WeightInfo::get_npos_voters(
validator_count,
nominator_count,
slashing_spans.len() as u32,
));
all_voters
}
/// This is a very expensive function and result should be cached versus being called multiple
/// times.
/// Get the targets for an upcoming npos election.
///
/// This function is self-weighing as [`DispatchClass::Mandatory`].
pub fn get_npos_targets() -> Vec<T::AccountId> {
Validators::<T>::iter().map(|(v, _)| v).collect::<Vec<_>>()
let mut validator_count = 0u32;
let targets = Validators::<T>::iter()
.map(|(v, _)| {
validator_count.saturating_inc();
v
})
.collect::<Vec<_>>();
Self::register_weight(T::WeightInfo::get_npos_targets(validator_count));
targets
}
/// This function will add a nominator to the `Nominators` storage map,
@@ -731,47 +746,58 @@ impl<T: Config> Pallet<T> {
false
}
}
/// Register some amount of weight directly with the system pallet.
///
/// This is always mandatory weight.
fn register_weight(weight: Weight) {
<frame_system::Pallet<T>>::register_extra_weight_unchecked(
weight,
DispatchClass::Mandatory,
);
}
}
impl<T: Config> frame_election_provider_support::ElectionDataProvider<T::AccountId, T::BlockNumber>
for Pallet<T>
{
const MAXIMUM_VOTES_PER_VOTER: u32 = T::MAX_NOMINATIONS;
fn desired_targets() -> data_provider::Result<(u32, Weight)> {
Ok((Self::validator_count(), <T as frame_system::Config>::DbWeight::get().reads(1)))
fn desired_targets() -> data_provider::Result<u32> {
Self::register_weight(T::DbWeight::get().reads(1));
Ok(Self::validator_count())
}
fn voters(
maybe_max_len: Option<usize>,
) -> data_provider::Result<(Vec<(T::AccountId, VoteWeight, Vec<T::AccountId>)>, Weight)> {
) -> 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());
// register the extra 2 reads
Self::register_weight(T::DbWeight::get().reads(2));
if maybe_max_len.map_or(false, |max_len| voter_count > max_len) {
return Err("Voter snapshot too big")
}
let slashing_span_count = <SlashingSpans<T>>::iter().count();
let weight = T::WeightInfo::get_npos_voters(
nominator_count,
validator_count,
slashing_span_count as u32,
);
Ok((Self::get_npos_voters(), weight))
Ok(Self::get_npos_voters())
}
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<(Vec<T::AccountId>, Weight)> {
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<T::AccountId>> {
let target_count = CounterForValidators::<T>::get() as usize;
// 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) {
return Err("Target snapshot too big")
}
let weight = <T as frame_system::Config>::DbWeight::get().reads(target_count as u64);
Ok((Self::get_npos_targets(), weight))
Ok(Self::get_npos_targets())
}
fn next_election_prediction(now: T::BlockNumber) -> T::BlockNumber {
@@ -807,7 +833,7 @@ impl<T: Config> frame_election_provider_support::ElectionDataProvider<T::Account
)
}
#[cfg(any(feature = "runtime-benchmarks", test))]
#[cfg(feature = "runtime-benchmarks")]
fn add_voter(voter: T::AccountId, weight: VoteWeight, targets: Vec<T::AccountId>) {
use sp_std::convert::TryFrom;
let stake = <BalanceOf<T>>::try_from(weight).unwrap_or_else(|_| {
@@ -827,7 +853,7 @@ impl<T: Config> frame_election_provider_support::ElectionDataProvider<T::Account
Self::do_add_nominator(&voter, Nominations { targets, submitted_in: 0, suppressed: false });
}
#[cfg(any(feature = "runtime-benchmarks", test))]
#[cfg(feature = "runtime-benchmarks")]
fn add_target(target: T::AccountId) {
let stake = MinValidatorBond::<T>::get() * 100u32.into();
<Bonded<T>>::insert(target.clone(), target.clone());
@@ -847,7 +873,7 @@ impl<T: Config> frame_election_provider_support::ElectionDataProvider<T::Account
);
}
#[cfg(any(feature = "runtime-benchmarks", test))]
#[cfg(feature = "runtime-benchmarks")]
fn clear() {
<Bonded<T>>::remove_all(None);
<Ledger<T>>::remove_all(None);
@@ -855,7 +881,7 @@ impl<T: Config> frame_election_provider_support::ElectionDataProvider<T::Account
<Nominators<T>>::remove_all(None);
}
#[cfg(any(feature = "runtime-benchmarks", test))]
#[cfg(feature = "runtime-benchmarks")]
fn put_snapshot(
voters: Vec<(T::AccountId, VoteWeight, Vec<T::AccountId>)>,
targets: Vec<T::AccountId>,
+2 -6
View File
@@ -1903,7 +1903,7 @@ fn bond_with_duplicate_vote_should_be_ignored_by_election_provider() {
// winners should be 21 and 31. Otherwise this election is taking duplicates into
// account.
let supports = <Test as Config>::ElectionProvider::elect().unwrap().0;
let supports = <Test as Config>::ElectionProvider::elect().unwrap();
assert_eq!(
supports,
vec![
@@ -1947,7 +1947,7 @@ fn bond_with_duplicate_vote_should_be_ignored_by_election_provider_elected() {
assert_ok!(Staking::nominate(Origin::signed(4), vec![21]));
// winners should be 21 and 11.
let supports = <Test as Config>::ElectionProvider::elect().unwrap().0;
let supports = <Test as Config>::ElectionProvider::elect().unwrap();
assert_eq!(
supports,
vec![
@@ -3826,7 +3826,6 @@ mod election_data_provider {
ExtBuilder::default().nominate(false).build_and_execute(|| {
assert!(<Validators<Test>>::iter().map(|(x, _)| x).all(|v| Staking::voters(None)
.unwrap()
.0
.into_iter()
.find(|(w, _, t)| { v == *w && t[0] == *w })
.is_some()))
@@ -3840,7 +3839,6 @@ mod election_data_provider {
assert_eq!(
<Staking as ElectionDataProvider<AccountId, BlockNumber>>::voters(None)
.unwrap()
.0
.iter()
.find(|x| x.0 == 101)
.unwrap()
@@ -3856,7 +3854,6 @@ mod election_data_provider {
assert_eq!(
<Staking as ElectionDataProvider<AccountId, BlockNumber>>::voters(None)
.unwrap()
.0
.iter()
.find(|x| x.0 == 101)
.unwrap()
@@ -3869,7 +3866,6 @@ mod election_data_provider {
assert_eq!(
<Staking as ElectionDataProvider<AccountId, BlockNumber>>::voters(None)
.unwrap()
.0
.iter()
.find(|x| x.0 == 101)
.unwrap()
+117 -119
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-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! DATE: 2021-08-18, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128
// Executed Command:
@@ -85,7 +85,7 @@ 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 {
(72_423_000 as Weight)
(73_523_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
@@ -93,7 +93,7 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking Ledger (r:1 w:1)
// Storage: Balances Locks (r:1 w:1)
fn bond_extra() -> Weight {
(56_157_000 as Weight)
(58_129_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
@@ -104,7 +104,7 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Balances Locks (r:1 w:1)
// Storage: System Account (r:1 w:1)
fn unbond() -> Weight {
(59_039_000 as Weight)
(61_542_000 as Weight)
.saturating_add(T::DbWeight::get().reads(6 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
@@ -113,9 +113,9 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Balances Locks (r:1 w:1)
// Storage: System Account (r:1 w:1)
fn withdraw_unbonded_update(s: u32, ) -> Weight {
(51_503_000 as Weight)
(53_160_000 as Weight)
// Standard Error: 0
.saturating_add((59_000 as Weight).saturating_mul(s as Weight))
.saturating_add((53_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))
}
@@ -130,9 +130,9 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking Payee (r:0 w:1)
// Storage: Staking SpanSlash (r:0 w:2)
fn withdraw_unbonded_kill(s: u32, ) -> Weight {
(84_211_000 as Weight)
// Standard Error: 4_000
.saturating_add((2_391_000 as Weight).saturating_mul(s as 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)))
@@ -144,16 +144,16 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking CounterForValidators (r:1 w:1)
fn validate() -> Weight {
(34_206_000 as Weight)
(34_936_000 as Weight)
.saturating_add(T::DbWeight::get().reads(6 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking Nominators (r:1 w:1)
fn kick(k: u32, ) -> Weight {
(22_863_000 as Weight)
// Standard Error: 13_000
.saturating_add((16_208_000 as Weight).saturating_mul(k as Weight))
(23_493_000 as Weight)
// Standard Error: 17_000
.saturating_add((16_632_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)))
@@ -166,9 +166,9 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking CurrentEra (r:1 w:0)
// Storage: Staking CounterForNominators (r:1 w:1)
fn nominate(n: u32, ) -> Weight {
(41_047_000 as Weight)
// Standard Error: 10_000
.saturating_add((5_611_000 as Weight).saturating_mul(n as 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))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(n as Weight)))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
@@ -177,46 +177,46 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking Validators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:0)
fn chill() -> Weight {
(17_489_000 as Weight)
(17_901_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
}
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking Payee (r:0 w:1)
fn set_payee() -> Weight {
(13_384_000 as Weight)
(13_760_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 {
(27_863_000 as Weight)
(28_388_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_468_000 as Weight)
(2_537_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_798_000 as Weight)
(2_749_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_763_000 as Weight)
(2_834_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_707_000 as Weight)
(2_800_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_353_000 as Weight)
(3_429_000 as Weight)
// Standard Error: 0
.saturating_add((56_000 as Weight).saturating_mul(v as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
@@ -231,18 +231,18 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking Payee (r:0 w:1)
// Storage: Staking SpanSlash (r:0 w:2)
fn force_unstake(s: u32, ) -> Weight {
(60_682_000 as Weight)
// Standard Error: 1_000
.saturating_add((2_384_000 as Weight).saturating_mul(s as Weight))
(61_799_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(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_368_335_000 as Weight)
// Standard Error: 221_000
.saturating_add((19_815_000 as Weight).saturating_mul(s as Weight))
(3_383_988_000 as Weight)
// Standard Error: 223_000
.saturating_add((19_981_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 +257,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 {
(108_594_000 as Weight)
// Standard Error: 15_000
.saturating_add((46_477_000 as Weight).saturating_mul(n as Weight))
(124_714_000 as Weight)
// Standard Error: 23_000
.saturating_add((47_575_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 +277,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 {
(157_564_000 as Weight)
// Standard Error: 20_000
.saturating_add((59_781_000 as Weight).saturating_mul(n as Weight))
(160_203_000 as Weight)
// Standard Error: 24_000
.saturating_add((61_321_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))
@@ -289,9 +289,9 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Balances Locks (r:1 w:1)
// Storage: System Account (r:1 w:1)
fn rebond(l: u32, ) -> Weight {
(48_497_000 as Weight)
(49_593_000 as Weight)
// Standard Error: 3_000
.saturating_add((89_000 as Weight).saturating_mul(l as Weight))
.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))
}
@@ -306,8 +306,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: 73_000
.saturating_add((34_176_000 as Weight).saturating_mul(e as Weight))
// Standard Error: 71_000
.saturating_add((35_237_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)))
@@ -323,22 +323,21 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking Payee (r:0 w:1)
// Storage: Staking SpanSlash (r:0 w:1)
fn reap_stash(s: u32, ) -> Weight {
(71_895_000 as Weight)
// Standard Error: 0
.saturating_add((2_376_000 as Weight).saturating_mul(s as 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))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
// Storage: Staking CounterForNominators (r:1 w:0)
// Storage: Staking CounterForValidators (r:1 w:0)
// Storage: Staking SlashingSpans (r:1 w:0)
// Storage: Staking Validators (r:2 w:0)
// 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: Staking ValidatorCount (r:1 w:0)
// Storage: System BlockWeight (r:1 w:1)
// Storage: Staking MinimumValidatorCount (r:1 w:0)
// Storage: Staking CurrentEra (r:1 w:1)
// Storage: Staking HistoryDepth (r:1 w:0)
@@ -349,14 +348,14 @@ 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: 980_000
.saturating_add((300_866_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 49_000
.saturating_add((46_397_000 as Weight).saturating_mul(n as Weight))
.saturating_add(T::DbWeight::get().reads(10 as Weight))
// Standard Error: 856_000
.saturating_add((305_057_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(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().writes(4 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 Validators (r:501 w:0)
@@ -367,11 +366,11 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
fn get_npos_voters(v: u32, n: u32, s: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 98_000
.saturating_add((24_916_000 as Weight).saturating_mul(v as Weight))
.saturating_add((25_610_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 98_000
.saturating_add((26_575_000 as Weight).saturating_mul(n as Weight))
// Standard Error: 3_335_000
.saturating_add((22_464_000 as Weight).saturating_mul(s as Weight))
.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))
.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)))
@@ -379,9 +378,9 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
}
// Storage: Staking Validators (r:501 w:0)
fn get_npos_targets(v: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 32_000
.saturating_add((10_706_000 as Weight).saturating_mul(v as Weight))
(30_422_000 as Weight)
// Standard Error: 33_000
.saturating_add((11_252_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)))
}
@@ -391,7 +390,7 @@ 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_463_000 as Weight)
(6_486_000 as Weight)
.saturating_add(T::DbWeight::get().writes(5 as Weight))
}
// Storage: Staking Ledger (r:1 w:0)
@@ -402,7 +401,7 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: Staking CounterForValidators (r:1 w:1)
// Storage: Staking MinValidatorBond (r:1 w:0)
fn chill_other() -> Weight {
(56_717_000 as Weight)
(58_222_000 as Weight)
.saturating_add(T::DbWeight::get().reads(7 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
@@ -417,7 +416,7 @@ impl WeightInfo for () {
// Storage: Balances Locks (r:1 w:1)
// Storage: Staking Payee (r:0 w:1)
fn bond() -> Weight {
(72_423_000 as Weight)
(73_523_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
@@ -425,7 +424,7 @@ impl WeightInfo for () {
// Storage: Staking Ledger (r:1 w:1)
// Storage: Balances Locks (r:1 w:1)
fn bond_extra() -> Weight {
(56_157_000 as Weight)
(58_129_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
}
@@ -436,7 +435,7 @@ impl WeightInfo for () {
// Storage: Balances Locks (r:1 w:1)
// Storage: System Account (r:1 w:1)
fn unbond() -> Weight {
(59_039_000 as Weight)
(61_542_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(6 as Weight))
.saturating_add(RocksDbWeight::get().writes(3 as Weight))
}
@@ -445,9 +444,9 @@ impl WeightInfo for () {
// Storage: Balances Locks (r:1 w:1)
// Storage: System Account (r:1 w:1)
fn withdraw_unbonded_update(s: u32, ) -> Weight {
(51_503_000 as Weight)
(53_160_000 as Weight)
// Standard Error: 0
.saturating_add((59_000 as Weight).saturating_mul(s as Weight))
.saturating_add((53_000 as Weight).saturating_mul(s as Weight))
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(3 as Weight))
}
@@ -462,9 +461,9 @@ impl WeightInfo for () {
// Storage: Staking Payee (r:0 w:1)
// Storage: Staking SpanSlash (r:0 w:2)
fn withdraw_unbonded_kill(s: u32, ) -> Weight {
(84_211_000 as Weight)
// Standard Error: 4_000
.saturating_add((2_391_000 as Weight).saturating_mul(s as 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)))
@@ -476,16 +475,16 @@ impl WeightInfo for () {
// Storage: Staking Nominators (r:1 w:0)
// Storage: Staking CounterForValidators (r:1 w:1)
fn validate() -> Weight {
(34_206_000 as Weight)
(34_936_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(6 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
}
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking Nominators (r:1 w:1)
fn kick(k: u32, ) -> Weight {
(22_863_000 as Weight)
// Standard Error: 13_000
.saturating_add((16_208_000 as Weight).saturating_mul(k as Weight))
(23_493_000 as Weight)
// Standard Error: 17_000
.saturating_add((16_632_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)))
@@ -498,9 +497,9 @@ impl WeightInfo for () {
// Storage: Staking CurrentEra (r:1 w:0)
// Storage: Staking CounterForNominators (r:1 w:1)
fn nominate(n: u32, ) -> Weight {
(41_047_000 as Weight)
// Standard Error: 10_000
.saturating_add((5_611_000 as Weight).saturating_mul(n as 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))
.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(n as Weight)))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
@@ -509,46 +508,46 @@ impl WeightInfo for () {
// Storage: Staking Validators (r:1 w:0)
// Storage: Staking Nominators (r:1 w:0)
fn chill() -> Weight {
(17_489_000 as Weight)
(17_901_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
}
// Storage: Staking Ledger (r:1 w:0)
// Storage: Staking Payee (r:0 w:1)
fn set_payee() -> Weight {
(13_384_000 as Weight)
(13_760_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 {
(27_863_000 as Weight)
(28_388_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_468_000 as Weight)
(2_537_000 as Weight)
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Staking ForceEra (r:0 w:1)
fn force_no_eras() -> Weight {
(2_798_000 as Weight)
(2_749_000 as Weight)
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Staking ForceEra (r:0 w:1)
fn force_new_era() -> Weight {
(2_763_000 as Weight)
(2_834_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_707_000 as Weight)
(2_800_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_353_000 as Weight)
(3_429_000 as Weight)
// Standard Error: 0
.saturating_add((56_000 as Weight).saturating_mul(v as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
@@ -563,18 +562,18 @@ impl WeightInfo for () {
// Storage: Staking Payee (r:0 w:1)
// Storage: Staking SpanSlash (r:0 w:2)
fn force_unstake(s: u32, ) -> Weight {
(60_682_000 as Weight)
// Standard Error: 1_000
.saturating_add((2_384_000 as Weight).saturating_mul(s as Weight))
(61_799_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(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_368_335_000 as Weight)
// Standard Error: 221_000
.saturating_add((19_815_000 as Weight).saturating_mul(s as Weight))
(3_383_988_000 as Weight)
// Standard Error: 223_000
.saturating_add((19_981_000 as Weight).saturating_mul(s as Weight))
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
@@ -589,9 +588,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 {
(108_594_000 as Weight)
// Standard Error: 15_000
.saturating_add((46_477_000 as Weight).saturating_mul(n as Weight))
(124_714_000 as Weight)
// Standard Error: 23_000
.saturating_add((47_575_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))
@@ -609,9 +608,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 {
(157_564_000 as Weight)
// Standard Error: 20_000
.saturating_add((59_781_000 as Weight).saturating_mul(n as Weight))
(160_203_000 as Weight)
// Standard Error: 24_000
.saturating_add((61_321_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))
@@ -621,9 +620,9 @@ impl WeightInfo for () {
// Storage: Balances Locks (r:1 w:1)
// Storage: System Account (r:1 w:1)
fn rebond(l: u32, ) -> Weight {
(48_497_000 as Weight)
(49_593_000 as Weight)
// Standard Error: 3_000
.saturating_add((89_000 as Weight).saturating_mul(l as Weight))
.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))
}
@@ -638,8 +637,8 @@ impl WeightInfo for () {
// Storage: Staking ErasStartSessionIndex (r:0 w:1)
fn set_history_depth(e: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 73_000
.saturating_add((34_176_000 as Weight).saturating_mul(e as Weight))
// Standard Error: 71_000
.saturating_add((35_237_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)))
@@ -655,22 +654,21 @@ impl WeightInfo for () {
// Storage: Staking Payee (r:0 w:1)
// Storage: Staking SpanSlash (r:0 w:1)
fn reap_stash(s: u32, ) -> Weight {
(71_895_000 as Weight)
// Standard Error: 0
.saturating_add((2_376_000 as Weight).saturating_mul(s as 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))
.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
// Storage: Staking CounterForNominators (r:1 w:0)
// Storage: Staking CounterForValidators (r:1 w:0)
// Storage: Staking SlashingSpans (r:1 w:0)
// Storage: Staking Validators (r:2 w:0)
// 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: Staking ValidatorCount (r:1 w:0)
// Storage: System BlockWeight (r:1 w:1)
// Storage: Staking MinimumValidatorCount (r:1 w:0)
// Storage: Staking CurrentEra (r:1 w:1)
// Storage: Staking HistoryDepth (r:1 w:0)
@@ -681,14 +679,14 @@ impl WeightInfo for () {
// Storage: Staking ErasStartSessionIndex (r:0 w:1)
fn new_era(v: u32, n: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 980_000
.saturating_add((300_866_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 49_000
.saturating_add((46_397_000 as Weight).saturating_mul(n as Weight))
.saturating_add(RocksDbWeight::get().reads(10 as Weight))
// Standard Error: 856_000
.saturating_add((305_057_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(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().writes(4 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 Validators (r:501 w:0)
@@ -699,11 +697,11 @@ impl WeightInfo for () {
fn get_npos_voters(v: u32, n: u32, s: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 98_000
.saturating_add((24_916_000 as Weight).saturating_mul(v as Weight))
.saturating_add((25_610_000 as Weight).saturating_mul(v as Weight))
// Standard Error: 98_000
.saturating_add((26_575_000 as Weight).saturating_mul(n as Weight))
// Standard Error: 3_335_000
.saturating_add((22_464_000 as Weight).saturating_mul(s as Weight))
.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))
.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)))
@@ -711,9 +709,9 @@ impl WeightInfo for () {
}
// Storage: Staking Validators (r:501 w:0)
fn get_npos_targets(v: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 32_000
.saturating_add((10_706_000 as Weight).saturating_mul(v as Weight))
(30_422_000 as Weight)
// Standard Error: 33_000
.saturating_add((11_252_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)))
}
@@ -723,7 +721,7 @@ impl WeightInfo for () {
// Storage: Staking MaxNominatorsCount (r:0 w:1)
// Storage: Staking MinNominatorBond (r:0 w:1)
fn set_staking_limits() -> Weight {
(6_463_000 as Weight)
(6_486_000 as Weight)
.saturating_add(RocksDbWeight::get().writes(5 as Weight))
}
// Storage: Staking Ledger (r:1 w:0)
@@ -734,7 +732,7 @@ impl WeightInfo for () {
// Storage: Staking CounterForValidators (r:1 w:1)
// Storage: Staking MinValidatorBond (r:1 w:0)
fn chill_other() -> Weight {
(56_717_000 as Weight)
(58_222_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(7 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
}
@@ -282,7 +282,7 @@ impl<B: BlockT> Builder<B> {
use serde_json::to_value;
let keys = self.get_keys_paged(prefix, at).await?;
let keys_count = keys.len();
info!(target: LOG_TARGET, "Querying a total of {} keys", keys.len());
debug!(target: LOG_TARGET, "Querying a total of {} keys", keys.len());
let mut key_values: Vec<KeyPair> = vec![];
let client = self.as_online().rpc_client();
@@ -338,7 +338,7 @@ impl<B: BlockT> Builder<B> {
impl<B: BlockT> Builder<B> {
/// Save the given data as state snapshot.
fn save_state_snapshot(&self, data: &[KeyPair], path: &Path) -> Result<(), &'static str> {
info!(target: LOG_TARGET, "writing to state snapshot file {:?}", path);
debug!(target: LOG_TARGET, "writing to state snapshot file {:?}", path);
fs::write(path, data.encode()).map_err(|_| "fs::write failed.")?;
Ok(())
}
@@ -403,7 +403,7 @@ impl<B: BlockT> Builder<B> {
pub(crate) async fn init_remote_client(&mut self) -> Result<(), &'static str> {
let mut online = self.as_online_mut();
info!(target: LOG_TARGET, "initializing remote client to {:?}", online.transport.uri);
debug!(target: LOG_TARGET, "initializing remote client to {:?}", online.transport.uri);
// First, initialize the ws client.
let ws_client = WsClientBuilder::default()
@@ -435,7 +435,7 @@ impl<B: BlockT> Builder<B> {
},
};
info!(
debug!(
target: LOG_TARGET,
"extending externalities with {} manually injected key-values",
self.inject.len()
@@ -487,7 +487,7 @@ impl<B: BlockT> Builder<B> {
let kv = self.pre_build().await?;
let mut ext = TestExternalities::new_empty();
info!(target: LOG_TARGET, "injecting a total of {} keys", kv.len());
debug!(target: LOG_TARGET, "injecting a total of {} keys", kv.len());
for (k, v) in kv {
let (k, v) = (k.0, v.0);
// Insert the key,value pair into the test trie backend