diff --git a/.maintain/frame-weight-template.hbs b/.maintain/frame-weight-template.hbs index 34852daf7d47b..7d7824ed3b295 100644 --- a/.maintain/frame-weight-template.hbs +++ b/.maintain/frame-weight-template.hbs @@ -30,7 +30,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for {{pallet}}. diff --git a/bin/node-template/runtime/src/lib.rs b/bin/node-template/runtime/src/lib.rs index 0145cacef8f7d..81440a09ab4c2 100644 --- a/bin/node-template/runtime/src/lib.rs +++ b/bin/node-template/runtime/src/lib.rs @@ -138,7 +138,10 @@ parameter_types! { pub const Version: RuntimeVersion = VERSION; /// We allow for 2 seconds of compute with a 6 second average block time. pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights - ::with_sensible_defaults(2 * WEIGHT_PER_SECOND, NORMAL_DISPATCH_RATIO); + ::with_sensible_defaults(Weight::new() + .set_computation(2 * WEIGHT_PER_SECOND) + .set_bandwidth(5 * 1024 * 1024), // 5 MB + NORMAL_DISPATCH_RATIO); pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength ::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); pub const SS58Prefix: u8 = 42; diff --git a/bin/node/executor/tests/basic.rs b/bin/node/executor/tests/basic.rs index da0f4e6afb319..eb76b6d31b9a3 100644 --- a/bin/node/executor/tests/basic.rs +++ b/bin/node/executor/tests/basic.rs @@ -18,7 +18,7 @@ use codec::{Decode, Encode, Joiner}; use frame_support::{ traits::Currency, - weights::{DispatchClass, DispatchInfo, GetDispatchInfo}, + weights::{DispatchClass, DispatchInfo, GetDispatchInfo, Weight}, }; use frame_system::{self, AccountInfo, EventRecord, Phase}; use sp_core::{storage::well_known_keys, traits::Externalities, NeverNativeValue}; @@ -700,7 +700,7 @@ fn deploying_wasm_contract_should_work() { function: Call::Contracts( pallet_contracts::Call::instantiate_with_code:: { value: 0, - gas_limit: 500_000_000, + gas_limit: Weight::from_computation(500_000_000), storage_deposit_limit: None, code: transfer_code, data: Vec::new(), @@ -713,7 +713,7 @@ fn deploying_wasm_contract_should_work() { function: Call::Contracts(pallet_contracts::Call::call:: { dest: sp_runtime::MultiAddress::Id(addr.clone()), value: 10, - gas_limit: 500_000_000, + gas_limit: Weight::from_computation(500_000_000), storage_deposit_limit: None, data: vec![0x00, 0x01, 0x02, 0x03], }), diff --git a/bin/node/executor/tests/fees.rs b/bin/node/executor/tests/fees.rs index a84ce1470d877..61b90906e5297 100644 --- a/bin/node/executor/tests/fees.rs +++ b/bin/node/executor/tests/fees.rs @@ -197,18 +197,18 @@ fn transaction_fee_is_correct() { let mut balance_alice = (100 - 69) * DOLLARS; let base_weight = ExtrinsicBaseWeight::get(); - let base_fee = IdentityFee::::calc(&base_weight); + let base_fee = IdentityFee::::calc(&base_weight.computation()); let length_fee = TransactionByteFee::get() * (xt.clone().encode().len() as Balance); balance_alice -= length_fee; let weight = default_transfer_call().get_dispatch_info().weight; - let weight_fee = IdentityFee::::calc(&weight); + let weight_fee = IdentityFee::::calc(&weight.computation()); // we know that weight to fee multiplier is effect-less in block 1. // current weight of transfer = 200_000_000 // Linear weight to fee is 1:1 right now (1 weight = 1 unit of balance) - assert_eq!(weight_fee, weight as Balance); + assert_eq!(weight_fee, weight.computation() as Balance); balance_alice -= base_fee; balance_alice -= weight_fee; balance_alice -= tip; diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index f73443920c213..d2b7efcb2a2e2 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -73,7 +73,9 @@ mod multiplier_tests { } fn target() -> Weight { - TargetBlockFullness::get() * max_normal() + Weight::new() + .set_computation(TargetBlockFullness::get() * max_normal().computation()) + .set_bandwidth(TargetBlockFullness::get() * max_normal().bandwidth()) } // update based on runtime impl. @@ -94,13 +96,13 @@ mod multiplier_tests { let previous_float = previous_float.max(min_multiplier().into_inner() as f64 / accuracy); // maximum tx weight - let m = max_normal() as f64; + let m = max_normal().computation() as f64; // block weight always truncated to max weight - let block_weight = (block_weight as f64).min(m); + let block_weight = (block_weight.computation() as f64).min(m); let v: f64 = AdjustmentVariable::get().to_float(); // Ideal saturation in terms of weight - let ss = target() as f64; + let ss = target().computation() as f64; // Current saturation in terms of weight let s = block_weight; @@ -119,7 +121,7 @@ mod multiplier_tests { .unwrap() .into(); t.execute_with(|| { - System::set_block_consumed_resources(w, 0); + System::set_block_consumed_resources(Some(w.computation()), Some(w.bandwidth()), None); assertions() }); } @@ -128,9 +130,9 @@ mod multiplier_tests { fn truth_value_update_poc_works() { let fm = Multiplier::saturating_from_rational(1, 2); let test_set = vec![ - (0, fm.clone()), - (100, fm.clone()), - (1000, fm.clone()), + (Weight::zero(), fm.clone()), + (Weight::from_computation(100), fm.clone()), + (Weight::from_computation(1000), fm.clone()), (target(), fm.clone()), (max_normal() / 2, fm.clone()), (max_normal(), fm.clone()), @@ -160,7 +162,7 @@ mod multiplier_tests { #[test] fn multiplier_cannot_go_below_limit() { // will not go any further below even if block is empty. - run_with_system_weight(0, || { + run_with_system_weight(Weight::zero(), || { let next = runtime_multiplier_update(min_multiplier()); assert_eq!(next, min_multiplier()); }) @@ -178,7 +180,7 @@ mod multiplier_tests { // 1 < 0.00001 * k * 0.1875 // 10^9 / 1875 < k // k > 533_333 ~ 18,5 days. - run_with_system_weight(0, || { + run_with_system_weight(Weight::zero(), || { // start from 1, the default. let mut fm = Multiplier::one(); let mut iterations: u64 = 0; @@ -214,7 +216,8 @@ mod multiplier_tests { // `cargo test congested_chain_simulation -- --nocapture` to get some insight. // almost full. The entire quota of normal transactions is taken. - let block_weight = BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap() - 100; + let block_weight = BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap() - + Weight::from_computation(100); // Default substrate weight. let tx_weight = frame_support::weights::constants::ExtrinsicBaseWeight::get(); @@ -233,8 +236,9 @@ mod multiplier_tests { } fm = next; iterations += 1; - let fee = - ::WeightToFee::calc(&tx_weight); + let fee = ::WeightToFee::calc( + &tx_weight.computation(), + ); let adjusted_fee = fm.saturating_mul_acc_int(fee); println!( "iteration {}, new fm = {:?}. Fee at this point is: {} units / {} millicents, \ @@ -336,27 +340,27 @@ mod multiplier_tests { #[test] fn weight_to_fee_should_not_overflow_on_large_weights() { - let kb = 1024 as Weight; + let kb = 1024 as u64; let mb = kb * kb; let max_fm = Multiplier::saturating_from_integer(i128::MAX); // check that for all values it can compute, correctly. vec![ - 0, - 1, - 10, - 1000, - kb, - 10 * kb, - 100 * kb, - mb, - 10 * mb, - 2147483647, - 4294967295, + Weight::zero(), + Weight::one(), + Weight::from_computation(10), + Weight::from_computation(1000), + Weight::from_computation(kb), + Weight::from_computation(10 * kb), + Weight::from_computation(100 * kb), + Weight::from_computation(mb), + Weight::from_computation(10 * mb), + Weight::from_computation(2147483647), + Weight::from_computation(4294967295), BlockWeights::get().max_block / 2, BlockWeights::get().max_block, - Weight::max_value() / 2, - Weight::max_value(), + Weight::MAX / 2, + Weight::MAX, ] .into_iter() .for_each(|i| { @@ -369,7 +373,7 @@ mod multiplier_tests { // Some values that are all above the target and will cause an increase. let t = target(); - vec![t + 100, t * 2, t * 4].into_iter().for_each(|i| { + vec![t + Weight::from_computation(100), t * 2, t * 4].into_iter().for_each(|i| { run_with_system_weight(i, || { let fm = runtime_multiplier_update(max_fm); // won't grow. The convert saturates everything. diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index c98bb5cc13f85..7a31a8828492f 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -66,7 +66,7 @@ use sp_runtime::{ generic, impl_opaque_keys, traits::{ self, BlakeTwo256, Block as BlockT, ConvertInto, NumberFor, OpaqueKeys, - SaturatedConversion, StaticLookup, + SaturatedConversion, Saturating, StaticLookup, }, transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity}, ApplyExtrinsicResult, FixedPointNumber, Perbill, Percent, Permill, Perquintill, @@ -169,7 +169,9 @@ const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10); /// by Operational extrinsics. const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); /// We allow for 2 seconds of compute with a 6 second average block time. -const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND; +const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::new() + .set_computation(2 * WEIGHT_PER_SECOND) + .set_bandwidth(5 * 1024 * 1024); // 5 MB parameter_types! { pub const BlockHashCount: BlockNumber = 2400; @@ -673,11 +675,11 @@ impl pallet_election_provider_multi_phase::MinerConfig for Runtime { // The unsigned submissions have to respect the weight of the submit_unsigned call, thus their // weight estimate function is wired to this call's weight. fn solution_weight(v: u32, t: u32, a: u32, d: u32) -> Weight { - < + Weight::from_computation(< ::WeightInfo as pallet_election_provider_multi_phase::WeightInfo - >::submit_unsigned(v, t, a, d) + >::submit_unsigned(v, t, a, d)) } } @@ -1090,7 +1092,7 @@ parameter_types! { pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / ( ::WeightInfo::on_initialize_per_queue_item(1) - ::WeightInfo::on_initialize_per_queue_item(0) - )) / 5) as u32; + )).computation() / 5) as u32; pub Schedule: pallet_contracts::Schedule = Default::default(); } @@ -1807,6 +1809,7 @@ impl_runtime_apis! { storage_deposit_limit: Option, input_data: Vec, ) -> pallet_contracts_primitives::ContractExecResult { + let gas_limit = Weight::from_computation(gas_limit); Contracts::bare_call(origin, dest, value, gas_limit, storage_deposit_limit, input_data, true) } @@ -1820,6 +1823,7 @@ impl_runtime_apis! { salt: Vec, ) -> pallet_contracts_primitives::ContractInstantiateResult { + let gas_limit = Weight::from_computation(gas_limit); Contracts::bare_instantiate(origin, value, gas_limit, storage_deposit_limit, code, data, salt, true) } diff --git a/frame/assets/src/weights.rs b/frame/assets/src/weights.rs index 453df22902ba2..ccec90b094e97 100644 --- a/frame/assets/src/weights.rs +++ b/frame/assets/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_assets. diff --git a/frame/atomic-swap/src/lib.rs b/frame/atomic-swap/src/lib.rs index b999aefaaa907..1434678657814 100644 --- a/frame/atomic-swap/src/lib.rs +++ b/frame/atomic-swap/src/lib.rs @@ -146,7 +146,7 @@ where } fn weight(&self) -> Weight { - T::DbWeight::get().reads_writes(1, 1) + Weight::from_computation(T::DbWeight::get().reads_writes(1, 1)) } fn cancel(&self, source: &AccountId) { @@ -281,12 +281,12 @@ pub mod pallet { /// - `proof`: Revealed proof of the claim. /// - `action`: Action defined in the swap, it must match the entry in blockchain. Otherwise /// the operation fails. This is used for weight calculation. - #[pallet::weight( - T::DbWeight::get().reads_writes(1, 1) + #[pallet::weight({ + let computation_weight = T::DbWeight::get().reads_writes(1, 1) .saturating_add(40_000_000) - .saturating_add((proof.len() as Weight).saturating_mul(100)) - .saturating_add(action.weight()) - )] + .saturating_add((proof.len() as u64).saturating_mul(100)); + Weight::from_computation(computation_weight).saturating_add(action.weight()) + })] pub fn claim_swap( origin: OriginFor, proof: Vec, diff --git a/frame/atomic-swap/src/tests.rs b/frame/atomic-swap/src/tests.rs index 2352e7852d090..8590c936597de 100644 --- a/frame/atomic-swap/src/tests.rs +++ b/frame/atomic-swap/src/tests.rs @@ -30,7 +30,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; diff --git a/frame/aura/src/lib.rs b/frame/aura/src/lib.rs index 222360dc3a7d3..ff6ee531a577d 100644 --- a/frame/aura/src/lib.rs +++ b/frame/aura/src/lib.rs @@ -105,9 +105,9 @@ pub mod pallet { // TODO [#3398] Generate offence report for all authorities that skipped their // slots. - T::DbWeight::get().reads_writes(2, 1) + Weight::from_computation(T::DbWeight::get().reads_writes(2, 1)) } else { - T::DbWeight::get().reads(1) + Weight::from_computation(T::DbWeight::get().reads(1)) } } } diff --git a/frame/aura/src/migrations.rs b/frame/aura/src/migrations.rs index d9b7cb8872a83..6aef56ad95770 100644 --- a/frame/aura/src/migrations.rs +++ b/frame/aura/src/migrations.rs @@ -41,5 +41,5 @@ pub trait RemoveLastTimestamp: super::Config { /// This migration requires a type `T` that implements [`RemoveLastTimestamp`]. pub fn remove_last_timestamp() -> Weight { LastTimestamp::::kill(); - T::DbWeight::get().writes(1) + Weight::from_computation(T::DbWeight::get().writes(1)) } diff --git a/frame/aura/src/mock.rs b/frame/aura/src/mock.rs index 636a28692ba28..1057b645bacbb 100644 --- a/frame/aura/src/mock.rs +++ b/frame/aura/src/mock.rs @@ -49,7 +49,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { diff --git a/frame/authority-discovery/src/lib.rs b/frame/authority-discovery/src/lib.rs index a56d8e785f6ac..e2ae0a1f17c8e 100644 --- a/frame/authority-discovery/src/lib.rs +++ b/frame/authority-discovery/src/lib.rs @@ -227,7 +227,10 @@ mod tests { pub const Period: BlockNumber = 1; pub const Offset: BlockNumber = 0; pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index 561db20849c2f..d492273873cec 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -27,7 +27,7 @@ use frame_support::{ traits::{FindAuthor, Get, VerifySeal}, }; use sp_authorship::{InherentError, UnclesInherentData, INHERENT_IDENTIFIER}; -use sp_runtime::traits::{Header as HeaderT, One, Saturating}; +use sp_runtime::traits::{Header as HeaderT, One, Saturating, Zero}; use sp_std::{collections::btree_set::BTreeSet, prelude::*, result}; const MAX_UNCLES: usize = 10; @@ -175,7 +175,7 @@ pub mod pallet { T::EventHandler::note_author(author); } - 0 + Weight::zero() } fn on_finalize(_: T::BlockNumber) { @@ -434,7 +434,10 @@ mod tests { parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { diff --git a/frame/babe/src/default_weights.rs b/frame/babe/src/default_weights.rs index 57c74323b7932..9d6e693af67ee 100644 --- a/frame/babe/src/default_weights.rs +++ b/frame/babe/src/default_weights.rs @@ -25,7 +25,7 @@ use frame_support::weights::{ impl crate::WeightInfo for () { fn plan_config_change() -> Weight { - DbWeight::get().writes(1) + Weight::from_computation(DbWeight::get().writes(1)) } fn report_equivocation(validator_count: u32) -> Weight { @@ -38,7 +38,7 @@ impl crate::WeightInfo for () { const MAX_NOMINATORS: u64 = 200; // checking membership proof - (35 * WEIGHT_PER_MICROS) + let weight = (35 * WEIGHT_PER_MICROS) .saturating_add((175 * WEIGHT_PER_NANOS).saturating_mul(validator_count)) .saturating_add(DbWeight::get().reads(5)) // check equivocation proof @@ -47,6 +47,8 @@ impl crate::WeightInfo for () { .saturating_add(110 * WEIGHT_PER_MICROS) .saturating_add(25 * WEIGHT_PER_MICROS * MAX_NOMINATORS) .saturating_add(DbWeight::get().reads(14 + 3 * MAX_NOMINATORS)) - .saturating_add(DbWeight::get().writes(10 + 3 * MAX_NOMINATORS)) + .saturating_add(DbWeight::get().writes(10 + 3 * MAX_NOMINATORS)); + + Weight::from_computation(weight) } } diff --git a/frame/babe/src/lib.rs b/frame/babe/src/lib.rs index 1effc2c1989fa..46bc22e56a238 100644 --- a/frame/babe/src/lib.rs +++ b/frame/babe/src/lib.rs @@ -336,7 +336,7 @@ pub mod pallet { /// Initialization fn on_initialize(now: BlockNumberFor) -> Weight { Self::initialize(now); - 0 + Weight::zero() } /// Block finalization @@ -880,7 +880,7 @@ impl frame_support::traits::EstimateNextSessionRotation frame_support::traits::EstimateNextSessionRotation::WeightInfo::report_equivocation) .collect::>() .windows(2) - .all(|w| w[0] < w[1])); + .all(|w| w[0].computation() < w[1].computation())); } #[test] @@ -852,7 +852,7 @@ fn valid_equivocation_reports_dont_pay_fees() { .get_dispatch_info(); // it should have non-zero weight and the fee has to be paid. - assert!(info.weight > 0); + assert!(!info.weight.is_zero()); assert_eq!(info.pays_fee, Pays::Yes); // report the equivocation. diff --git a/frame/bags-list/src/weights.rs b/frame/bags-list/src/weights.rs index 8a8a14a75218d..0b372c62995ac 100644 --- a/frame/bags-list/src/weights.rs +++ b/frame/bags-list/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_bags_list. diff --git a/frame/balances/src/tests.rs b/frame/balances/src/tests.rs index 8f5470ae3cac2..a27735d84582f 100644 --- a/frame/balances/src/tests.rs +++ b/frame/balances/src/tests.rs @@ -24,7 +24,7 @@ macro_rules! decl_tests { ($test:ty, $ext_builder:ty, $existential_deposit:expr) => { use crate::*; - use sp_runtime::{ArithmeticError, FixedPointNumber, traits::{SignedExtension, BadOrigin}}; + use sp_runtime::{ArithmeticError, FixedPointNumber, traits::{SignedExtension, BadOrigin, One}}; use frame_support::{ assert_noop, assert_storage_noop, assert_ok, assert_err, traits::{ @@ -188,14 +188,14 @@ macro_rules! decl_tests { ChargeTransactionPayment::from(1), &1, CALL, - &info_from_weight(1), + &info_from_weight(One::one()), 1, ).is_err()); assert_ok!( as SignedExtension>::pre_dispatch( ChargeTransactionPayment::from(0), &1, CALL, - &info_from_weight(1), + &info_from_weight(One::one()), 1, )); @@ -206,14 +206,14 @@ macro_rules! decl_tests { ChargeTransactionPayment::from(1), &1, CALL, - &info_from_weight(1), + &info_from_weight(One::one()), 1, ).is_err()); assert!( as SignedExtension>::pre_dispatch( ChargeTransactionPayment::from(0), &1, CALL, - &info_from_weight(1), + &info_from_weight(One::one()), 1, ).is_err()); }); diff --git a/frame/balances/src/tests_composite.rs b/frame/balances/src/tests_composite.rs index 4a2cc1d91936d..8d4e3ae2a89c7 100644 --- a/frame/balances/src/tests_composite.rs +++ b/frame/balances/src/tests_composite.rs @@ -46,7 +46,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); pub static ExistentialDeposit: u64 = 0; } impl frame_system::Config for Test { diff --git a/frame/balances/src/tests_local.rs b/frame/balances/src/tests_local.rs index cfc7f84ab3a38..b757f9d86b945 100644 --- a/frame/balances/src/tests_local.rs +++ b/frame/balances/src/tests_local.rs @@ -47,7 +47,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); pub static ExistentialDeposit: u64 = 0; } impl frame_system::Config for Test { diff --git a/frame/balances/src/tests_reentrancy.rs b/frame/balances/src/tests_reentrancy.rs index 7037e9615afd8..92a39fdf506ac 100644 --- a/frame/balances/src/tests_reentrancy.rs +++ b/frame/balances/src/tests_reentrancy.rs @@ -53,7 +53,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); pub static ExistentialDeposit: u64 = 0; } impl frame_system::Config for Test { diff --git a/frame/balances/src/weights.rs b/frame/balances/src/weights.rs index dd22e7ca778f8..16fea4c377736 100644 --- a/frame/balances/src/weights.rs +++ b/frame/balances/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_balances. diff --git a/frame/benchmarking/src/utils.rs b/frame/benchmarking/src/utils.rs index 8c642f74358db..99488b899a6a9 100644 --- a/frame/benchmarking/src/utils.rs +++ b/frame/benchmarking/src/utils.rs @@ -127,6 +127,7 @@ pub struct BenchmarkResult { impl BenchmarkResult { pub fn from_weight(w: Weight) -> Self { + let w = w.computation(); Self { extrinsic_time: (w as u128) / 1_000, ..Default::default() } } } diff --git a/frame/benchmarking/src/weights.rs b/frame/benchmarking/src/weights.rs index 24643bb391152..c4bc42ba71157 100644 --- a/frame/benchmarking/src/weights.rs +++ b/frame/benchmarking/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for frame_benchmarking. diff --git a/frame/bounties/src/lib.rs b/frame/bounties/src/lib.rs index b01a36b430a4e..567df103ff502 100644 --- a/frame/bounties/src/lib.rs +++ b/frame/bounties/src/lib.rs @@ -888,7 +888,8 @@ impl pallet_treasury::SpendFunds for Pallet { bounties_approval_len }); - *total_weight += ::WeightInfo::spend_funds(bounties_len); + *total_weight += + Weight::from_computation(::WeightInfo::spend_funds(bounties_len)); } } diff --git a/frame/bounties/src/migrations/v4.rs b/frame/bounties/src/migrations/v4.rs index 8f5f3ebe55bf4..d732dda0c1db4 100644 --- a/frame/bounties/src/migrations/v4.rs +++ b/frame/bounties/src/migrations/v4.rs @@ -25,6 +25,7 @@ use frame_support::{ }; use sp_core::hexdisplay::HexDisplay; use sp_io::{hashing::twox_128, storage}; +use sp_runtime::traits::Zero; use sp_std::str; use crate as pallet_bounties; @@ -54,7 +55,7 @@ pub fn migrate< target: "runtime::bounties", "New pallet name is equal to the old prefix. No migration needs to be done.", ); - return 0 + return Weight::zero() } let on_chain_storage_version =

::on_chain_storage_version(); @@ -105,7 +106,7 @@ pub fn migrate< "Attempted to apply migration to v4 but failed because storage version is {:?}", on_chain_storage_version, ); - 0 + Weight::zero() } } diff --git a/frame/bounties/src/weights.rs b/frame/bounties/src/weights.rs index a1019b3e5c52c..beb145046cc62 100644 --- a/frame/bounties/src/weights.rs +++ b/frame/bounties/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_bounties. diff --git a/frame/child-bounties/src/tests.rs b/frame/child-bounties/src/tests.rs index 61545561a26c3..97022c3aeca60 100644 --- a/frame/child-bounties/src/tests.rs +++ b/frame/child-bounties/src/tests.rs @@ -28,7 +28,6 @@ use frame_support::{ pallet_prelude::GenesisBuild, parameter_types, traits::{ConstU32, ConstU64, OnInitialize}, - weights::Weight, PalletId, }; @@ -60,7 +59,6 @@ frame_support::construct_runtime!( ); parameter_types! { - pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } diff --git a/frame/child-bounties/src/weights.rs b/frame/child-bounties/src/weights.rs index d11de89bcf5c3..5a5ef14c57f18 100644 --- a/frame/child-bounties/src/weights.rs +++ b/frame/child-bounties/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_child_bounties. diff --git a/frame/collective/src/benchmarking.rs b/frame/collective/src/benchmarking.rs index 076afcd203030..7568829bb6f1c 100644 --- a/frame/collective/src/benchmarking.rs +++ b/frame/collective/src/benchmarking.rs @@ -436,7 +436,7 @@ benchmarks_instance_pallet! { index, approve, )?; - }: close(SystemOrigin::Signed(caller), last_hash, index, Weight::max_value(), bytes_in_storage) + }: close(SystemOrigin::Signed(caller), last_hash, index, Weight::MAX, bytes_in_storage) verify { // The last proposal is removed. assert_eq!(Collective::::proposals().len(), (p - 1) as usize); @@ -511,7 +511,7 @@ benchmarks_instance_pallet! { assert_eq!(Collective::::proposals().len(), p as usize); // Prime nay will close it as disapproved - }: close(SystemOrigin::Signed(caller), last_hash, index, Weight::max_value(), bytes_in_storage) + }: close(SystemOrigin::Signed(caller), last_hash, index, Weight::MAX, bytes_in_storage) verify { assert_eq!(Collective::::proposals().len(), (p - 1) as usize); assert_last_event::(Event::Disapproved { proposal_hash: last_hash }.into()); @@ -583,7 +583,7 @@ benchmarks_instance_pallet! { assert_eq!(Collective::::proposals().len(), p as usize); // Prime aye will close it as approved - }: close(SystemOrigin::Signed(caller), last_hash, p - 1, Weight::max_value(), bytes_in_storage) + }: close(SystemOrigin::Signed(caller), last_hash, p - 1, Weight::MAX, bytes_in_storage) verify { assert_eq!(Collective::::proposals().len(), (p - 1) as usize); assert_last_event::(Event::Executed { proposal_hash: last_hash, result: Err(DispatchError::BadOrigin) }.into()); diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 9fce1762c6ea7..8021879b7b47a 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -420,13 +420,17 @@ pub mod pallet { /// - DB: 1 read (codec `O(M)`) + DB access of `proposal` /// - 1 event /// # - #[pallet::weight(( - T::WeightInfo::execute( + #[pallet::weight({ + let computation_weight = T::WeightInfo::execute( *length_bound, // B T::MaxMembers::get(), // M - ).saturating_add(proposal.get_dispatch_info().weight), // P - DispatchClass::Operational - ))] + ); + + let final_weight = Weight::from_computation(computation_weight) + .saturating_add(proposal.get_dispatch_info().weight); // P + + (final_weight, DispatchClass::Operational) + })] pub fn execute( origin: OriginFor, proposal: Box<>::Proposal>, @@ -447,11 +451,11 @@ pub mod pallet { Ok(get_result_weight(result) .map(|w| { - T::WeightInfo::execute( + let computation_weight = T::WeightInfo::execute( proposal_len as u32, // B members.len() as u32, // M - ) - .saturating_add(w) // P + ); + Weight::from_computation(computation_weight).saturating_add(w) // P }) .into()) } @@ -485,16 +489,17 @@ pub mod pallet { /// # #[pallet::weight(( if *threshold < 2 { - T::WeightInfo::propose_execute( + let computation_weight = T::WeightInfo::propose_execute( *length_bound, // B T::MaxMembers::get(), // M - ).saturating_add(proposal.get_dispatch_info().weight) // P1 + ); + Weight::from_computation(computation_weight).saturating_add(proposal.get_dispatch_info().weight) // P1 } else { - T::WeightInfo::propose_proposed( + Weight::from_computation(T::WeightInfo::propose_proposed( *length_bound, // B T::MaxMembers::get(), // M T::MaxProposals::get(), // P2 - ) + )) }, DispatchClass::Operational ))] @@ -526,11 +531,11 @@ pub mod pallet { Ok(get_result_weight(result) .map(|w| { - T::WeightInfo::propose_execute( + let computation_weight = T::WeightInfo::propose_execute( proposal_len as u32, // B members.len() as u32, // M - ) - .saturating_add(w) // P1 + ); + Weight::from_computation(computation_weight).saturating_add(w) // P1 }) .into()) } else { @@ -676,7 +681,7 @@ pub mod pallet { { let b = *length_bound; let m = T::MaxMembers::get(); - let p1 = *proposal_weight_bound; + let p1 = proposal_weight_bound.computation(); let p2 = T::MaxProposals::get(); T::WeightInfo::close_early_approved(b, m, p2) .max(T::WeightInfo::close_early_disapproved(m, p2)) @@ -690,7 +695,7 @@ pub mod pallet { origin: OriginFor, proposal_hash: T::Hash, #[pallet::compact] index: ProposalIndex, - #[pallet::compact] proposal_weight_bound: Weight, + proposal_weight_bound: Weight, #[pallet::compact] length_bound: u32, ) -> DispatchResultWithPostInfo { let _ = ensure_signed(origin)?; @@ -714,10 +719,11 @@ pub mod pallet { let (proposal_weight, proposal_count) = Self::do_approve_proposal(seats, yes_votes, proposal_hash, proposal); return Ok(( - Some( - T::WeightInfo::close_early_approved(len as u32, seats, proposal_count) - .saturating_add(proposal_weight), - ), + Some({ + let computation_weight = + T::WeightInfo::close_early_approved(len as u32, seats, proposal_count); + Weight::from_computation(computation_weight).saturating_add(proposal_weight) + }), Pays::Yes, ) .into()) @@ -759,10 +765,11 @@ pub mod pallet { let (proposal_weight, proposal_count) = Self::do_approve_proposal(seats, yes_votes, proposal_hash, proposal); Ok(( - Some( - T::WeightInfo::close_approved(len as u32, seats, proposal_count) - .saturating_add(proposal_weight), - ), + Some({ + let computation_weight = + T::WeightInfo::close_approved(len as u32, seats, proposal_count); + Weight::from_computation(computation_weight).saturating_add(proposal_weight) + }), Pays::Yes, ) .into()) @@ -833,7 +840,10 @@ impl, I: 'static> Pallet { ensure!(proposal_len <= length_bound, Error::::WrongProposalLength); let proposal = ProposalOf::::get(hash).ok_or(Error::::ProposalMissing)?; let proposal_weight = proposal.get_dispatch_info().weight; - ensure!(proposal_weight <= weight_bound, Error::::WrongProposalWeight); + ensure!( + proposal_weight.is_strictly_less_than_or_equal(&weight_bound), + Error::::WrongProposalWeight + ); Ok((proposal, proposal_len as usize)) } diff --git a/frame/collective/src/migrations/v4.rs b/frame/collective/src/migrations/v4.rs index 4e6cd05584138..af526b1d3d237 100644 --- a/frame/collective/src/migrations/v4.rs +++ b/frame/collective/src/migrations/v4.rs @@ -24,6 +24,7 @@ use frame_support::{ }, weights::Weight, }; +use sp_runtime::traits::Zero; /// Migrate the entire storage of this pallet to a new prefix. /// @@ -45,7 +46,7 @@ pub fn migrate::on_chain_storage_version(); @@ -70,7 +71,7 @@ pub fn migrate::WrongProposalWeight ); assert_ok!(Collective::close(Origin::signed(4), hash, 0, proposal_weight, proposal_len)); @@ -301,7 +310,7 @@ fn proposal_weight_limit_ignored_on_disapprove() { Origin::signed(4), hash, 0, - proposal_weight - 100, + proposal_weight - Weight::from_computation(100), proposal_len )); }) @@ -687,7 +696,11 @@ fn correct_validate_and_get_proposal() { Error::::WrongProposalLength ); assert_noop!( - Collective::validate_and_get_proposal(&hash, length, weight - 10), + Collective::validate_and_get_proposal( + &hash, + length, + weight - Weight::from_computation(10) + ), Error::::WrongProposalWeight ); let res = Collective::validate_and_get_proposal(&hash, length, weight); @@ -1196,18 +1209,18 @@ fn close_disapprove_does_not_care_about_weight_or_len() { assert_ok!(Collective::vote(Origin::signed(2), hash, 0, true)); // It will not close with bad weight/len information assert_noop!( - Collective::close(Origin::signed(2), hash, 0, 0, 0), + Collective::close(Origin::signed(2), hash, 0, Weight::zero(), 0), Error::::WrongProposalLength, ); assert_noop!( - Collective::close(Origin::signed(2), hash, 0, 0, proposal_len), + Collective::close(Origin::signed(2), hash, 0, Weight::zero(), proposal_len), Error::::WrongProposalWeight, ); // Now we make the proposal fail assert_ok!(Collective::vote(Origin::signed(1), hash, 0, false)); assert_ok!(Collective::vote(Origin::signed(2), hash, 0, false)); // It can close even if the weight/len information is bad - assert_ok!(Collective::close(Origin::signed(2), hash, 0, 0, 0)); + assert_ok!(Collective::close(Origin::signed(2), hash, 0, Weight::zero(), 0)); }) } diff --git a/frame/collective/src/weights.rs b/frame/collective/src/weights.rs index 6392f86de6530..c40d892404633 100644 --- a/frame/collective/src/weights.rs +++ b/frame/collective/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_collective. diff --git a/frame/contracts/src/benchmarking/mod.rs b/frame/contracts/src/benchmarking/mod.rs index 4241456389ec7..72548353f424f 100644 --- a/frame/contracts/src/benchmarking/mod.rs +++ b/frame/contracts/src/benchmarking/mod.rs @@ -204,7 +204,7 @@ benchmarks! { // The base weight without any actual work performed apart from the setup costs. on_initialize {}: { - Storage::::process_deletion_queue_batch(Weight::MAX) + Storage::::process_deletion_queue_batch(Weight::MAX.computation()) } #[skip_meta] @@ -213,7 +213,7 @@ benchmarks! { let instance = Contract::::with_storage(WasmModule::dummy(), k, T::Schedule::get().limits.payload_len)?; Storage::::queue_trie_for_deletion(&instance.info()?)?; }: { - Storage::::process_deletion_queue_batch(Weight::MAX) + Storage::::process_deletion_queue_batch(Weight::MAX.computation()) } on_initialize_per_queue_item { @@ -224,7 +224,7 @@ benchmarks! { ContractInfoOf::::remove(instance.account_id); } }: { - Storage::::process_deletion_queue_batch(Weight::MAX) + Storage::::process_deletion_queue_batch(Weight::MAX.computation()) } // This benchmarks the additional weight that is charged when a contract is executed the @@ -2815,8 +2815,8 @@ benchmarks! { { let weight_per_key = T::WeightInfo::on_initialize_per_trie_key(1) - T::WeightInfo::on_initialize_per_trie_key(0); - let weight_per_queue_item = T::WeightInfo::on_initialize_per_queue_item(1) - - T::WeightInfo::on_initialize_per_queue_item(0); + let weight_per_queue_item = Weight::from_computation(T::WeightInfo::on_initialize_per_queue_item(1) - + T::WeightInfo::on_initialize_per_queue_item(0)); let weight_limit = T::DeletionWeightLimit::get(); let queue_depth: u64 = T::DeletionQueueDepth::get().into(); println!("{:#?}", Schedule::::default()); diff --git a/frame/contracts/src/chain_extension.rs b/frame/contracts/src/chain_extension.rs index ed447719933be..d6415a900d96b 100644 --- a/frame/contracts/src/chain_extension.rs +++ b/frame/contracts/src/chain_extension.rs @@ -60,7 +60,7 @@ use crate::{ Error, }; use codec::{Decode, MaxEncodedLen}; -use frame_support::weights::Weight; +use frame_support::weights::ComputationWeight as Weight; use sp_runtime::DispatchError; use sp_std::{marker::PhantomData, vec::Vec}; diff --git a/frame/contracts/src/exec.rs b/frame/contracts/src/exec.rs index e3ff4788791a5..d6ed00d3fee58 100644 --- a/frame/contracts/src/exec.rs +++ b/frame/contracts/src/exec.rs @@ -33,7 +33,7 @@ use pallet_contracts_primitives::ExecReturnValue; use smallvec::{Array, SmallVec}; use sp_core::{crypto::UncheckedFrom, ecdsa::Public as ECDSAPublic}; use sp_io::crypto::secp256k1_ecdsa_recover_compressed; -use sp_runtime::traits::Convert; +use sp_runtime::traits::{Convert, Zero}; use sp_std::{marker::PhantomData, mem, prelude::*}; pub type AccountIdOf = ::AccountId; @@ -610,7 +610,7 @@ where debug_message: Option<&'a mut Vec>, ) -> Result<(Self, E), ExecError> { let (first_frame, executable, nonce) = - Self::new_frame(args, value, gas_meter, storage_meter, 0, schedule)?; + Self::new_frame(args, value, gas_meter, storage_meter, Weight::zero(), schedule)?; let stack = Self { origin, schedule, @@ -1029,7 +1029,7 @@ where delegated_call: Some(DelegatedCall { executable, caller: self.caller().clone() }), }, value, - 0, + Weight::zero(), )?; self.run(executable, input_data) } @@ -1670,7 +1670,7 @@ mod tests { let value = Default::default(); let recurse_ch = MockLoader::insert(Call, |ctx, _| { // Try to call into yourself. - let r = ctx.ext.call(0, BOB, 0, vec![], true); + let r = ctx.ext.call(Weight::zero(), BOB, 0, vec![], true); REACHED_BOTTOM.with(|reached_bottom| { let mut reached_bottom = reached_bottom.borrow_mut(); @@ -1725,7 +1725,7 @@ mod tests { .with(|caller| *caller.borrow_mut() = Some(ctx.ext.caller().clone())); // Call into CHARLIE contract. - assert_matches!(ctx.ext.call(0, CHARLIE, 0, vec![], true), Ok(_)); + assert_matches!(ctx.ext.call(Weight::zero(), CHARLIE, 0, vec![], true), Ok(_)); exec_success() }); let charlie_ch = MockLoader::insert(Call, |ctx, _| { @@ -1856,7 +1856,7 @@ mod tests { // ALICE is the origin of the call stack assert!(ctx.ext.caller_is_origin()); // BOB calls CHARLIE - ctx.ext.call(0, CHARLIE, 0, vec![], true) + ctx.ext.call(Weight::zero(), CHARLIE, 0, vec![], true) }); ExtBuilder::default().build().execute_with(|| { @@ -1886,7 +1886,7 @@ mod tests { assert_eq!(*ctx.ext.address(), BOB); // Call into charlie contract. - assert_matches!(ctx.ext.call(0, CHARLIE, 0, vec![], true), Ok(_)); + assert_matches!(ctx.ext.call(Weight::zero(), CHARLIE, 0, vec![], true), Ok(_)); exec_success() }); let charlie_ch = MockLoader::insert(Call, |ctx, _| { @@ -2036,7 +2036,7 @@ mod tests { let (address, output) = ctx .ext .instantiate( - 0, + Weight::zero(), dummy_ch, ::Currency::minimum_balance(), vec![], @@ -2097,7 +2097,7 @@ mod tests { // Instantiate a contract and save it's address in `instantiated_contract_address`. assert_matches!( ctx.ext.instantiate( - 0, + Weight::zero(), dummy_ch, ::Currency::minimum_balance(), vec![], @@ -2189,13 +2189,13 @@ mod tests { let info = ctx.ext.contract_info(); assert_eq!(info.storage_deposit, 0); info.storage_deposit = 42; - assert_eq!(ctx.ext.call(0, CHARLIE, 0, vec![], true), exec_trapped()); + assert_eq!(ctx.ext.call(Weight::zero(), CHARLIE, 0, vec![], true), exec_trapped()); assert_eq!(ctx.ext.contract_info().storage_deposit, 42); } exec_success() }); let code_charlie = MockLoader::insert(Call, |ctx, _| { - assert!(ctx.ext.call(0, BOB, 0, vec![99], true).is_ok()); + assert!(ctx.ext.call(Weight::zero(), BOB, 0, vec![99], true).is_ok()); exec_trapped() }); @@ -2224,7 +2224,7 @@ mod tests { fn recursive_call_during_constructor_fails() { let code = MockLoader::insert(Constructor, |ctx, _| { assert_matches!( - ctx.ext.call(0, ctx.ext.address().clone(), 0, vec![], true), + ctx.ext.call(Weight::zero(), ctx.ext.address().clone(), 0, vec![], true), Err(ExecError{error, ..}) if error == >::ContractNotFound.into() ); exec_success() @@ -2326,7 +2326,7 @@ mod tests { // call the contract passed as input with disabled reentry let code_bob = MockLoader::insert(Call, |ctx, _| { let dest = Decode::decode(&mut ctx.input_data.as_ref()).unwrap(); - ctx.ext.call(0, dest, 0, vec![], false) + ctx.ext.call(Weight::zero(), dest, 0, vec![], false) }); let code_charlie = MockLoader::insert(Call, |_, _| exec_success()); @@ -2371,7 +2371,7 @@ mod tests { fn call_deny_reentry() { let code_bob = MockLoader::insert(Call, |ctx, _| { if ctx.input_data[0] == 0 { - ctx.ext.call(0, CHARLIE, 0, vec![], false) + ctx.ext.call(Weight::zero(), CHARLIE, 0, vec![], false) } else { exec_success() } @@ -2379,7 +2379,7 @@ mod tests { // call BOB with input set to '1' let code_charlie = - MockLoader::insert(Call, |ctx, _| ctx.ext.call(0, BOB, 0, vec![1], true)); + MockLoader::insert(Call, |ctx, _| ctx.ext.call(Weight::zero(), BOB, 0, vec![1], true)); ExtBuilder::default().build().execute_with(|| { let schedule = ::Schedule::get(); @@ -2542,18 +2542,30 @@ mod tests { let success_code = MockLoader::insert(Constructor, |_, _| exec_success()); let succ_fail_code = MockLoader::insert(Constructor, move |ctx, _| { ctx.ext - .instantiate(0, fail_code, ctx.ext.minimum_balance() * 100, vec![], &[]) + .instantiate( + Weight::zero(), + fail_code, + ctx.ext.minimum_balance() * 100, + vec![], + &[], + ) .ok(); exec_success() }); let succ_succ_code = MockLoader::insert(Constructor, move |ctx, _| { let (account_id, _) = ctx .ext - .instantiate(0, success_code, ctx.ext.minimum_balance() * 100, vec![], &[]) + .instantiate( + Weight::zero(), + success_code, + ctx.ext.minimum_balance() * 100, + vec![], + &[], + ) .unwrap(); // a plain call should not influence the account counter - ctx.ext.call(0, account_id, 0, vec![], false).unwrap(); + ctx.ext.call(Weight::zero(), account_id, 0, vec![], false).unwrap(); exec_success() }); diff --git a/frame/contracts/src/gas.rs b/frame/contracts/src/gas.rs index 41df125da0170..65bd478f793dc 100644 --- a/frame/contracts/src/gas.rs +++ b/frame/contracts/src/gas.rs @@ -24,7 +24,7 @@ use frame_support::{ DefaultNoBound, }; use sp_core::crypto::UncheckedFrom; -use sp_runtime::traits::Zero; +use sp_runtime::traits::{CheckedSub, Saturating, Zero}; use sp_std::marker::PhantomData; #[cfg(test)] @@ -107,11 +107,11 @@ where /// /// Passing `0` as amount is interpreted as "all remaining gas". pub fn nested(&mut self, amount: Weight) -> Result { - let amount = if amount == 0 { self.gas_left } else { amount }; + let amount = if amount.is_zero() { self.gas_left } else { amount }; // NOTE that it is ok to allocate all available gas since it still ensured // by `charge` that it doesn't reach zero. - if self.gas_left < amount { + if self.gas_left.is_any_less_than(&amount) { Err(>::OutOfGas.into()) } else { self.gas_left -= amount; @@ -121,7 +121,7 @@ where /// Absorb the remaining gas of a nested meter after we are done using it. pub fn absorb_nested(&mut self, nested: Self) { - if self.gas_left == 0 { + if self.gas_left.is_zero() { // All of the remaining gas was inherited by the nested gas meter. When absorbing // we can therefore safely inherit the lowest gas that the nested gas meter experienced // as long as it is lower than the lowest gas that was experienced by the parent. @@ -157,7 +157,7 @@ where } let amount = token.weight(); - let new_value = self.gas_left.checked_sub(amount); + let new_value = self.gas_left.checked_sub(&amount); // We always consume the gas even if there is not enough gas. self.gas_left = new_value.unwrap_or_else(Zero::zero); @@ -229,6 +229,8 @@ where mod tests { use super::{GasMeter, Token}; use crate::tests::Test; + use frame_support::weights::Weight; + use sp_runtime::traits::Zero; /// A simple utility macro that helps to match against a /// list of tokens. @@ -271,20 +273,20 @@ mod tests { #[derive(Copy, Clone, PartialEq, Eq, Debug)] struct SimpleToken(u64); impl Token for SimpleToken { - fn weight(&self) -> u64 { - self.0 + fn weight(&self) -> Weight { + Weight::from_computation(self.0) } } #[test] fn it_works() { - let gas_meter = GasMeter::::new(50000); - assert_eq!(gas_meter.gas_left(), 50000); + let gas_meter = GasMeter::::new(Weight::from_computation(50000)); + assert_eq!(gas_meter.gas_left(), Weight::from_computation(50000)); } #[test] fn tracing() { - let mut gas_meter = GasMeter::::new(50000); + let mut gas_meter = GasMeter::::new(Weight::from_computation(50000)); assert!(!gas_meter.charge(SimpleToken(1)).is_err()); let mut tokens = gas_meter.tokens().iter(); @@ -294,7 +296,7 @@ mod tests { // This test makes sure that nothing can be executed if there is no gas. #[test] fn refuse_to_execute_anything_if_zero() { - let mut gas_meter = GasMeter::::new(0); + let mut gas_meter = GasMeter::::new(Weight::zero()); assert!(gas_meter.charge(SimpleToken(1)).is_err()); } @@ -305,7 +307,7 @@ mod tests { // if the gas meter runs out of gas. However, this is just a nice property to have. #[test] fn overcharge_is_unrecoverable() { - let mut gas_meter = GasMeter::::new(200); + let mut gas_meter = GasMeter::::new(Weight::from_computation(200)); // The first charge is should lead to OOG. assert!(gas_meter.charge(SimpleToken(300)).is_err()); @@ -318,7 +320,7 @@ mod tests { // possible. #[test] fn charge_exact_amount() { - let mut gas_meter = GasMeter::::new(25); + let mut gas_meter = GasMeter::::new(Weight::from_computation(25)); assert!(!gas_meter.charge(SimpleToken(25)).is_err()); } } diff --git a/frame/contracts/src/lib.rs b/frame/contracts/src/lib.rs index a8d1e18efd2cc..4d74a42a581fb 100644 --- a/frame/contracts/src/lib.rs +++ b/frame/contracts/src/lib.rs @@ -115,7 +115,7 @@ use frame_support::{ dispatch::Dispatchable, ensure, traits::{ConstU32, Contains, Currency, Get, Randomness, ReservableCurrency, Time}, - weights::{DispatchClass, GetDispatchInfo, Pays, PostDispatchInfo, Weight}, + weights::{ComputationWeight, DispatchClass, GetDispatchInfo, Pays, PostDispatchInfo, Weight}, BoundedVec, }; use frame_system::{limits::BlockWeights, Pallet as System}; @@ -212,7 +212,7 @@ impl, const P: u32> Get for DefaultContractAccessWe .get(DispatchClass::Normal) .max_total .unwrap_or(block_weights.max_block) / - Weight::from(P) + (P as ComputationWeight) } } @@ -387,8 +387,11 @@ pub mod pallet { .max_block .saturating_sub(System::::block_weight().total()) .min(T::DeletionWeightLimit::get()); - Storage::::process_deletion_queue_batch(weight_limit) - .saturating_add(T::WeightInfo::on_initialize()) + let computation_weight = + Storage::::process_deletion_queue_batch(weight_limit.computation()) + .saturating_add(T::WeightInfo::on_initialize()); + + Weight::from_computation(computation_weight) } } @@ -415,12 +418,15 @@ pub mod pallet { /// * If the account is a regular account, any value will be transferred. /// * If no account exists and the call value is not less than `existential_deposit`, /// a regular account will be created and any value will be transferred. - #[pallet::weight(T::WeightInfo::call().saturating_add(*gas_limit))] + #[pallet::weight({ + let computation_weight = T::WeightInfo::call(); + Weight::from_computation(computation_weight).saturating_add(*gas_limit) + })] pub fn call( origin: OriginFor, dest: ::Source, #[pallet::compact] value: BalanceOf, - #[pallet::compact] gas_limit: Weight, + gas_limit: Weight, storage_deposit_limit: Option< as codec::HasCompact>::Type>, data: Vec, ) -> DispatchResultWithPostInfo { @@ -440,7 +446,10 @@ pub mod pallet { output.result = Err(>::ContractReverted.into()); } } - output.gas_meter.into_dispatch_result(output.result, T::WeightInfo::call()) + output.gas_meter.into_dispatch_result( + output.result, + Weight::from_computation(T::WeightInfo::call()), + ) } /// Instantiates a new contract from the supplied `code` optionally transferring @@ -469,14 +478,14 @@ pub mod pallet { /// - The smart-contract account is created at the computed address. /// - The `value` is transferred to the new account. /// - The `deploy` function is executed in the context of the newly-created account. - #[pallet::weight( - T::WeightInfo::instantiate_with_code(code.len() as u32, salt.len() as u32) - .saturating_add(*gas_limit) - )] + #[pallet::weight({ + let computation_weight = T::WeightInfo::instantiate_with_code(code.len() as u32, salt.len() as u32); + Weight::from_computation(computation_weight).saturating_add(*gas_limit) + })] pub fn instantiate_with_code( origin: OriginFor, #[pallet::compact] value: BalanceOf, - #[pallet::compact] gas_limit: Weight, + gas_limit: Weight, storage_deposit_limit: Option< as codec::HasCompact>::Type>, code: Vec, data: Vec, @@ -502,7 +511,7 @@ pub mod pallet { } output.gas_meter.into_dispatch_result( output.result.map(|(_address, result)| result), - T::WeightInfo::instantiate_with_code(code_len, salt_len), + Weight::from_computation(T::WeightInfo::instantiate_with_code(code_len, salt_len)), ) } @@ -511,13 +520,14 @@ pub mod pallet { /// This function is identical to [`Self::instantiate_with_code`] but without the /// code deployment step. Instead, the `code_hash` of an on-chain deployed wasm binary /// must be supplied. - #[pallet::weight( - T::WeightInfo::instantiate(salt.len() as u32).saturating_add(*gas_limit) - )] + #[pallet::weight({ + let computation_weight = T::WeightInfo::instantiate(salt.len() as u32); + Weight::from_computation(computation_weight).saturating_add(*gas_limit) + })] pub fn instantiate( origin: OriginFor, #[pallet::compact] value: BalanceOf, - #[pallet::compact] gas_limit: Weight, + gas_limit: Weight, storage_deposit_limit: Option< as codec::HasCompact>::Type>, code_hash: CodeHash, data: Vec, @@ -542,7 +552,7 @@ pub mod pallet { } output.gas_meter.into_dispatch_result( output.result.map(|(_address, output)| output), - T::WeightInfo::instantiate(salt_len), + Weight::from_computation(T::WeightInfo::instantiate(salt_len)), ) } @@ -855,8 +865,8 @@ where ); ContractExecResult { result: output.result.map_err(|r| r.error), - gas_consumed: output.gas_meter.gas_consumed(), - gas_required: output.gas_meter.gas_required(), + gas_consumed: output.gas_meter.gas_consumed().computation(), + gas_required: output.gas_meter.gas_required().computation(), storage_deposit: output.storage_deposit, debug_message: debug_message.unwrap_or_default(), } @@ -900,8 +910,8 @@ where .result .map(|(account_id, result)| InstantiateReturnValue { result, account_id }) .map_err(|e| e.error), - gas_consumed: output.gas_meter.gas_consumed(), - gas_required: output.gas_meter.gas_required(), + gas_consumed: output.gas_meter.gas_consumed().computation(), + gas_required: output.gas_meter.gas_required().computation(), storage_deposit: output.storage_deposit, debug_message: debug_message.unwrap_or_default(), } diff --git a/frame/contracts/src/migration.rs b/frame/contracts/src/migration.rs index 0832ebadac9c6..278c1e3b58942 100644 --- a/frame/contracts/src/migration.rs +++ b/frame/contracts/src/migration.rs @@ -21,12 +21,13 @@ use frame_support::{ codec, pallet_prelude::*, storage::migration, storage_alias, traits::Get, Identity, Twox64Concat, }; +use sp_runtime::traits::{Saturating, Zero}; use sp_std::{marker::PhantomData, prelude::*}; /// Wrapper for all migrations of this pallet, based on `StorageVersion`. pub fn migrate() -> Weight { let version = StorageVersion::get::>(); - let mut weight: Weight = 0; + let mut weight = Weight::zero(); if version < 4 { weight = weight.saturating_add(v4::migrate::()); @@ -57,7 +58,7 @@ mod v4 { pub fn migrate() -> Weight { migration::remove_storage_prefix(>::name().as_bytes(), b"CurrentSchedule", b""); - T::DbWeight::get().writes(1) + Weight::from_computation(T::DbWeight::get().writes(1)) } } @@ -126,10 +127,11 @@ mod v5 { type DeletionQueue = StorageValue, Vec>; pub fn migrate() -> Weight { - let mut weight: Weight = 0; + let mut weight = Weight::zero(); >::translate(|_key, old: OldContractInfo| { - weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 1)); + weight = weight + .saturating_add(Weight::from_computation(T::DbWeight::get().reads_writes(1, 1))); match old { OldContractInfo::Alive(old) => Some(ContractInfo:: { trie_id: old.trie_id, @@ -141,7 +143,8 @@ mod v5 { }); DeletionQueue::::translate(|old: Option>| { - weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 1)); + weight = weight + .saturating_add(Weight::from_computation(T::DbWeight::get().reads_writes(1, 1))); old.map(|old| old.into_iter().map(|o| DeletedContract { trie_id: o.trie_id }).collect()) }) .ok(); @@ -215,10 +218,11 @@ mod v6 { type OwnerInfoOf = StorageMap, Identity, CodeHash, OwnerInfo>; pub fn migrate() -> Weight { - let mut weight: Weight = 0; + let mut weight = Weight::zero(); >::translate(|_key, old: OldContractInfo| { - weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 1)); + weight = weight + .saturating_add(Weight::from_computation(T::DbWeight::get().reads_writes(1, 1))); Some(ContractInfo:: { trie_id: old.trie_id, code_hash: old.code_hash, @@ -230,7 +234,8 @@ mod v6 { .expect("Infinite input; no dead input space; qed"); >::translate(|key, old: OldPrefabWasmModule| { - weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 2)); + weight = weight + .saturating_add(Weight::from_computation(T::DbWeight::get().reads_writes(1, 2))); >::insert( key, OwnerInfo { @@ -262,6 +267,6 @@ mod v7 { type Nonce = StorageValue, u64, ValueQuery>; Nonce::::set(AccountCounter::::take()); - T::DbWeight::get().reads_writes(1, 2) + Weight::from_computation(T::DbWeight::get().reads_writes(1, 2)) } } diff --git a/frame/contracts/src/schedule.rs b/frame/contracts/src/schedule.rs index 907ce9e088648..a8c264706ae77 100644 --- a/frame/contracts/src/schedule.rs +++ b/frame/contracts/src/schedule.rs @@ -21,7 +21,7 @@ use crate::{weights::WeightInfo, Config}; use codec::{Decode, Encode}; -use frame_support::{weights::Weight, DefaultNoBound}; +use frame_support::{weights::ComputationWeight as Weight, DefaultNoBound}; use pallet_contracts_proc_macro::{ScheduleDebug, WeightDebug}; use scale_info::TypeInfo; #[cfg(feature = "std")] diff --git a/frame/contracts/src/storage.rs b/frame/contracts/src/storage.rs index a9a78f12581d8..c5ffa10f1ef43 100644 --- a/frame/contracts/src/storage.rs +++ b/frame/contracts/src/storage.rs @@ -28,7 +28,7 @@ use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ dispatch::{DispatchError, DispatchResult}, storage::child::{self, ChildInfo, KillStorageResult}, - weights::Weight, + weights::ComputationWeight as Weight, }; use scale_info::TypeInfo; use sp_core::crypto::UncheckedFrom; @@ -229,7 +229,7 @@ where T::WeightInfo::on_initialize_per_queue_item(0); let weight_per_key = T::WeightInfo::on_initialize_per_trie_key(1) - T::WeightInfo::on_initialize_per_trie_key(0); - let decoding_weight = weight_per_queue_item.saturating_mul(queue_len as Weight); + let decoding_weight = weight_per_queue_item.saturating_mul(queue_len as u64); // `weight_per_key` being zero makes no sense and would constitute a failure to // benchmark properly. We opt for not removing any keys at all in this case. @@ -237,7 +237,7 @@ where .saturating_sub(base_weight) .saturating_sub(decoding_weight) .checked_div(weight_per_key) - .unwrap_or(0) as u32; + .unwrap_or(Zero::zero()) as u32; (weight_per_key, key_budget) } @@ -248,7 +248,7 @@ where pub fn process_deletion_queue_batch(weight_limit: Weight) -> Weight { let queue_len = >::decode_len().unwrap_or(0); if queue_len == 0 { - return 0 + return Weight::zero() } let (weight_per_key, mut remaining_key_budget) = diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index 5a6a29786c629..60658a8b15d6f 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -179,7 +179,10 @@ impl ChainExtension for TestExtension { parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(2 * WEIGHT_PER_SECOND); + frame_system::limits::BlockWeights::simple_max(Weight::new() + .set_computation(2 * WEIGHT_PER_SECOND) + .set_bandwidth(1024), + ); pub static ExistentialDeposit: u64 = 1; } impl frame_system::Config for Test { @@ -243,11 +246,12 @@ parameter_types! { }; pub static DepositPerByte: BalanceOf = 1; pub const DepositPerItem: BalanceOf = 2; + pub const DeletionWeightLimit: Weight = Weight::from_computation(500_000_000_000); } impl Convert> for Test { fn convert(w: Weight) -> BalanceOf { - w + w.computation() } } @@ -282,7 +286,7 @@ impl Config for Test { type WeightInfo = (); type ChainExtension = TestExtension; type DeletionQueueDepth = ConstU32<1024>; - type DeletionWeightLimit = ConstU64<500_000_000_000>; + type DeletionWeightLimit = DeletionWeightLimit; type Schedule = MySchedule; type DepositPerByte = DepositPerByte; type DepositPerItem = DepositPerItem; @@ -297,7 +301,7 @@ pub const BOB: AccountId32 = AccountId32::new([2u8; 32]); pub const CHARLIE: AccountId32 = AccountId32::new([3u8; 32]); pub const DJANGO: AccountId32 = AccountId32::new([4u8; 32]); -pub const GAS_LIMIT: Weight = 100_000_000_000; +pub const GAS_LIMIT: Weight = Weight::from_computation(100_000_000_000); pub struct ExtBuilder { existential_deposit: u64, @@ -364,7 +368,7 @@ fn calling_plain_account_fails() { Err(DispatchErrorWithPostInfo { error: Error::::ContractNotFound.into(), post_info: PostDispatchInfo { - actual_weight: Some(base_cost), + actual_weight: Some(Weight::from_computation(base_cost)), pays_fee: Default::default(), }, }) @@ -532,7 +536,7 @@ fn run_out_of_gas() { Origin::signed(ALICE), addr, // newly created account 0, - 1_000_000_000_000, + Weight::from_computation(1_000_000_000_000), None, vec![], ), @@ -1610,7 +1614,7 @@ fn lazy_removal_works() { assert_matches!(child::get(trie, &[99]), Some(42)); // Run the lazy removal - Contracts::on_initialize(Weight::max_value()); + Contracts::on_initialize(Weight::MAX.computation()); // Value should be gone now assert_matches!(child::get::(trie, &[99]), None); @@ -1661,7 +1665,7 @@ fn lazy_batch_removal_works() { } // Run single lazy removal - Contracts::on_initialize(Weight::max_value()); + Contracts::on_initialize(Weight::MAX.computation()); // The single lazy removal should have removed all queued tries for trie in tries.iter() { @@ -1821,9 +1825,9 @@ fn lazy_removal_does_no_run_on_full_block() { // Run the lazy removal without any limit so that all keys would be removed if there // had been some weight left in the block. - let weight_used = Contracts::on_initialize(Weight::max_value()); + let weight_used = Contracts::on_initialize(Weight::MAX.computation()); let base = <::WeightInfo as WeightInfo>::on_initialize(); - assert_eq!(weight_used, base); + assert_eq!(weight_used.computation(), base); // All the keys are still in place for val in &vals { @@ -1831,7 +1835,7 @@ fn lazy_removal_does_no_run_on_full_block() { } // Run the lazy removal directly which disregards the block limits - Storage::::process_deletion_queue_batch(Weight::max_value()); + Storage::::process_deletion_queue_batch(Weight::MAX.computation()); // Now the keys should be gone for val in &vals { @@ -2172,7 +2176,7 @@ fn gas_estimation_nested_call_fixed_limit() { let input: Vec = AsRef::<[u8]>::as_ref(&addr_callee) .iter() .cloned() - .chain((GAS_LIMIT / 5).to_le_bytes()) + .chain((GAS_LIMIT.computation() / 5).to_le_bytes()) .collect(); // Call in order to determine the gas that is required for this call @@ -2196,7 +2200,7 @@ fn gas_estimation_nested_call_fixed_limit() { ALICE, addr_caller, 0, - result.gas_required, + Weight::from_computation(result.gas_required), Some(result.storage_deposit.charge_or_zero()), input, false, @@ -2266,7 +2270,7 @@ fn gas_estimation_call_runtime() { ALICE, addr_caller, 0, - result.gas_required, + Weight::from_computation(result.gas_required), None, call.encode(), false, diff --git a/frame/contracts/src/wasm/code_cache.rs b/frame/contracts/src/wasm/code_cache.rs index 10de436bfb155..eae67b62a3fdb 100644 --- a/frame/contracts/src/wasm/code_cache.rs +++ b/frame/contracts/src/wasm/code_cache.rs @@ -218,14 +218,17 @@ impl Token for CodeToken { // contract code. This is why we substract `T::*::(0)`. We need to do this at this // point because when charging the general weight for calling the contract we not know the // size of the contract. - match *self { + let computation_weight = match *self { Reinstrument(len) => T::WeightInfo::reinstrument(len), Load(len) => { let computation = T::WeightInfo::call_with_code_per_byte(len) .saturating_sub(T::WeightInfo::call_with_code_per_byte(0)); - let bandwith = T::ContractAccessWeight::get().saturating_mul(len.into()); + let bandwith = + T::ContractAccessWeight::get().computation().saturating_mul(len.into()); computation.max(bandwith) }, - } + }; + + Weight::from_computation(computation_weight) } } diff --git a/frame/contracts/src/wasm/env_def/macros.rs b/frame/contracts/src/wasm/env_def/macros.rs index aa5a1626681f4..65a636b923eb4 100644 --- a/frame/contracts/src/wasm/env_def/macros.rs +++ b/frame/contracts/src/wasm/env_def/macros.rs @@ -326,7 +326,7 @@ mod tests { #[test] fn macro_define_func() { define_func!( Ext seal_gas (_ctx, amount: u32) => { - let amount = Weight::from(amount); + let amount = Weight::from_computation(amount.into()); if !amount.is_zero() { Ok(()) } else { @@ -377,7 +377,7 @@ mod tests { define_env!(Env, , [seal0] seal_gas( _ctx, amount: u32 ) => { - let amount = Weight::from(amount); + let amount = Weight::from_computation(amount.into()); if !amount.is_zero() { Ok(()) } else { diff --git a/frame/contracts/src/wasm/mod.rs b/frame/contracts/src/wasm/mod.rs index c385b5d2f7cc2..3f8352a0d9258 100644 --- a/frame/contracts/src/wasm/mod.rs +++ b/frame/contracts/src/wasm/mod.rs @@ -364,7 +364,7 @@ mod tests { events: Default::default(), runtime_calls: Default::default(), schedule: Default::default(), - gas_meter: GasMeter::new(10_000_000_000), + gas_meter: GasMeter::new(Weight::from_computation(10_000_000_000)), debug_buffer: Default::default(), ecdsa_recover: Default::default(), } @@ -405,7 +405,7 @@ mod tests { code_hash: code_hash.clone(), value, data: data.to_vec(), - gas_left: gas_limit, + gas_left: gas_limit.computation(), salt: salt.to_vec(), }); Ok(( @@ -493,7 +493,7 @@ mod tests { 16_384 } fn get_weight_price(&self, weight: Weight) -> BalanceOf { - BalanceOf::::from(1312_u32).saturating_mul(weight.into()) + BalanceOf::::from(1312_u32).saturating_mul(weight.computation().into()) } fn schedule(&self) -> &Schedule { &self.schedule @@ -1448,10 +1448,10 @@ mod tests { let output = execute(CODE_GAS_LEFT, vec![], &mut ext).unwrap(); - let gas_left = Weight::decode(&mut &*output.data).unwrap(); + let gas_left = u64::decode(&mut &*output.data).unwrap(); let actual_left = ext.gas_meter.gas_left(); - assert!(gas_left < gas_limit, "gas_left must be less than initial"); - assert!(gas_left > actual_left, "gas_left must be greater than final"); + assert!(gas_left < gas_limit.computation(), "gas_left must be less than initial"); + assert!(gas_left > actual_left.computation(), "gas_left must be greater than final"); } const CODE_VALUE_TRANSFERRED: &str = r#" @@ -1806,7 +1806,7 @@ mod tests { )] ); - assert!(mock_ext.gas_meter.gas_left() > 0); + assert!(mock_ext.gas_meter.gas_left().computation() > 0); } const CODE_DEPOSIT_EVENT_MAX_TOPICS: &str = r#" diff --git a/frame/contracts/src/wasm/runtime.rs b/frame/contracts/src/wasm/runtime.rs index 850794fc9b09e..c2d0740ccc0ac 100644 --- a/frame/contracts/src/wasm/runtime.rs +++ b/frame/contracts/src/wasm/runtime.rs @@ -232,7 +232,7 @@ impl RuntimeCosts { T::AccountId: UncheckedFrom + AsRef<[u8]>, { use self::RuntimeCosts::*; - let weight = match *self { + let computation_weight = match *self { MeteringBlock(amount) => s.gas.saturating_add(amount.into()), CopyFromContract(len) => s.return_per_byte.saturating_mul(len.into()), CopyToContract(len) => s.input_per_byte.saturating_mul(len.into()), @@ -299,10 +299,12 @@ impl RuntimeCosts { EcdsaRecovery => s.ecdsa_recover, ChainExtension(amount) => amount, #[cfg(feature = "unstable-interface")] - CallRuntime(weight) => weight, + CallRuntime(weight) => weight.computation(), SetCodeHash => s.set_code_hash, EcdsaToEthAddress => s.ecdsa_to_eth_address, }; + + let weight = Weight::from_computation(computation_weight); RuntimeToken { #[cfg(test)] _created_from: *self, @@ -755,7 +757,7 @@ where self.charge_gas(RuntimeCosts::CallSurchargeTransfer)?; } self.ext.call( - gas, + Weight::from_computation(gas), callee, value, input_data, @@ -812,7 +814,13 @@ where let code_hash: CodeHash<::T> = self.read_sandbox_memory_as(code_hash_ptr)?; let input_data = self.read_sandbox_memory(input_data_ptr, input_data_len)?; let salt = self.read_sandbox_memory(salt_ptr, salt_len)?; - let instantiate_outcome = self.ext.instantiate(gas, code_hash, value, input_data, &salt); + let instantiate_outcome = self.ext.instantiate( + Weight::from_computation(gas), + code_hash, + value, + input_data, + &salt, + ); if let Ok((address, output)) = &instantiate_outcome { if !output.flags.contains(ReturnFlags::REVERT) { self.write_sandbox_output( @@ -1455,6 +1463,7 @@ define_env!(Env, , // gas can be smaller than one. [seal0] seal_weight_to_fee(ctx, gas: u64, out_ptr: u32, out_len_ptr: u32) => { ctx.charge_gas(RuntimeCosts::WeightToFee)?; + let gas = Weight::from_computation(gas); Ok(ctx.write_sandbox_output( out_ptr, out_len_ptr, &ctx.ext.get_weight_price(gas).encode(), false, already_charged )?) @@ -1470,7 +1479,7 @@ define_env!(Env, , // The data is encoded as Gas. [seal0] seal_gas_left(ctx, out_ptr: u32, out_len_ptr: u32) => { ctx.charge_gas(RuntimeCosts::GasLeft)?; - let gas_left = &ctx.ext.gas_meter().gas_left().encode(); + let gas_left = &ctx.ext.gas_meter().gas_left().computation().encode(); Ok(ctx.write_sandbox_output( out_ptr, out_len_ptr, gas_left, false, already_charged, )?) diff --git a/frame/contracts/src/weights.rs b/frame/contracts/src/weights.rs index c6e83d34e90b1..70af0fe03b8af 100644 --- a/frame/contracts/src/weights.rs +++ b/frame/contracts/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_contracts. diff --git a/frame/conviction-voting/src/tests.rs b/frame/conviction-voting/src/tests.rs index 6a8bad5d8944e..9274c6759955c 100644 --- a/frame/conviction-voting/src/tests.rs +++ b/frame/conviction-voting/src/tests.rs @@ -57,7 +57,10 @@ impl Contains for BaseFilter { parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1_000_000); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { type BaseCallFilter = BaseFilter; diff --git a/frame/conviction-voting/src/weights.rs b/frame/conviction-voting/src/weights.rs index 6946317475ae2..89bf19cac58da 100644 --- a/frame/conviction-voting/src/weights.rs +++ b/frame/conviction-voting/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_conviction_voting. diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index 91362a0a3edf7..bc29ad27d3ed3 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -1754,7 +1754,7 @@ impl Pallet { /// - Db reads per R: `DepositOf`, `ReferendumInfoOf` /// # fn begin_block(now: T::BlockNumber) -> Weight { - let max_block_weight = T::BlockWeights::get().max_block; + let max_block_weight = T::BlockWeights::get().max_block.computation(); let mut weight = 0; let next = Self::lowest_unbaked(); @@ -1799,7 +1799,7 @@ impl Pallet { } }); - weight + Weight::from_computation(weight) } /// Reads the length of account in DepositOf without getting the complete value in the runtime. diff --git a/frame/democracy/src/tests.rs b/frame/democracy/src/tests.rs index 0fe83a07610d1..6c796e416344a 100644 --- a/frame/democracy/src/tests.rs +++ b/frame/democracy/src/tests.rs @@ -78,7 +78,10 @@ impl Contains for BaseFilter { parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1_000_000); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { type BaseCallFilter = BaseFilter; diff --git a/frame/democracy/src/weights.rs b/frame/democracy/src/weights.rs index 50b4f3ab6ba22..362b3ee01bdd0 100644 --- a/frame/democracy/src/weights.rs +++ b/frame/democracy/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_democracy. diff --git a/frame/election-provider-multi-phase/src/lib.rs b/frame/election-provider-multi-phase/src/lib.rs index 7d8559050f300..6f4a1532ec946 100644 --- a/frame/election-provider-multi-phase/src/lib.rs +++ b/frame/election-provider-multi-phase/src/lib.rs @@ -237,7 +237,7 @@ use frame_support::{ dispatch::DispatchResultWithPostInfo, ensure, traits::{Currency, Get, OnUnbalanced, ReservableCurrency}, - weights::{DispatchClass, Weight}, + weights::{ComputationWeight, DispatchClass, Weight}, }; use frame_system::{ensure_none, offchain::SendTransactionTypes}; use scale_info::TypeInfo; @@ -725,7 +725,7 @@ pub mod pallet { next_election, Self::snapshot_metadata() ); - match current_phase { + let computation_weight = 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::create_snapshot() { @@ -783,7 +783,9 @@ pub mod pallet { } }, _ => T::WeightInfo::on_initialize_nothing(), - } + }; + + Weight::from_computation(computation_weight) } fn offchain_worker(now: T::BlockNumber) { @@ -905,7 +907,7 @@ pub mod pallet { prev_ejected: ejected_a_solution, }); - Ok(None.into()) + Ok(None::.into()) } /// Set a new value for `MinimumUntrustedScore`. @@ -984,7 +986,8 @@ pub mod pallet { let size = Self::snapshot_metadata().ok_or(Error::::MissingSnapshotMetadata)?; ensure!( - Self::solution_weight_of(&raw_solution, size) < T::SignedMaxWeight::get(), + Self::solution_weight_of(&raw_solution, size) < + T::SignedMaxWeight::get().computation(), Error::::SignedTooMuchWeight, ); @@ -992,7 +995,7 @@ pub mod pallet { let deposit = Self::deposit_for(&raw_solution, size); let call_fee = { let call = Call::submit { raw_solution: raw_solution.clone() }; - T::EstimateCallFee::estimate_call_fee(&call, None.into()) + T::EstimateCallFee::estimate_call_fee(&call, None::.into()) }; let submission = SignedSubmission { @@ -1411,9 +1414,9 @@ impl Pallet { /// Register some amount of weight directly with the system pallet. /// /// This is always mandatory weight. - fn register_weight(weight: Weight) { + fn register_weight(weight: ComputationWeight) { >::register_extra_weight_unchecked( - weight, + Weight::from_computation(weight), DispatchClass::Mandatory, ); } @@ -2205,7 +2208,7 @@ mod tests { let mut active = 1; while weight_with(active) <= - ::BlockWeights::get().max_block || + ::BlockWeights::get().max_block.computation() || active == all_voters { active += 1; diff --git a/frame/election-provider-multi-phase/src/mock.rs b/frame/election-provider-multi-phase/src/mock.rs index bbc2d6d43beee..6df767d1b3456 100644 --- a/frame/election-provider-multi-phase/src/mock.rs +++ b/frame/election-provider-multi-phase/src/mock.rs @@ -26,9 +26,10 @@ pub use frame_support::{assert_noop, assert_ok, pallet_prelude::GetDefault}; use frame_support::{ bounded_vec, parameter_types, traits::{ConstU32, Hooks}, - weights::Weight, + weights::{ComputationWeight, Weight}, BoundedVec, }; +use frame_system::limits::BlockWeights; use multi_phase::unsigned::{IndexAssignmentOf, VoterOf}; use parking_lot::RwLock; use sp_core::{ @@ -211,7 +212,7 @@ impl frame_system::Config for Runtime { type BlockHashCount = (); type DbWeight = (); type BlockLength = (); - type BlockWeights = BlockWeights; + type BlockWeights = SystemBlockWeights; type Version = (); type PalletInfo = PalletInfo; type AccountData = pallet_balances::AccountData; @@ -225,8 +226,10 @@ impl frame_system::Config for Runtime { const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); parameter_types! { pub const ExistentialDeposit: u64 = 1; - pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights - ::with_sensible_defaults(2 * frame_support::weights::constants::WEIGHT_PER_SECOND, NORMAL_DISPATCH_RATIO); + pub SystemBlockWeights: BlockWeights = BlockWeights::with_sensible_defaults(Weight::new() + .set_computation(2 * frame_support::weights::constants::WEIGHT_PER_SECOND) + .set_bandwidth(1024), + NORMAL_DISPATCH_RATIO); } impl pallet_balances::Config for Runtime { @@ -271,12 +274,12 @@ parameter_types! { pub static SignedDepositByte: Balance = 0; pub static SignedDepositWeight: Balance = 0; pub static SignedRewardBase: Balance = 7; - pub static SignedMaxWeight: Weight = BlockWeights::get().max_block; + pub static SignedMaxWeight: Weight = SystemBlockWeights::get().max_block; pub static MinerTxPriority: u64 = 100; pub static BetterSignedThreshold: Perbill = Perbill::zero(); pub static BetterUnsignedThreshold: Perbill = Perbill::zero(); pub static OffchainRepeat: BlockNumber = 5; - pub static MinerMaxWeight: Weight = BlockWeights::get().max_block; + pub static MinerMaxWeight: Weight = SystemBlockWeights::get().max_block; pub static MinerMaxLength: u32 = 256; pub static MockWeightInfo: MockedWeightInfo = MockedWeightInfo::Real; pub static MaxElectingVoters: VoterIndex = u32::max_value(); @@ -348,13 +351,15 @@ impl MinerConfig for Runtime { type Solution = TestNposSolution; fn solution_weight(v: u32, t: u32, a: u32, d: u32) -> Weight { - match MockWeightInfo::get() { - MockedWeightInfo::Basic => - (10 as Weight).saturating_add((5 as Weight).saturating_mul(a as Weight)), - MockedWeightInfo::Complex => (0 * v + 0 * t + 1000 * a + 0 * d) as Weight, + let computation_weight = match MockWeightInfo::get() { + MockedWeightInfo::Basic => (10 as ComputationWeight) + .saturating_add((5 as ComputationWeight).saturating_mul(a as ComputationWeight)), + MockedWeightInfo::Complex => (0 * v + 0 * t + 1000 * a + 0 * d) as ComputationWeight, MockedWeightInfo::Real => <() as multi_phase::weights::WeightInfo>::feasibility_check(v, t, a, d), - } + }; + + Weight::from_computation(computation_weight) } } @@ -504,8 +509,8 @@ impl ExtBuilder { ::set(onchain); self } - pub fn miner_weight(self, weight: Weight) -> Self { - ::set(weight); + pub fn miner_weight(self, weight: ComputationWeight) -> Self { + ::set(Weight::from_computation(weight)); self } pub fn mock_weight_info(self, mock: MockedWeightInfo) -> Self { @@ -535,8 +540,8 @@ impl ExtBuilder { ::set(weight); self } - pub fn signed_weight(self, weight: Weight) -> Self { - ::set(weight); + pub fn signed_weight(self, weight: ComputationWeight) -> Self { + ::set(Weight::from_computation(weight)); self } pub fn build(self) -> sp_io::TestExternalities { diff --git a/frame/election-provider-multi-phase/src/signed.rs b/frame/election-provider-multi-phase/src/signed.rs index eca75139f925a..f889b30a00b08 100644 --- a/frame/election-provider-multi-phase/src/signed.rs +++ b/frame/election-provider-multi-phase/src/signed.rs @@ -27,6 +27,7 @@ use frame_election_provider_support::NposSolution; use frame_support::{ storage::bounded_btree_map::BoundedBTreeMap, traits::{defensive_prelude::*, Currency, Get, OnUnbalanced, ReservableCurrency}, + weights::ComputationWeight, }; use sp_arithmetic::traits::SaturatedConversion; use sp_npos_elections::ElectionScore; @@ -365,7 +366,7 @@ impl Pallet { /// being called. pub fn finalize_signed_phase() -> bool { let (weight, found_solution) = Self::finalize_signed_phase_internal(); - Self::register_weight(weight); + Self::register_weight(weight.computation()); found_solution } @@ -443,7 +444,7 @@ impl Pallet { discarded ); - (weight, found_solution) + (Weight::from_computation(weight), found_solution) } /// Helper function for the case where a solution is accepted in the signed phase. /// @@ -489,13 +490,14 @@ impl Pallet { pub fn solution_weight_of( raw_solution: &RawSolution>, size: SolutionOrSnapshotSize, - ) -> Weight { + ) -> ComputationWeight { T::MinerConfig::solution_weight( size.voters, size.targets, raw_solution.solution.voter_count() as u32, raw_solution.solution.unique_targets().len() as u32, ) + .computation() } /// Collect a sufficient deposit to store this solution. @@ -971,13 +973,13 @@ mod tests { raw.solution.unique_targets().len() as u32, ); // default solution will have 5 edges (5 * 5 + 10) - assert_eq!(solution_weight, 35); + assert_eq!(solution_weight.computation(), 35); assert_eq!(raw.solution.voter_count(), 5); - assert_eq!(::SignedMaxWeight::get(), 40); + assert_eq!(::SignedMaxWeight::get().computation(), 40); assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(raw.clone()))); - ::set(30); + ::set(Weight::from_computation(30)); // note: resubmitting the same solution is technically okay as long as the queue has // space. diff --git a/frame/election-provider-multi-phase/src/unsigned.rs b/frame/election-provider-multi-phase/src/unsigned.rs index 9a1b52d354569..153064f0ba632 100644 --- a/frame/election-provider-multi-phase/src/unsigned.rs +++ b/frame/election-provider-multi-phase/src/unsigned.rs @@ -23,7 +23,9 @@ use crate::{ }; use codec::Encode; use frame_election_provider_support::{NposSolution, NposSolver, PerThing128, VoteWeight}; -use frame_support::{dispatch::DispatchResult, ensure, traits::Get, BoundedVec}; +use frame_support::{ + dispatch::DispatchResult, ensure, traits::Get, weights::ComputationWeight, BoundedVec, +}; use frame_system::offchain::SubmitTransaction; use scale_info::TypeInfo; use sp_npos_elections::{ @@ -622,7 +624,7 @@ impl Miner { assignments: &mut Vec>, ) { let maximum_allowed_voters = - Self::maximum_voter_for_weight(desired_targets, size, max_weight); + Self::maximum_voter_for_weight(desired_targets, size, max_weight.computation()); let removing: usize = assignments.len().saturating_sub(maximum_allowed_voters.saturated_into()); log_no_system!( @@ -641,7 +643,7 @@ impl Miner { pub fn maximum_voter_for_weight( desired_winners: u32, size: SolutionOrSnapshotSize, - max_weight: Weight, + max_weight: ComputationWeight, ) -> u32 { if size.voters < 1 { return size.voters @@ -651,23 +653,25 @@ impl Miner { let mut voters = max_voters; // helper closures. - let weight_with = |active_voters: u32| -> Weight { + let weight_with = |active_voters: u32| -> ComputationWeight { T::solution_weight(size.voters, size.targets, active_voters, desired_winners) + .computation() }; - let next_voters = |current_weight: Weight, voters: u32, step: u32| -> Result { - match current_weight.cmp(&max_weight) { - Ordering::Less => { - let next_voters = voters.checked_add(step); - match next_voters { - Some(voters) if voters < max_voters => Ok(voters), - _ => Err(()), - } - }, - Ordering::Greater => voters.checked_sub(step).ok_or(()), - Ordering::Equal => Ok(voters), - } - }; + let next_voters = + |current_weight: ComputationWeight, voters: u32, step: u32| -> Result { + match current_weight.cmp(&max_weight) { + Ordering::Less => { + let next_voters = voters.checked_add(step); + match next_voters { + Some(voters) if voters < max_voters => Ok(voters), + _ => Err(()), + } + }, + Ordering::Greater => voters.checked_sub(step).ok_or(()), + Ordering::Equal => Ok(voters), + } + }; // First binary-search the right amount of voters let mut step = voters / 2; @@ -785,6 +789,7 @@ mod tests { use frame_election_provider_support::IndexAssignment; use frame_support::{ assert_noop, assert_ok, bounded_vec, dispatch::Dispatchable, traits::OffchainWorker, + weights::Weight, }; use sp_npos_elections::ElectionScore; use sp_runtime::{ @@ -1056,11 +1061,11 @@ mod tests { raw.solution.unique_targets().len() as u32, ); // default solution will have 5 edges (5 * 5 + 10) - assert_eq!(solution_weight, 35); + assert_eq!(solution_weight.computation(), 35); assert_eq!(raw.solution.voter_count(), 5); // now reduce the max weight - ::set(25); + ::set(Weight::from_computation(25)); let (raw, witness) = MultiPhase::mine_solution().unwrap(); let solution_weight = ::solution_weight( @@ -1070,7 +1075,7 @@ mod tests { raw.solution.unique_targets().len() as u32, ); // default solution will have 5 edges (5 * 5 + 10) - assert_eq!(solution_weight, 25); + assert_eq!(solution_weight.computation(), 25); assert_eq!(raw.solution.voter_count(), 3); }) } diff --git a/frame/election-provider-multi-phase/src/weights.rs b/frame/election-provider-multi-phase/src/weights.rs index d4802210ba23f..43e7a0333a43e 100644 --- a/frame/election-provider-multi-phase/src/weights.rs +++ b/frame/election-provider-multi-phase/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_election_provider_multi_phase. diff --git a/frame/election-provider-support/src/lib.rs b/frame/election-provider-support/src/lib.rs index 27bf7a37f9622..91de34785405e 100644 --- a/frame/election-provider-support/src/lib.rs +++ b/frame/election-provider-support/src/lib.rs @@ -586,7 +586,7 @@ impl< } fn weight(voters: u32, targets: u32, vote_degree: u32) -> Weight { - T::phragmen(voters, targets, vote_degree) + Weight::from_computation(T::phragmen(voters, targets, vote_degree)) } } @@ -614,7 +614,7 @@ impl< } fn weight(voters: u32, targets: u32, vote_degree: u32) -> Weight { - T::phragmms(voters, targets, vote_degree) + Weight::from_computation(T::phragmms(voters, targets, vote_degree)) } } diff --git a/frame/election-provider-support/src/weights.rs b/frame/election-provider-support/src/weights.rs index f288ae63bb5da..82465123682ff 100644 --- a/frame/election-provider-support/src/weights.rs +++ b/frame/election-provider-support/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_election_provider_support_benchmarking. diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index ec2234cde5a6e..c6492914d61f6 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -263,7 +263,7 @@ pub mod pallet { if !term_duration.is_zero() && (n % term_duration).is_zero() { Self::do_phragmen() } else { - 0 + Zero::zero() } } } @@ -347,7 +347,7 @@ pub mod pallet { T::Currency::set_lock(T::PalletId::get(), &who, locked_stake, WithdrawReasons::all()); Voting::::insert(&who, Voter { votes, deposit: new_deposit, stake: locked_stake }); - Ok(None.into()) + Ok(None::.into()) } /// Remove `origin` as a voter. @@ -360,7 +360,7 @@ pub mod pallet { let who = ensure_signed(origin)?; ensure!(Self::is_voter(&who), Error::::MustBeVoter); Self::do_remove_voter(&who); - Ok(None.into()) + Ok(None::.into()) } /// Submit oneself for candidacy. A fixed amount of deposit is recorded. @@ -397,7 +397,7 @@ pub mod pallet { .map_err(|_| Error::::InsufficientCandidateFunds)?; >::mutate(|c| c.insert(index, (who, T::CandidacyBond::get()))); - Ok(None.into()) + Ok(None::.into()) } /// Renounce one's intention to be a candidate for the next election round. 3 potential @@ -462,7 +462,7 @@ pub mod pallet { })?; }, }; - Ok(None.into()) + Ok(None::.into()) } /// Remove a particular member from the set. This is effective immediately and the bond of @@ -497,7 +497,7 @@ pub mod pallet { // In both cases, we will change more weight than need. Refund and abort. return Err(Error::::InvalidReplacement.with_weight( // refund. The weight value comes from a benchmark which is special to this. - T::WeightInfo::remove_member_wrong_refund(), + Weight::from_computation(T::WeightInfo::remove_member_wrong_refund()), )) } @@ -510,7 +510,7 @@ pub mod pallet { } // no refund needed. - Ok(None.into()) + Ok(None::.into()) } /// Clean all voters who are defunct (i.e. they do not serve any purpose at all). The @@ -534,7 +534,7 @@ pub mod pallet { .filter(|(_, x)| Self::is_defunct_voter(&x.votes)) .for_each(|(dv, _)| Self::do_remove_voter(&dv)); - Ok(None.into()) + Ok(None::.into()) } } @@ -893,7 +893,7 @@ impl Pallet { if candidates_and_deposit.len().is_zero() { Self::deposit_event(Event::EmptyTerm); - return T::DbWeight::get().reads(5) + return Weight::from_computation(T::DbWeight::get().reads(5)) } // All of the new winners that come out of phragmen will thus have a deposit recorded. @@ -1074,7 +1074,11 @@ impl Pallet { Self::deposit_event(Event::ElectionError); }); - T::WeightInfo::election_phragmen(weight_candidates, weight_voters, weight_edges) + Weight::from_computation(T::WeightInfo::election_phragmen( + weight_candidates, + weight_voters, + weight_edges, + )) } } @@ -1143,7 +1147,10 @@ mod tests { parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { diff --git a/frame/elections-phragmen/src/migrations/v3.rs b/frame/elections-phragmen/src/migrations/v3.rs index b1cdd4be98541..ae32efa449718 100644 --- a/frame/elections-phragmen/src/migrations/v3.rs +++ b/frame/elections-phragmen/src/migrations/v3.rs @@ -19,6 +19,7 @@ use crate::{Config, Pallet}; use codec::{Decode, Encode, FullCodec}; +use frame_benchmarking::Zero; use frame_support::{ pallet_prelude::ValueQuery, traits::StorageVersion, weights::Weight, RuntimeDebug, Twox64Concat, }; @@ -101,14 +102,14 @@ pub fn apply( StorageVersion::new(3).put::>(); - Weight::max_value() + Weight::MAX } else { log::warn!( target: "runtime::elections-phragmen", "Attempted to apply migration to V3 but failed because storage version is {:?}", storage_version, ); - 0 + Weight::zero() } } diff --git a/frame/elections-phragmen/src/migrations/v4.rs b/frame/elections-phragmen/src/migrations/v4.rs index e0fc17ec2a12d..d9edc6567f144 100644 --- a/frame/elections-phragmen/src/migrations/v4.rs +++ b/frame/elections-phragmen/src/migrations/v4.rs @@ -18,6 +18,7 @@ //! Migrations to version [`4.0.0`], as denoted by the changelog. use frame_support::{ + dispatch::Zero, traits::{Get, StorageVersion}, weights::Weight, }; @@ -38,7 +39,7 @@ pub fn migrate>(new_pallet_name: N) -> Weight { target: "runtime::elections-phragmen", "New pallet name is equal to the old prefix. No migration needs to be done.", ); - return 0 + return Weight::zero() } let storage_version = StorageVersion::get::>(); log::info!( @@ -63,7 +64,7 @@ pub fn migrate>(new_pallet_name: N) -> Weight { "Attempted to apply migration to v4 but failed because storage version is {:?}", storage_version, ); - 0 + Weight::zero() } } diff --git a/frame/elections-phragmen/src/migrations/v5.rs b/frame/elections-phragmen/src/migrations/v5.rs index a9fb018ba0219..4493624f2e6ec 100644 --- a/frame/elections-phragmen/src/migrations/v5.rs +++ b/frame/elections-phragmen/src/migrations/v5.rs @@ -28,7 +28,7 @@ pub fn migrate(to_migrate: Vec) -> Weight { } } - weight + Weight::from_computation(weight) } /// Given the list of voters to migrate return a function that does some checks and information diff --git a/frame/elections-phragmen/src/weights.rs b/frame/elections-phragmen/src/weights.rs index 6cb2924fd7cf8..dab100a22dac2 100644 --- a/frame/elections-phragmen/src/weights.rs +++ b/frame/elections-phragmen/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_elections_phragmen. diff --git a/frame/examples/basic/src/lib.rs b/frame/examples/basic/src/lib.rs index f8acc1962388f..acd723ff5803b 100644 --- a/frame/examples/basic/src/lib.rs +++ b/frame/examples/basic/src/lib.rs @@ -281,7 +281,7 @@ use frame_system::ensure_signed; use log::info; use scale_info::TypeInfo; use sp_runtime::{ - traits::{Bounded, DispatchInfoOf, SaturatedConversion, Saturating, SignedExtension}, + traits::{Bounded, DispatchInfoOf, SaturatedConversion, Saturating, SignedExtension, Zero}, transaction_validity::{ InvalidTransaction, TransactionValidity, TransactionValidityError, ValidTransaction, }, @@ -329,7 +329,9 @@ impl WeighData<(&BalanceOf,)> for WeightForSetDum let multiplier = self.0; // *target.0 is the amount passed into the extrinsic let cents = *target.0 / >::from(MILLICENTS); - (cents * multiplier).saturated_into::() + let computation_weight = (cents * multiplier).saturated_into::(); + + Weight::from_computation(computation_weight) } } @@ -392,7 +394,7 @@ pub mod pallet { fn on_initialize(_n: T::BlockNumber) -> Weight { // Anything that needs to be done at the start of the block. // We don't do anything here. - 0 + Weight::zero() } // `on_finalize` is executed at the end of block after all extrinsic are dispatched. diff --git a/frame/examples/basic/src/tests.rs b/frame/examples/basic/src/tests.rs index 0f659e12fb443..e389a77532084 100644 --- a/frame/examples/basic/src/tests.rs +++ b/frame/examples/basic/src/tests.rs @@ -28,7 +28,7 @@ use sp_core::H256; // or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, IdentityLookup}, + traits::{BlakeTwo256, IdentityLookup, Zero}, BuildStorage, }; // Reexport crate as its pallet name for construct_runtime. @@ -52,7 +52,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; @@ -190,11 +193,11 @@ fn weights_work() { let default_call = pallet_example_basic::Call::::accumulate_dummy { increase_by: 10 }; let info1 = default_call.get_dispatch_info(); // aka. `let info = as GetDispatchInfo>::get_dispatch_info(&default_call);` - assert!(info1.weight > 0); + assert!(!info1.weight.is_zero()); // `set_dummy` is simpler than `accumulate_dummy`, and the weight // should be less. let custom_call = pallet_example_basic::Call::::set_dummy { new_value: 20 }; let info2 = custom_call.get_dispatch_info(); - assert!(info1.weight > info2.weight); + assert!(info1.weight.is_any_greater_than(&info2.weight)); } diff --git a/frame/examples/basic/src/weights.rs b/frame/examples/basic/src/weights.rs index 5fc6434e396eb..f844c4f9e1ff1 100644 --- a/frame/examples/basic/src/weights.rs +++ b/frame/examples/basic/src/weights.rs @@ -49,7 +49,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_example_basic. diff --git a/frame/examples/offchain-worker/src/tests.rs b/frame/examples/offchain-worker/src/tests.rs index e5bd9fabc629b..4038a0b961c39 100644 --- a/frame/examples/offchain-worker/src/tests.rs +++ b/frame/examples/offchain-worker/src/tests.rs @@ -53,7 +53,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index 4affc26f831fd..e3ceb2744c389 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -95,7 +95,7 @@ //! # use sp_runtime::transaction_validity::{ //! # TransactionValidity, UnknownTransaction, TransactionSource, //! # }; -//! # use sp_runtime::traits::ValidateUnsigned; +//! # use sp_runtime::traits::{ValidateUnsigned, Zero}; //! # impl ValidateUnsigned for Runtime { //! # type Call = (); //! # @@ -107,7 +107,7 @@ //! impl frame_support::traits::OnRuntimeUpgrade for CustomOnRuntimeUpgrade { //! fn on_runtime_upgrade() -> frame_support::weights::Weight { //! // Do whatever you want. -//! 0 +//! Zero::zero() //! } //! } //! @@ -299,7 +299,7 @@ where // This means the format of all the event related storages must always be compatible. >::reset_events(); - let mut weight = 0; + let mut weight: frame_support::weights::Weight = Zero::zero(); if Self::runtime_upgraded() { weight = weight.saturating_add(Self::execute_on_runtime_upgrade()); } @@ -413,7 +413,7 @@ where let max_weight = >::get().max_block; let remaining_weight = max_weight.saturating_sub(weight.total()); - if remaining_weight > 0 { + if remaining_weight.is_strictly_greater_than(&Zero::zero()) { let used_weight = >::on_idle( block_number, remaining_weight, @@ -604,12 +604,12 @@ mod tests { // one with block number arg and one without fn on_initialize(n: T::BlockNumber) -> Weight { println!("on_initialize({})", n); - 175 + Weight::from_computation(175) } fn on_idle(n: T::BlockNumber, remaining_weight: Weight) -> Weight { println!("on_idle{}, {})", n, remaining_weight); - 175 + Weight::from_computation(175) } fn on_finalize(n: T::BlockNumber) { @@ -618,7 +618,7 @@ mod tests { fn on_runtime_upgrade() -> Weight { sp_io::storage::set(super::TEST_KEY, "module".as_bytes()); - 200 + Weight::from_computation(200) } fn offchain_worker(n: T::BlockNumber) { @@ -730,12 +730,35 @@ mod tests { ); parameter_types! { - pub BlockWeights: frame_system::limits::BlockWeights = + pub NormalBlockWeights: frame_system::limits::BlockWeights = + frame_system::limits::BlockWeights::builder() + .base_block(Weight::from_computation(10)) + .for_class(DispatchClass::all(), |weights| weights.base_extrinsic = Weight::from_computation(5)) + .for_class(DispatchClass::non_mandatory(), |weights| + weights.max_total = Some(Weight::new().set_computation(1024).set_bandwidth(512)) + ) + .build_or_panic(); + + pub MaxBandwidthBlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights::builder() - .base_block(10) - .for_class(DispatchClass::all(), |weights| weights.base_extrinsic = 5) - .for_class(DispatchClass::non_mandatory(), |weights| weights.max_total = 1024.into()) + .base_block(Weight::from_computation(10)) + .for_class(DispatchClass::all(), |weights| weights.base_extrinsic = Weight::from_computation(5)) + .for_class(DispatchClass::non_mandatory(), |weights| + weights.max_total = Some(Weight::new().set_computation(1024).set_bandwidth(u64::MAX)) + ) .build_or_panic(); + + pub MaxComputationBlockWeights: frame_system::limits::BlockWeights = + frame_system::limits::BlockWeights::builder() + .base_block(Weight::from_computation(10)) + .for_class(DispatchClass::all(), |weights| weights.base_extrinsic = Weight::from_computation(5)) + .for_class(DispatchClass::non_mandatory(), |weights| + weights.max_total = Some(Weight::new().set_computation(u64::MAX).set_bandwidth(1024)) + ) + .build_or_panic(); + + pub static BlockWeights: frame_system::limits::BlockWeights = NormalBlockWeights::get(); + pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 10, write: 100, @@ -824,7 +847,7 @@ mod tests { sp_io::storage::set(TEST_KEY, "custom_upgrade".as_bytes()); sp_io::storage::set(CUSTOM_ON_RUNTIME_KEY, &true.encode()); System::deposit_event(frame_system::Event::CodeUpdated); - 100 + Weight::from_computation(100) } } @@ -865,8 +888,9 @@ mod tests { ::BlockWeights::get() .get(DispatchClass::Normal) .base_extrinsic; - let fee: Balance = - ::WeightToFee::calc(&weight); + let fee: Balance = ::WeightToFee::calc( + &weight.computation(), + ); let mut t = sp_io::TestExternalities::new(t); t.execute_with(|| { Executive::initialize_block(&Header::new( @@ -903,11 +927,11 @@ mod tests { fn block_import_works() { block_import_works_inner( new_test_ext_v0(1), - hex!("1039e1a4bd0cf5deefe65f313577e70169c41c7773d6acf31ca8d671397559f5").into(), + hex!("5883ac48292e6055c049a25365ff5497838811a8333bf665d596826d2ad6e445").into(), ); block_import_works_inner( new_test_ext(1), - hex!("75e7d8f360d375bbe91bcf8019c01ab6362448b4a89e3b329717eb9d910340e5").into(), + hex!("1fbc38c2151bd200b463efc913f669222db9837883dab39320414eb271fa0734").into(), ); } fn block_import_works_inner(mut ext: sp_io::TestExternalities, state_root: H256) { @@ -990,20 +1014,22 @@ mod tests { } #[test] - fn block_weight_limit_enforced() { + fn computational_block_weight_limit_enforced() { let mut t = new_test_ext(10000); // given: TestXt uses the encoded len as fixed Len: let xt = TestXt::new( Call::Balances(BalancesCall::transfer { dest: 33, value: 0 }), sign_extra(1, 0, 0), ); + // Ignore the bandwidth limits + BlockWeights::set(MaxBandwidthBlockWeights::get()); let encoded = xt.encode(); - let encoded_len = encoded.len() as Weight; + let encoded_len = encoded.len() as u64; // on_initialize weight + base block execution weight let block_weights = ::BlockWeights::get(); - let base_block_weight = 175 + block_weights.base_block; + let base_block_weight = Weight::from_computation(175) + block_weights.base_block; let limit = block_weights.get(DispatchClass::Normal).max_total.unwrap() - base_block_weight; - let num_to_exhaust_block = limit / (encoded_len + 5); + let num_to_exhaust_block = limit.computation() / (encoded_len + 5); t.execute_with(|| { Executive::initialize_block(&Header::new( 1, @@ -1024,9 +1050,61 @@ mod tests { if nonce != num_to_exhaust_block { assert!(res.is_ok()); assert_eq!( - >::block_weight().total(), + >::block_weight().total().computation(), //--------------------- on_initialize + block_execution + extrinsic_base weight - (encoded_len + 5) * (nonce + 1) + base_block_weight, + (encoded_len + 5) * (nonce + 1) + base_block_weight.computation(), + ); + assert_eq!( + >::extrinsic_index(), + Some(nonce as u32 + 1) + ); + } else { + assert_eq!(res, Err(InvalidTransaction::ExhaustsResources.into())); + } + } + }); + } + + #[test] + fn bandwidth_block_weight_limit_enforced() { + let mut t = new_test_ext(10000); + // given: TestXt uses the encoded len as fixed Len: + let xt = TestXt::new( + Call::Balances(BalancesCall::transfer { dest: 33, value: 0 }), + sign_extra(1, 0, 0), + ); + // Ignore the bandwidth limits + BlockWeights::set(MaxComputationBlockWeights::get()); + let encoded = xt.encode(); + let encoded_len = encoded.len() as u64; + // on_initialize weight + base block execution weight + let block_weights = ::BlockWeights::get(); + let base_block_weight = Weight::from_computation(175) + block_weights.base_block; + let limit = block_weights.get(DispatchClass::Normal).max_total.unwrap() - base_block_weight; + let num_to_exhaust_block = limit.bandwidth() / encoded_len; + t.execute_with(|| { + Executive::initialize_block(&Header::new( + 1, + H256::default(), + H256::default(), + [69u8; 32].into(), + Digest::default(), + )); + // Base block execution weight + `on_initialize` weight from the custom module. + assert_eq!(>::block_weight().total(), base_block_weight); + + for nonce in 0..=num_to_exhaust_block { + let xt = TestXt::new( + Call::Balances(BalancesCall::transfer { dest: 33, value: 0 }), + sign_extra(1, nonce.into(), 0), + ); + let res = Executive::apply_extrinsic(xt); + if nonce != num_to_exhaust_block { + assert!(res.is_ok()); + assert_eq!( + >::block_weight().total().computation(), + //--------------------- on_initialize + block_execution + extrinsic_base weight + (encoded_len + 5) * (nonce + 1) + base_block_weight.computation(), ); assert_eq!( >::extrinsic_index(), @@ -1057,8 +1135,8 @@ mod tests { let mut t = new_test_ext(1); t.execute_with(|| { // Block execution weight + on_initialize weight from custom module - let base_block_weight = - 175 + ::BlockWeights::get().base_block; + let base_block_weight = Weight::from_computation(175) + + ::BlockWeights::get().base_block; Executive::initialize_block(&Header::new( 1, @@ -1076,13 +1154,14 @@ mod tests { assert!(Executive::apply_extrinsic(x2.clone()).unwrap().is_ok()); // default weight for `TestXt` == encoded length. - let extrinsic_weight = len as Weight + - ::BlockWeights::get() - .get(DispatchClass::Normal) - .base_extrinsic; + let extrinsic_weight = + Weight::new().set_computation(len.into()).set_bandwidth(len.into()) + + ::BlockWeights::get() + .get(DispatchClass::Normal) + .base_extrinsic; assert_eq!( >::block_weight().total(), - base_block_weight + 3 * extrinsic_weight, + base_block_weight + extrinsic_weight * 3, ); assert_eq!(>::all_extrinsics_len(), 3 * len); @@ -1153,7 +1232,9 @@ mod tests { .get(DispatchClass::Normal) .base_extrinsic; let fee: Balance = - ::WeightToFee::calc(&weight); + ::WeightToFee::calc( + &weight.computation(), + ); Executive::initialize_block(&Header::new( 1, H256::default(), @@ -1188,7 +1269,10 @@ mod tests { // NOTE: might need updates over time if new weights are introduced. // For now it only accounts for the base block execution weight and // the `on_initialize` weight defined in the custom test module. - assert_eq!(>::block_weight().total(), 175 + 175 + 10); + assert_eq!( + >::block_weight().total(), + Weight::from_computation(175 + 175 + 10) + ); }) } diff --git a/frame/gilt/src/lib.rs b/frame/gilt/src/lib.rs index 59522f9a106f2..f02acf7b09ea7 100644 --- a/frame/gilt/src/lib.rs +++ b/frame/gilt/src/lib.rs @@ -335,7 +335,7 @@ pub mod pallet { if (n % T::IntakePeriod::get()).is_zero() { Self::pursue_target(T::MaxIntakeBids::get()) } else { - 0 + Weight::zero() } } } @@ -576,9 +576,9 @@ pub mod pallet { let first_from_each_queue = T::WeightInfo::pursue_target_per_queue(queues_hit); let rest_from_each_queue = T::WeightInfo::pursue_target_per_item(bids_taken) .saturating_sub(T::WeightInfo::pursue_target_per_item(queues_hit)); - first_from_each_queue + rest_from_each_queue + Weight::from_computation(first_from_each_queue + rest_from_each_queue) } else { - T::WeightInfo::pursue_target_noop() + Weight::from_computation(T::WeightInfo::pursue_target_noop()) } } diff --git a/frame/gilt/src/weights.rs b/frame/gilt/src/weights.rs index 99e58d070e493..52f137cb34193 100644 --- a/frame/gilt/src/weights.rs +++ b/frame/gilt/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_gilt. diff --git a/frame/grandpa/src/default_weights.rs b/frame/grandpa/src/default_weights.rs index 330e9bb255177..c2574bc76397a 100644 --- a/frame/grandpa/src/default_weights.rs +++ b/frame/grandpa/src/default_weights.rs @@ -34,7 +34,7 @@ impl crate::WeightInfo for () { const MAX_NOMINATORS: u64 = 200; // checking membership proof - (35 * WEIGHT_PER_MICROS) + let computation_weight = (35 * WEIGHT_PER_MICROS) .saturating_add((175 * WEIGHT_PER_NANOS).saturating_mul(validator_count)) .saturating_add(DbWeight::get().reads(5)) // check equivocation proof @@ -45,10 +45,12 @@ impl crate::WeightInfo for () { .saturating_add(DbWeight::get().reads(14 + 3 * MAX_NOMINATORS)) .saturating_add(DbWeight::get().writes(10 + 3 * MAX_NOMINATORS)) // fetching set id -> session index mappings - .saturating_add(DbWeight::get().reads(2)) + .saturating_add(DbWeight::get().reads(2)); + + Weight::from_computation(computation_weight) } fn note_stalled() -> Weight { - (3 * WEIGHT_PER_MICROS).saturating_add(DbWeight::get().writes(1)) + Weight::from_computation((3 * WEIGHT_PER_MICROS).saturating_add(DbWeight::get().writes(1))) } } diff --git a/frame/grandpa/src/migrations/v4.rs b/frame/grandpa/src/migrations/v4.rs index ab43f7baef4e9..80d30e95b6fd6 100644 --- a/frame/grandpa/src/migrations/v4.rs +++ b/frame/grandpa/src/migrations/v4.rs @@ -20,6 +20,7 @@ use frame_support::{ weights::Weight, }; use sp_io::hashing::twox_128; +use sp_runtime::traits::Zero; /// The old prefix. pub const OLD_PREFIX: &[u8] = b"GrandpaFinality"; @@ -37,7 +38,7 @@ pub fn migrate>(new_pallet_name: N) -> Weight { target: "runtime::afg", "New pallet name is equal to the old prefix. No migration needs to be done.", ); - return 0 + return Weight::zero() } let storage_version = StorageVersion::get::>(); log::info!( @@ -57,7 +58,7 @@ pub fn migrate>(new_pallet_name: N) -> Weight { ::BlockWeights::get().max_block } else { - 0 + Weight::zero() } } diff --git a/frame/grandpa/src/mock.rs b/frame/grandpa/src/mock.rs index 5e6c955c441c5..221ac38476bd0 100644 --- a/frame/grandpa/src/mock.rs +++ b/frame/grandpa/src/mock.rs @@ -71,7 +71,10 @@ impl_opaque_keys! { parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { diff --git a/frame/grandpa/src/tests.rs b/frame/grandpa/src/tests.rs index ab0a9c677b00e..11fe9944deb5f 100644 --- a/frame/grandpa/src/tests.rs +++ b/frame/grandpa/src/tests.rs @@ -823,7 +823,7 @@ fn report_equivocation_has_valid_weight() { .map(::WeightInfo::report_equivocation) .collect::>() .windows(2) - .all(|w| w[0] < w[1])); + .all(|w| w[0].is_any_less_than(&w[1]))); } #[test] @@ -856,7 +856,7 @@ fn valid_equivocation_reports_dont_pay_fees() { .get_dispatch_info(); // it should have non-zero weight and the fee has to be paid. - assert!(info.weight > 0); + assert!(!info.weight.is_zero()); assert_eq!(info.pays_fee, Pays::Yes); // report the equivocation. diff --git a/frame/identity/src/tests.rs b/frame/identity/src/tests.rs index 8cb0563ebeaa1..351ad44ccd93f 100644 --- a/frame/identity/src/tests.rs +++ b/frame/identity/src/tests.rs @@ -50,7 +50,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; diff --git a/frame/identity/src/weights.rs b/frame/identity/src/weights.rs index 77c5915f0ec99..0c4822df1d70e 100644 --- a/frame/identity/src/weights.rs +++ b/frame/identity/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_identity. diff --git a/frame/im-online/src/mock.rs b/frame/im-online/src/mock.rs index 2459f7e748941..00eaef6e7fa8d 100644 --- a/frame/im-online/src/mock.rs +++ b/frame/im-online/src/mock.rs @@ -123,7 +123,10 @@ pub fn new_test_ext() -> sp_io::TestExternalities { parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Runtime { diff --git a/frame/im-online/src/weights.rs b/frame/im-online/src/weights.rs index 187499b1f957f..92bddc073ff4a 100644 --- a/frame/im-online/src/weights.rs +++ b/frame/im-online/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_im_online. diff --git a/frame/indices/src/mock.rs b/frame/indices/src/mock.rs index 6bd79708c3dd2..ef1d875ab9cef 100644 --- a/frame/indices/src/mock.rs +++ b/frame/indices/src/mock.rs @@ -44,7 +44,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { diff --git a/frame/indices/src/weights.rs b/frame/indices/src/weights.rs index 5fba8fc2377a0..21613de3922ac 100644 --- a/frame/indices/src/weights.rs +++ b/frame/indices/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_indices. diff --git a/frame/lottery/src/lib.rs b/frame/lottery/src/lib.rs index 02df65a3336bf..16387e5e18bd7 100644 --- a/frame/lottery/src/lib.rs +++ b/frame/lottery/src/lib.rs @@ -267,18 +267,18 @@ pub mod pallet { LotteryIndex::::mutate(|index| *index = index.saturating_add(1)); // Set a new start with the current block. config.start = n; - return T::WeightInfo::on_initialize_repeat() + return Weight::from_computation(T::WeightInfo::on_initialize_repeat()) } else { // Else, kill the lottery storage. *lottery = None; - return T::WeightInfo::on_initialize_end() + return Weight::from_computation(T::WeightInfo::on_initialize_end()) } // We choose not need to kill Participants and Tickets to avoid a large // number of writes at one time. Instead, data persists between lotteries, // but is not used if it is not relevant. } } - T::DbWeight::get().reads(1) + Weight::from_computation(T::DbWeight::get().reads(1)) }) } } @@ -296,10 +296,11 @@ pub mod pallet { /// should listen for the `TicketBought` event. /// /// This extrinsic must be called by a signed origin. - #[pallet::weight( - T::WeightInfo::buy_ticket() + #[pallet::weight({ + let benchmarked_weight = Weight::from_computation(T::WeightInfo::buy_ticket()); + benchmarked_weight .saturating_add(call.get_dispatch_info().weight) - )] + })] pub fn buy_ticket(origin: OriginFor, call: Box<::Call>) -> DispatchResult { let caller = ensure_signed(origin.clone())?; call.clone().dispatch(origin).map_err(|e| e.error)?; diff --git a/frame/lottery/src/weights.rs b/frame/lottery/src/weights.rs index d3626dc9080ec..4941007fffdd3 100644 --- a/frame/lottery/src/weights.rs +++ b/frame/lottery/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_lottery. diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index 8e7ea9eeec313..f870d1888aaa0 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -525,7 +525,10 @@ mod tests { parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); pub static Members: Vec = vec![]; pub static Prime: Option = None; } diff --git a/frame/membership/src/migrations/v4.rs b/frame/membership/src/migrations/v4.rs index b3b52751d9598..25a52dd840382 100644 --- a/frame/membership/src/migrations/v4.rs +++ b/frame/membership/src/migrations/v4.rs @@ -24,6 +24,7 @@ use frame_support::{ }, weights::Weight, }; +use sp_runtime::traits::Zero; /// Migrate the entire storage of this pallet to a new prefix. /// @@ -46,7 +47,7 @@ pub fn migrate::on_chain_storage_version(); @@ -71,7 +72,7 @@ pub fn migrate Weight { + fn on_initialize(peaks: u64) -> ComputationWeight { // Reading the parent hash. let leaf_weight = DbWeight::get().reads(1); // Blake2 hash cost. diff --git a/frame/merkle-mountain-range/src/lib.rs b/frame/merkle-mountain-range/src/lib.rs index d6cf3240692fc..5262254200e64 100644 --- a/frame/merkle-mountain-range/src/lib.rs +++ b/frame/merkle-mountain-range/src/lib.rs @@ -97,7 +97,7 @@ impl LeafDataProvider for ParentNumberAndHash { } pub trait WeightInfo { - fn on_initialize(peaks: NodeIndex) -> Weight; + fn on_initialize(peaks: NodeIndex) -> frame_support::weights::ComputationWeight; } #[frame_support::pallet] @@ -215,7 +215,7 @@ pub mod pallet { >::put(root); let peaks_after = mmr::utils::NodesUtils::new(leaves).number_of_peaks(); - T::WeightInfo::on_initialize(peaks_before.max(peaks_after)) + Weight::from_computation(T::WeightInfo::on_initialize(peaks_before.max(peaks_after))) } } } diff --git a/frame/merkle-mountain-range/src/tests.rs b/frame/merkle-mountain-range/src/tests.rs index d025910a9ee5c..efa6496586a52 100644 --- a/frame/merkle-mountain-range/src/tests.rs +++ b/frame/merkle-mountain-range/src/tests.rs @@ -24,6 +24,7 @@ use sp_core::{ H256, }; use sp_mmr_primitives::{BatchProof, Compact}; +use sp_runtime::traits::Zero; pub(crate) fn new_test_ext() -> sp_io::TestExternalities { frame_system::GenesisConfig::default().build_storage::().unwrap().into() @@ -35,7 +36,7 @@ fn register_offchain_ext(ext: &mut sp_io::TestExternalities) { ext.register_extension(OffchainWorkerExt::new(offchain)); } -fn new_block() -> u64 { +fn new_block() -> Weight { let number = frame_system::Pallet::::block_number() + 1; let hash = H256::repeat_byte(number as u8); LEAF_DATA.with(|r| r.borrow_mut().a = number); @@ -107,7 +108,7 @@ fn should_start_empty() { crate::RootHash::::get(), hex("4320435e8c3318562dba60116bdbcc0b82ffcecb9bb39aae3300cfda3ad0b8b0") ); - assert!(weight != 0); + assert!(!weight.is_zero()); }); } diff --git a/frame/multisig/src/benchmarking.rs b/frame/multisig/src/benchmarking.rs index 8201426f5330f..e8f321bd37063 100644 --- a/frame/multisig/src/benchmarking.rs +++ b/frame/multisig/src/benchmarking.rs @@ -80,7 +80,7 @@ benchmarks! { // Whitelist caller account from further DB operations. let caller_key = frame_system::Account::::hashed_key_for(&caller); frame_benchmarking::benchmarking::add_to_whitelist(caller_key.into()); - }: as_multi(RawOrigin::Signed(caller), s as u16, signatories, None, call, false, 0) + }: as_multi(RawOrigin::Signed(caller), s as u16, signatories, None, call, false, Zero::zero()) verify { assert!(Multisigs::::contains_key(multi_account_id, call_hash)); assert!(!Calls::::contains_key(call_hash)); @@ -99,7 +99,7 @@ benchmarks! { // Whitelist caller account from further DB operations. let caller_key = frame_system::Account::::hashed_key_for(&caller); frame_benchmarking::benchmarking::add_to_whitelist(caller_key.into()); - }: as_multi(RawOrigin::Signed(caller), s as u16, signatories, None, call, true, 0) + }: as_multi(RawOrigin::Signed(caller), s as u16, signatories, None, call, true, Zero::zero()) verify { assert!(Multisigs::::contains_key(multi_account_id, call_hash)); assert!(Calls::::contains_key(call_hash)); @@ -118,13 +118,13 @@ benchmarks! { // before the call, get the timepoint let timepoint = Multisig::::timepoint(); // Create the multi, storing for worst case - Multisig::::as_multi(RawOrigin::Signed(caller).into(), s as u16, signatories, None, call.clone(), true, 0)?; + Multisig::::as_multi(RawOrigin::Signed(caller).into(), s as u16, signatories, None, call.clone(), true, Zero::zero())?; assert!(Calls::::contains_key(call_hash)); let caller2 = signatories2.remove(0); // Whitelist caller account from further DB operations. let caller_key = frame_system::Account::::hashed_key_for(&caller2); frame_benchmarking::benchmarking::add_to_whitelist(caller_key.into()); - }: as_multi(RawOrigin::Signed(caller2), s as u16, signatories2, Some(timepoint), call, false, 0) + }: as_multi(RawOrigin::Signed(caller2), s as u16, signatories2, Some(timepoint), call, false, Zero::zero()) verify { let multisig = Multisigs::::get(multi_account_id, call_hash).ok_or("multisig not created")?; assert_eq!(multisig.approvals.len(), 2); @@ -143,13 +143,13 @@ benchmarks! { // before the call, get the timepoint let timepoint = Multisig::::timepoint(); // Create the multi, not storing - Multisig::::as_multi(RawOrigin::Signed(caller).into(), s as u16, signatories, None, call.clone(), false, 0)?; + Multisig::::as_multi(RawOrigin::Signed(caller).into(), s as u16, signatories, None, call.clone(), false, Zero::zero())?; assert!(!Calls::::contains_key(call_hash)); let caller2 = signatories2.remove(0); // Whitelist caller account from further DB operations. let caller_key = frame_system::Account::::hashed_key_for(&caller2); frame_benchmarking::benchmarking::add_to_whitelist(caller_key.into()); - }: as_multi(RawOrigin::Signed(caller2), s as u16, signatories2, Some(timepoint), call, true, 0) + }: as_multi(RawOrigin::Signed(caller2), s as u16, signatories2, Some(timepoint), call, true, Zero::zero()) verify { let multisig = Multisigs::::get(multi_account_id, call_hash).ok_or("multisig not created")?; assert_eq!(multisig.approvals.len(), 2); @@ -169,20 +169,20 @@ benchmarks! { // before the call, get the timepoint let timepoint = Multisig::::timepoint(); // Create the multi, storing it for worst case - Multisig::::as_multi(RawOrigin::Signed(caller).into(), s as u16, signatories, None, call.clone(), true, 0)?; + Multisig::::as_multi(RawOrigin::Signed(caller).into(), s as u16, signatories, None, call.clone(), true, Zero::zero())?; // Everyone except the first person approves for i in 1 .. s - 1 { let mut signatories_loop = signatories2.clone(); let caller_loop = signatories_loop.remove(i as usize); let o = RawOrigin::Signed(caller_loop).into(); - Multisig::::as_multi(o, s as u16, signatories_loop, Some(timepoint), call.clone(), false, 0)?; + Multisig::::as_multi(o, s as u16, signatories_loop, Some(timepoint), call.clone(), false, Zero::zero())?; } let caller2 = signatories2.remove(0); assert!(Multisigs::::contains_key(&multi_account_id, call_hash)); // Whitelist caller account from further DB operations. let caller_key = frame_system::Account::::hashed_key_for(&caller2); frame_benchmarking::benchmarking::add_to_whitelist(caller_key.into()); - }: as_multi(RawOrigin::Signed(caller2), s as u16, signatories2, Some(timepoint), call, false, Weight::max_value()) + }: as_multi(RawOrigin::Signed(caller2), s as u16, signatories2, Some(timepoint), call, false, Weight::MAX) verify { assert!(!Multisigs::::contains_key(&multi_account_id, call_hash)); } @@ -200,7 +200,7 @@ benchmarks! { let caller_key = frame_system::Account::::hashed_key_for(&caller); frame_benchmarking::benchmarking::add_to_whitelist(caller_key.into()); // Create the multi - }: approve_as_multi(RawOrigin::Signed(caller), s as u16, signatories, None, call_hash, 0) + }: approve_as_multi(RawOrigin::Signed(caller), s as u16, signatories, None, call_hash, Zero::zero()) verify { assert!(Multisigs::::contains_key(multi_account_id, call_hash)); } @@ -225,13 +225,13 @@ benchmarks! { None, call, false, - 0 + Zero::zero() )?; let caller2 = signatories2.remove(0); // Whitelist caller account from further DB operations. let caller_key = frame_system::Account::::hashed_key_for(&caller2); frame_benchmarking::benchmarking::add_to_whitelist(caller_key.into()); - }: approve_as_multi(RawOrigin::Signed(caller2), s as u16, signatories2, Some(timepoint), call_hash, 0) + }: approve_as_multi(RawOrigin::Signed(caller2), s as u16, signatories2, Some(timepoint), call_hash, Zero::zero()) verify { let multisig = Multisigs::::get(multi_account_id, call_hash).ok_or("multisig not created")?; assert_eq!(multisig.approvals.len(), 2); @@ -251,13 +251,13 @@ benchmarks! { // before the call, get the timepoint let timepoint = Multisig::::timepoint(); // Create the multi - Multisig::::as_multi(RawOrigin::Signed(caller).into(), s as u16, signatories, None, call.clone(), true, 0)?; + Multisig::::as_multi(RawOrigin::Signed(caller).into(), s as u16, signatories, None, call.clone(), true, Zero::zero())?; // Everyone except the first person approves for i in 1 .. s - 1 { let mut signatories_loop = signatories2.clone(); let caller_loop = signatories_loop.remove(i as usize); let o = RawOrigin::Signed(caller_loop).into(); - Multisig::::as_multi(o, s as u16, signatories_loop, Some(timepoint), call.clone(), false, 0)?; + Multisig::::as_multi(o, s as u16, signatories_loop, Some(timepoint), call.clone(), false, Zero::zero())?; } let caller2 = signatories2.remove(0); assert!(Multisigs::::contains_key(&multi_account_id, call_hash)); @@ -270,7 +270,7 @@ benchmarks! { signatories2, Some(timepoint), call_hash, - Weight::max_value() + Weight::MAX ) verify { assert!(!Multisigs::::contains_key(multi_account_id, call_hash)); @@ -288,7 +288,7 @@ benchmarks! { let timepoint = Multisig::::timepoint(); // Create the multi let o = RawOrigin::Signed(caller.clone()).into(); - Multisig::::as_multi(o, s as u16, signatories.clone(), None, call, true, 0)?; + Multisig::::as_multi(o, s as u16, signatories.clone(), None, call, true, Zero::zero())?; assert!(Multisigs::::contains_key(&multi_account_id, call_hash)); assert!(Calls::::contains_key(call_hash)); // Whitelist caller account from further DB operations. diff --git a/frame/multisig/src/lib.rs b/frame/multisig/src/lib.rs index d4ea041e5820e..6b4c1d0e66620 100644 --- a/frame/multisig/src/lib.rs +++ b/frame/multisig/src/lib.rs @@ -257,7 +257,7 @@ pub mod pallet { let dispatch_info = call.get_dispatch_info(); ( T::WeightInfo::as_multi_threshold_1(call.using_encoded(|c| c.len() as u32)) - .saturating_add(dispatch_info.weight) + .saturating_add(dispatch_info.weight.computation()) // AccountData for inner call origin accountdata. .saturating_add(T::DbWeight::get().reads_writes(1, 1)), dispatch_info.class, @@ -286,14 +286,14 @@ pub mod pallet { .actual_weight .map(|actual_weight| { T::WeightInfo::as_multi_threshold_1(call_len as u32) - .saturating_add(actual_weight) + .saturating_add(actual_weight.computation()) }) .into() }) .map_err(|err| match err.post_info.actual_weight { Some(actual_weight) => { let weight_used = T::WeightInfo::as_multi_threshold_1(call_len as u32) - .saturating_add(actual_weight); + .saturating_add(actual_weight.computation()); let post_info = Some(weight_used).into(); DispatchErrorWithPostInfo { post_info, error: err.error } }, @@ -354,7 +354,7 @@ pub mod pallet { .max(T::WeightInfo::as_multi_create_store(s, z)) .max(T::WeightInfo::as_multi_approve(s, z)) .max(T::WeightInfo::as_multi_complete(s, z)) - .saturating_add(*max_weight) + .saturating_add(max_weight.computation()) })] pub fn as_multi( origin: OriginFor, @@ -417,7 +417,7 @@ pub mod pallet { T::WeightInfo::approve_as_multi_create(s) .max(T::WeightInfo::approve_as_multi_approve(s)) .max(T::WeightInfo::approve_as_multi_complete(s)) - .saturating_add(*max_weight) + .saturating_add(max_weight.computation()) })] pub fn approve_as_multi( origin: OriginFor, @@ -563,7 +563,10 @@ impl Pallet { if let Some((call, call_len)) = maybe_approved_call { // verify weight - ensure!(call.get_dispatch_info().weight <= max_weight, Error::::MaxWeightTooLow); + ensure!( + call.get_dispatch_info().weight.is_strictly_less_than_or_equal(&max_weight), + Error::::MaxWeightTooLow + ); // Clean up storage before executing call to avoid an possibility of reentrancy // attack. @@ -585,7 +588,7 @@ impl Pallet { other_signatories_len as u32, call_len as u32, ) - .saturating_add(actual_weight) + .saturating_add(actual_weight.computation()) }) .into()) } else { diff --git a/frame/multisig/src/tests.rs b/frame/multisig/src/tests.rs index d67d06e1bce05..4f33347f2b333 100644 --- a/frame/multisig/src/tests.rs +++ b/frame/multisig/src/tests.rs @@ -50,7 +50,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { type BaseCallFilter = TestBaseCallFilter; @@ -152,7 +155,7 @@ fn multisig_deposit_is_taken_and_returned() { None, OpaqueCall::from_encoded(data.clone()), false, - 0 + Zero::zero() )); assert_eq!(Balances::free_balance(1), 2); assert_eq!(Balances::reserved_balance(1), 3); @@ -190,7 +193,7 @@ fn multisig_deposit_is_taken_and_returned_with_call_storage() { None, OpaqueCall::from_encoded(data), true, - 0 + Zero::zero() )); assert_eq!(Balances::free_balance(1), 0); assert_eq!(Balances::reserved_balance(1), 5); @@ -227,7 +230,7 @@ fn multisig_deposit_is_taken_and_returned_with_alt_call_storage() { vec![2, 3], None, hash.clone(), - 0 + Zero::zero() )); assert_eq!(Balances::free_balance(1), 1); assert_eq!(Balances::reserved_balance(1), 4); @@ -239,7 +242,7 @@ fn multisig_deposit_is_taken_and_returned_with_alt_call_storage() { Some(now()), OpaqueCall::from_encoded(data), true, - 0 + Zero::zero() )); assert_eq!(Balances::free_balance(2), 3); assert_eq!(Balances::reserved_balance(2), 2); @@ -272,7 +275,7 @@ fn cancel_multisig_returns_deposit() { vec![2, 3], None, hash.clone(), - 0 + Zero::zero() )); assert_ok!(Multisig::approve_as_multi( Origin::signed(2), @@ -280,7 +283,7 @@ fn cancel_multisig_returns_deposit() { vec![1, 3], Some(now()), hash.clone(), - 0 + Zero::zero() )); assert_eq!(Balances::free_balance(1), 6); assert_eq!(Balances::reserved_balance(1), 4); @@ -314,12 +317,19 @@ fn timepoint_checking_works() { vec![1, 3], Some(now()), hash.clone(), - 0 + Zero::zero() ), Error::::UnexpectedTimepoint, ); - assert_ok!(Multisig::approve_as_multi(Origin::signed(1), 2, vec![2, 3], None, hash, 0)); + assert_ok!(Multisig::approve_as_multi( + Origin::signed(1), + 2, + vec![2, 3], + None, + hash, + Zero::zero() + )); assert_noop!( Multisig::as_multi( @@ -329,7 +339,7 @@ fn timepoint_checking_works() { None, OpaqueCall::from_encoded(call.clone()), false, - 0 + Zero::zero() ), Error::::NoTimepoint, ); @@ -342,7 +352,7 @@ fn timepoint_checking_works() { Some(later), OpaqueCall::from_encoded(call), false, - 0 + Zero::zero() ), Error::::WrongTimepoint, ); @@ -368,7 +378,7 @@ fn multisig_2_of_3_works_with_call_storing() { None, OpaqueCall::from_encoded(data), true, - 0 + Zero::zero() )); assert_eq!(Balances::free_balance(6), 0); @@ -396,7 +406,14 @@ fn multisig_2_of_3_works() { let call_weight = call.get_dispatch_info().weight; let data = call.encode(); let hash = blake2_256(&data); - assert_ok!(Multisig::approve_as_multi(Origin::signed(1), 2, vec![2, 3], None, hash, 0)); + assert_ok!(Multisig::approve_as_multi( + Origin::signed(1), + 2, + vec![2, 3], + None, + hash, + Zero::zero() + )); assert_eq!(Balances::free_balance(6), 0); assert_ok!(Multisig::as_multi( @@ -430,7 +447,7 @@ fn multisig_3_of_3_works() { vec![2, 3], None, hash.clone(), - 0 + Zero::zero() )); assert_ok!(Multisig::approve_as_multi( Origin::signed(2), @@ -438,7 +455,7 @@ fn multisig_3_of_3_works() { vec![1, 3], Some(now()), hash.clone(), - 0 + Zero::zero() )); assert_eq!(Balances::free_balance(6), 0); @@ -466,7 +483,7 @@ fn cancel_multisig_works() { vec![2, 3], None, hash.clone(), - 0 + Zero::zero() )); assert_ok!(Multisig::approve_as_multi( Origin::signed(2), @@ -474,7 +491,7 @@ fn cancel_multisig_works() { vec![1, 3], Some(now()), hash.clone(), - 0 + Zero::zero() )); assert_noop!( Multisig::cancel_as_multi(Origin::signed(2), 3, vec![1, 3], now(), hash.clone()), @@ -502,7 +519,7 @@ fn cancel_multisig_with_call_storage_works() { None, OpaqueCall::from_encoded(call), true, - 0 + Zero::zero() )); assert_eq!(Balances::free_balance(1), 4); assert_ok!(Multisig::approve_as_multi( @@ -511,7 +528,7 @@ fn cancel_multisig_with_call_storage_works() { vec![1, 3], Some(now()), hash.clone(), - 0 + Zero::zero() )); assert_noop!( Multisig::cancel_as_multi(Origin::signed(2), 3, vec![1, 3], now(), hash.clone()), @@ -539,7 +556,7 @@ fn cancel_multisig_with_alt_call_storage_works() { vec![2, 3], None, hash.clone(), - 0 + Zero::zero() )); assert_eq!(Balances::free_balance(1), 6); assert_ok!(Multisig::as_multi( @@ -549,7 +566,7 @@ fn cancel_multisig_with_alt_call_storage_works() { Some(now()), OpaqueCall::from_encoded(call), true, - 0 + Zero::zero() )); assert_eq!(Balances::free_balance(2), 8); assert_ok!(Multisig::cancel_as_multi(Origin::signed(1), 3, vec![2, 3], now(), hash)); @@ -576,7 +593,7 @@ fn multisig_2_of_3_as_multi_works() { None, OpaqueCall::from_encoded(data.clone()), false, - 0 + Zero::zero() )); assert_eq!(Balances::free_balance(6), 0); @@ -615,7 +632,7 @@ fn multisig_2_of_3_as_multi_with_many_calls_works() { None, OpaqueCall::from_encoded(data1.clone()), false, - 0 + Zero::zero() )); assert_ok!(Multisig::as_multi( Origin::signed(2), @@ -624,7 +641,7 @@ fn multisig_2_of_3_as_multi_with_many_calls_works() { None, OpaqueCall::from_encoded(data2.clone()), false, - 0 + Zero::zero() )); assert_ok!(Multisig::as_multi( Origin::signed(3), @@ -669,7 +686,7 @@ fn multisig_2_of_3_cannot_reissue_same_call() { None, OpaqueCall::from_encoded(data.clone()), false, - 0 + Zero::zero() )); assert_ok!(Multisig::as_multi( Origin::signed(2), @@ -689,7 +706,7 @@ fn multisig_2_of_3_cannot_reissue_same_call() { None, OpaqueCall::from_encoded(data.clone()), false, - 0 + Zero::zero() )); assert_ok!(Multisig::as_multi( Origin::signed(3), @@ -727,7 +744,7 @@ fn minimum_threshold_check_works() { None, OpaqueCall::from_encoded(call.clone()), false, - 0 + Zero::zero() ), Error::::MinimumThreshold, ); @@ -739,7 +756,7 @@ fn minimum_threshold_check_works() { None, OpaqueCall::from_encoded(call.clone()), false, - 0 + Zero::zero() ), Error::::MinimumThreshold, ); @@ -758,7 +775,7 @@ fn too_many_signatories_fails() { None, OpaqueCall::from_encoded(call), false, - 0 + Zero::zero() ), Error::::TooManySignatories, ); @@ -776,7 +793,7 @@ fn duplicate_approvals_are_ignored() { vec![2, 3], None, hash.clone(), - 0 + Zero::zero() )); assert_noop!( Multisig::approve_as_multi( @@ -785,7 +802,7 @@ fn duplicate_approvals_are_ignored() { vec![2, 3], Some(now()), hash.clone(), - 0 + Zero::zero() ), Error::::AlreadyApproved, ); @@ -795,7 +812,7 @@ fn duplicate_approvals_are_ignored() { vec![1, 3], Some(now()), hash.clone(), - 0 + Zero::zero() )); assert_noop!( Multisig::approve_as_multi( @@ -804,7 +821,7 @@ fn duplicate_approvals_are_ignored() { vec![1, 2], Some(now()), hash.clone(), - 0 + Zero::zero() ), Error::::AlreadyApproved, ); @@ -822,7 +839,14 @@ fn multisig_1_of_3_works() { let call = call_transfer(6, 15).encode(); let hash = blake2_256(&call); assert_noop!( - Multisig::approve_as_multi(Origin::signed(1), 1, vec![2, 3], None, hash.clone(), 0), + Multisig::approve_as_multi( + Origin::signed(1), + 1, + vec![2, 3], + None, + hash.clone(), + Zero::zero() + ), Error::::MinimumThreshold, ); assert_noop!( @@ -833,7 +857,7 @@ fn multisig_1_of_3_works() { None, OpaqueCall::from_encoded(call), false, - 0 + Zero::zero() ), Error::::MinimumThreshold, ); @@ -872,7 +896,7 @@ fn weight_check_works() { None, OpaqueCall::from_encoded(data.clone()), false, - 0 + Zero::zero() )); assert_eq!(Balances::free_balance(6), 0); @@ -884,7 +908,7 @@ fn weight_check_works() { Some(now()), OpaqueCall::from_encoded(data), false, - 0 + Zero::zero() ), Error::::MaxWeightTooLow, ); @@ -912,7 +936,7 @@ fn multisig_handles_no_preimage_after_all_approve() { vec![2, 3], None, hash.clone(), - 0 + Zero::zero() )); assert_ok!(Multisig::approve_as_multi( Origin::signed(2), @@ -920,7 +944,7 @@ fn multisig_handles_no_preimage_after_all_approve() { vec![1, 3], Some(now()), hash.clone(), - 0 + Zero::zero() )); assert_ok!(Multisig::approve_as_multi( Origin::signed(3), @@ -928,7 +952,7 @@ fn multisig_handles_no_preimage_after_all_approve() { vec![1, 2], Some(now()), hash.clone(), - 0 + Zero::zero() )); assert_eq!(Balances::free_balance(6), 0); diff --git a/frame/multisig/src/weights.rs b/frame/multisig/src/weights.rs index 563dd20bae63d..86ea86f9dbf0b 100644 --- a/frame/multisig/src/weights.rs +++ b/frame/multisig/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_multisig. diff --git a/frame/nicks/src/lib.rs b/frame/nicks/src/lib.rs index 5da06a24df3e5..a4971c199f83f 100644 --- a/frame/nicks/src/lib.rs +++ b/frame/nicks/src/lib.rs @@ -275,7 +275,10 @@ mod tests { parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; diff --git a/frame/node-authorization/src/weights.rs b/frame/node-authorization/src/weights.rs index cf182f94273ce..59c6d67064405 100644 --- a/frame/node-authorization/src/weights.rs +++ b/frame/node-authorization/src/weights.rs @@ -21,7 +21,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; pub trait WeightInfo { diff --git a/frame/nomination-pools/src/migration.rs b/frame/nomination-pools/src/migration.rs index e23a35fe85602..219068db7cb51 100644 --- a/frame/nomination-pools/src/migration.rs +++ b/frame/nomination-pools/src/migration.rs @@ -88,10 +88,12 @@ pub mod v1 { log!(info, "Upgraded {} pools, storage to version {:?}", translated, current); - T::DbWeight::get().reads_writes(translated + 1, translated + 1) + Weight::from_computation( + T::DbWeight::get().reads_writes(translated + 1, translated + 1), + ) } else { log!(info, "Migration did not executed. This probably should be removed"); - T::DbWeight::get().reads(1) + Weight::from_computation(T::DbWeight::get().reads(1)) } } diff --git a/frame/nomination-pools/src/weights.rs b/frame/nomination-pools/src/weights.rs index ef339231fe7bb..112b9b70170ca 100644 --- a/frame/nomination-pools/src/weights.rs +++ b/frame/nomination-pools/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_nomination_pools. diff --git a/frame/offences/benchmarking/src/mock.rs b/frame/offences/benchmarking/src/mock.rs index d51a81b1212c0..94d986a648d78 100644 --- a/frame/offences/benchmarking/src/mock.rs +++ b/frame/offences/benchmarking/src/mock.rs @@ -24,7 +24,6 @@ use frame_election_provider_support::{onchain, SequentialPhragmen}; use frame_support::{ parameter_types, traits::{ConstU32, ConstU64}, - weights::constants::WEIGHT_PER_SECOND, }; use frame_system as system; use pallet_session::historical as pallet_session_historical; @@ -40,7 +39,10 @@ type Balance = u64; parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(2 * WEIGHT_PER_SECOND); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { diff --git a/frame/offences/src/migration.rs b/frame/offences/src/migration.rs index e8fab1c0babc7..b950dd2b74cb1 100644 --- a/frame/offences/src/migration.rs +++ b/frame/offences/src/migration.rs @@ -44,10 +44,10 @@ pub fn remove_deferred_storage() -> Weight { *session, DisableStrategy::WhenSlashed, ); - weight = weight.saturating_add(consumed); + weight = weight.saturating_add(consumed.computation()); } - weight + Weight::from_computation(weight) } #[cfg(test)] @@ -83,7 +83,7 @@ mod test { // when assert_eq!( - remove_deferred_storage::(), + remove_deferred_storage::().computation(), ::DbWeight::get().reads_writes(1, 1), ); diff --git a/frame/offences/src/mock.rs b/frame/offences/src/mock.rs index b3dfbdd90b19d..49454dcf7c937 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -25,10 +25,7 @@ use codec::Encode; use frame_support::{ parameter_types, traits::{ConstU32, ConstU64}, - weights::{ - constants::{RocksDbWeight, WEIGHT_PER_SECOND}, - Weight, - }, + weights::{constants::RocksDbWeight, Weight}, }; use sp_core::H256; use sp_runtime::{ @@ -86,7 +83,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(2 * WEIGHT_PER_SECOND); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; diff --git a/frame/preimage/src/mock.rs b/frame/preimage/src/mock.rs index 109806049a0fd..13914a9f2e1f4 100644 --- a/frame/preimage/src/mock.rs +++ b/frame/preimage/src/mock.rs @@ -50,7 +50,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(2_000_000_000_000); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { type BaseCallFilter = Everything; diff --git a/frame/preimage/src/weights.rs b/frame/preimage/src/weights.rs index 801ad627e07d9..d6936c8866c27 100644 --- a/frame/preimage/src/weights.rs +++ b/frame/preimage/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_preimage. diff --git a/frame/proxy/src/lib.rs b/frame/proxy/src/lib.rs index 9945626efbeb1..b08ed9f1b2e71 100644 --- a/frame/proxy/src/lib.rs +++ b/frame/proxy/src/lib.rs @@ -38,7 +38,7 @@ use frame_support::{ dispatch::DispatchError, ensure, traits::{Currency, Get, InstanceFilter, IsSubType, IsType, OriginTrait, ReservableCurrency}, - weights::GetDispatchInfo, + weights::{GetDispatchInfo, Weight}, RuntimeDebug, }; use frame_system::{self as system}; @@ -196,10 +196,10 @@ pub mod pallet { /// # #[pallet::weight({ let di = call.get_dispatch_info(); - (T::WeightInfo::proxy(T::MaxProxies::get()) + (Weight::from_computation(T::WeightInfo::proxy(T::MaxProxies::get())) .saturating_add(di.weight) // AccountData for inner call origin accountdata. - .saturating_add(T::DbWeight::get().reads_writes(1, 1)), + .saturating_add(Weight::from_computation(T::DbWeight::get().reads_writes(1, 1))), di.class) })] pub fn proxy( @@ -519,10 +519,10 @@ pub mod pallet { /// # #[pallet::weight({ let di = call.get_dispatch_info(); - (T::WeightInfo::proxy_announced(T::MaxPending::get(), T::MaxProxies::get()) + (Weight::from_computation(T::WeightInfo::proxy_announced(T::MaxPending::get(), T::MaxProxies::get())) .saturating_add(di.weight) // AccountData for inner call origin accountdata. - .saturating_add(T::DbWeight::get().reads_writes(1, 1)), + .saturating_add(Weight::from_computation(T::DbWeight::get().reads_writes(1, 1))), di.class) })] pub fn proxy_announced( diff --git a/frame/proxy/src/tests.rs b/frame/proxy/src/tests.rs index a0807f1d3d0b6..3f5e55d4f2651 100644 --- a/frame/proxy/src/tests.rs +++ b/frame/proxy/src/tests.rs @@ -54,7 +54,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { type BaseCallFilter = BaseFilter; diff --git a/frame/proxy/src/weights.rs b/frame/proxy/src/weights.rs index a0df59204f673..5dc62e854693d 100644 --- a/frame/proxy/src/weights.rs +++ b/frame/proxy/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_proxy. diff --git a/frame/randomness-collective-flip/src/lib.rs b/frame/randomness-collective-flip/src/lib.rs index f709578f6941a..2f08a126913a2 100644 --- a/frame/randomness-collective-flip/src/lib.rs +++ b/frame/randomness-collective-flip/src/lib.rs @@ -107,7 +107,7 @@ pub mod pallet { } }); - T::DbWeight::get().reads_writes(1, 1) + Weight::from_computation(T::DbWeight::get().reads_writes(1, 1)) } } @@ -186,10 +186,11 @@ mod tests { ); parameter_types! { - pub BlockWeights: limits::BlockWeights = limits::BlockWeights - ::simple_max(1024); - pub BlockLength: limits::BlockLength = limits::BlockLength - ::max(2 * 1024); + pub BlockWeights: limits::BlockWeights = limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); + pub BlockLength: limits::BlockLength = limits::BlockLength::max(2 * 1024); } impl frame_system::Config for Test { diff --git a/frame/recovery/src/lib.rs b/frame/recovery/src/lib.rs index b839d25e32b47..eac756357af6f 100644 --- a/frame/recovery/src/lib.rs +++ b/frame/recovery/src/lib.rs @@ -375,9 +375,11 @@ pub mod pallet { /// - `account`: The recovered account you want to make a call on-behalf-of. /// - `call`: The call you want to make with the recovered account. #[pallet::weight({ - let dispatch_info = call.get_dispatch_info(); + let mut dispatch_info = call.get_dispatch_info(); + *dispatch_info.weight.computation_mut() = dispatch_info.weight.computation() + .saturating_add(T::WeightInfo::as_recovered()); ( - T::WeightInfo::as_recovered().saturating_add(dispatch_info.weight), + dispatch_info.weight, dispatch_info.class, )})] pub fn as_recovered( diff --git a/frame/recovery/src/mock.rs b/frame/recovery/src/mock.rs index 44fc4d72a4a5f..096da6b826146 100644 --- a/frame/recovery/src/mock.rs +++ b/frame/recovery/src/mock.rs @@ -47,7 +47,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { diff --git a/frame/recovery/src/weights.rs b/frame/recovery/src/weights.rs index 34a58b9e51ff2..ce2e2f1cd027a 100644 --- a/frame/recovery/src/weights.rs +++ b/frame/recovery/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_recovery. diff --git a/frame/referenda/src/branch.rs b/frame/referenda/src/branch.rs index f381f5fe5b709..d751a0e74bc77 100644 --- a/frame/referenda/src/branch.rs +++ b/frame/referenda/src/branch.rs @@ -19,6 +19,7 @@ use super::Config; use crate::weights::WeightInfo; +use frame_support::weights::Weight; /// Branches within the `begin_deciding` function. pub enum BeginDecidingBranch { @@ -59,9 +60,9 @@ impl From for ServiceBranch { impl ServiceBranch { /// Return the weight of the `nudge` function when it takes the branch denoted by `self`. - pub fn weight_of_nudge, I: 'static>(self) -> frame_support::weights::Weight { + pub fn weight_of_nudge, I: 'static>(self) -> Weight { use ServiceBranch::*; - match self { + let computation_weight = match self { NoDeposit => T::WeightInfo::nudge_referendum_no_deposit(), Preparing => T::WeightInfo::nudge_referendum_preparing(), Queued => T::WeightInfo::nudge_referendum_queued(), @@ -77,12 +78,15 @@ impl ServiceBranch { Approved => T::WeightInfo::nudge_referendum_approved(), Rejected => T::WeightInfo::nudge_referendum_rejected(), TimedOut | Fail => T::WeightInfo::nudge_referendum_timed_out(), - } + }; + + Weight::from_computation(computation_weight) } /// Return the maximum possible weight of the `nudge` function. - pub fn max_weight_of_nudge, I: 'static>() -> frame_support::weights::Weight { - 0.max(T::WeightInfo::nudge_referendum_no_deposit()) + pub fn max_weight_of_nudge, I: 'static>() -> Weight { + let computation_weight = 0 + .max(T::WeightInfo::nudge_referendum_no_deposit()) .max(T::WeightInfo::nudge_referendum_preparing()) .max(T::WeightInfo::nudge_referendum_queued()) .max(T::WeightInfo::nudge_referendum_not_queued()) @@ -96,16 +100,16 @@ impl ServiceBranch { .max(T::WeightInfo::nudge_referendum_continue_not_confirming()) .max(T::WeightInfo::nudge_referendum_approved()) .max(T::WeightInfo::nudge_referendum_rejected()) - .max(T::WeightInfo::nudge_referendum_timed_out()) + .max(T::WeightInfo::nudge_referendum_timed_out()); + + Weight::from_computation(computation_weight) } /// Return the weight of the `place_decision_deposit` function when it takes the branch denoted /// by `self`. - pub fn weight_of_deposit, I: 'static>( - self, - ) -> Option { + pub fn weight_of_deposit, I: 'static>(self) -> Option { use ServiceBranch::*; - Some(match self { + let computation_weight = match self { Preparing => T::WeightInfo::place_decision_deposit_preparing(), Queued => T::WeightInfo::place_decision_deposit_queued(), NotQueued => T::WeightInfo::place_decision_deposit_not_queued(), @@ -122,16 +126,20 @@ impl ServiceBranch { TimedOut | Fail | NoDeposit => return None, - }) + }; + + Some(Weight::from_computation(computation_weight)) } /// Return the maximum possible weight of the `place_decision_deposit` function. - pub fn max_weight_of_deposit, I: 'static>() -> frame_support::weights::Weight { - 0.max(T::WeightInfo::place_decision_deposit_preparing()) + pub fn max_weight_of_deposit, I: 'static>() -> Weight { + let computation_weight = 0 + .max(T::WeightInfo::place_decision_deposit_preparing()) .max(T::WeightInfo::place_decision_deposit_queued()) .max(T::WeightInfo::place_decision_deposit_not_queued()) .max(T::WeightInfo::place_decision_deposit_passing()) - .max(T::WeightInfo::place_decision_deposit_failing()) + .max(T::WeightInfo::place_decision_deposit_failing()); + Weight::from_computation(computation_weight) } } @@ -156,19 +164,22 @@ impl From for OneFewerDecidingBranch { impl OneFewerDecidingBranch { /// Return the weight of the `one_fewer_deciding` function when it takes the branch denoted /// by `self`. - pub fn weight, I: 'static>(self) -> frame_support::weights::Weight { + pub fn weight, I: 'static>(self) -> Weight { use OneFewerDecidingBranch::*; - match self { + let computation_weight = match self { QueueEmpty => T::WeightInfo::one_fewer_deciding_queue_empty(), BeginDecidingPassing => T::WeightInfo::one_fewer_deciding_passing(), BeginDecidingFailing => T::WeightInfo::one_fewer_deciding_failing(), - } + }; + Weight::from_computation(computation_weight) } /// Return the maximum possible weight of the `one_fewer_deciding` function. - pub fn max_weight, I: 'static>() -> frame_support::weights::Weight { - 0.max(T::WeightInfo::one_fewer_deciding_queue_empty()) + pub fn max_weight, I: 'static>() -> Weight { + let computation_weight = 0 + .max(T::WeightInfo::one_fewer_deciding_queue_empty()) .max(T::WeightInfo::one_fewer_deciding_passing()) - .max(T::WeightInfo::one_fewer_deciding_failing()) + .max(T::WeightInfo::one_fewer_deciding_failing()); + Weight::from_computation(computation_weight) } } diff --git a/frame/referenda/src/mock.rs b/frame/referenda/src/mock.rs index 1b0bbba24bbe6..e3189f8c4bb70 100644 --- a/frame/referenda/src/mock.rs +++ b/frame/referenda/src/mock.rs @@ -26,6 +26,7 @@ use frame_support::{ ConstU32, ConstU64, Contains, EqualPrivilegeOnly, OnInitialize, OriginTrait, Polling, PreimageRecipient, SortedMembers, }, + weights::Weight, }; use frame_system::{EnsureRoot, EnsureSignedBy}; use sp_core::H256; @@ -62,8 +63,12 @@ impl Contains for BaseFilter { parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1_000_000); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } + impl frame_system::Config for Test { type BaseCallFilter = BaseFilter; type BlockWeights = (); @@ -99,12 +104,19 @@ impl pallet_preimage::Config for Test { type BaseDeposit = (); type ByteDeposit = (); } + +parameter_types! { + pub MaximumSchedulerWeight: Weight = Weight::new() + .set_computation(2_000_000_000_000) + .set_bandwidth(2_000_000_000_000); +} + impl pallet_scheduler::Config for Test { type Event = Event; type Origin = Origin; type PalletsOrigin = OriginCaller; type Call = Call; - type MaximumWeight = ConstU64<2_000_000_000_000>; + type MaximumWeight = MaximumSchedulerWeight; type ScheduleOrigin = EnsureRoot; type MaxScheduledPerBlock = ConstU32<100>; type WeightInfo = (); diff --git a/frame/referenda/src/weights.rs b/frame/referenda/src/weights.rs index d9ddbed49e883..94abf53bfc754 100644 --- a/frame/referenda/src/weights.rs +++ b/frame/referenda/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_referenda. diff --git a/frame/remark/src/weights.rs b/frame/remark/src/weights.rs index b667a03bbd472..b530854bcc788 100644 --- a/frame/remark/src/weights.rs +++ b/frame/remark/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_remark. diff --git a/frame/scheduler/src/lib.rs b/frame/scheduler/src/lib.rs index 9b0fc87587e3a..9bc6f9c2e41a2 100644 --- a/frame/scheduler/src/lib.rs +++ b/frame/scheduler/src/lib.rs @@ -150,7 +150,7 @@ pub use preimage_provider::PreimageProviderAndMaybeRecipient; pub(crate) trait MarginalWeightInfo: WeightInfo { fn item(periodic: bool, named: bool, resolved: Option) -> Weight { - match (periodic, named, resolved) { + let computation_weight = match (periodic, named, resolved) { (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1), (_, true, None) => Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1), @@ -170,7 +170,9 @@ pub(crate) trait MarginalWeightInfo: WeightInfo { (true, true, Some(true)) => Self::on_initialize_periodic_named_resolved(2) - Self::on_initialize_periodic_named_resolved(1), - } + }; + + Weight::from_computation(computation_weight) } } impl MarginalWeightInfo for T {} @@ -314,7 +316,8 @@ pub mod pallet { let next = now + One::one(); - let mut total_weight: Weight = T::WeightInfo::on_initialize(0); + let mut total_weight: Weight = + Weight::from_computation(T::WeightInfo::on_initialize(0)); for (order, (index, mut s)) in queued.into_iter().enumerate() { let named = if let Some(ref id) = s.maybe_id { Lookup::::remove(id); @@ -358,7 +361,9 @@ pub mod pallet { .into(); if ensure_signed(origin).is_ok() { // Weights of Signed dispatches expect their signing account to be whitelisted. - item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1)); + item_weight.saturating_accrue(Weight::from_computation( + T::DbWeight::get().reads_writes(1, 1), + )); } // We allow a scheduled call if any is true: @@ -368,7 +373,7 @@ pub mod pallet { let hard_deadline = s.priority <= schedule::HARD_DEADLINE; let test_weight = total_weight.saturating_add(call_weight).saturating_add(item_weight); - if !hard_deadline && order > 0 && test_weight > limit { + if !hard_deadline && order > 0 && test_weight.is_any_greater_than(&limit) { // Cannot be scheduled this block - postpone until next. total_weight.saturating_accrue(T::WeightInfo::item(false, named, None)); if let Some(ref id) = s.maybe_id { @@ -573,7 +578,7 @@ impl Pallet { StorageVersion::new(3).put::(); - weight + T::DbWeight::get().writes(2) + Weight::from_computation(weight + T::DbWeight::get().writes(2)) } /// Migrate storage format from V2 to V3. @@ -609,7 +614,7 @@ impl Pallet { StorageVersion::new(3).put::(); - weight + T::DbWeight::get().writes(2) + Weight::from_computation(weight + T::DbWeight::get().writes(2)) } #[cfg(feature = "try-runtime")] diff --git a/frame/scheduler/src/mock.rs b/frame/scheduler/src/mock.rs index ecd04c3e48b52..b542610c327bf 100644 --- a/frame/scheduler/src/mock.rs +++ b/frame/scheduler/src/mock.rs @@ -119,8 +119,12 @@ impl Contains for BaseFilter { parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(2_000_000_000_000); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(2_000_000_000_000) + .set_bandwidth(2_000_000_000_000) + ); } + impl system::Config for Test { type BaseCallFilter = BaseFilter; type BlockWeights = (); diff --git a/frame/scheduler/src/tests.rs b/frame/scheduler/src/tests.rs index d2a795cb19fa4..83c4deab124c6 100644 --- a/frame/scheduler/src/tests.rs +++ b/frame/scheduler/src/tests.rs @@ -30,7 +30,7 @@ use substrate_test_utils::assert_eq_uvec; #[test] fn basic_scheduling_works() { new_test_ext().execute_with(|| { - let call = Call::Logger(LoggerCall::log { i: 42, weight: 1000 }); + let call = Call::Logger(LoggerCall::log { i: 42, weight: Weight::from_computation(1000) }); assert!(!::BaseCallFilter::contains(&call)); assert_ok!(Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.into())); run_to_block(3); @@ -45,7 +45,7 @@ fn basic_scheduling_works() { #[test] fn scheduling_with_preimages_works() { new_test_ext().execute_with(|| { - let call = Call::Logger(LoggerCall::log { i: 42, weight: 1000 }); + let call = Call::Logger(LoggerCall::log { i: 42, weight: Weight::from_computation(1000) }); let hash = ::Hashing::hash_of(&call); let hashed = MaybeHashed::Hash(hash.clone()); assert_ok!(Preimage::note_preimage(Origin::signed(0), call.encode())); @@ -65,7 +65,7 @@ fn scheduling_with_preimages_works() { #[test] fn scheduling_with_preimage_postpones_correctly() { new_test_ext().execute_with(|| { - let call = Call::Logger(LoggerCall::log { i: 42, weight: 1000 }); + let call = Call::Logger(LoggerCall::log { i: 42, weight: Weight::from_computation(1000) }); let hash = ::Hashing::hash_of(&call); let hashed = MaybeHashed::Hash(hash.clone()); @@ -98,7 +98,7 @@ fn scheduling_with_preimage_postpones_correctly() { fn schedule_after_works() { new_test_ext().execute_with(|| { run_to_block(2); - let call = Call::Logger(LoggerCall::log { i: 42, weight: 1000 }); + let call = Call::Logger(LoggerCall::log { i: 42, weight: Weight::from_computation(1000) }); assert!(!::BaseCallFilter::contains(&call)); // This will schedule the call 3 blocks after the next block... so block 3 + 3 = 6 assert_ok!(Scheduler::do_schedule(DispatchTime::After(3), None, 127, root(), call.into())); @@ -115,7 +115,7 @@ fn schedule_after_works() { fn schedule_after_zero_works() { new_test_ext().execute_with(|| { run_to_block(2); - let call = Call::Logger(LoggerCall::log { i: 42, weight: 1000 }); + let call = Call::Logger(LoggerCall::log { i: 42, weight: Weight::from_computation(1000) }); assert!(!::BaseCallFilter::contains(&call)); assert_ok!(Scheduler::do_schedule(DispatchTime::After(0), None, 127, root(), call.into())); // Will trigger on the next block. @@ -135,7 +135,8 @@ fn periodic_scheduling_works() { Some((3, 3)), 127, root(), - Call::Logger(logger::Call::log { i: 42, weight: 1000 }).into() + Call::Logger(logger::Call::log { i: 42, weight: Weight::from_computation(1000) }) + .into() )); run_to_block(3); assert!(logger::log().is_empty()); @@ -157,7 +158,7 @@ fn periodic_scheduling_works() { #[test] fn reschedule_works() { new_test_ext().execute_with(|| { - let call = Call::Logger(LoggerCall::log { i: 42, weight: 1000 }); + let call = Call::Logger(LoggerCall::log { i: 42, weight: Weight::from_computation(1000) }); assert!(!::BaseCallFilter::contains(&call)); assert_eq!( Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.into()).unwrap(), @@ -188,7 +189,7 @@ fn reschedule_works() { #[test] fn reschedule_named_works() { new_test_ext().execute_with(|| { - let call = Call::Logger(LoggerCall::log { i: 42, weight: 1000 }); + let call = Call::Logger(LoggerCall::log { i: 42, weight: Weight::from_computation(1000) }); assert!(!::BaseCallFilter::contains(&call)); assert_eq!( Scheduler::do_schedule_named( @@ -230,7 +231,7 @@ fn reschedule_named_works() { #[test] fn reschedule_named_perodic_works() { new_test_ext().execute_with(|| { - let call = Call::Logger(LoggerCall::log { i: 42, weight: 1000 }); + let call = Call::Logger(LoggerCall::log { i: 42, weight: Weight::from_computation(1000) }); assert!(!::BaseCallFilter::contains(&call)); assert_eq!( Scheduler::do_schedule_named( @@ -292,7 +293,7 @@ fn cancel_named_scheduling_works_with_normal_cancel() { None, 127, root(), - Call::Logger(LoggerCall::log { i: 69, weight: 1000 }).into(), + Call::Logger(LoggerCall::log { i: 69, weight: Weight::from_computation(1000) }).into(), ) .unwrap(); let i = Scheduler::do_schedule( @@ -300,7 +301,7 @@ fn cancel_named_scheduling_works_with_normal_cancel() { None, 127, root(), - Call::Logger(LoggerCall::log { i: 42, weight: 1000 }).into(), + Call::Logger(LoggerCall::log { i: 42, weight: Weight::from_computation(1000) }).into(), ) .unwrap(); run_to_block(3); @@ -322,7 +323,7 @@ fn cancel_named_periodic_scheduling_works() { Some((3, 3)), 127, root(), - Call::Logger(LoggerCall::log { i: 42, weight: 1000 }).into(), + Call::Logger(LoggerCall::log { i: 42, weight: Weight::from_computation(1000) }).into(), ) .unwrap(); // same id results in error. @@ -332,7 +333,7 @@ fn cancel_named_periodic_scheduling_works() { None, 127, root(), - Call::Logger(LoggerCall::log { i: 69, weight: 1000 }).into(), + Call::Logger(LoggerCall::log { i: 69, weight: Weight::from_computation(1000) }).into(), ) .is_err()); // different id is ok. @@ -342,7 +343,7 @@ fn cancel_named_periodic_scheduling_works() { None, 127, root(), - Call::Logger(LoggerCall::log { i: 69, weight: 1000 }).into(), + Call::Logger(LoggerCall::log { i: 69, weight: Weight::from_computation(1000) }).into(), ) .unwrap(); run_to_block(3); @@ -436,9 +437,11 @@ fn scheduler_respects_priority_ordering() { #[test] fn scheduler_respects_priority_ordering_with_soft_deadlines() { new_test_ext().execute_with(|| { - let max_weight = MaximumSchedulerWeight::get() - <() as WeightInfo>::on_initialize(0); - let item_weight = - <() as WeightInfo>::on_initialize(1) - <() as WeightInfo>::on_initialize(0); + let max_weight = MaximumSchedulerWeight::get() - + Weight::from_computation(<() as WeightInfo>::on_initialize(0)); + let item_weight = Weight::from_computation( + <() as WeightInfo>::on_initialize(1) - <() as WeightInfo>::on_initialize(0), + ); assert_ok!(Scheduler::do_schedule( DispatchTime::At(4), None, @@ -458,8 +461,11 @@ fn scheduler_respects_priority_ordering_with_soft_deadlines() { None, 126, root(), - Call::Logger(LoggerCall::log { i: 2600, weight: max_weight / 2 - item_weight + 1 }) - .into(), + Call::Logger(LoggerCall::log { + i: 2600, + weight: max_weight / 2 - item_weight + One::one() + }) + .into(), )); // 2600 does not fit with 69 or 42, but has higher priority, so will go through @@ -474,7 +480,7 @@ fn scheduler_respects_priority_ordering_with_soft_deadlines() { #[test] fn on_initialize_weight_is_correct() { new_test_ext().execute_with(|| { - let base_weight = <() as WeightInfo>::on_initialize(0); + let base_weight = Weight::from_computation(<() as WeightInfo>::on_initialize(0)); let call_weight = MaximumSchedulerWeight::get() / 4; // Named @@ -484,7 +490,11 @@ fn on_initialize_weight_is_correct() { None, 255, root(), - Call::Logger(LoggerCall::log { i: 3, weight: call_weight + 1 }).into(), + Call::Logger(LoggerCall::log { + i: 3, + weight: call_weight + Weight::from_computation(1) + }) + .into(), )); // Anon Periodic assert_ok!(Scheduler::do_schedule( @@ -492,7 +502,11 @@ fn on_initialize_weight_is_correct() { Some((1000, 3)), 128, root(), - Call::Logger(LoggerCall::log { i: 42, weight: call_weight + 2 }).into(), + Call::Logger(LoggerCall::log { + i: 42, + weight: call_weight + Weight::from_computation(2) + }) + .into(), )); // Anon assert_ok!(Scheduler::do_schedule( @@ -500,7 +514,11 @@ fn on_initialize_weight_is_correct() { None, 127, root(), - Call::Logger(LoggerCall::log { i: 69, weight: call_weight + 3 }).into(), + Call::Logger(LoggerCall::log { + i: 69, + weight: call_weight + Weight::from_computation(3) + }) + .into(), )); // Named Periodic assert_ok!(Scheduler::do_schedule_named( @@ -509,7 +527,11 @@ fn on_initialize_weight_is_correct() { Some((1000, 3)), 126, root(), - Call::Logger(LoggerCall::log { i: 2600, weight: call_weight + 4 }).into(), + Call::Logger(LoggerCall::log { + i: 2600, + weight: call_weight + Weight::from_computation(4) + }) + .into(), )); // Will include the named periodic only @@ -517,7 +539,8 @@ fn on_initialize_weight_is_correct() { assert_eq!( actual_weight, base_weight + - call_weight + 4 + <() as MarginalWeightInfo>::item(true, true, Some(false)) + call_weight + Weight::from_computation(4) + + <() as MarginalWeightInfo>::item(true, true, Some(false)) ); assert_eq!(logger::log(), vec![(root(), 2600u32)]); @@ -526,8 +549,10 @@ fn on_initialize_weight_is_correct() { assert_eq!( actual_weight, base_weight + - call_weight + 2 + <() as MarginalWeightInfo>::item(false, false, Some(false)) + - call_weight + 3 + <() as MarginalWeightInfo>::item(true, false, Some(false)) + call_weight + Weight::from_computation(2) + + <() as MarginalWeightInfo>::item(false, false, Some(false)) + + call_weight + Weight::from_computation(3) + + <() as MarginalWeightInfo>::item(true, false, Some(false)) ); assert_eq!(logger::log(), vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]); @@ -536,7 +561,8 @@ fn on_initialize_weight_is_correct() { assert_eq!( actual_weight, base_weight + - call_weight + 1 + <() as MarginalWeightInfo>::item(false, true, Some(false)) + call_weight + Weight::from_computation(1) + + <() as MarginalWeightInfo>::item(false, true, Some(false)) ); assert_eq!( logger::log(), @@ -552,8 +578,12 @@ fn on_initialize_weight_is_correct() { #[test] fn root_calls_works() { new_test_ext().execute_with(|| { - let call = Box::new(Call::Logger(LoggerCall::log { i: 69, weight: 1000 }).into()); - let call2 = Box::new(Call::Logger(LoggerCall::log { i: 42, weight: 1000 }).into()); + let call = Box::new( + Call::Logger(LoggerCall::log { i: 69, weight: Weight::from_computation(1000) }).into(), + ); + let call2 = Box::new( + Call::Logger(LoggerCall::log { i: 42, weight: Weight::from_computation(1000) }).into(), + ); assert_ok!(Scheduler::schedule_named(Origin::root(), 1u32.encode(), 4, None, 127, call,)); assert_ok!(Scheduler::schedule(Origin::root(), 4, None, 127, call2)); run_to_block(3); @@ -573,9 +603,15 @@ fn fails_to_schedule_task_in_the_past() { new_test_ext().execute_with(|| { run_to_block(3); - let call1 = Box::new(Call::Logger(LoggerCall::log { i: 69, weight: 1000 }).into()); - let call2 = Box::new(Call::Logger(LoggerCall::log { i: 42, weight: 1000 }).into()); - let call3 = Box::new(Call::Logger(LoggerCall::log { i: 42, weight: 1000 }).into()); + let call1 = Box::new( + Call::Logger(LoggerCall::log { i: 69, weight: Weight::from_computation(1000) }).into(), + ); + let call2 = Box::new( + Call::Logger(LoggerCall::log { i: 42, weight: Weight::from_computation(1000) }).into(), + ); + let call3 = Box::new( + Call::Logger(LoggerCall::log { i: 42, weight: Weight::from_computation(1000) }).into(), + ); assert_err!( Scheduler::schedule_named(Origin::root(), 1u32.encode(), 2, None, 127, call1), @@ -597,8 +633,12 @@ fn fails_to_schedule_task_in_the_past() { #[test] fn should_use_orign() { new_test_ext().execute_with(|| { - let call = Box::new(Call::Logger(LoggerCall::log { i: 69, weight: 1000 }).into()); - let call2 = Box::new(Call::Logger(LoggerCall::log { i: 42, weight: 1000 }).into()); + let call = Box::new( + Call::Logger(LoggerCall::log { i: 69, weight: Weight::from_computation(1000) }).into(), + ); + let call2 = Box::new( + Call::Logger(LoggerCall::log { i: 42, weight: Weight::from_computation(1000) }).into(), + ); assert_ok!(Scheduler::schedule_named( system::RawOrigin::Signed(1).into(), 1u32.encode(), @@ -623,8 +663,12 @@ fn should_use_orign() { #[test] fn should_check_orign() { new_test_ext().execute_with(|| { - let call = Box::new(Call::Logger(LoggerCall::log { i: 69, weight: 1000 }).into()); - let call2 = Box::new(Call::Logger(LoggerCall::log { i: 42, weight: 1000 }).into()); + let call = Box::new( + Call::Logger(LoggerCall::log { i: 69, weight: Weight::from_computation(1000) }).into(), + ); + let call2 = Box::new( + Call::Logger(LoggerCall::log { i: 42, weight: Weight::from_computation(1000) }).into(), + ); assert_noop!( Scheduler::schedule_named( system::RawOrigin::Signed(2).into(), @@ -646,10 +690,20 @@ fn should_check_orign() { #[test] fn should_check_orign_for_cancel() { new_test_ext().execute_with(|| { - let call = - Box::new(Call::Logger(LoggerCall::log_without_filter { i: 69, weight: 1000 }).into()); - let call2 = - Box::new(Call::Logger(LoggerCall::log_without_filter { i: 42, weight: 1000 }).into()); + let call = Box::new( + Call::Logger(LoggerCall::log_without_filter { + i: 69, + weight: Weight::from_computation(1000), + }) + .into(), + ); + let call2 = Box::new( + Call::Logger(LoggerCall::log_without_filter { + i: 42, + weight: Weight::from_computation(1000), + }) + .into(), + ); assert_ok!(Scheduler::schedule_named( system::RawOrigin::Signed(1).into(), 1u32.encode(), @@ -693,14 +747,20 @@ fn migration_to_v3_works() { Some(ScheduledV1 { maybe_id: None, priority: i as u8 + 10, - call: Call::Logger(LoggerCall::log { i: 96, weight: 100 }), + call: Call::Logger(LoggerCall::log { + i: 96, + weight: Weight::from_computation(100), + }), maybe_periodic: None, }), None, Some(ScheduledV1 { maybe_id: Some(b"test".to_vec()), priority: 123, - call: Call::Logger(LoggerCall::log { i: 69, weight: 1000 }), + call: Call::Logger(LoggerCall::log { + i: 69, + weight: Weight::from_computation(1000), + }), maybe_periodic: Some((456u64, 10)), }), ]; @@ -718,7 +778,11 @@ fn migration_to_v3_works() { Some(ScheduledV3Of:: { maybe_id: None, priority: 10, - call: Call::Logger(LoggerCall::log { i: 96, weight: 100 }).into(), + call: Call::Logger(LoggerCall::log { + i: 96, + weight: Weight::from_computation(100) + }) + .into(), maybe_periodic: None, origin: root(), _phantom: PhantomData::::default(), @@ -727,7 +791,11 @@ fn migration_to_v3_works() { Some(ScheduledV3Of:: { maybe_id: Some(b"test".to_vec()), priority: 123, - call: Call::Logger(LoggerCall::log { i: 69, weight: 1000 }).into(), + call: Call::Logger(LoggerCall::log { + i: 69, + weight: Weight::from_computation(1000) + }) + .into(), maybe_periodic: Some((456u64, 10)), origin: root(), _phantom: PhantomData::::default(), @@ -740,7 +808,11 @@ fn migration_to_v3_works() { Some(ScheduledV3Of:: { maybe_id: None, priority: 11, - call: Call::Logger(LoggerCall::log { i: 96, weight: 100 }).into(), + call: Call::Logger(LoggerCall::log { + i: 96, + weight: Weight::from_computation(100) + }) + .into(), maybe_periodic: None, origin: root(), _phantom: PhantomData::::default(), @@ -749,7 +821,11 @@ fn migration_to_v3_works() { Some(ScheduledV3Of:: { maybe_id: Some(b"test".to_vec()), priority: 123, - call: Call::Logger(LoggerCall::log { i: 69, weight: 1000 }).into(), + call: Call::Logger(LoggerCall::log { + i: 69, + weight: Weight::from_computation(1000) + }) + .into(), maybe_periodic: Some((456u64, 10)), origin: root(), _phantom: PhantomData::::default(), @@ -762,7 +838,11 @@ fn migration_to_v3_works() { Some(ScheduledV3Of:: { maybe_id: None, priority: 12, - call: Call::Logger(LoggerCall::log { i: 96, weight: 100 }).into(), + call: Call::Logger(LoggerCall::log { + i: 96, + weight: Weight::from_computation(100) + }) + .into(), maybe_periodic: None, origin: root(), _phantom: PhantomData::::default(), @@ -771,7 +851,11 @@ fn migration_to_v3_works() { Some(ScheduledV3Of:: { maybe_id: Some(b"test".to_vec()), priority: 123, - call: Call::Logger(LoggerCall::log { i: 69, weight: 1000 }).into(), + call: Call::Logger(LoggerCall::log { + i: 69, + weight: Weight::from_computation(1000) + }) + .into(), maybe_periodic: Some((456u64, 10)), origin: root(), _phantom: PhantomData::::default(), @@ -794,7 +878,11 @@ fn test_migrate_origin() { Some(Scheduled { maybe_id: None, priority: i as u8 + 10, - call: Call::Logger(LoggerCall::log { i: 96, weight: 100 }).into(), + call: Call::Logger(LoggerCall::log { + i: 96, + weight: Weight::from_computation(100), + }) + .into(), origin: 3u32, maybe_periodic: None, _phantom: Default::default(), @@ -804,7 +892,11 @@ fn test_migrate_origin() { maybe_id: Some(b"test".to_vec()), priority: 123, origin: 2u32, - call: Call::Logger(LoggerCall::log { i: 69, weight: 1000 }).into(), + call: Call::Logger(LoggerCall::log { + i: 69, + weight: Weight::from_computation(1000), + }) + .into(), maybe_periodic: Some((456u64, 10)), _phantom: Default::default(), }), @@ -833,7 +925,11 @@ fn test_migrate_origin() { Some(ScheduledV2::, u64, OriginCaller, u64> { maybe_id: None, priority: 10, - call: Call::Logger(LoggerCall::log { i: 96, weight: 100 }).into(), + call: Call::Logger(LoggerCall::log { + i: 96, + weight: Weight::from_computation(100) + }) + .into(), maybe_periodic: None, origin: system::RawOrigin::Root.into(), _phantom: PhantomData::::default(), @@ -842,7 +938,11 @@ fn test_migrate_origin() { Some(ScheduledV2 { maybe_id: Some(b"test".to_vec()), priority: 123, - call: Call::Logger(LoggerCall::log { i: 69, weight: 1000 }).into(), + call: Call::Logger(LoggerCall::log { + i: 69, + weight: Weight::from_computation(1000) + }) + .into(), maybe_periodic: Some((456u64, 10)), origin: system::RawOrigin::None.into(), _phantom: PhantomData::::default(), @@ -855,7 +955,11 @@ fn test_migrate_origin() { Some(ScheduledV2 { maybe_id: None, priority: 11, - call: Call::Logger(LoggerCall::log { i: 96, weight: 100 }).into(), + call: Call::Logger(LoggerCall::log { + i: 96, + weight: Weight::from_computation(100) + }) + .into(), maybe_periodic: None, origin: system::RawOrigin::Root.into(), _phantom: PhantomData::::default(), @@ -864,7 +968,11 @@ fn test_migrate_origin() { Some(ScheduledV2 { maybe_id: Some(b"test".to_vec()), priority: 123, - call: Call::Logger(LoggerCall::log { i: 69, weight: 1000 }).into(), + call: Call::Logger(LoggerCall::log { + i: 69, + weight: Weight::from_computation(1000) + }) + .into(), maybe_periodic: Some((456u64, 10)), origin: system::RawOrigin::None.into(), _phantom: PhantomData::::default(), @@ -877,7 +985,11 @@ fn test_migrate_origin() { Some(ScheduledV2 { maybe_id: None, priority: 12, - call: Call::Logger(LoggerCall::log { i: 96, weight: 100 }).into(), + call: Call::Logger(LoggerCall::log { + i: 96, + weight: Weight::from_computation(100) + }) + .into(), maybe_periodic: None, origin: system::RawOrigin::Root.into(), _phantom: PhantomData::::default(), @@ -886,7 +998,11 @@ fn test_migrate_origin() { Some(ScheduledV2 { maybe_id: Some(b"test".to_vec()), priority: 123, - call: Call::Logger(LoggerCall::log { i: 69, weight: 1000 }).into(), + call: Call::Logger(LoggerCall::log { + i: 69, + weight: Weight::from_computation(1000) + }) + .into(), maybe_periodic: Some((456u64, 10)), origin: system::RawOrigin::None.into(), _phantom: PhantomData::::default(), diff --git a/frame/scheduler/src/weights.rs b/frame/scheduler/src/weights.rs index d56c3208b44af..41feff259b7e2 100644 --- a/frame/scheduler/src/weights.rs +++ b/frame/scheduler/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_scheduler. diff --git a/frame/scored-pool/src/lib.rs b/frame/scored-pool/src/lib.rs index abdb9b2acc9b5..e8081b1242665 100644 --- a/frame/scored-pool/src/lib.rs +++ b/frame/scored-pool/src/lib.rs @@ -280,7 +280,7 @@ pub mod pallet { let pool = >::get(); >::refresh_members(pool, ChangeReceiver::MembershipChanged); } - 0 + Zero::zero() } } diff --git a/frame/scored-pool/src/mock.rs b/frame/scored-pool/src/mock.rs index 4fef5385eb2c5..8e7fca071813b 100644 --- a/frame/scored-pool/src/mock.rs +++ b/frame/scored-pool/src/mock.rs @@ -50,7 +50,10 @@ frame_support::construct_runtime!( parameter_types! { pub const CandidateDeposit: u64 = 25; pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } ord_parameter_types! { pub const KickOrigin: u64 = 2; diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index 71ee9d1e0758a..34c560984661d 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -574,7 +574,7 @@ pub mod pallet { // NOTE: the non-database part of the weight for `should_end_session(n)` is // included as weight for empty block, the database part is expected to be in // cache. - 0 + Weight::zero() } } } diff --git a/frame/session/src/migrations/v1.rs b/frame/session/src/migrations/v1.rs index 3c687ea7d9d66..2d47dfc0ac81c 100644 --- a/frame/session/src/migrations/v1.rs +++ b/frame/session/src/migrations/v1.rs @@ -16,6 +16,7 @@ // limitations under the License. use sp_io::hashing::twox_128; +use sp_runtime::traits::Zero; use sp_std::str; use frame_support::{ @@ -47,7 +48,7 @@ pub fn migrate::on_chain_storage_version(); @@ -82,7 +83,7 @@ pub fn migrate sp_io::TestExternalities { parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { diff --git a/frame/session/src/weights.rs b/frame/session/src/weights.rs index eabb26dcb32f4..958f44e4ab6b5 100644 --- a/frame/session/src/weights.rs +++ b/frame/session/src/weights.rs @@ -39,8 +39,9 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; +use sp_runtime::traits::Saturating; /// Weight functions needed for pallet_session. pub trait WeightInfo { diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index 2973ecd68092e..86abc31ce2dda 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -613,7 +613,7 @@ pub mod pallet { fn on_initialize(n: T::BlockNumber) -> Weight { let mut members = vec![]; - let mut weight = 0; + let mut weight = Zero::zero(); let weights = T::BlockWeights::get(); // Run a candidate/membership rotation diff --git a/frame/society/src/mock.rs b/frame/society/src/mock.rs index 04ea705eed556..211046dbcf579 100644 --- a/frame/society/src/mock.rs +++ b/frame/society/src/mock.rs @@ -50,7 +50,10 @@ frame_support::construct_runtime!( parameter_types! { pub const SocietyPalletId: PalletId = PalletId(*b"py/socie"); pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } ord_parameter_types! { diff --git a/frame/staking/src/migrations.rs b/frame/staking/src/migrations.rs index 14846da8a5d54..c2667279369b9 100644 --- a/frame/staking/src/migrations.rs +++ b/frame/staking/src/migrations.rs @@ -55,7 +55,7 @@ pub mod v9 { "InjectValidatorsIntoVoterList being executed on the wrong storage \ version, expected Releases::V8_0_0" ); - T::DbWeight::get().reads(1) + Weight::from_computation(T::DbWeight::get().reads(1)) } } @@ -125,7 +125,7 @@ pub mod v8 { T::BlockWeights::get().max_block } else { - T::DbWeight::get().reads(1) + Weight::from_computation(T::DbWeight::get().reads(1)) } } @@ -172,7 +172,10 @@ pub mod v7 { StorageVersion::::put(Releases::V7_0_0); log!(info, "Completed staking migration to Releases::V7_0_0"); - T::DbWeight::get().reads_writes(validator_count.saturating_add(nominator_count).into(), 2) + Weight::from_computation( + T::DbWeight::get() + .reads_writes(validator_count.saturating_add(nominator_count).into(), 2), + ) } } @@ -223,6 +226,6 @@ pub mod v6 { StorageVersion::::put(Releases::V6_0_0); log!(info, "Done."); - T::DbWeight::get().writes(6 + 1) + Weight::from_computation(T::DbWeight::get().writes(6 + 1)) } } diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index bd2d8cdc32ce9..44121eb55d77c 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -117,8 +117,9 @@ impl FindAuthor for Author11 { parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max( - frame_support::weights::constants::WEIGHT_PER_SECOND * 2 + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) ); pub static SessionsPerEra: SessionIndex = 3; pub static ExistentialDeposit: Balance = 1; diff --git a/frame/staking/src/pallet/impls.rs b/frame/staking/src/pallet/impls.rs index 4de1ea36cb591..dd87a3d2a2832 100644 --- a/frame/staking/src/pallet/impls.rs +++ b/frame/staking/src/pallet/impls.rs @@ -95,28 +95,26 @@ impl Pallet { validator_stash: T::AccountId, era: EraIndex, ) -> DispatchResultWithPostInfo { + let payout_stakers_alive_staked_weight = + Weight::from_computation(T::WeightInfo::payout_stakers_alive_staked(0)); // Validate input data let current_era = CurrentEra::::get().ok_or_else(|| { - Error::::InvalidEraToReward - .with_weight(T::WeightInfo::payout_stakers_alive_staked(0)) + Error::::InvalidEraToReward.with_weight(payout_stakers_alive_staked_weight) })?; let history_depth = Self::history_depth(); ensure!( era <= current_era && era >= current_era.saturating_sub(history_depth), - Error::::InvalidEraToReward - .with_weight(T::WeightInfo::payout_stakers_alive_staked(0)) + Error::::InvalidEraToReward.with_weight(payout_stakers_alive_staked_weight) ); // Note: if era has no reward to be claimed, era may be future. better not to update // `ledger.claimed_rewards` in this case. let era_payout = >::get(&era).ok_or_else(|| { - Error::::InvalidEraToReward - .with_weight(T::WeightInfo::payout_stakers_alive_staked(0)) + Error::::InvalidEraToReward.with_weight(payout_stakers_alive_staked_weight) })?; - let controller = Self::bonded(&validator_stash).ok_or_else(|| { - Error::::NotStash.with_weight(T::WeightInfo::payout_stakers_alive_staked(0)) - })?; + let controller = Self::bonded(&validator_stash) + .ok_or_else(|| Error::::NotStash.with_weight(payout_stakers_alive_staked_weight))?; let mut ledger = >::get(&controller).ok_or(Error::::NotController)?; ledger @@ -124,8 +122,9 @@ impl Pallet { .retain(|&x| x >= current_era.saturating_sub(history_depth)); match ledger.claimed_rewards.binary_search(&era) { Ok(_) => - return Err(Error::::AlreadyClaimed - .with_weight(T::WeightInfo::payout_stakers_alive_staked(0))), + return Err( + Error::::AlreadyClaimed.with_weight(payout_stakers_alive_staked_weight) + ), Err(pos) => ledger.claimed_rewards.insert(pos, era), } @@ -868,9 +867,9 @@ impl Pallet { /// Register some amount of weight directly with the system pallet. /// /// This is always mandatory weight. - fn register_weight(weight: Weight) { + fn register_weight(weight: frame_support::weights::ComputationWeight) { >::register_extra_weight_unchecked( - weight, + Weight::from_computation(weight), DispatchClass::Mandatory, ); } @@ -1163,9 +1162,10 @@ where disable_strategy: DisableStrategy, ) -> Weight { let reward_proportion = SlashRewardFraction::::get(); - let mut consumed_weight: Weight = 0; + let mut consumed_weight = Weight::zero(); let mut add_db_reads_writes = |reads, writes| { - consumed_weight += T::DbWeight::get().reads_writes(reads, writes); + consumed_weight += + Weight::from_computation(T::DbWeight::get().reads_writes(reads, writes)); }; let active_era = { @@ -1413,7 +1413,9 @@ impl StakingInterface for Pallet { .map(|post_info| { post_info .actual_weight - .unwrap_or(T::WeightInfo::withdraw_unbonded_kill(num_slashing_spans)) + .map_or(T::WeightInfo::withdraw_unbonded_kill(num_slashing_spans), |w| { + w.computation() + }) }) .map_err(|err_with_post_info| err_with_post_info.error) } diff --git a/frame/staking/src/pallet/mod.rs b/frame/staking/src/pallet/mod.rs index e53464195de23..da75f2eee1c10 100644 --- a/frame/staking/src/pallet/mod.rs +++ b/frame/staking/src/pallet/mod.rs @@ -711,7 +711,7 @@ pub mod pallet { impl Hooks> for Pallet { fn on_initialize(_now: BlockNumberFor) -> Weight { // just return the weight of the on_finalize. - T::DbWeight::get().reads(1) + Weight::from_computation(T::DbWeight::get().reads(1)) } fn on_finalize(_n: BlockNumberFor) { diff --git a/frame/staking/src/tests.rs b/frame/staking/src/tests.rs index ccd9558c5c21d..cb0257224e88f 100644 --- a/frame/staking/src/tests.rs +++ b/frame/staking/src/tests.rs @@ -3690,7 +3690,7 @@ fn payout_stakers_handles_weight_refund() { let info = call.get_dispatch_info(); let result = call.dispatch(Origin::signed(20)); assert_ok!(result); - assert_eq!(extract_actual_weight(&result, &info), zero_nom_payouts_weight); + assert_eq!(extract_actual_weight(&result, &info).computation(), zero_nom_payouts_weight); // The validator is not rewarded in this era; so there will be zero payouts to claim for // this era. @@ -3704,7 +3704,7 @@ fn payout_stakers_handles_weight_refund() { let info = call.get_dispatch_info(); let result = call.dispatch(Origin::signed(20)); assert_ok!(result); - assert_eq!(extract_actual_weight(&result, &info), zero_nom_payouts_weight); + assert_eq!(extract_actual_weight(&result, &info).computation(), zero_nom_payouts_weight); // Reward the validator and its nominators. Staking::reward_by_ids(vec![(11, 1)]); @@ -3718,7 +3718,10 @@ fn payout_stakers_handles_weight_refund() { let info = call.get_dispatch_info(); let result = call.dispatch(Origin::signed(20)); assert_ok!(result); - assert_eq!(extract_actual_weight(&result, &info), half_max_nom_rewarded_weight); + assert_eq!( + extract_actual_weight(&result, &info).computation(), + half_max_nom_rewarded_weight + ); // Add enough nominators so that we are at the limit. They will be active nominators // in the next era. @@ -3742,7 +3745,7 @@ fn payout_stakers_handles_weight_refund() { let info = call.get_dispatch_info(); let result = call.dispatch(Origin::signed(20)); assert_ok!(result); - assert_eq!(extract_actual_weight(&result, &info), max_nom_rewarded_weight); + assert_eq!(extract_actual_weight(&result, &info).computation(), max_nom_rewarded_weight); // Try and collect payouts for an era that has already been collected. let call = @@ -3751,7 +3754,7 @@ fn payout_stakers_handles_weight_refund() { let result = call.dispatch(Origin::signed(20)); assert!(result.is_err()); // When there is an error the consumed weight == weight when there are 0 nominator payouts. - assert_eq!(extract_actual_weight(&result, &info), zero_nom_payouts_weight); + assert_eq!(extract_actual_weight(&result, &info).computation(), zero_nom_payouts_weight); }); } @@ -3801,12 +3804,12 @@ fn bond_during_era_correctly_populates_claimed_rewards() { fn offences_weight_calculated_correctly() { ExtBuilder::default().nominate(true).build_and_execute(|| { // On offence with zero offenders: 4 Reads, 1 Write - let zero_offence_weight = ::DbWeight::get().reads_writes(4, 1); + let zero_offence_weight = Weight::from_computation(::DbWeight::get().reads_writes(4, 1)); assert_eq!(Staking::on_offence(&[], &[Perbill::from_percent(50)], 0, DisableStrategy::WhenSlashed), zero_offence_weight); // On Offence with N offenders, Unapplied: 4 Reads, 1 Write + 4 Reads, 5 Writes - let n_offence_unapplied_weight = ::DbWeight::get().reads_writes(4, 1) - + ::DbWeight::get().reads_writes(4, 5); + let n_offence_unapplied_weight = Weight::from_computation(::DbWeight::get().reads_writes(4, 1) + + ::DbWeight::get().reads_writes(4, 5)); let offenders: Vec::AccountId, pallet_session::historical::IdentificationTuple>> = (1..10).map(|i| @@ -3836,7 +3839,7 @@ fn offences_weight_calculated_correctly() { // `reward_cost` * reporters (1) + ::DbWeight::get().reads_writes(2, 2); - assert_eq!(Staking::on_offence(&one_offender, &[Perbill::from_percent(50)], 0, DisableStrategy::WhenSlashed), one_offence_unapplied_weight); + assert_eq!(Staking::on_offence(&one_offender, &[Perbill::from_percent(50)], 0, DisableStrategy::WhenSlashed), Weight::from_computation(one_offence_unapplied_weight)); }); } @@ -4115,7 +4118,7 @@ fn do_not_die_when_active_is_ed() { fn on_finalize_weight_is_nonzero() { ExtBuilder::default().build_and_execute(|| { let on_finalize_weight = ::DbWeight::get().reads(1); - assert!(>::on_initialize(1) >= on_finalize_weight); + assert!(>::on_initialize(1).computation() >= on_finalize_weight); }) } diff --git a/frame/staking/src/weights.rs b/frame/staking/src/weights.rs index e7f2e06e6dd07..f4f9666d2098e 100644 --- a/frame/staking/src/weights.rs +++ b/frame/staking/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_staking. diff --git a/frame/state-trie-migration/src/lib.rs b/frame/state-trie-migration/src/lib.rs index 899250cc3f3c3..a7bce1418cd55 100644 --- a/frame/state-trie-migration/src/lib.rs +++ b/frame/state-trie-migration/src/lib.rs @@ -101,25 +101,25 @@ pub mod pallet { impl WeightInfo for () { fn process_top_key(_: u32) -> Weight { - 1000000 + Weight::from_computation(1000000) } fn continue_migrate() -> Weight { - 1000000 + Weight::from_computation(1000000) } fn continue_migrate_wrong_witness() -> Weight { - 1000000 + Weight::from_computation(1000000) } fn migrate_custom_top_fail() -> Weight { - 1000000 + Weight::from_computation(1000000) } fn migrate_custom_top_success() -> Weight { - 1000000 + Weight::from_computation(1000000) } fn migrate_custom_child_fail() -> Weight { - 1000000 + Weight::from_computation(1000000) } fn migrate_custom_child_success() -> Weight { - 1000000 + Weight::from_computation(1000000) } } @@ -778,7 +778,7 @@ pub mod pallet { weight } else { - T::DbWeight::get().reads(1) + Weight::from_computation(T::DbWeight::get().reads(1)) } } } @@ -786,10 +786,11 @@ pub mod pallet { impl Pallet { /// The real weight of a migration of the given number of `items` with total `size`. fn dynamic_weight(items: u32, size: u32) -> frame_support::pallet_prelude::Weight { - let items = items as Weight; - items - .saturating_mul(::DbWeight::get().reads_writes(1, 1)) - // we assume that the read/write per-byte weight is the same for child and top tree. + let items = items as u64; + let computation_weight = items + .saturating_mul(::DbWeight::get().reads_writes(1, 1)); + // we assume that the read/write per-byte weight is the same for child and top tree. + Weight::from_computation(computation_weight) .saturating_add(T::WeightInfo::process_top_key(size)) } @@ -985,6 +986,7 @@ mod mock { use frame_support::{ parameter_types, traits::{ConstU32, ConstU64, Hooks}, + weights::Weight, }; use frame_system::{EnsureRoot, EnsureSigned}; use sp_core::{ @@ -992,7 +994,7 @@ mod mock { H256, }; use sp_runtime::{ - traits::{BlakeTwo256, Header as _, IdentityLookup}, + traits::{BlakeTwo256, Header as _, IdentityLookup, Zero}, StorageChild, }; @@ -1151,9 +1153,9 @@ mod mock { (custom_storage, version).into() } - pub(crate) fn run_to_block(n: u32) -> (H256, u64) { + pub(crate) fn run_to_block(n: u32) -> (H256, Weight) { let mut root = Default::default(); - let mut weight_sum = 0; + let mut weight_sum = Weight::zero(); log::trace!(target: LOG_TARGET, "running from {:?} to {:?}", System::block_number(), n); while System::block_number() < n { System::set_block_number(System::block_number() + 1); @@ -1446,7 +1448,10 @@ pub(crate) mod remote_tests { use crate::{AutoLimits, MigrationLimits, Pallet as StateTrieMigration, LOG_TARGET}; use codec::Encode; use frame_benchmarking::Zero; - use frame_support::traits::{Get, Hooks}; + use frame_support::{ + traits::{Get, Hooks}, + weights::Weight, + }; use frame_system::Pallet as System; use remote_externalities::Mode; use sp_core::H256; @@ -1455,9 +1460,9 @@ pub(crate) mod remote_tests { fn run_to_block>( n: ::BlockNumber, - ) -> (H256, u64) { + ) -> (H256, Weight) { let mut root = Default::default(); - let mut weight_sum = 0; + let mut weight_sum = Weight::zero(); while System::::block_number() < n { System::::set_block_number(System::::block_number() + One::one()); System::::on_initialize(System::::block_number()); diff --git a/frame/state-trie-migration/src/weights.rs b/frame/state-trie-migration/src/weights.rs index f08b115378f21..85ff10cabe5bc 100644 --- a/frame/state-trie-migration/src/weights.rs +++ b/frame/state-trie-migration/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_state_trie_migration. diff --git a/frame/sudo/src/lib.rs b/frame/sudo/src/lib.rs index d9e72b37f2970..7106d499853c0 100644 --- a/frame/sudo/src/lib.rs +++ b/frame/sudo/src/lib.rs @@ -137,7 +137,7 @@ pub mod pallet { /// # #[pallet::weight({ let dispatch_info = call.get_dispatch_info(); - (dispatch_info.weight.saturating_add(10_000), dispatch_info.class) + (dispatch_info.weight.saturating_add(Weight::from_computation(10_000)), dispatch_info.class) })] pub fn sudo( origin: OriginFor, @@ -217,12 +217,12 @@ pub mod pallet { /// - Weight of derivative `call` execution + 10,000. /// # #[pallet::weight({ - let dispatch_info = call.get_dispatch_info(); + let mut dispatch_info = call.get_dispatch_info(); + dispatch_info.weight = dispatch_info.weight + // AccountData for inner call origin accountdata. + .saturating_add(Weight::from_computation(T::DbWeight::get().reads_writes(1, 1))); ( - dispatch_info.weight - .saturating_add(10_000) - // AccountData for inner call origin accountdata. - .saturating_add(T::DbWeight::get().reads_writes(1, 1)), + dispatch_info.weight, dispatch_info.class, ) })] diff --git a/frame/sudo/src/mock.rs b/frame/sudo/src/mock.rs index 2e2a4abafcd98..9b4c06294e8b6 100644 --- a/frame/sudo/src/mock.rs +++ b/frame/sudo/src/mock.rs @@ -109,7 +109,10 @@ frame_support::construct_runtime!( ); parameter_types! { - pub BlockWeights: limits::BlockWeights = limits::BlockWeights::simple_max(1024); + pub BlockWeights: limits::BlockWeights = limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } pub struct BlockEverything; diff --git a/frame/sudo/src/tests.rs b/frame/sudo/src/tests.rs index 84c8e0c5c254e..2f3242648d4b9 100644 --- a/frame/sudo/src/tests.rs +++ b/frame/sudo/src/tests.rs @@ -18,7 +18,7 @@ //! Tests for the module. use super::*; -use frame_support::{assert_noop, assert_ok}; +use frame_support::{assert_noop, assert_ok, weights::Weight}; use mock::{ new_test_ext, Call, Event as TestEvent, Logger, LoggerCall, Origin, Sudo, SudoCall, System, Test, @@ -39,12 +39,18 @@ fn sudo_basics() { // Configure a default test environment and set the root `key` to 1. new_test_ext(1).execute_with(|| { // A privileged function should work when `sudo` is passed the root `key` as `origin`. - let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log { i: 42, weight: 1_000 })); + let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log { + i: 42, + weight: Weight::from_computation(1_000), + })); assert_ok!(Sudo::sudo(Origin::signed(1), call)); assert_eq!(Logger::i32_log(), vec![42i32]); // A privileged function should not work when `sudo` is passed a non-root `key` as `origin`. - let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log { i: 42, weight: 1_000 })); + let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log { + i: 42, + weight: Weight::from_computation(1_000), + })); assert_noop!(Sudo::sudo(Origin::signed(2), call), Error::::RequireSudo); }); } @@ -56,7 +62,10 @@ fn sudo_emits_events_correctly() { System::set_block_number(1); // Should emit event to indicate success when called with the root `key` and `call` is `Ok`. - let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log { i: 42, weight: 1 })); + let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log { + i: 42, + weight: Weight::from_computation(1), + })); assert_ok!(Sudo::sudo(Origin::signed(1), call)); System::assert_has_event(TestEvent::Sudo(Event::Sudid { sudo_result: Ok(()) })); }) @@ -66,24 +75,38 @@ fn sudo_emits_events_correctly() { fn sudo_unchecked_weight_basics() { new_test_ext(1).execute_with(|| { // A privileged function should work when `sudo` is passed the root `key` as origin. - let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log { i: 42, weight: 1_000 })); - assert_ok!(Sudo::sudo_unchecked_weight(Origin::signed(1), call, 1_000)); + let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log { + i: 42, + weight: Weight::from_computation(1_000), + })); + assert_ok!(Sudo::sudo_unchecked_weight( + Origin::signed(1), + call, + Weight::from_computation(1_000) + )); assert_eq!(Logger::i32_log(), vec![42i32]); // A privileged function should not work when called with a non-root `key`. - let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log { i: 42, weight: 1_000 })); + let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log { + i: 42, + weight: Weight::from_computation(1_000), + })); assert_noop!( - Sudo::sudo_unchecked_weight(Origin::signed(2), call, 1_000), + Sudo::sudo_unchecked_weight(Origin::signed(2), call, Weight::from_computation(1_000)), Error::::RequireSudo, ); // `I32Log` is unchanged after unsuccessful call. assert_eq!(Logger::i32_log(), vec![42i32]); // Controls the dispatched weight. - let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log { i: 42, weight: 1 })); - let sudo_unchecked_weight_call = SudoCall::sudo_unchecked_weight { call, weight: 1_000 }; + let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log { + i: 42, + weight: Weight::from_computation(1), + })); + let sudo_unchecked_weight_call = + SudoCall::sudo_unchecked_weight { call, weight: Weight::from_computation(1_000) }; let info = sudo_unchecked_weight_call.get_dispatch_info(); - assert_eq!(info.weight, 1_000); + assert_eq!(info.weight, Weight::from_computation(1_000)); }); } @@ -94,8 +117,15 @@ fn sudo_unchecked_weight_emits_events_correctly() { System::set_block_number(1); // Should emit event to indicate success when called with the root `key` and `call` is `Ok`. - let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log { i: 42, weight: 1 })); - assert_ok!(Sudo::sudo_unchecked_weight(Origin::signed(1), call, 1_000)); + let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log { + i: 42, + weight: Weight::from_computation(1), + })); + assert_ok!(Sudo::sudo_unchecked_weight( + Origin::signed(1), + call, + Weight::from_computation(1_000) + )); System::assert_has_event(TestEvent::Sudo(Event::Sudid { sudo_result: Ok(()) })); }) } @@ -134,17 +164,26 @@ fn set_key_emits_events_correctly() { fn sudo_as_basics() { new_test_ext(1).execute_with(|| { // A privileged function will not work when passed to `sudo_as`. - let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log { i: 42, weight: 1_000 })); + let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log { + i: 42, + weight: Weight::from_computation(1_000), + })); assert_ok!(Sudo::sudo_as(Origin::signed(1), 2, call)); assert!(Logger::i32_log().is_empty()); assert!(Logger::account_log().is_empty()); // A non-privileged function should not work when called with a non-root `key`. - let call = Box::new(Call::Logger(LoggerCall::non_privileged_log { i: 42, weight: 1 })); + let call = Box::new(Call::Logger(LoggerCall::non_privileged_log { + i: 42, + weight: Weight::from_computation(1), + })); assert_noop!(Sudo::sudo_as(Origin::signed(3), 2, call), Error::::RequireSudo); // A non-privileged function will work when passed to `sudo_as` with the root `key`. - let call = Box::new(Call::Logger(LoggerCall::non_privileged_log { i: 42, weight: 1 })); + let call = Box::new(Call::Logger(LoggerCall::non_privileged_log { + i: 42, + weight: Weight::from_computation(1), + })); assert_ok!(Sudo::sudo_as(Origin::signed(1), 2, call)); assert_eq!(Logger::i32_log(), vec![42i32]); // The correct user makes the call within `sudo_as`. @@ -159,7 +198,10 @@ fn sudo_as_emits_events_correctly() { System::set_block_number(1); // A non-privileged function will work when passed to `sudo_as` with the root `key`. - let call = Box::new(Call::Logger(LoggerCall::non_privileged_log { i: 42, weight: 1 })); + let call = Box::new(Call::Logger(LoggerCall::non_privileged_log { + i: 42, + weight: Weight::from_computation(1), + })); assert_ok!(Sudo::sudo_as(Origin::signed(1), 2, call)); System::assert_has_event(TestEvent::Sudo(Event::SudoAsDone { sudo_result: Ok(()) })); }); diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index 7ccf796167297..905081852cc16 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -34,7 +34,10 @@ pub use crate::{ TransactionPriority, WeighData, Weight, WithPostDispatchInfo, }, }; -pub use sp_runtime::{traits::Dispatchable, DispatchError, RuntimeDebug}; +pub use sp_runtime::{ + traits::{Dispatchable, Zero}, + DispatchError, RuntimeDebug, +}; /// The return type of a `Dispatchable` in frame. When returned explicitly from /// a dispatchable function it allows overriding the default `PostDispatchInfo` @@ -174,18 +177,19 @@ impl Parameter for T where T: Codec + EncodeLike + Clone + Eq + fmt::Debug + /// ``` /// # #[macro_use] /// # extern crate frame_support; -/// # use frame_support::dispatch::{DispatchResultWithPostInfo, WithPostDispatchInfo}; +/// # use frame_support::{dispatch::{DispatchResultWithPostInfo, WithPostDispatchInfo}, weights::Weight}; /// # use frame_system::{Config, ensure_signed}; /// decl_module! { /// pub struct Module for enum Call where origin: T::Origin { /// #[weight = 1_000_000] /// fn my_long_function(origin, do_expensive_calc: bool) -> DispatchResultWithPostInfo { -/// ensure_signed(origin).map_err(|e| e.with_weight(100_000))?; +/// ensure_signed(origin).map_err(|e| e.with_weight(Weight::new().set_computation(100_000).set_bandwidth(100_000)))?; /// if do_expensive_calc { /// // do the expensive calculation /// // ... /// // return None to indicate that we are using all weight (the default) -/// return Ok(None.into()); +/// let none: Option = None; +/// return Ok(none.into()); /// } /// // expensive calculation not executed: use only a portion of the weight /// Ok(Some(100_000).into()) @@ -1607,7 +1611,7 @@ macro_rules! decl_module { pallet_name, ); - 0 + <$crate::weights::Weight as $crate::dispatch::Zero>::zero() } #[cfg(feature = "try-runtime")] @@ -2587,7 +2591,7 @@ mod tests { CrateVersion, Get, GetCallName, IntegrityTest, OnFinalize, OnIdle, OnInitialize, OnRuntimeUpgrade, PalletInfo, }, - weights::{DispatchClass, DispatchInfo, Pays, RuntimeDbWeight}, + weights::{DispatchClass, DispatchInfo, Pays, RuntimeDbWeight, Weight}, }; pub trait Config: system::Config + Sized @@ -2638,13 +2642,13 @@ mod tests { #[weight = (5, DispatchClass::Operational)] fn operational(_origin) { unreachable!() } - fn on_initialize(n: T::BlockNumber,) -> Weight { if n.into() == 42 { panic!("on_initialize") } 7 } + fn on_initialize(n: T::BlockNumber,) -> Weight { if n.into() == 42 { panic!("on_initialize") } Weight::from_computation(7) } fn on_idle(n: T::BlockNumber, remaining_weight: Weight,) -> Weight { - if n.into() == 42 || remaining_weight == 42 { panic!("on_idle") } - 7 + if n.into() == 42 || remaining_weight == Weight::from_computation(42) { panic!("on_idle") } + Weight::from_computation(7) } fn on_finalize(n: T::BlockNumber,) { if n.into() == 42 { panic!("on_finalize") } } - fn on_runtime_upgrade() -> Weight { 10 } + fn on_runtime_upgrade() -> Weight { Weight::from_computation(10) } fn offchain_worker() {} /// Some doc fn integrity_test() { panic!("integrity_test") } @@ -2798,24 +2802,30 @@ mod tests { #[test] fn on_initialize_should_work_2() { - assert_eq!( as OnInitialize>::on_initialize(10), 7); + assert_eq!( + as OnInitialize>::on_initialize(10), + Weight::from_computation(7) + ); } #[test] #[should_panic(expected = "on_idle")] fn on_idle_should_work_1() { - as OnIdle>::on_idle(42, 9); + as OnIdle>::on_idle(42, Weight::from_computation(9)); } #[test] #[should_panic(expected = "on_idle")] fn on_idle_should_work_2() { - as OnIdle>::on_idle(9, 42); + as OnIdle>::on_idle(9, Weight::from_computation(42)); } #[test] fn on_idle_should_work_3() { - assert_eq!( as OnIdle>::on_idle(10, 11), 7); + assert_eq!( + as OnIdle>::on_idle(10, Weight::from_computation(11)), + Weight::from_computation(7) + ); } #[test] @@ -2827,7 +2837,10 @@ mod tests { #[test] fn on_runtime_upgrade_should_work() { sp_io::TestExternalities::default().execute_with(|| { - assert_eq!( as OnRuntimeUpgrade>::on_runtime_upgrade(), 10) + assert_eq!( + as OnRuntimeUpgrade>::on_runtime_upgrade(), + Weight::from_computation(10) + ) }); } @@ -2836,12 +2849,20 @@ mod tests { // operational. assert_eq!( Call::::operational {}.get_dispatch_info(), - DispatchInfo { weight: 5, class: DispatchClass::Operational, pays_fee: Pays::Yes }, + DispatchInfo { + weight: Weight::from_computation(5), + class: DispatchClass::Operational, + pays_fee: Pays::Yes + }, ); // custom basic assert_eq!( Call::::aux_3 {}.get_dispatch_info(), - DispatchInfo { weight: 3, class: DispatchClass::Normal, pays_fee: Pays::Yes }, + DispatchInfo { + weight: Weight::from_computation(3), + class: DispatchClass::Normal, + pays_fee: Pays::Yes + }, ); } diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 03f1553293a47..f4693784f975d 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -1326,7 +1326,7 @@ pub mod pallet_prelude { pub use codec::{Decode, Encode, MaxEncodedLen}; pub use scale_info::TypeInfo; pub use sp_runtime::{ - traits::{MaybeSerializeDeserialize, Member, ValidateUnsigned}, + traits::{MaybeSerializeDeserialize, Member, Saturating, ValidateUnsigned}, transaction_validity::{ InvalidTransaction, TransactionLongevity, TransactionPriority, TransactionSource, TransactionTag, TransactionValidity, TransactionValidityError, UnknownTransaction, diff --git a/frame/support/src/migrations.rs b/frame/support/src/migrations.rs index 05833e0515c07..df58b6507bb64 100644 --- a/frame/support/src/migrations.rs +++ b/frame/support/src/migrations.rs @@ -19,6 +19,7 @@ use crate::{ traits::{GetStorageVersion, PalletInfoAccess}, weights::{RuntimeDbWeight, Weight}, }; +use sp_runtime::traits::{Saturating, Zero}; /// Trait used by [`migrate_from_pallet_version_to_storage_version`] to do the actual migration. pub trait PalletVersionToStorageVersionHelper { @@ -38,14 +39,14 @@ impl PalletVersionToStorageVersionHelpe let version = ::current_storage_version(); version.put::(); - db_weight.writes(2) + db_weight.writes(2).into() } } #[impl_trait_for_tuples::impl_for_tuples(30)] impl PalletVersionToStorageVersionHelper for T { fn migrate(db_weight: &RuntimeDbWeight) -> Weight { - let mut weight: Weight = 0; + let mut weight = Weight::zero(); for_tuples!( #( weight = weight.saturating_add(T::migrate(db_weight)); )* ); diff --git a/frame/support/src/traits/hooks.rs b/frame/support/src/traits/hooks.rs index 385db4e4d1ad9..8bd04435ba89d 100644 --- a/frame/support/src/traits/hooks.rs +++ b/frame/support/src/traits/hooks.rs @@ -17,9 +17,10 @@ //! Traits for hooking tasks to events in a blockchain's lifecycle. +use crate::weights::Weight; use impl_trait_for_tuples::impl_for_tuples; use sp_arithmetic::traits::Saturating; -use sp_runtime::traits::AtLeast32BitUnsigned; +use sp_runtime::traits::{AtLeast32BitUnsigned, Zero}; /// The block initialization trait. /// @@ -33,15 +34,15 @@ pub trait OnInitialize { /// NOTE: This function is called BEFORE ANY extrinsic in a block is applied, /// including inherent extrinsics. Hence for instance, if you runtime includes /// `pallet_timestamp`, the `timestamp` is not yet up to date at this point. - fn on_initialize(_n: BlockNumber) -> crate::weights::Weight { - 0 + fn on_initialize(_n: BlockNumber) -> Weight { + Weight::zero() } } #[impl_for_tuples(30)] impl OnInitialize for Tuple { - fn on_initialize(n: BlockNumber) -> crate::weights::Weight { - let mut weight = 0; + fn on_initialize(n: BlockNumber) -> Weight { + let mut weight = Weight::zero(); for_tuples!( #( weight = weight.saturating_add(Tuple::on_initialize(n.clone())); )* ); weight } @@ -71,22 +72,17 @@ pub trait OnIdle { /// /// NOTE: This function is called AFTER ALL extrinsics - including inherent extrinsics - /// in a block are applied but before `on_finalize` is executed. - fn on_idle( - _n: BlockNumber, - _remaining_weight: crate::weights::Weight, - ) -> crate::weights::Weight { - 0 + fn on_idle(_n: BlockNumber, _remaining_weight: Weight) -> Weight { + Weight::zero() } } #[impl_for_tuples(30)] impl OnIdle for Tuple { - fn on_idle(n: BlockNumber, remaining_weight: crate::weights::Weight) -> crate::weights::Weight { - let on_idle_functions: &[fn( - BlockNumber, - crate::weights::Weight, - ) -> crate::weights::Weight] = &[for_tuples!( #( Tuple::on_idle ),* )]; - let mut weight = 0; + fn on_idle(n: BlockNumber, remaining_weight: Weight) -> Weight { + let on_idle_functions: &[fn(BlockNumber, Weight) -> Weight] = + &[for_tuples!( #( Tuple::on_idle ),* )]; + let mut weight = Weight::zero(); let len = on_idle_functions.len(); let start_index = n % (len as u32).into(); let start_index = start_index.try_into().ok().expect( @@ -96,7 +92,7 @@ impl OnIdle for Tuple { let adjusted_remaining_weight = remaining_weight.saturating_sub(weight); weight = weight.saturating_add(on_idle(n, adjusted_remaining_weight)); } - weight + weight.into() } } @@ -166,8 +162,8 @@ pub trait OnRuntimeUpgrade { /// block local data are not accessible. /// /// Return the non-negotiable weight consumed for runtime upgrade. - fn on_runtime_upgrade() -> crate::weights::Weight { - 0 + fn on_runtime_upgrade() -> Weight { + Weight::zero() } /// Execute some pre-checks prior to a runtime upgrade. @@ -189,8 +185,8 @@ pub trait OnRuntimeUpgrade { #[impl_for_tuples(30)] impl OnRuntimeUpgrade for Tuple { - fn on_runtime_upgrade() -> crate::weights::Weight { - let mut weight = 0; + fn on_runtime_upgrade() -> Weight { + let mut weight = Weight::zero(); for_tuples!( #( weight = weight.saturating_add(Tuple::on_runtime_upgrade()); )* ); weight } @@ -220,18 +216,15 @@ pub trait Hooks { /// Will not fire if the remaining weight is 0. /// Return the weight used, the hook will subtract it from current weight used /// and pass the result to the next `on_idle` hook if it exists. - fn on_idle( - _n: BlockNumber, - _remaining_weight: crate::weights::Weight, - ) -> crate::weights::Weight { - 0 + fn on_idle(_n: BlockNumber, _remaining_weight: Weight) -> Weight { + Weight::zero() } /// The block is being initialized. Implement to have something happen. /// /// Return the non-negotiable weight consumed in the block. - fn on_initialize(_n: BlockNumber) -> crate::weights::Weight { - 0 + fn on_initialize(_n: BlockNumber) -> Weight { + Weight::zero() } /// Perform a module upgrade. @@ -253,8 +246,8 @@ pub trait Hooks { /// pallet is discouraged and might get deprecated in the future. Alternatively, export the same /// logic as a free-function from your pallet, and pass it to `type Executive` from the /// top-level runtime. - fn on_runtime_upgrade() -> crate::weights::Weight { - 0 + fn on_runtime_upgrade() -> Weight { + Weight::zero() } /// Execute some pre-checks prior to a runtime upgrade. @@ -335,18 +328,18 @@ mod tests { fn on_initialize_and_on_runtime_upgrade_weight_merge_works() { struct Test; impl OnInitialize for Test { - fn on_initialize(_n: u8) -> crate::weights::Weight { - 10 + fn on_initialize(_n: u8) -> Weight { + Weight::from_computation(10) } } impl OnRuntimeUpgrade for Test { - fn on_runtime_upgrade() -> crate::weights::Weight { - 20 + fn on_runtime_upgrade() -> Weight { + Weight::from_computation(20) } } - assert_eq!(<(Test, Test)>::on_initialize(0), 20); - assert_eq!(<(Test, Test)>::on_runtime_upgrade(), 40); + assert_eq!(<(Test, Test)>::on_initialize(0), Weight::from_computation(20)); + assert_eq!(<(Test, Test)>::on_runtime_upgrade(), Weight::from_computation(40)); } #[test] @@ -358,48 +351,48 @@ mod tests { struct Test3; type TestTuple = (Test1, Test2, Test3); impl OnIdle for Test1 { - fn on_idle(_n: u32, _weight: crate::weights::Weight) -> crate::weights::Weight { + fn on_idle(_n: u32, _weight: Weight) -> Weight { unsafe { ON_IDLE_INVOCATION_ORDER.push("Test1"); } - 0 + Weight::zero() } } impl OnIdle for Test2 { - fn on_idle(_n: u32, _weight: crate::weights::Weight) -> crate::weights::Weight { + fn on_idle(_n: u32, _weight: Weight) -> Weight { unsafe { ON_IDLE_INVOCATION_ORDER.push("Test2"); } - 0 + Weight::zero() } } impl OnIdle for Test3 { - fn on_idle(_n: u32, _weight: crate::weights::Weight) -> crate::weights::Weight { + fn on_idle(_n: u32, _weight: Weight) -> Weight { unsafe { ON_IDLE_INVOCATION_ORDER.push("Test3"); } - 0 + Weight::zero() } } unsafe { - TestTuple::on_idle(0, 0); + TestTuple::on_idle(0, Weight::zero()); assert_eq!(ON_IDLE_INVOCATION_ORDER, ["Test1", "Test2", "Test3"].to_vec()); ON_IDLE_INVOCATION_ORDER.clear(); - TestTuple::on_idle(1, 0); + TestTuple::on_idle(1, Weight::zero()); assert_eq!(ON_IDLE_INVOCATION_ORDER, ["Test2", "Test3", "Test1"].to_vec()); ON_IDLE_INVOCATION_ORDER.clear(); - TestTuple::on_idle(2, 0); + TestTuple::on_idle(2, Weight::zero()); assert_eq!(ON_IDLE_INVOCATION_ORDER, ["Test3", "Test1", "Test2"].to_vec()); ON_IDLE_INVOCATION_ORDER.clear(); - TestTuple::on_idle(3, 0); + TestTuple::on_idle(3, Weight::zero()); assert_eq!(ON_IDLE_INVOCATION_ORDER, ["Test1", "Test2", "Test3"].to_vec()); ON_IDLE_INVOCATION_ORDER.clear(); - TestTuple::on_idle(4, 0); + TestTuple::on_idle(4, Weight::zero()); assert_eq!(ON_IDLE_INVOCATION_ORDER, ["Test2", "Test3", "Test1"].to_vec()); ON_IDLE_INVOCATION_ORDER.clear(); } diff --git a/frame/support/src/weights.rs b/frame/support/src/weights.rs index fc85a031b0852..bf5c75a92e21f 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -91,30 +91,20 @@ //! # fn main() {} //! ``` //! -//! ### 2. Define weights as a function of input arguments using `FunctionOf` tuple struct. -//! -//! This struct works in a similar manner as above. 3 items must be provided and each can be either -//! a fixed value or a function/closure with the same parameters list as the dispatchable function -//! itself, wrapper in a tuple. -//! -//! Using this only makes sense if you want to use a function for at least one of the elements. If -//! all 3 are static values, providing a raw tuple is easier. +//! ### 2. Define weights as a function of input arguments. //! //! ``` //! # use frame_system::Config; -//! # use frame_support::weights::{DispatchClass, FunctionOf, Pays}; +//! # use frame_support::weights::{DispatchClass, Pays}; //! frame_support::decl_module! { -//! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = FunctionOf( -//! // weight, function. -//! |args: (&u32, &u64)| *args.0 as u64 + args.1, -//! // class, fixed. -//! DispatchClass::Operational, -//! // pays fee, function. -//! |args: (&u32, &u64)| if *args.0 > 1000 { Pays::Yes } else { Pays::No }, -//! )] -//! fn dispatching(origin, a: u32, b: u64) { unimplemented!() } -//! } +//! pub struct Module for enum Call where origin: T::Origin { +//! #[weight = { +//! let final_weight = b.saturating_add((*a).into()); +//! let pays = if *a > 1000 { Pays::Yes } else { Pays::No }; +//! (final_weight, DispatchClass::Operational, pays) +//! }] +//! fn dispatching(origin, a: u32, b: u64) { unimplemented!() } +//! } //! } //! # fn main() {} //! ``` @@ -131,6 +121,7 @@ mod block_weights; mod extrinsic_weights; mod paritydb_weights; mod rocksdb_weights; +mod weight_v2; use crate::{ dispatch::{DispatchError, DispatchErrorWithPostInfo, DispatchResultWithPostInfo}, @@ -147,25 +138,31 @@ use sp_arithmetic::{ }; use sp_runtime::{ generic::{CheckedExtrinsic, UncheckedExtrinsic}, - traits::{SaturatedConversion, SignedExtension}, + traits::{CheckedAdd, SaturatedConversion, SignedExtension, Zero}, RuntimeDebug, }; /// Re-export priority as type pub use sp_runtime::transaction_validity::TransactionPriority; -/// Numeric range of a transaction weight. -pub type Weight = u64; +/// The current canonical version of Weight. +pub type Weight = weight_v2::Weight; + +/// Numeric range of a transaction time weight. +pub type ComputationWeight = u64; + +/// Numeric range of a transaction storage weight. +pub type BandwidthWeight = u64; /// These constants are specific to FRAME, and the current implementation of its various components. /// For example: FRAME System, FRAME Executive, our FRAME support libraries, etc... pub mod constants { - use super::Weight; + use super::ComputationWeight; - pub const WEIGHT_PER_SECOND: Weight = 1_000_000_000_000; - pub const WEIGHT_PER_MILLIS: Weight = WEIGHT_PER_SECOND / 1000; // 1_000_000_000 - pub const WEIGHT_PER_MICROS: Weight = WEIGHT_PER_MILLIS / 1000; // 1_000_000 - pub const WEIGHT_PER_NANOS: Weight = WEIGHT_PER_MICROS / 1000; // 1_000 + pub const WEIGHT_PER_SECOND: ComputationWeight = 1_000_000_000_000; + pub const WEIGHT_PER_MILLIS: ComputationWeight = WEIGHT_PER_SECOND / 1000; // 1_000_000_000 + pub const WEIGHT_PER_MICROS: ComputationWeight = WEIGHT_PER_MILLIS / 1000; // 1_000_000 + pub const WEIGHT_PER_NANOS: ComputationWeight = WEIGHT_PER_MICROS / 1000; // 1_000 // Expose the Block and Extrinsic base weights. pub use super::{block_weights::BlockExecutionWeight, extrinsic_weights::ExtrinsicBaseWeight}; @@ -358,9 +355,13 @@ pub fn extract_actual_weight(result: &DispatchResultWithPostInfo, info: &Dispatc .calc_actual_weight(info) } -impl From<(Option, Pays)> for PostDispatchInfo { - fn from(post_weight_info: (Option, Pays)) -> Self { - let (actual_weight, pays_fee) = post_weight_info; +impl From<(Option, Pays)> for PostDispatchInfo { + fn from(post_weight_info: (Option, Pays)) -> Self { + let (maybe_actual_time, pays_fee) = post_weight_info; + let actual_weight = match maybe_actual_time { + Some(actual_time) => Some(Weight::new().set_computation(actual_time)), + None => None, + }; Self { actual_weight, pays_fee } } } @@ -371,8 +372,12 @@ impl From for PostDispatchInfo { } } -impl From> for PostDispatchInfo { - fn from(actual_weight: Option) -> Self { +impl From> for PostDispatchInfo { + fn from(maybe_actual_computation: Option) -> Self { + let actual_weight = match maybe_actual_computation { + Some(actual_computation) => Some(Weight::new().set_computation(actual_computation)), + None => None, + }; Self { actual_weight, pays_fee: Default::default() } } } @@ -387,7 +392,14 @@ impl sp_runtime::traits::Printable for PostDispatchInfo { fn print(&self) { "actual_weight=".print(); match self.actual_weight { - Some(weight) => weight.print(), + Some(weight) => { + "time(".print(); + weight.computation().print(); + ")".print(); + "bandwidth(".print(); + ")".print(); + weight.bandwidth().print(); + }, None => "max-weight".print(), }; "pays_fee=".print(); @@ -406,20 +418,20 @@ pub trait WithPostDispatchInfo { /// # Example /// /// ```ignore - /// let who = ensure_signed(origin).map_err(|e| e.with_weight(100))?; - /// ensure!(who == me, Error::::NotMe.with_weight(200_000)); + /// let who = ensure_signed(origin).map_err(|e| e.with_weight(Weight::new().set_computation(100).set_bandwidth(100)))?; + /// ensure!(who == me, Error::::NotMe.with_weight(Weight { computation: 200_000, bandwidth: 100 })); /// ``` - fn with_weight(self, actual_weight: Weight) -> DispatchErrorWithPostInfo; + fn with_weight(self, actual_weight: impl Into) -> DispatchErrorWithPostInfo; } impl WithPostDispatchInfo for T where T: Into, { - fn with_weight(self, actual_weight: Weight) -> DispatchErrorWithPostInfo { + fn with_weight(self, actual_weight: impl Into) -> DispatchErrorWithPostInfo { DispatchErrorWithPostInfo { post_info: PostDispatchInfo { - actual_weight: Some(actual_weight), + actual_weight: Some(actual_weight.into()), pays_fee: Default::default(), }, error: self.into(), @@ -427,147 +439,78 @@ where } } -impl WeighData for Weight { +impl WeighData for ComputationWeight { fn weigh_data(&self, _: T) -> Weight { - *self + return Weight::new().set_computation(*self) } } -impl ClassifyDispatch for Weight { +impl ClassifyDispatch for ComputationWeight { fn classify_dispatch(&self, _: T) -> DispatchClass { DispatchClass::Normal } } -impl PaysFee for Weight { +impl PaysFee for ComputationWeight { fn pays_fee(&self, _: T) -> Pays { Pays::Yes } } -impl WeighData for (Weight, DispatchClass, Pays) { - fn weigh_data(&self, _: T) -> Weight { - self.0 +impl WeighData for (ComputationWeight, DispatchClass, Pays) { + fn weigh_data(&self, args: T) -> Weight { + return self.0.weigh_data(args) } } -impl ClassifyDispatch for (Weight, DispatchClass, Pays) { +impl ClassifyDispatch for (ComputationWeight, DispatchClass, Pays) { fn classify_dispatch(&self, _: T) -> DispatchClass { self.1 } } -impl PaysFee for (Weight, DispatchClass, Pays) { +impl PaysFee for (ComputationWeight, DispatchClass, Pays) { fn pays_fee(&self, _: T) -> Pays { self.2 } } -impl WeighData for (Weight, DispatchClass) { - fn weigh_data(&self, _: T) -> Weight { - self.0 +impl WeighData for (ComputationWeight, DispatchClass) { + fn weigh_data(&self, args: T) -> Weight { + return self.0.weigh_data(args) } } -impl ClassifyDispatch for (Weight, DispatchClass) { +impl ClassifyDispatch for (ComputationWeight, DispatchClass) { fn classify_dispatch(&self, _: T) -> DispatchClass { self.1 } } -impl PaysFee for (Weight, DispatchClass) { +impl PaysFee for (ComputationWeight, DispatchClass) { fn pays_fee(&self, _: T) -> Pays { Pays::Yes } } -impl WeighData for (Weight, Pays) { - fn weigh_data(&self, _: T) -> Weight { - self.0 +impl WeighData for (ComputationWeight, Pays) { + fn weigh_data(&self, args: T) -> Weight { + return self.0.weigh_data(args) } } -impl ClassifyDispatch for (Weight, Pays) { +impl ClassifyDispatch for (ComputationWeight, Pays) { fn classify_dispatch(&self, _: T) -> DispatchClass { DispatchClass::Normal } } -impl PaysFee for (Weight, Pays) { +impl PaysFee for (ComputationWeight, Pays) { fn pays_fee(&self, _: T) -> Pays { self.1 } } -/// A struct to represent a weight which is a function of the input arguments. The given items have -/// the following types: -/// -/// - `WD`: a raw `Weight` value or a closure that returns a `Weight` with the same argument list as -/// the dispatched, wrapped in a tuple. -/// - `CD`: a raw `DispatchClass` value or a closure that returns a `DispatchClass` with the same -/// argument list as the dispatched, wrapped in a tuple. -/// - `PF`: a `Pays` variant for whether this dispatch pays fee or not or a closure that returns a -/// `Pays` variant with the same argument list as the dispatched, wrapped in a tuple. -#[deprecated = "Function arguments are available directly inside the annotation now."] -pub struct FunctionOf(pub WD, pub CD, pub PF); - -// `WeighData` as a raw value -#[allow(deprecated)] -impl WeighData for FunctionOf { - fn weigh_data(&self, _: Args) -> Weight { - self.0 - } -} - -// `WeighData` as a closure -#[allow(deprecated)] -impl WeighData for FunctionOf -where - WD: Fn(Args) -> Weight, -{ - fn weigh_data(&self, args: Args) -> Weight { - (self.0)(args) - } -} - -// `ClassifyDispatch` as a raw value -#[allow(deprecated)] -impl ClassifyDispatch for FunctionOf { - fn classify_dispatch(&self, _: Args) -> DispatchClass { - self.1 - } -} - -// `ClassifyDispatch` as a raw value -#[allow(deprecated)] -impl ClassifyDispatch for FunctionOf -where - CD: Fn(Args) -> DispatchClass, -{ - fn classify_dispatch(&self, args: Args) -> DispatchClass { - (self.1)(args) - } -} - -// `PaysFee` as a raw value -#[allow(deprecated)] -impl PaysFee for FunctionOf { - fn pays_fee(&self, _: Args) -> Pays { - self.2 - } -} - -// `PaysFee` as a closure -#[allow(deprecated)] -impl PaysFee for FunctionOf -where - PF: Fn(Args) -> Pays, -{ - fn pays_fee(&self, args: Args) -> Pays { - (self.2)(args) - } -} - /// Implementation for unchecked extrinsic. impl GetDispatchInfo for UncheckedExtrinsic @@ -595,27 +538,33 @@ where impl GetDispatchInfo for sp_runtime::testing::TestXt { fn get_dispatch_info(&self) -> DispatchInfo { // for testing: weight == size. - DispatchInfo { weight: self.encode().len() as _, pays_fee: Pays::Yes, ..Default::default() } + DispatchInfo { + weight: Weight::new() + .set_computation(self.encode().len() as _) + .set_bandwidth(self.encode().len() as _), + pays_fee: Pays::Yes, + ..Default::default() + } } } /// The weight of database operations that the runtime can invoke. #[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo)] pub struct RuntimeDbWeight { - pub read: Weight, - pub write: Weight, + pub read: ComputationWeight, + pub write: ComputationWeight, } impl RuntimeDbWeight { - pub fn reads(self, r: Weight) -> Weight { + pub fn reads(self, r: ComputationWeight) -> ComputationWeight { self.read.saturating_mul(r) } - pub fn writes(self, w: Weight) -> Weight { + pub fn writes(self, w: ComputationWeight) -> ComputationWeight { self.write.saturating_mul(w) } - pub fn reads_writes(self, r: Weight, w: Weight) -> Weight { + pub fn reads_writes(self, r: ComputationWeight, w: ComputationWeight) -> ComputationWeight { let read_weight = self.read.saturating_mul(r); let write_weight = self.write.saturating_mul(w); read_weight.saturating_add(write_weight) @@ -666,7 +615,7 @@ pub trait WeightToFeePolynomial { /// /// This should not be overriden in most circumstances. Calculation is done in the /// `Balance` type and never overflows. All evaluation is saturating. - fn calc(weight: &Weight) -> Self::Balance { + fn calc(weight: &ComputationWeight) -> Self::Balance { Self::polynomial() .iter() .fold(Self::Balance::saturated_from(0u32), |mut acc, args| { @@ -708,7 +657,7 @@ where }) } - fn calc(weight: &Weight) -> Self::Balance { + fn calc(weight: &ComputationWeight) -> Self::Balance { Self::Balance::saturated_from(*weight) } } @@ -740,7 +689,7 @@ where }) } - fn calc(weight: &Weight) -> Self::Balance { + fn calc(weight: &ComputationWeight) -> Self::Balance { Self::Balance::saturated_from(*weight).saturating_mul(M::get()) } } @@ -797,7 +746,7 @@ impl PerDispatchClass { impl PerDispatchClass { /// Returns the total weight consumed by all extrinsics in the block. pub fn total(&self) -> Weight { - let mut sum = 0; + let mut sum = Weight::zero(); for class in DispatchClass::all() { sum = sum.saturating_add(*self.get(*class)); } @@ -814,7 +763,7 @@ impl PerDispatchClass { /// occur. pub fn checked_add(&mut self, weight: Weight, class: DispatchClass) -> Result<(), ()> { let value = self.get_mut(class); - *value = value.checked_add(weight).ok_or(())?; + *value = value.checked_add(&weight).ok_or(())?; Ok(()) } @@ -830,7 +779,7 @@ impl PerDispatchClass { #[allow(dead_code)] mod tests { use super::*; - use crate::{decl_module, parameter_types, traits::Get}; + use crate::{decl_module, parameter_types, traits::Get, weights::Weight}; pub trait Config: 'static { type Origin; @@ -873,7 +822,7 @@ mod tests { fn f03(_origin) { unimplemented!(); } // weight = a x 10 + b - #[weight = ((_a * 10 + _eb * 1) as Weight, DispatchClass::Normal, Pays::Yes)] + #[weight = ((_a * 10 + _eb * 1) as ComputationWeight, DispatchClass::Normal, Pays::Yes)] fn f11(_origin, _a: u32, _eb: u32) { unimplemented!(); } #[weight = (0, DispatchClass::Operational, Pays::Yes)] @@ -892,68 +841,91 @@ mod tests { fn weights_are_correct() { // #[weight = 1000] let info = Call::::f00 {}.get_dispatch_info(); - assert_eq!(info.weight, 1000); + assert_eq!(info.weight, Weight::from_computation(1000)); assert_eq!(info.class, DispatchClass::Normal); assert_eq!(info.pays_fee, Pays::Yes); // #[weight = (1000, DispatchClass::Mandatory)] let info = Call::::f01 {}.get_dispatch_info(); - assert_eq!(info.weight, 1000); + assert_eq!(info.weight, Weight::from_computation(1000)); assert_eq!(info.class, DispatchClass::Mandatory); assert_eq!(info.pays_fee, Pays::Yes); // #[weight = (1000, Pays::No)] let info = Call::::f02 {}.get_dispatch_info(); - assert_eq!(info.weight, 1000); + assert_eq!(info.weight, Weight::from_computation(1000)); assert_eq!(info.class, DispatchClass::Normal); assert_eq!(info.pays_fee, Pays::No); // #[weight = (1000, DispatchClass::Operational, Pays::No)] let info = Call::::f03 {}.get_dispatch_info(); - assert_eq!(info.weight, 1000); + assert_eq!(info.weight, Weight::from_computation(1000)); assert_eq!(info.class, DispatchClass::Operational); assert_eq!(info.pays_fee, Pays::No); // #[weight = ((_a * 10 + _eb * 1) as Weight, DispatchClass::Normal, Pays::Yes)] let info = Call::::f11 { _a: 13, _eb: 20 }.get_dispatch_info(); - assert_eq!(info.weight, 150); // 13*10 + 20 + assert_eq!(info.weight, Weight::from_computation(150)); // 13*10 + 20 assert_eq!(info.class, DispatchClass::Normal); assert_eq!(info.pays_fee, Pays::Yes); // #[weight = (0, DispatchClass::Operational, Pays::Yes)] let info = Call::::f12 { _a: 10, _eb: 20 }.get_dispatch_info(); - assert_eq!(info.weight, 0); + assert_eq!(info.weight, Weight::from_computation(0)); assert_eq!(info.class, DispatchClass::Operational); assert_eq!(info.pays_fee, Pays::Yes); // #[weight = T::DbWeight::get().reads(3) + T::DbWeight::get().writes(2) + 10_000] let info = Call::::f20 {}.get_dispatch_info(); - assert_eq!(info.weight, 12300); // 100*3 + 1000*2 + 10_1000 + assert_eq!(info.weight, Weight::from_computation(12300)); // 100*3 + 1000*2 + 10_1000 assert_eq!(info.class, DispatchClass::Normal); assert_eq!(info.pays_fee, Pays::Yes); // #[weight = T::DbWeight::get().reads_writes(6, 5) + 40_000] let info = Call::::f21 {}.get_dispatch_info(); - assert_eq!(info.weight, 45600); // 100*6 + 1000*5 + 40_1000 + assert_eq!(info.weight, Weight::from_computation(45600)); // 100*6 + 1000*5 + 40_1000 assert_eq!(info.class, DispatchClass::Normal); assert_eq!(info.pays_fee, Pays::Yes); } #[test] fn extract_actual_weight_works() { - let pre = DispatchInfo { weight: 1000, ..Default::default() }; - assert_eq!(extract_actual_weight(&Ok(Some(7).into()), &pre), 7); - assert_eq!(extract_actual_weight(&Ok(Some(1000).into()), &pre), 1000); - assert_eq!(extract_actual_weight(&Err(DispatchError::BadOrigin.with_weight(9)), &pre), 9); + let pre = DispatchInfo { + weight: Weight::new().set_computation(1000).set_bandwidth(123), + ..Default::default() + }; + assert_eq!(extract_actual_weight(&Ok(Some(7).into()), &pre), Weight::from_computation(7)); + assert_eq!( + extract_actual_weight(&Ok(Some(1000).into()), &pre), + Weight::from_computation(1000) + ); + assert_eq!( + extract_actual_weight( + &Err(DispatchError::BadOrigin + .with_weight(Weight::new().set_computation(9).set_bandwidth(99))), + &pre + ), + Weight::new().set_computation(9).set_bandwidth(99) + ); } #[test] fn extract_actual_weight_caps_at_pre_weight() { - let pre = DispatchInfo { weight: 1000, ..Default::default() }; - assert_eq!(extract_actual_weight(&Ok(Some(1250).into()), &pre), 1000); + let pre = DispatchInfo { + weight: Weight::new().set_computation(1000).set_bandwidth(120), + ..Default::default() + }; + assert_eq!( + extract_actual_weight(&Ok(Some(1250).into()), &pre), + Weight::from_computation(1000) + ); assert_eq!( - extract_actual_weight(&Err(DispatchError::BadOrigin.with_weight(1300)), &pre), - 1000 + extract_actual_weight( + &Err(DispatchError::BadOrigin + .with_weight(Weight::new().set_computation(1300).set_bandwidth(130))), + &pre + ), + Weight::new().set_computation(1000).set_bandwidth(120) ); } @@ -1010,14 +982,14 @@ mod tests { #[test] fn polynomial_does_not_overflow() { - assert_eq!(Poly::calc(&Weight::max_value()), Balance::max_value() - 10_000); + assert_eq!(Poly::calc(&u64::MAX), Balance::max_value() - 10_000); } #[test] fn identity_fee_works() { assert_eq!(IdentityFee::::calc(&0), 0); assert_eq!(IdentityFee::::calc(&50), 50); - assert_eq!(IdentityFee::::calc(&Weight::max_value()), Balance::max_value()); + assert_eq!(IdentityFee::::calc(&u64::MAX), Balance::max_value()); } #[test] diff --git a/frame/support/src/weights/block_weights.rs b/frame/support/src/weights/block_weights.rs index d1d5f8320d104..67c0fdb3d97ee 100644 --- a/frame/support/src/weights/block_weights.rs +++ b/frame/support/src/weights/block_weights.rs @@ -53,7 +53,7 @@ parameter_types! { /// 99th: 5_470_141 /// 95th: 5_418_269 /// 75th: 5_355_579 - pub const BlockExecutionWeight: Weight = 5_343_308 * WEIGHT_PER_NANOS; + pub const BlockExecutionWeight: Weight = Weight::from_computation(5_343_308 * WEIGHT_PER_NANOS); } #[cfg(test)] @@ -68,8 +68,14 @@ mod test_weights { let w = super::BlockExecutionWeight::get(); // At least 100 µs. - assert!(w >= 100 * constants::WEIGHT_PER_MICROS, "Weight should be at least 100 µs."); + assert!( + w.computation() >= 100 * constants::WEIGHT_PER_MICROS, + "Weight should be at least 100 µs." + ); // At most 50 ms. - assert!(w <= 50 * constants::WEIGHT_PER_MILLIS, "Weight should be at most 50 ms."); + assert!( + w.computation() <= 50 * constants::WEIGHT_PER_MILLIS, + "Weight should be at most 50 ms." + ); } } diff --git a/frame/support/src/weights/extrinsic_weights.rs b/frame/support/src/weights/extrinsic_weights.rs index 1a5a4e7a460c0..8b231fc9b4c6d 100644 --- a/frame/support/src/weights/extrinsic_weights.rs +++ b/frame/support/src/weights/extrinsic_weights.rs @@ -53,7 +53,7 @@ parameter_types! { /// 99th: 86_115 /// 95th: 86_069 /// 75th: 85_937 - pub const ExtrinsicBaseWeight: Weight = 85_795 * WEIGHT_PER_NANOS; + pub const ExtrinsicBaseWeight: Weight = Weight::from_computation(85_795 * WEIGHT_PER_NANOS); } #[cfg(test)] @@ -68,8 +68,11 @@ mod test_weights { let w = super::ExtrinsicBaseWeight::get(); // At least 10 µs. - assert!(w >= 10 * constants::WEIGHT_PER_MICROS, "Weight should be at least 10 µs."); + assert!( + w.computation() >= 10 * constants::WEIGHT_PER_MICROS, + "Weight should be at least 10 µs." + ); // At most 1 ms. - assert!(w <= constants::WEIGHT_PER_MILLIS, "Weight should be at most 1 ms."); + assert!(w.computation() <= constants::WEIGHT_PER_MILLIS, "Weight should be at most 1 ms."); } } diff --git a/frame/support/src/weights/weight_v2.rs b/frame/support/src/weights/weight_v2.rs new file mode 100644 index 0000000000000..36621ec842aab --- /dev/null +++ b/frame/support/src/weights/weight_v2.rs @@ -0,0 +1,451 @@ +// This file is part of Substrate. + +// Copyright (C) 2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use codec::{Decode, Encode, MaxEncodedLen}; +use core::ops::{Add, AddAssign, Div, Mul, Sub, SubAssign}; +use sp_runtime::{ + traits::{Bounded, CheckedAdd, CheckedSub, One, Zero}, + RuntimeDebug, +}; + +use super::*; + +#[derive( + Encode, Decode, MaxEncodedLen, TypeInfo, Eq, PartialEq, Copy, Clone, RuntimeDebug, Default, +)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +pub struct Weight { + /// The weight of computational time used. + computation: ComputationWeight, + /// The weight of the storage bandwidth used. + bandwidth: BandwidthWeight, +} + +impl Weight { + /// Create a new Weight with zero computation and bandwidth. + pub const fn new() -> Self { + Self { computation: 0, bandwidth: 0 } + } + + /// Set the computational part of the weight. + pub const fn set_computation(mut self, c: ComputationWeight) -> Self { + self.computation = c; + self + } + + /// Set the bandwidth part of the weight. + pub const fn set_bandwidth(mut self, b: BandwidthWeight) -> Self { + self.bandwidth = b; + self + } + + /// Return the computational part of the weight. + pub const fn computation(&self) -> ComputationWeight { + self.computation + } + + /// Return the bandwidth part of the weight. + pub const fn bandwidth(&self) -> BandwidthWeight { + self.bandwidth + } + + /// Return a mutable computational part of the weight. + pub fn computation_mut(&mut self) -> &mut ComputationWeight { + &mut self.computation + } + + /// Return a mutable bandwidth part of the weight. + pub fn bandwidth_mut(&mut self) -> &mut BandwidthWeight { + &mut self.bandwidth + } + + pub const MAX: Self = + Self { computation: ComputationWeight::MAX, bandwidth: BandwidthWeight::MAX }; + + /// Get the conservative min of `self` and `other` weight. + pub fn min(&self, other: Self) -> Self { + Self { + computation: self.computation.min(other.computation), + bandwidth: self.bandwidth.min(other.bandwidth), + } + } + + /// Get the aggressive max of `self` and `other` weight. + pub fn max(&self, other: Self) -> Self { + Self { + computation: self.computation.max(other.computation), + bandwidth: self.bandwidth.max(other.bandwidth), + } + } + + /// Try to add some `other` weight while upholding the `limit`. + pub fn try_add(&self, other: &Self, limit: &Self) -> Option { + let total = self.checked_add(other)?; + if total.computation > limit.computation || total.bandwidth > limit.bandwidth { + None + } else { + Some(total) + } + } + + /// Construct with computation weight only (zero `bandwith`). + pub const fn from_computation(computation: ComputationWeight) -> Self { + Self { computation, bandwidth: 0 } + } + + /// Checks if any param of `self` is less than `other`. + pub fn is_any_less_than(&self, other: &Self) -> bool { + self.computation < other.computation || self.bandwidth < other.bandwidth + } + + /// Checks if any param of `self` is less than `other`. + pub fn is_any_greater_than(&self, other: &Self) -> bool { + self.computation > other.computation || self.bandwidth > other.bandwidth + } + + /// Checks if all params of `self` are less than `other`. + pub fn is_strictly_less_than(&self, other: &Self) -> bool { + self.computation < other.computation && self.bandwidth < other.bandwidth + } + + /// Checks if all params of `self` are greater than `other`. + pub fn is_strictly_greater_than(&self, other: &Self) -> bool { + self.computation > other.computation && self.bandwidth > other.bandwidth + } + + /// Checks if all params of `self` are less than or equal to `other`. + pub fn is_strictly_less_than_or_equal(&self, other: &Self) -> bool { + self.computation <= other.computation && self.bandwidth <= other.bandwidth + } + + /// Checks if all params of `self` are greater than or equal to `other`. + pub fn is_strictly_greater_than_or_equal(&self, other: &Self) -> bool { + self.computation >= other.computation && self.bandwidth >= other.bandwidth + } + + pub fn checked_mul(self, rhs: u64) -> Option { + let computation = self.computation.checked_mul(rhs)?; + let bandwidth = self.bandwidth.checked_mul(rhs)?; + Some(Self { computation, bandwidth }) + } + + pub fn checked_div(self, rhs: u64) -> Option { + let computation = self.computation.checked_div(rhs)?; + let bandwidth = self.bandwidth.checked_div(rhs)?; + Some(Self { computation, bandwidth }) + } +} + +impl From<(ComputationWeight, BandwidthWeight)> for Weight { + fn from(a: (ComputationWeight, BandwidthWeight)) -> Self { + Self { computation: a.0, bandwidth: a.1 } + } +} + +impl Zero for Weight { + fn zero() -> Self { + Self { computation: 0, bandwidth: 0 } + } + + fn is_zero(&self) -> bool { + self.computation == 0 && self.bandwidth == 0 + } +} + +impl One for Weight { + fn one() -> Self { + Self { computation: 1, bandwidth: 1 } + } +} + +impl Add for Weight { + type Output = Self; + fn add(self, rhs: Self) -> Self { + Self { + computation: self.computation + rhs.computation, + bandwidth: self.bandwidth + rhs.bandwidth, + } + } +} + +impl Sub for Weight { + type Output = Self; + fn sub(self, rhs: Self) -> Self { + Self { + computation: self.computation - rhs.computation, + bandwidth: self.bandwidth - rhs.bandwidth, + } + } +} + +impl From for Weight { + fn from(t: ComputationWeight) -> Self { + Self { computation: t, bandwidth: 0 } + } +} + +impl Mul for Weight { + type Output = Self; + fn mul(self, b: Self) -> Self { + Self { + computation: b.computation * self.computation, + bandwidth: b.bandwidth * self.bandwidth, + } + } +} + +impl Mul for Weight +where + T: Mul + Copy, +{ + type Output = Self; + fn mul(self, b: T) -> Self { + Self { computation: b * self.computation, bandwidth: b * self.bandwidth } + } +} + +impl Div for Weight +where + u64: Div, + T: Copy, +{ + type Output = Self; + fn div(self, b: T) -> Self { + Self { computation: self.computation / b, bandwidth: self.bandwidth / b } + } +} + +impl Mul for Perbill { + type Output = Weight; + fn mul(self, b: Weight) -> Weight { + Weight { computation: self * b.computation, bandwidth: self * b.bandwidth } + } +} + +impl Saturating for Weight { + fn saturating_add(self, rhs: Self) -> Self { + Self { + computation: self.computation.saturating_add(rhs.computation), + bandwidth: self.bandwidth.saturating_add(rhs.bandwidth), + } + } + + fn saturating_sub(self, rhs: Self) -> Self { + Self { + computation: self.computation.saturating_sub(rhs.computation), + bandwidth: self.bandwidth.saturating_sub(rhs.bandwidth), + } + } + + fn saturating_mul(self, rhs: Self) -> Self { + Self { + computation: self.computation.saturating_mul(rhs.computation), + bandwidth: self.bandwidth.saturating_mul(rhs.bandwidth), + } + } + + fn saturating_pow(self, exp: usize) -> Self { + Self { + computation: self.computation.saturating_pow(exp as u32), + bandwidth: self.bandwidth.saturating_pow(exp as u32), + } + } +} + +impl CheckedAdd for Weight { + fn checked_add(&self, rhs: &Self) -> Option { + let computation = self.computation.checked_add(rhs.computation)?; + let bandwidth = self.bandwidth.checked_add(rhs.bandwidth)?; + Some(Self { computation, bandwidth }) + } +} + +impl CheckedSub for Weight { + fn checked_sub(&self, rhs: &Self) -> Option { + let computation = self.computation.checked_sub(rhs.computation)?; + let bandwidth = self.bandwidth.checked_sub(rhs.bandwidth)?; + Some(Self { computation, bandwidth }) + } +} + +impl PaysFee for (Weight, DispatchClass, Pays) { + fn pays_fee(&self, _: T) -> Pays { + self.2 + } +} + +impl WeighData for (Weight, DispatchClass) { + fn weigh_data(&self, args: T) -> Weight { + return self.0.weigh_data(args) + } +} + +impl WeighData for (Weight, DispatchClass, Pays) { + fn weigh_data(&self, args: T) -> Weight { + return self.0.weigh_data(args) + } +} + +impl ClassifyDispatch for (Weight, DispatchClass) { + fn classify_dispatch(&self, _: T) -> DispatchClass { + self.1 + } +} + +impl PaysFee for (Weight, DispatchClass) { + fn pays_fee(&self, _: T) -> Pays { + Pays::Yes + } +} + +impl WeighData for (Weight, Pays) { + fn weigh_data(&self, args: T) -> Weight { + return self.0.weigh_data(args) + } +} + +impl ClassifyDispatch for (Weight, Pays) { + fn classify_dispatch(&self, _: T) -> DispatchClass { + DispatchClass::Normal + } +} + +impl PaysFee for (Weight, Pays) { + fn pays_fee(&self, _: T) -> Pays { + self.1 + } +} + +impl From<(Option, Pays)> for PostDispatchInfo { + fn from(post_weight_info: (Option, Pays)) -> Self { + let (actual_weight, pays_fee) = post_weight_info; + Self { actual_weight, pays_fee } + } +} + +impl From> for PostDispatchInfo { + fn from(actual_weight: Option) -> Self { + Self { actual_weight, pays_fee: Default::default() } + } +} + +impl WeighData for Weight { + fn weigh_data(&self, _: T) -> Weight { + return *self + } +} + +impl ClassifyDispatch for Weight { + fn classify_dispatch(&self, _: T) -> DispatchClass { + DispatchClass::Normal + } +} + +impl PaysFee for Weight { + fn pays_fee(&self, _: T) -> Pays { + Pays::Yes + } +} + +impl ClassifyDispatch for (Weight, DispatchClass, Pays) { + fn classify_dispatch(&self, _: T) -> DispatchClass { + self.1 + } +} + +impl core::fmt::Display for Weight { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "Weight(computation: {}, bandwidth: {})", self.computation, self.bandwidth) + } +} + +impl Bounded for Weight { + fn min_value() -> Self { + Zero::zero() + } + fn max_value() -> Self { + Self::MAX + } +} + +impl AddAssign for Weight { + fn add_assign(&mut self, other: Self) { + *self = Self { + computation: self.computation + other.computation, + bandwidth: self.bandwidth + other.bandwidth, + }; + } +} + +impl SubAssign for Weight { + fn sub_assign(&mut self, other: Self) { + *self = Self { + computation: self.computation - other.computation, + bandwidth: self.bandwidth - other.bandwidth, + }; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn comparison_functions_work_as_expected() { + let weight_99_1 = Weight { computation: 99, bandwidth: 1 }; + let weight_1_99 = Weight { computation: 1, bandwidth: 99 }; + let weight_50_50 = Weight { computation: 50, bandwidth: 50 }; + let weight_1_1 = Weight { computation: 1, bandwidth: 1 }; + + assert!(!weight_1_1.is_any_greater_than(&weight_50_50)); + assert!(weight_99_1.is_any_greater_than(&weight_1_99)); + assert!(weight_1_99.is_any_greater_than(&weight_99_1)); + + assert!(!weight_99_1.is_strictly_greater_than(&weight_1_1)); + assert!(weight_50_50.is_strictly_greater_than(&weight_1_1)); + + assert!(weight_99_1.is_strictly_greater_than_or_equal(&weight_1_1)); + assert!(!weight_1_1.is_strictly_greater_than_or_equal(&weight_99_1)); + + assert!(!weight_50_50.is_any_less_than(&weight_1_1)); + assert!(weight_99_1.is_any_less_than(&weight_1_99)); + assert!(weight_1_99.is_any_less_than(&weight_99_1)); + + assert!(!weight_1_1.is_strictly_less_than(&weight_1_99)); + assert!(weight_1_1.is_strictly_less_than(&weight_50_50)); + + assert!(weight_1_1.is_strictly_less_than_or_equal(&weight_1_99)); + assert!(!weight_99_1.is_strictly_less_than_or_equal(&weight_1_99)); + } + + #[test] + fn try_add_works_as_expected() { + let limit = Weight { computation: 100, bandwidth: 100 }; + + let weight_99_1 = Weight { computation: 99, bandwidth: 1 }; + let weight_1_99 = Weight { computation: 1, bandwidth: 99 }; + let weight_50_50 = Weight { computation: 50, bandwidth: 50 }; + + let total1 = weight_99_1.try_add(&weight_1_99, &limit); + let total2 = weight_99_1.try_add(&weight_50_50, &limit); + let total3 = weight_1_99.try_add(&weight_50_50, &limit); + + assert_eq!(total1.unwrap(), limit); + assert!(total2.is_none()); + assert!(total3.is_none()); + } +} diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index 804deb08919a4..1e1dd99ed2ec4 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -21,7 +21,10 @@ #![recursion_limit = "128"] -use frame_support::traits::{CrateVersion, PalletInfo as _}; +use frame_support::{ + traits::{CrateVersion, PalletInfo as _}, + weights::Weight, +}; use scale_info::TypeInfo; use sp_core::{sr25519, H256}; use sp_runtime::{ @@ -497,12 +500,20 @@ fn call_weight_should_attach_to_call_enum() { // operational. assert_eq!( module3::Call::::operational {}.get_dispatch_info(), - DispatchInfo { weight: 5, class: DispatchClass::Operational, pays_fee: Pays::Yes }, + DispatchInfo { + weight: Weight::from_computation(5), + class: DispatchClass::Operational, + pays_fee: Pays::Yes + }, ); // custom basic assert_eq!( module3::Call::::aux_4 {}.get_dispatch_info(), - DispatchInfo { weight: 3, class: DispatchClass::Normal, pays_fee: Pays::Yes }, + DispatchInfo { + weight: Weight::from_computation(3), + class: DispatchClass::Normal, + pays_fee: Pays::Yes + }, ); } diff --git a/frame/support/test/tests/pallet.rs b/frame/support/test/tests/pallet.rs index 792fd93299705..04fadcb76a3eb 100644 --- a/frame/support/test/tests/pallet.rs +++ b/frame/support/test/tests/pallet.rs @@ -23,7 +23,7 @@ use frame_support::{ ConstU32, GetCallName, GetStorageVersion, OnFinalize, OnGenesis, OnInitialize, OnRuntimeUpgrade, PalletError, PalletInfoAccess, StorageVersion, }, - weights::{DispatchClass, DispatchInfo, GetDispatchInfo, Pays, RuntimeDbWeight}, + weights::{DispatchClass, DispatchInfo, GetDispatchInfo, Pays, RuntimeDbWeight, Weight}, }; use scale_info::{meta_type, TypeInfo}; use sp_io::{ @@ -165,7 +165,7 @@ pub mod pallet { let _ = T::AccountId::from(SomeType1); // Test for where clause let _ = T::AccountId::from(SomeType2); // Test for where clause Self::deposit_event(Event::Something(10)); - 10 + Weight::from_computation(10) } fn on_finalize(_: BlockNumberFor) { let _ = T::AccountId::from(SomeType1); // Test for where clause @@ -176,7 +176,7 @@ pub mod pallet { let _ = T::AccountId::from(SomeType1); // Test for where clause let _ = T::AccountId::from(SomeType2); // Test for where clause Self::deposit_event(Event::Something(30)); - 30 + Weight::from_computation(30) } fn integrity_test() { let _ = T::AccountId::from(SomeType1); // Test for where clause @@ -190,7 +190,7 @@ pub mod pallet { T::AccountId: From + From + SomeAssociation1, { /// Doc comment put in metadata - #[pallet::weight(Weight::from(*_foo))] + #[pallet::weight(Weight::from_computation(*_foo as u64))] pub fn foo( origin: OriginFor, #[pallet::compact] _foo: u32, @@ -461,14 +461,14 @@ pub mod pallet2 { { fn on_initialize(_: BlockNumberFor) -> Weight { Self::deposit_event(Event::Something(11)); - 0 + Weight::from_computation(0) } fn on_finalize(_: BlockNumberFor) { Self::deposit_event(Event::Something(21)); } fn on_runtime_upgrade() -> Weight { Self::deposit_event(Event::Something(31)); - 0 + Weight::from_computation(0) } } @@ -635,7 +635,11 @@ fn call_expand() { let call_foo = pallet::Call::::foo { foo: 3, bar: 0 }; assert_eq!( call_foo.get_dispatch_info(), - DispatchInfo { weight: 3, class: DispatchClass::Normal, pays_fee: Pays::Yes } + DispatchInfo { + weight: Weight::from_computation(3), + class: DispatchClass::Normal, + pays_fee: Pays::Yes + } ); assert_eq!(call_foo.get_call_name(), "foo"); assert_eq!( @@ -981,10 +985,10 @@ fn pallet_hooks_expand() { TestExternalities::default().execute_with(|| { frame_system::Pallet::::set_block_number(1); - assert_eq!(AllPalletsWithoutSystem::on_initialize(1), 10); + assert_eq!(AllPalletsWithoutSystem::on_initialize(1), Weight::from_computation(10)); AllPalletsWithoutSystem::on_finalize(1); - assert_eq!(AllPalletsWithoutSystem::on_runtime_upgrade(), 30); + assert_eq!(AllPalletsWithoutSystem::on_runtime_upgrade(), Weight::from_computation(30)); assert_eq!( frame_system::Pallet::::events()[0].event, @@ -1020,10 +1024,16 @@ fn all_pallets_type_reversed_order_is_correct() { #[allow(deprecated)] { - assert_eq!(AllPalletsWithoutSystemReversed::on_initialize(1), 10); + assert_eq!( + AllPalletsWithoutSystemReversed::on_initialize(1), + Weight::from_computation(10) + ); AllPalletsWithoutSystemReversed::on_finalize(1); - assert_eq!(AllPalletsWithoutSystemReversed::on_runtime_upgrade(), 30); + assert_eq!( + AllPalletsWithoutSystemReversed::on_runtime_upgrade(), + Weight::from_computation(30) + ); } assert_eq!( @@ -1090,7 +1100,7 @@ fn migrate_from_pallet_version_to_storage_version() { >(&db_weight); // 4 pallets, 2 writes and every write costs 5 weight. - assert_eq!(4 * 2 * 5, weight); + assert_eq!(Weight::from_computation(4 * 2 * 5), weight); // All pallet versions should be removed assert!(sp_io::storage::get(&pallet_version_key(Example::name())).is_none()); diff --git a/frame/support/test/tests/pallet_compatibility.rs b/frame/support/test/tests/pallet_compatibility.rs index 9327f5b6a3304..e9c5ba701154d 100644 --- a/frame/support/test/tests/pallet_compatibility.rs +++ b/frame/support/test/tests/pallet_compatibility.rs @@ -85,7 +85,7 @@ mod pallet_old { fn on_initialize(_n: T::BlockNumber) -> Weight { >::put(T::Balance::from(10)); - 10 + Weight::from_computation(10) } fn on_finalize(_n: T::BlockNumber) { @@ -131,7 +131,7 @@ pub mod pallet { impl Hooks for Pallet { fn on_initialize(_n: T::BlockNumber) -> Weight { >::put(T::Balance::from(10)); - 10 + Weight::from_computation(10) } fn on_finalize(_n: T::BlockNumber) { diff --git a/frame/support/test/tests/pallet_compatibility_instance.rs b/frame/support/test/tests/pallet_compatibility_instance.rs index 3de45df223674..63c7055596708 100644 --- a/frame/support/test/tests/pallet_compatibility_instance.rs +++ b/frame/support/test/tests/pallet_compatibility_instance.rs @@ -72,7 +72,7 @@ mod pallet_old { fn on_initialize(_n: T::BlockNumber) -> Weight { >::put(T::Balance::from(10)); - 10 + Weight::from_computation(10) } fn on_finalize(_n: T::BlockNumber) { @@ -116,7 +116,7 @@ pub mod pallet { impl, I: 'static> Hooks for Pallet { fn on_initialize(_n: T::BlockNumber) -> Weight { >::put(T::Balance::from(10)); - 10 + Weight::from_computation(10) } fn on_finalize(_n: T::BlockNumber) { diff --git a/frame/support/test/tests/pallet_instance.rs b/frame/support/test/tests/pallet_instance.rs index 29074843f4bbb..0116ea7e215a0 100644 --- a/frame/support/test/tests/pallet_instance.rs +++ b/frame/support/test/tests/pallet_instance.rs @@ -20,7 +20,7 @@ use frame_support::{ pallet_prelude::ValueQuery, storage::unhashed, traits::{ConstU32, GetCallName, OnFinalize, OnGenesis, OnInitialize, OnRuntimeUpgrade}, - weights::{DispatchClass, DispatchInfo, GetDispatchInfo, Pays}, + weights::{DispatchClass, DispatchInfo, GetDispatchInfo, Pays, Weight}, }; use sp_io::{ hashing::{blake2_128, twox_128, twox_64}, @@ -53,10 +53,10 @@ pub mod pallet { fn on_initialize(_: BlockNumberFor) -> Weight { if TypeId::of::() == TypeId::of::<()>() { Self::deposit_event(Event::Something(10)); - 10 + Weight::from_computation(10) } else { Self::deposit_event(Event::Something(11)); - 11 + Weight::from_computation(11) } } fn on_finalize(_: BlockNumberFor) { @@ -69,10 +69,10 @@ pub mod pallet { fn on_runtime_upgrade() -> Weight { if TypeId::of::() == TypeId::of::<()>() { Self::deposit_event(Event::Something(30)); - 30 + Weight::from_computation(30) } else { Self::deposit_event(Event::Something(31)); - 31 + Weight::from_computation(31) } } fn integrity_test() {} @@ -81,7 +81,7 @@ pub mod pallet { #[pallet::call] impl, I: 'static> Pallet { /// Doc comment put in metadata - #[pallet::weight(Weight::from(*_foo))] + #[pallet::weight(Weight::from_computation(*_foo as u64))] pub fn foo( origin: OriginFor, #[pallet::compact] _foo: u32, @@ -313,7 +313,11 @@ fn call_expand() { let call_foo = pallet::Call::::foo { foo: 3 }; assert_eq!( call_foo.get_dispatch_info(), - DispatchInfo { weight: 3, class: DispatchClass::Normal, pays_fee: Pays::Yes } + DispatchInfo { + weight: Weight::from_computation(3), + class: DispatchClass::Normal, + pays_fee: Pays::Yes + } ); assert_eq!(call_foo.get_call_name(), "foo"); assert_eq!(pallet::Call::::get_call_names(), &["foo", "foo_transactional"]); @@ -321,7 +325,11 @@ fn call_expand() { let call_foo = pallet::Call::::foo { foo: 3 }; assert_eq!( call_foo.get_dispatch_info(), - DispatchInfo { weight: 3, class: DispatchClass::Normal, pays_fee: Pays::Yes } + DispatchInfo { + weight: Weight::from_computation(3), + class: DispatchClass::Normal, + pays_fee: Pays::Yes + } ); assert_eq!(call_foo.get_call_name(), "foo"); assert_eq!( @@ -556,10 +564,10 @@ fn pallet_hooks_expand() { TestExternalities::default().execute_with(|| { frame_system::Pallet::::set_block_number(1); - assert_eq!(AllPalletsWithoutSystem::on_initialize(1), 21); + assert_eq!(AllPalletsWithoutSystem::on_initialize(1), Weight::from_computation(21)); AllPalletsWithoutSystem::on_finalize(1); - assert_eq!(AllPalletsWithoutSystem::on_runtime_upgrade(), 61); + assert_eq!(AllPalletsWithoutSystem::on_runtime_upgrade(), Weight::from_computation(61)); assert_eq!( frame_system::Pallet::::events()[0].event, diff --git a/frame/support/test/tests/pallet_ui/hooks_invalid_item.stderr b/frame/support/test/tests/pallet_ui/hooks_invalid_item.stderr index d1a89fbb850e9..ff52a094d6f8d 100644 --- a/frame/support/test/tests/pallet_ui/hooks_invalid_item.stderr +++ b/frame/support/test/tests/pallet_ui/hooks_invalid_item.stderr @@ -1,13 +1,13 @@ error[E0107]: missing generics for trait `Hooks` - --> $DIR/hooks_invalid_item.rs:12:18 + --> tests/pallet_ui/hooks_invalid_item.rs:12:18 | 12 | impl Hooks for Pallet {} | ^^^^^ expected 1 generic argument | note: trait defined here, with 1 generic parameter: `BlockNumber` - --> $DIR/hooks.rs:214:11 + --> $WORKSPACE/frame/support/src/traits/hooks.rs | -214 | pub trait Hooks { + | pub trait Hooks { | ^^^^^ ----------- help: add missing generic argument | diff --git a/frame/support/test/tests/pallet_ui/store_trait_leak_private.stderr b/frame/support/test/tests/pallet_ui/store_trait_leak_private.stderr index d8c62faa303ee..0d3ad73acd1f4 100644 --- a/frame/support/test/tests/pallet_ui/store_trait_leak_private.stderr +++ b/frame/support/test/tests/pallet_ui/store_trait_leak_private.stderr @@ -1,5 +1,5 @@ error[E0446]: private type `_GeneratedPrefixForStorageFoo` in public interface - --> $DIR/store_trait_leak_private.rs:11:37 + --> tests/pallet_ui/store_trait_leak_private.rs:11:37 | 11 | #[pallet::generate_store(pub trait Store)] | ^^^^^ can't leak private type diff --git a/frame/support/test/tests/pallet_with_name_trait_is_valid.rs b/frame/support/test/tests/pallet_with_name_trait_is_valid.rs index 7ed8454668327..3c716a0f37606 100644 --- a/frame/support/test/tests/pallet_with_name_trait_is_valid.rs +++ b/frame/support/test/tests/pallet_with_name_trait_is_valid.rs @@ -15,6 +15,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +use frame_support::weights::Weight; +use sp_runtime::traits::Zero; + pub trait Trait: frame_system::Config { type Balance: frame_support::dispatch::Parameter; /// The overarching event type. @@ -53,8 +56,8 @@ frame_support::decl_module! { unimplemented!(); } - fn on_initialize(_n: T::BlockNumber) -> frame_support::weights::Weight { - 0 + fn on_initialize(_n: T::BlockNumber) -> Weight { + Weight::zero() } } } diff --git a/frame/system/benches/bench.rs b/frame/system/benches/bench.rs index 0bc34fcbc5be2..ce15ab9676ad6 100644 --- a/frame/system/benches/bench.rs +++ b/frame/system/benches/bench.rs @@ -16,7 +16,10 @@ // limitations under the License. use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use frame_support::traits::{ConstU32, ConstU64}; +use frame_support::{ + traits::{ConstU32, ConstU64}, + weights::Weight, +}; use sp_core::H256; use sp_runtime::{ testing::Header, @@ -61,7 +64,7 @@ frame_support::construct_runtime!( frame_support::parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights::with_sensible_defaults( - 4 * 1024 * 1024, Perbill::from_percent(75), + Weight::from_computation(4 * 1024 * 1024), Perbill::from_percent(75), ); pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength::max_with_normal_ratio( diff --git a/frame/system/src/extensions/check_mortality.rs b/frame/system/src/extensions/check_mortality.rs index 2fb99c9f45e2b..9ecfd2b069903 100644 --- a/frame/system/src/extensions/check_mortality.rs +++ b/frame/system/src/extensions/check_mortality.rs @@ -101,7 +101,7 @@ impl SignedExtension for CheckMortality { mod tests { use super::*; use crate::mock::{new_test_ext, System, Test, CALL}; - use frame_support::weights::{DispatchClass, DispatchInfo, Pays}; + use frame_support::weights::{DispatchClass, DispatchInfo, Pays, Weight}; use sp_core::H256; #[test] @@ -126,8 +126,11 @@ mod tests { #[test] fn signed_ext_check_era_should_change_longevity() { new_test_ext().execute_with(|| { - let normal = - DispatchInfo { weight: 100, class: DispatchClass::Normal, pays_fee: Pays::Yes }; + let normal = DispatchInfo { + weight: Weight::new().set_computation(100).set_bandwidth(50), + class: DispatchClass::Normal, + pays_fee: Pays::Yes, + }; let len = 0_usize; let ext = ( crate::CheckWeight::::new(), diff --git a/frame/system/src/extensions/check_weight.rs b/frame/system/src/extensions/check_weight.rs index b59c36ecb53b5..f5f336456d5db 100644 --- a/frame/system/src/extensions/check_weight.rs +++ b/frame/system/src/extensions/check_weight.rs @@ -23,7 +23,7 @@ use frame_support::{ }; use scale_info::TypeInfo; use sp_runtime::{ - traits::{DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SignedExtension}, + traits::{DispatchInfoOf, Dispatchable, PostDispatchInfoOf, Saturating, SignedExtension, Zero}, transaction_validity::{InvalidTransaction, TransactionValidity, TransactionValidityError}, DispatchResult, }; @@ -49,7 +49,8 @@ where ) -> Result<(), TransactionValidityError> { let max = T::BlockWeights::get().get(info.class).max_extrinsic; match max { - Some(max) if info.weight > max => Err(InvalidTransaction::ExhaustsResources.into()), + Some(max) if info.weight.is_any_greater_than(&max) => + Err(InvalidTransaction::ExhaustsResources.into()), _ => Ok(()), } } @@ -144,7 +145,8 @@ where // Check if we don't exceed per-class allowance match limit_per_class.max_total { - Some(max) if per_class > max => return Err(InvalidTransaction::ExhaustsResources.into()), + Some(max) if per_class.is_any_greater_than(&max) => + return Err(InvalidTransaction::ExhaustsResources.into()), // There is no `max_total` limit (`None`), // or we are below the limit. _ => {}, @@ -152,10 +154,10 @@ where // In cases total block weight is exceeded, we need to fall back // to `reserved` pool if there is any. - if all_weight.total() > maximum_weight.max_block { + if all_weight.total().is_any_greater_than(&maximum_weight.max_block) { match limit_per_class.reserved { // We are over the limit in reserved pool. - Some(reserved) if per_class > reserved => + Some(reserved) if per_class.is_any_greater_than(&reserved) => return Err(InvalidTransaction::ExhaustsResources.into()), // There is either no limit in reserved pool (`None`), // or we are below the limit. @@ -238,7 +240,7 @@ where } let unspent = post_info.calc_unspent(info); - if unspent > 0 { + if unspent != Zero::zero() { crate::BlockWeight::::mutate(|current_weight| { current_weight.sub(unspent, info.class); }) @@ -265,7 +267,7 @@ mod tests { use super::*; use crate::{ mock::{new_test_ext, System, Test, CALL}, - AllExtrinsicsLen, BlockWeight, + AllExtrinsicsLen, BlockWeight, One, }; use frame_support::{ assert_err, assert_ok, @@ -297,7 +299,7 @@ mod tests { fn check(call: impl FnOnce(&DispatchInfo, usize)) { new_test_ext().execute_with(|| { let max = DispatchInfo { - weight: Weight::max_value(), + weight: Weight::MAX, class: DispatchClass::Mandatory, ..Default::default() }; @@ -309,8 +311,8 @@ mod tests { check(|max, len| { assert_ok!(CheckWeight::::do_pre_dispatch(max, len)); - assert_eq!(System::block_weight().total(), Weight::max_value()); - assert!(System::block_weight().total() > block_weight_limit()); + assert_eq!(System::block_weight().total(), Weight::MAX); + assert!(System::block_weight().total().is_any_greater_than(&block_weight_limit())); }); check(|max, len| { assert_ok!(CheckWeight::::do_validate(max, len)); @@ -321,7 +323,8 @@ mod tests { fn normal_extrinsic_limited_by_maximum_extrinsic_weight() { new_test_ext().execute_with(|| { let max = DispatchInfo { - weight: block_weights().get(DispatchClass::Normal).max_extrinsic.unwrap() + 1, + weight: block_weights().get(DispatchClass::Normal).max_extrinsic.unwrap() + + One::one(), class: DispatchClass::Normal, ..Default::default() }; @@ -347,7 +350,7 @@ mod tests { let okay = DispatchInfo { weight, class: DispatchClass::Operational, ..Default::default() }; let max = DispatchInfo { - weight: weight + 1, + weight: weight + One::one(), class: DispatchClass::Operational, ..Default::default() }; @@ -364,9 +367,9 @@ mod tests { #[test] fn register_extra_weight_unchecked_doesnt_care_about_limits() { new_test_ext().execute_with(|| { - System::register_extra_weight_unchecked(Weight::max_value(), DispatchClass::Normal); - assert_eq!(System::block_weight().total(), Weight::max_value()); - assert!(System::block_weight().total() > block_weight_limit()); + System::register_extra_weight_unchecked(Weight::MAX, DispatchClass::Normal); + assert_eq!(System::block_weight().total(), Weight::MAX); + assert!(System::block_weight().total().is_any_greater_than(&block_weight_limit())); }); } @@ -378,9 +381,12 @@ mod tests { // 10 is taken for block execution weight // So normal extrinsic can be 758 weight (-5 for base extrinsic weight) // And Operational can be 256 to produce a full block (-5 for base) - let max_normal = DispatchInfo { weight: 753, ..Default::default() }; + let max_normal = DispatchInfo { + weight: Weight::new().set_computation(753).set_bandwidth(753), + ..Default::default() + }; let rest_operational = DispatchInfo { - weight: 251, + weight: Weight::new().set_computation(251).set_bandwidth(251), class: DispatchClass::Operational, ..Default::default() }; @@ -388,9 +394,15 @@ mod tests { let len = 0_usize; assert_ok!(CheckWeight::::do_pre_dispatch(&max_normal, len)); - assert_eq!(System::block_weight().total(), 768); + assert_eq!( + System::block_weight().total(), + Weight::new().set_computation(768).set_bandwidth(768) + ); assert_ok!(CheckWeight::::do_pre_dispatch(&rest_operational, len)); - assert_eq!(block_weight_limit(), 1024); + assert_eq!( + block_weight_limit(), + Weight::new().set_computation(1024).set_bandwidth(1024) + ); assert_eq!(System::block_weight().total(), block_weight_limit()); // Checking single extrinsic should not take current block weight into account. assert_eq!(CheckWeight::::check_extrinsic_weight(&rest_operational), Ok(())); @@ -401,9 +413,12 @@ mod tests { fn dispatch_order_does_not_effect_weight_logic() { new_test_ext().execute_with(|| { // We switch the order of `full_block_with_normal_and_operational` - let max_normal = DispatchInfo { weight: 753, ..Default::default() }; + let max_normal = DispatchInfo { + weight: Weight::new().set_computation(753).set_bandwidth(753), + ..Default::default() + }; let rest_operational = DispatchInfo { - weight: 251, + weight: Weight::new().set_computation(251).set_bandwidth(251), class: DispatchClass::Operational, ..Default::default() }; @@ -412,9 +427,15 @@ mod tests { assert_ok!(CheckWeight::::do_pre_dispatch(&rest_operational, len)); // Extra 15 here from block execution + base extrinsic weight - assert_eq!(System::block_weight().total(), 266); + assert_eq!( + System::block_weight().total(), + Weight::new().set_computation(266).set_bandwidth(266) + ); assert_ok!(CheckWeight::::do_pre_dispatch(&max_normal, len)); - assert_eq!(block_weight_limit(), 1024); + assert_eq!( + block_weight_limit(), + Weight::new().set_computation(1024).set_bandwidth(1024) + ); assert_eq!(System::block_weight().total(), block_weight_limit()); }); } @@ -423,11 +444,14 @@ mod tests { fn operational_works_on_full_block() { new_test_ext().execute_with(|| { // An on_initialize takes up the whole block! (Every time!) - System::register_extra_weight_unchecked(Weight::max_value(), DispatchClass::Mandatory); - let dispatch_normal = - DispatchInfo { weight: 251, class: DispatchClass::Normal, ..Default::default() }; + System::register_extra_weight_unchecked(Weight::MAX, DispatchClass::Mandatory); + let dispatch_normal = DispatchInfo { + weight: Weight::new().set_computation(251).set_bandwidth(251), + class: DispatchClass::Normal, + ..Default::default() + }; let dispatch_operational = DispatchInfo { - weight: 251, + weight: Weight::new().set_computation(251).set_bandwidth(251), class: DispatchClass::Operational, ..Default::default() }; @@ -453,9 +477,12 @@ mod tests { #[test] fn signed_ext_check_weight_works_operational_tx() { new_test_ext().execute_with(|| { - let normal = DispatchInfo { weight: 100, ..Default::default() }; + let normal = DispatchInfo { + weight: Weight::new().set_computation(100).set_bandwidth(100), + ..Default::default() + }; let op = DispatchInfo { - weight: 100, + weight: Weight::new().set_computation(100).set_bandwidth(100), class: DispatchClass::Operational, pays_fee: Pays::Yes, }; @@ -489,7 +516,7 @@ mod tests { fn signed_ext_check_weight_block_size_works() { new_test_ext().execute_with(|| { let normal = DispatchInfo::default(); - let normal_limit = normal_weight_limit() as usize; + let normal_limit = normal_weight_limit(); let reset_check_weight = |tx, s, f| { AllExtrinsicsLen::::put(0); let r = CheckWeight::(PhantomData).pre_dispatch(&1, CALL, tx, s); @@ -500,15 +527,18 @@ mod tests { } }; - reset_check_weight(&normal, normal_limit - 1, false); - reset_check_weight(&normal, normal_limit, false); - reset_check_weight(&normal, normal_limit + 1, true); + reset_check_weight(&normal, (normal_limit.computation() - 1) as usize, false); + reset_check_weight(&normal, normal_limit.computation() as usize, false); + reset_check_weight(&normal, (normal_limit.computation() + 1) as usize, true); // Operational ones don't have this limit. - let op = - DispatchInfo { weight: 0, class: DispatchClass::Operational, pays_fee: Pays::Yes }; - reset_check_weight(&op, normal_limit, false); - reset_check_weight(&op, normal_limit + 100, false); + let op = DispatchInfo { + weight: Weight::zero(), + class: DispatchClass::Operational, + pays_fee: Pays::Yes, + }; + reset_check_weight(&op, normal_limit.computation() as usize, false); + reset_check_weight(&op, normal_limit.computation() as usize, false); reset_check_weight(&op, 1024, false); reset_check_weight(&op, 1025, true); }) @@ -518,12 +548,17 @@ mod tests { fn signed_ext_check_weight_works_normal_tx() { new_test_ext().execute_with(|| { let normal_limit = normal_weight_limit(); - let small = DispatchInfo { weight: 100, ..Default::default() }; + let small = DispatchInfo { + weight: Weight::new().set_computation(100).set_bandwidth(100), + ..Default::default() + }; let base_extrinsic = block_weights().get(DispatchClass::Normal).base_extrinsic; let medium = DispatchInfo { weight: normal_limit - base_extrinsic, ..Default::default() }; - let big = - DispatchInfo { weight: normal_limit - base_extrinsic + 1, ..Default::default() }; + let big = DispatchInfo { + weight: normal_limit - base_extrinsic + One::one(), + ..Default::default() + }; let len = 0_usize; let reset_check_weight = |i, f, s| { @@ -538,9 +573,9 @@ mod tests { } }; - reset_check_weight(&small, false, 0); - reset_check_weight(&medium, false, 0); - reset_check_weight(&big, true, 1); + reset_check_weight(&small, false, Zero::zero()); + reset_check_weight(&medium, false, Zero::zero()); + reset_check_weight(&big, true, One::one()); }) } @@ -548,20 +583,31 @@ mod tests { fn signed_ext_check_weight_refund_works() { new_test_ext().execute_with(|| { // This is half of the max block weight - let info = DispatchInfo { weight: 512, ..Default::default() }; - let post_info = - PostDispatchInfo { actual_weight: Some(128), pays_fee: Default::default() }; + let info = DispatchInfo { + weight: Weight::new().set_computation(512).set_bandwidth(512), + ..Default::default() + }; + let post_info = PostDispatchInfo { + actual_weight: Some(Weight::new().set_computation(128).set_bandwidth(128)), + pays_fee: Default::default(), + }; let len = 0_usize; let base_extrinsic = block_weights().get(DispatchClass::Normal).base_extrinsic; // We allow 75% for normal transaction, so we put 25% - extrinsic base weight BlockWeight::::mutate(|current_weight| { - current_weight.set(0, DispatchClass::Mandatory); - current_weight.set(256 - base_extrinsic, DispatchClass::Normal); + current_weight.set(Zero::zero(), DispatchClass::Mandatory); + current_weight.set( + Weight::new().set_computation(256).set_bandwidth(256) - base_extrinsic, + DispatchClass::Normal, + ); }); let pre = CheckWeight::(PhantomData).pre_dispatch(&1, CALL, &info, len).unwrap(); - assert_eq!(BlockWeight::::get().total(), info.weight + 256); + assert_eq!( + BlockWeight::::get().total(), + info.weight + Weight::new().set_computation(256).set_bandwidth(256) + ); assert_ok!(CheckWeight::::post_dispatch( Some(pre), @@ -570,27 +616,41 @@ mod tests { len, &Ok(()) )); - assert_eq!(BlockWeight::::get().total(), post_info.actual_weight.unwrap() + 256); + assert_eq!( + BlockWeight::::get().total(), + post_info.actual_weight.unwrap() + + Weight::new().set_computation(256).set_bandwidth(256) + ); }) } #[test] fn signed_ext_check_weight_actual_weight_higher_than_max_is_capped() { new_test_ext().execute_with(|| { - let info = DispatchInfo { weight: 512, ..Default::default() }; - let post_info = - PostDispatchInfo { actual_weight: Some(700), pays_fee: Default::default() }; + let info = DispatchInfo { + weight: Weight::new().set_computation(512).set_bandwidth(512), + ..Default::default() + }; + let post_info = PostDispatchInfo { + actual_weight: Some(Weight::new().set_computation(700).set_bandwidth(700)), + pays_fee: Default::default(), + }; let len = 0_usize; BlockWeight::::mutate(|current_weight| { - current_weight.set(0, DispatchClass::Mandatory); - current_weight.set(128, DispatchClass::Normal); + current_weight.set(Zero::zero(), DispatchClass::Mandatory); + current_weight.set( + Weight::new().set_computation(128).set_bandwidth(128), + DispatchClass::Normal, + ); }); let pre = CheckWeight::(PhantomData).pre_dispatch(&1, CALL, &info, len).unwrap(); assert_eq!( BlockWeight::::get().total(), - info.weight + 128 + block_weights().get(DispatchClass::Normal).base_extrinsic, + info.weight + + Weight::new().set_computation(128).set_bandwidth(128) + + block_weights().get(DispatchClass::Normal).base_extrinsic, ); assert_ok!(CheckWeight::::post_dispatch( @@ -602,7 +662,9 @@ mod tests { )); assert_eq!( BlockWeight::::get().total(), - info.weight + 128 + block_weights().get(DispatchClass::Normal).base_extrinsic, + info.weight + + Weight::new().set_computation(128).set_bandwidth(128) + + block_weights().get(DispatchClass::Normal).base_extrinsic, ); }) } @@ -611,7 +673,7 @@ mod tests { fn zero_weight_extrinsic_still_has_base_weight() { new_test_ext().execute_with(|| { let weights = block_weights(); - let free = DispatchInfo { weight: 0, ..Default::default() }; + let free = DispatchInfo { weight: Weight::zero(), ..Default::default() }; let len = 0_usize; // Initial weight from `weights.base_block` @@ -630,9 +692,12 @@ mod tests { // Max block is 1024 // Max normal is 768 (75%) // Max mandatory is unlimited - let max_normal = DispatchInfo { weight: 753, ..Default::default() }; + let max_normal = DispatchInfo { + weight: Weight::new().set_computation(753).set_bandwidth(753), + ..Default::default() + }; let mandatory = DispatchInfo { - weight: 1019, + weight: Weight::new().set_computation(1019).set_bandwidth(1019), class: DispatchClass::Mandatory, ..Default::default() }; @@ -640,10 +705,19 @@ mod tests { let len = 0_usize; assert_ok!(CheckWeight::::do_pre_dispatch(&max_normal, len)); - assert_eq!(System::block_weight().total(), 768); + assert_eq!( + System::block_weight().total(), + Weight::new().set_computation(768).set_bandwidth(768) + ); assert_ok!(CheckWeight::::do_pre_dispatch(&mandatory, len)); - assert_eq!(block_weight_limit(), 1024); - assert_eq!(System::block_weight().total(), 1024 + 768); + assert_eq!( + block_weight_limit(), + Weight::new().set_computation(1024).set_bandwidth(1024) + ); + assert_eq!( + System::block_weight().total(), + Weight::new().set_computation(1024 + 768).set_bandwidth(1024 + 768) + ); assert_eq!(CheckWeight::::check_extrinsic_weight(&mandatory), Ok(())); }); } @@ -652,30 +726,36 @@ mod tests { fn no_max_total_should_still_be_limited_by_max_block() { // given let maximum_weight = BlockWeights::builder() - .base_block(0) + .base_block(Zero::zero()) .for_class(DispatchClass::non_mandatory(), |w| { - w.base_extrinsic = 0; - w.max_total = Some(20); + w.base_extrinsic = Zero::zero(); + w.max_total = Some(Weight::new().set_computation(20).set_bandwidth(20)); }) .for_class(DispatchClass::Mandatory, |w| { - w.base_extrinsic = 0; - w.reserved = Some(5); + w.base_extrinsic = Zero::zero(); + w.reserved = Some(Weight::new().set_computation(5).set_bandwidth(5)); w.max_total = None; }) .build_or_panic(); let all_weight = crate::ConsumedWeight::new(|class| match class { - DispatchClass::Normal => 10, - DispatchClass::Operational => 10, - DispatchClass::Mandatory => 0, + DispatchClass::Normal => Weight::new().set_computation(10).set_bandwidth(10), + DispatchClass::Operational => Weight::new().set_computation(10).set_bandwidth(10), + DispatchClass::Mandatory => Zero::zero(), }); assert_eq!(maximum_weight.max_block, all_weight.total()); // fits into reserved - let mandatory1 = - DispatchInfo { weight: 5, class: DispatchClass::Mandatory, ..Default::default() }; + let mandatory1 = DispatchInfo { + weight: Weight::new().set_computation(5).set_bandwidth(5), + class: DispatchClass::Mandatory, + ..Default::default() + }; // does not fit into reserved and the block is full. - let mandatory2 = - DispatchInfo { weight: 6, class: DispatchClass::Mandatory, ..Default::default() }; + let mandatory2 = DispatchInfo { + weight: Weight::new().set_computation(6).set_bandwidth(6), + class: DispatchClass::Mandatory, + ..Default::default() + }; // when assert_ok!(calculate_consumed_weight::<::Call>( diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index ba494dfbd9f8c..eed56bfba286a 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -1272,8 +1272,8 @@ impl Pallet { pub fn finalize() -> T::Header { log::debug!( target: "runtime::system", - "[{:?}] length: {} (normal {}%, op: {}%, mandatory {}%) / normal weight: {} ({}%) \ - / op weight {} ({}%) / mandatory weight {} ({}%)", + "[{:?}] length: {} (normal {}%, op: {}%, mandatory {}%) / normal weight {} ({}% / {}%) \ + / op weight {} ({}% / {}%) / mandatory weight {} ({}% / {}%)", Self::block_number(), Self::all_extrinsics_len(), sp_runtime::Percent::from_rational( @@ -1290,18 +1290,30 @@ impl Pallet { ).deconstruct(), Self::block_weight().get(DispatchClass::Normal), sp_runtime::Percent::from_rational( - *Self::block_weight().get(DispatchClass::Normal), - T::BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap_or(Bounded::max_value()) + Self::block_weight().get(DispatchClass::Normal).computation(), + T::BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap_or(Bounded::max_value()).computation() + ).deconstruct(), + sp_runtime::Percent::from_rational( + Self::block_weight().get(DispatchClass::Normal).bandwidth(), + T::BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap_or(Bounded::max_value()).bandwidth() ).deconstruct(), Self::block_weight().get(DispatchClass::Operational), sp_runtime::Percent::from_rational( - *Self::block_weight().get(DispatchClass::Operational), - T::BlockWeights::get().get(DispatchClass::Operational).max_total.unwrap_or(Bounded::max_value()) + Self::block_weight().get(DispatchClass::Operational).computation(), + T::BlockWeights::get().get(DispatchClass::Operational).max_total.unwrap_or(Bounded::max_value()).computation() + ).deconstruct(), + sp_runtime::Percent::from_rational( + Self::block_weight().get(DispatchClass::Operational).bandwidth(), + T::BlockWeights::get().get(DispatchClass::Operational).max_total.unwrap_or(Bounded::max_value()).bandwidth() ).deconstruct(), Self::block_weight().get(DispatchClass::Mandatory), sp_runtime::Percent::from_rational( - *Self::block_weight().get(DispatchClass::Mandatory), - T::BlockWeights::get().get(DispatchClass::Mandatory).max_total.unwrap_or(Bounded::max_value()) + Self::block_weight().get(DispatchClass::Mandatory).computation(), + T::BlockWeights::get().get(DispatchClass::Mandatory).max_total.unwrap_or(Bounded::max_value()).computation() + ).deconstruct(), + sp_runtime::Percent::from_rational( + Self::block_weight().get(DispatchClass::Mandatory).bandwidth(), + T::BlockWeights::get().get(DispatchClass::Mandatory).max_total.unwrap_or(Bounded::max_value()).bandwidth() ).deconstruct(), ); ExecutionPhase::::kill(); @@ -1413,11 +1425,24 @@ impl Pallet { /// Set the current block weight. This should only be used in some integration tests. #[cfg(any(feature = "std", test))] - pub fn set_block_consumed_resources(weight: Weight, len: usize) { + pub fn set_block_consumed_resources( + maybe_computation: Option, + maybe_bandwidth: Option, + maybe_len: Option, + ) { BlockWeight::::mutate(|current_weight| { - current_weight.set(weight, DispatchClass::Normal) + let mut new_weight: Weight = *current_weight.get(DispatchClass::Normal); + if let Some(computation) = maybe_computation { + *new_weight.computation_mut() = computation; + } + if let Some(bandwidth) = maybe_bandwidth { + *new_weight.bandwidth_mut() = bandwidth; + } + current_weight.set(new_weight, DispatchClass::Normal) }); - AllExtrinsicsLen::::put(len as u32); + if let Some(len) = maybe_len { + AllExtrinsicsLen::::put(len as u32); + } } /// Reset events. diff --git a/frame/system/src/limits.rs b/frame/system/src/limits.rs index d3c108afb6f32..a1ee43fe7f72b 100644 --- a/frame/system/src/limits.rs +++ b/frame/system/src/limits.rs @@ -27,7 +27,10 @@ use frame_support::weights::{constants, DispatchClass, OneOrMany, PerDispatchClass, Weight}; use scale_info::TypeInfo; -use sp_runtime::{Perbill, RuntimeDebug}; +use sp_runtime::{ + traits::{Saturating, Zero}, + Perbill, RuntimeDebug, +}; /// Block length limit configuration. #[derive(RuntimeDebug, Clone, codec::Encode, codec::Decode, TypeInfo)] @@ -204,7 +207,12 @@ pub struct BlockWeights { impl Default for BlockWeights { fn default() -> Self { - Self::with_sensible_defaults(1 * constants::WEIGHT_PER_SECOND, DEFAULT_NORMAL_RATIO) + Self::with_sensible_defaults( + Weight::new() + .set_computation(1 * constants::WEIGHT_PER_SECOND) + .set_bandwidth(5 * 1024 * 1024), // 5 MB + DEFAULT_NORMAL_RATIO, + ) } } @@ -217,7 +225,7 @@ impl BlockWeights { /// Verifies correctness of this `BlockWeights` object. pub fn validate(self) -> ValidationResult { fn or_max(w: Option) -> Weight { - w.unwrap_or_else(Weight::max_value) + w.unwrap_or_else(|| Weight::MAX) } let mut error = ValidationErrors::default(); @@ -229,15 +237,21 @@ impl BlockWeights { // Make sure that if total is set it's greater than base_block && // base_for_class error_assert!( - (max_for_class > self.base_block && max_for_class > base_for_class) - || max_for_class == 0, + ( + max_for_class.is_strictly_greater_than(&self.base_block) && + max_for_class.is_strictly_greater_than(&base_for_class) + ) + || max_for_class == Zero::zero(), &mut error, "[{:?}] {:?} (total) has to be greater than {:?} (base block) & {:?} (base extrinsic)", class, max_for_class, self.base_block, base_for_class, ); // Max extrinsic can't be greater than max_for_class. error_assert!( - weights.max_extrinsic.unwrap_or(0) <= max_for_class.saturating_sub(base_for_class), + weights + .max_extrinsic + .unwrap_or(Zero::zero()) + .is_strictly_less_than_or_equal(&max_for_class.saturating_sub(base_for_class)), &mut error, "[{:?}] {:?} (max_extrinsic) can't be greater than {:?} (max for class)", class, @@ -246,14 +260,14 @@ impl BlockWeights { ); // Max extrinsic should not be 0 error_assert!( - weights.max_extrinsic.unwrap_or_else(Weight::max_value) > 0, + weights.max_extrinsic.unwrap_or_else(|| Weight::MAX).is_strictly_greater_than(&Weight::zero()), &mut error, "[{:?}] {:?} (max_extrinsic) must not be 0. Check base cost and average initialization cost.", class, weights.max_extrinsic, ); // Make sure that if reserved is set it's greater than base_for_class. error_assert!( - reserved > base_for_class || reserved == 0, + reserved.is_strictly_greater_than(&base_for_class) || reserved == Zero::zero(), &mut error, "[{:?}] {:?} (reserved) has to be greater than {:?} (base extrinsic) if set", class, @@ -262,7 +276,8 @@ impl BlockWeights { ); // Make sure max block is greater than max_total if it's set. error_assert!( - self.max_block >= weights.max_total.unwrap_or(0), + self.max_block + .is_strictly_greater_than_or_equal(&weights.max_total.unwrap_or(Zero::zero())), &mut error, "[{:?}] {:?} (max block) has to be greater than {:?} (max for class)", class, @@ -271,7 +286,7 @@ impl BlockWeights { ); // Make sure we can fit at least one extrinsic. error_assert!( - self.max_block > base_for_class + self.base_block, + self.max_block.is_strictly_greater_than(&(base_for_class + self.base_block)), &mut error, "[{:?}] {:?} (max block) must fit at least one extrinsic {:?} (base weight)", class, @@ -294,9 +309,9 @@ impl BlockWeights { /// is not suitable for production deployments. pub fn simple_max(block_weight: Weight) -> Self { Self::builder() - .base_block(0) + .base_block(Zero::zero()) .for_class(DispatchClass::all(), |weights| { - weights.base_extrinsic = 0; + weights.base_extrinsic = Zero::zero(); }) .for_class(DispatchClass::non_mandatory(), |weights| { weights.max_total = block_weight.into(); @@ -333,9 +348,10 @@ impl BlockWeights { BlockWeightsBuilder { weights: BlockWeights { base_block: constants::BlockExecutionWeight::get(), - max_block: 0, + max_block: Zero::zero(), per_class: PerDispatchClass::new(|class| { - let initial = if class == DispatchClass::Mandatory { None } else { Some(0) }; + let initial = + if class == DispatchClass::Mandatory { None } else { Some(Zero::zero()) }; WeightsPerClass { base_extrinsic: constants::ExtrinsicBaseWeight::get(), max_extrinsic: None, @@ -398,7 +414,7 @@ impl BlockWeightsBuilder { // compute max block size. for class in DispatchClass::all() { weights.max_block = match weights.per_class.get(*class).max_total { - Some(max) if max > weights.max_block => max, + Some(max) if weights.max_block.is_strictly_less_than(&max) => max, _ => weights.max_block, }; } diff --git a/frame/system/src/migrations/mod.rs b/frame/system/src/migrations/mod.rs index f02af7a316fe1..15746d7376ac5 100644 --- a/frame/system/src/migrations/mod.rs +++ b/frame/system/src/migrations/mod.rs @@ -81,7 +81,7 @@ pub fn migrate_from_single_u8_to_triple_ref_count() -> Wei ); >::put(true); >::put(true); - Weight::max_value() + Weight::MAX } /// Migrate from unique `u32` reference counting to triple `u32` reference counting. @@ -99,7 +99,7 @@ pub fn migrate_from_single_to_triple_ref_count() -> Weight translated ); >::put(true); - Weight::max_value() + Weight::MAX } /// Migrate from dual `u32` reference counting to triple `u32` reference counting. @@ -117,5 +117,5 @@ pub fn migrate_from_dual_to_triple_ref_count() -> Weight { translated ); >::put(true); - Weight::max_value() + Weight::MAX } diff --git a/frame/system/src/mock.rs b/frame/system/src/mock.rs index f3f542aa83a9a..2ce814feb6dac 100644 --- a/frame/system/src/mock.rs +++ b/frame/system/src/mock.rs @@ -42,7 +42,7 @@ frame_support::construct_runtime!( ); const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); -const MAX_BLOCK_WEIGHT: Weight = 1024; +const MAX_BLOCK_WEIGHT: Weight = Weight::new().set_computation(1024).set_bandwidth(1024); parameter_types! { pub Version: RuntimeVersion = RuntimeVersion { @@ -60,9 +60,14 @@ parameter_types! { write: 100, }; pub RuntimeBlockWeights: limits::BlockWeights = limits::BlockWeights::builder() - .base_block(10) + .base_block(Weight::new() + .set_computation(10) + .set_bandwidth(10) + ) .for_class(DispatchClass::all(), |weights| { - weights.base_extrinsic = 5; + weights.base_extrinsic = Weight::new() + .set_computation(5) + .set_bandwidth(5); }) .for_class(DispatchClass::Normal, |weights| { weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAX_BLOCK_WEIGHT); diff --git a/frame/system/src/tests.rs b/frame/system/src/tests.rs index 0facd796b2a0c..b2ce30b427633 100644 --- a/frame/system/src/tests.rs +++ b/frame/system/src/tests.rs @@ -222,7 +222,10 @@ fn deposit_event_uses_actual_weight() { System::initialize(&1, &[0u8; 32].into(), &Default::default()); System::note_finished_initialize(); - let pre_info = DispatchInfo { weight: 1000, ..Default::default() }; + let pre_info = DispatchInfo { + weight: Weight::new().set_computation(1000).set_bandwidth(1000), + ..Default::default() + }; System::note_applied_extrinsic(&Ok(Some(300).into()), pre_info); System::note_applied_extrinsic(&Ok(Some(1000).into()), pre_info); System::note_applied_extrinsic( @@ -230,7 +233,11 @@ fn deposit_event_uses_actual_weight() { &Ok(Some(1200).into()), pre_info, ); - System::note_applied_extrinsic(&Err(DispatchError::BadOrigin.with_weight(999)), pre_info); + System::note_applied_extrinsic( + &Err(DispatchError::BadOrigin + .with_weight(Weight::new().set_computation(999).set_bandwidth(999))), + pre_info, + ); assert_eq!( System::events(), @@ -238,7 +245,10 @@ fn deposit_event_uses_actual_weight() { EventRecord { phase: Phase::ApplyExtrinsic(0), event: SysEvent::ExtrinsicSuccess { - dispatch_info: DispatchInfo { weight: 300, ..Default::default() }, + dispatch_info: DispatchInfo { + weight: Weight::from_computation(300), + ..Default::default() + }, } .into(), topics: vec![] @@ -246,7 +256,10 @@ fn deposit_event_uses_actual_weight() { EventRecord { phase: Phase::ApplyExtrinsic(1), event: SysEvent::ExtrinsicSuccess { - dispatch_info: DispatchInfo { weight: 1000, ..Default::default() }, + dispatch_info: DispatchInfo { + weight: Weight::from_computation(1000), + ..Default::default() + }, } .into(), topics: vec![] @@ -254,7 +267,10 @@ fn deposit_event_uses_actual_weight() { EventRecord { phase: Phase::ApplyExtrinsic(2), event: SysEvent::ExtrinsicSuccess { - dispatch_info: DispatchInfo { weight: 1000, ..Default::default() }, + dispatch_info: DispatchInfo { + weight: Weight::from_computation(1000), + ..Default::default() + }, } .into(), topics: vec![] @@ -263,7 +279,10 @@ fn deposit_event_uses_actual_weight() { phase: Phase::ApplyExtrinsic(3), event: SysEvent::ExtrinsicFailed { dispatch_error: DispatchError::BadOrigin.into(), - dispatch_info: DispatchInfo { weight: 999, ..Default::default() }, + dispatch_info: DispatchInfo { + weight: Weight::new().set_computation(999).set_bandwidth(999), + ..Default::default() + }, } .into(), topics: vec![] diff --git a/frame/system/src/weights.rs b/frame/system/src/weights.rs index 813183ecce188..c355f4d6d645d 100644 --- a/frame/system/src/weights.rs +++ b/frame/system/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for frame_system. diff --git a/frame/timestamp/src/lib.rs b/frame/timestamp/src/lib.rs index 81ed67913c2e6..5a6c525dc1b4d 100644 --- a/frame/timestamp/src/lib.rs +++ b/frame/timestamp/src/lib.rs @@ -168,7 +168,7 @@ pub mod pallet { /// dummy `on_initialize` to return the weight used in `on_finalize`. fn on_initialize(_n: BlockNumberFor) -> Weight { // weight of `on_finalize` - T::WeightInfo::on_finalize() + Weight::from_computation(T::WeightInfo::on_finalize()) } /// # diff --git a/frame/timestamp/src/mock.rs b/frame/timestamp/src/mock.rs index 9536414c54db6..0b22261f77c6b 100644 --- a/frame/timestamp/src/mock.rs +++ b/frame/timestamp/src/mock.rs @@ -49,7 +49,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; diff --git a/frame/timestamp/src/weights.rs b/frame/timestamp/src/weights.rs index 7c130d69c51d6..83515551460bc 100644 --- a/frame/timestamp/src/weights.rs +++ b/frame/timestamp/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_timestamp. diff --git a/frame/tips/src/migrations/v4.rs b/frame/tips/src/migrations/v4.rs index 34f7a43ec12de..460db6341d227 100644 --- a/frame/tips/src/migrations/v4.rs +++ b/frame/tips/src/migrations/v4.rs @@ -16,6 +16,7 @@ // limitations under the License. use sp_io::hashing::twox_128; +use sp_runtime::traits::Zero; use sp_std::str; use frame_support::{ @@ -49,7 +50,7 @@ pub fn migrate::on_chain_storage_version(); @@ -84,7 +85,7 @@ pub fn migrate for BlockWeights { fn get() -> frame_system::limits::BlockWeights { frame_system::limits::BlockWeights::builder() - .base_block(0) + .base_block(Weight::zero()) .for_class(DispatchClass::all(), |weights| { weights.base_extrinsic = EXTRINSIC_BASE_WEIGHT.with(|v| *v.borrow()).into(); }) .for_class(DispatchClass::non_mandatory(), |weights| { - weights.max_total = 1024.into(); + weights.max_total = Some(Weight::new().set_computation(1024).set_bandwidth(1024)); }) .build_or_panic() } @@ -256,13 +256,16 @@ impl ExtBuilder { } /// create a transaction info struct from weight. Handy to avoid building the whole struct. -pub fn info_from_weight(w: Weight) -> DispatchInfo { +pub fn info_from_weight(w: ComputationWeight) -> DispatchInfo { // pays_fee: Pays::Yes -- class: DispatchClass::Normal - DispatchInfo { weight: w, ..Default::default() } + DispatchInfo { weight: Weight::from_computation(w), ..Default::default() } } -fn post_info_from_weight(w: Weight) -> PostDispatchInfo { - PostDispatchInfo { actual_weight: Some(w), pays_fee: Default::default() } +fn post_info_from_weight(w: ComputationWeight) -> PostDispatchInfo { + PostDispatchInfo { + actual_weight: Some(Weight::from_computation(w)), + pays_fee: Default::default(), + } } fn info_from_pays(p: Pays) -> DispatchInfo { diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index 45c8b8f479c9f..14bd04ad4e637 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -190,11 +190,13 @@ where weights.get(DispatchClass::Normal).max_total.unwrap_or(weights.max_block); let current_block_weight = >::block_weight(); let normal_block_weight = - *current_block_weight.get(DispatchClass::Normal).min(&normal_max_weight); + current_block_weight.get(DispatchClass::Normal).min(normal_max_weight); let s = S::get(); let v = V::get(); + let normal_max_weight = normal_max_weight.computation(); + let normal_block_weight = normal_block_weight.computation(); let target_weight = (s * normal_max_weight) as u128; let block_weight = normal_block_weight as u128; @@ -204,7 +206,8 @@ where // defensive only, a test case assures that the maximum weight diff can fit in Multiplier // without any saturation. - let diff = Multiplier::saturating_from_rational(diff_abs, normal_max_weight.max(1)); + let diff = + Multiplier::saturating_from_rational(diff_abs, normal_max_weight.max(One::one())); let diff_squared = diff.saturating_mul(diff); let v_squared_2 = v.saturating_mul(v) / Multiplier::saturating_from_integer(2); @@ -352,16 +355,20 @@ pub mod pallet { assert!( ::max_value() >= Multiplier::checked_from_integer::( - T::BlockWeights::get().max_block.try_into().unwrap() + T::BlockWeights::get().max_block.computation().try_into().unwrap() ) .unwrap(), ); let target = T::FeeMultiplierUpdate::target() * - T::BlockWeights::get().get(DispatchClass::Normal).max_total.expect( - "Setting `max_total` for `Normal` dispatch class is not compatible with \ + T::BlockWeights::get() + .get(DispatchClass::Normal) + .max_total + .expect( + "Setting `max_total` for `Normal` dispatch class is not compatible with \ `transaction-payment` pallet.", - ); + ) + .computation(); // add 1 percent; let addition = target / 100; if addition == 0 { @@ -379,7 +386,7 @@ pub mod pallet { let target = target + addition; - >::set_block_consumed_resources(target, 0); + >::set_block_consumed_resources(Some(target), None, None); let next = T::FeeMultiplierUpdate::convert(min_value); assert!( next > min_value, @@ -533,14 +540,14 @@ where } fn length_to_fee(length: u32) -> BalanceOf { - T::LengthToFee::calc(&(length as Weight)) + T::LengthToFee::calc(&(length.into())) } fn weight_to_fee(weight: Weight) -> BalanceOf { // cap the weight to the maximum defined in runtime, otherwise it will be the // `Bounded` maximum of its data type, which is not desired. let capped_weight = weight.min(T::BlockWeights::get().max_block); - T::WeightToFee::calc(&capped_weight) + T::WeightToFee::calc(&capped_weight.computation()) } } @@ -634,8 +641,11 @@ where let max_block_weight = T::BlockWeights::get().max_block; let max_block_length = *T::BlockLength::get().max.get(info.class) as u64; - let bounded_weight = info.weight.max(1).min(max_block_weight); - let bounded_length = (len as u64).max(1).min(max_block_length); + let bounded_weight = info.weight.max(One::one()).min(max_block_weight); + let bounded_length = (len as u64).max(One::one()).min(max_block_length); + + let bounded_weight = bounded_weight.computation(); + let max_block_weight = max_block_weight.computation(); let max_tx_per_block_weight = max_block_weight / bounded_weight; let max_tx_per_block_length = max_block_length / bounded_length; @@ -823,12 +833,12 @@ mod tests { impl Get for BlockWeights { fn get() -> frame_system::limits::BlockWeights { frame_system::limits::BlockWeights::builder() - .base_block(0) + .base_block(Zero::zero()) .for_class(DispatchClass::all(), |weights| { weights.base_extrinsic = EXTRINSIC_BASE_WEIGHT.with(|v| *v.borrow()).into(); }) .for_class(DispatchClass::non_mandatory(), |weights| { - weights.max_total = 1024.into(); + weights.max_total = Some(Weight::new().set_computation(1024).set_bandwidth(1)); }) .build_or_panic() } @@ -941,7 +951,7 @@ mod tests { impl Default for ExtBuilder { fn default() -> Self { - Self { balance_factor: 1, base_weight: 0, byte_fee: 1, weight_to_fee: 1 } + Self { balance_factor: 1, base_weight: Zero::zero(), byte_fee: 1, weight_to_fee: 1 } } } @@ -1017,13 +1027,18 @@ mod tests { .execute_with(|| { let len = 10; let pre = ChargeTransactionPayment::::from(0) - .pre_dispatch(&1, CALL, &info_from_weight(5), len) + .pre_dispatch( + &1, + CALL, + &info_from_weight(Weight::new().set_computation(5).set_bandwidth(1)), + len, + ) .unwrap(); assert_eq!(Balances::free_balance(1), 100 - 5 - 5 - 10); assert_ok!(ChargeTransactionPayment::::post_dispatch( Some(pre), - &info_from_weight(5), + &info_from_weight(Weight::new().set_computation(5).set_bandwidth(1)), &default_post_info(), len, &Ok(()) @@ -1035,14 +1050,19 @@ mod tests { FEE_UNBALANCED_AMOUNT.with(|a| *a.borrow_mut() = 0); let pre = ChargeTransactionPayment::::from(5 /* tipped */) - .pre_dispatch(&2, CALL, &info_from_weight(100), len) + .pre_dispatch( + &2, + CALL, + &info_from_weight(Weight::new().set_computation(100).set_bandwidth(1)), + len, + ) .unwrap(); assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 100 - 5); assert_ok!(ChargeTransactionPayment::::post_dispatch( Some(pre), - &info_from_weight(100), - &post_info_from_weight(50), + &info_from_weight(Weight::new().set_computation(100).set_bandwidth(1)), + &post_info_from_weight(Weight::new().set_computation(50).set_bandwidth(1)), len, &Ok(()) )); @@ -1063,15 +1083,20 @@ mod tests { >::put(Multiplier::saturating_from_rational(3, 2)); let pre = ChargeTransactionPayment::::from(5 /* tipped */) - .pre_dispatch(&2, CALL, &info_from_weight(100), len) + .pre_dispatch( + &2, + CALL, + &info_from_weight(Weight::new().set_computation(100).set_bandwidth(1)), + len, + ) .unwrap(); // 5 base fee, 10 byte fee, 3/2 * 100 weight fee, 5 tip assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 150 - 5); assert_ok!(ChargeTransactionPayment::::post_dispatch( Some(pre), - &info_from_weight(100), - &post_info_from_weight(50), + &info_from_weight(Weight::new().set_computation(100).set_bandwidth(1)), + &post_info_from_weight(Weight::new().set_computation(50).set_bandwidth(1)), len, &Ok(()) )); @@ -1087,13 +1112,16 @@ mod tests { assert_ok!(ChargeTransactionPayment::::from(0).pre_dispatch( &1, CALL, - &info_from_weight(Weight::max_value()), + &info_from_weight(Weight::MAX), 10 )); // fee will be proportional to what is the actual maximum weight in the runtime. assert_eq!( Balances::free_balance(&1), - (10000 - ::BlockWeights::get().max_block) as u64 + (10000 - + ::BlockWeights::get() + .max_block + .computation()) as u64 ); }); } @@ -1112,7 +1140,7 @@ mod tests { // This is a completely free (and thus wholly insecure/DoS-ridden) transaction. let operational_transaction = DispatchInfo { - weight: 0, + weight: Zero::zero(), class: DispatchClass::Operational, pays_fee: Pays::No, }; @@ -1124,8 +1152,11 @@ mod tests { )); // like a InsecureFreeNormal - let free_transaction = - DispatchInfo { weight: 0, class: DispatchClass::Normal, pays_fee: Pays::Yes }; + let free_transaction = DispatchInfo { + weight: Zero::zero(), + class: DispatchClass::Normal, + pays_fee: Pays::Yes, + }; assert_noop!( ChargeTransactionPayment::::from(0).validate( &1, @@ -1150,7 +1181,12 @@ mod tests { let len = 10; assert_ok!(ChargeTransactionPayment::::from(10) // tipped - .pre_dispatch(&1, CALL, &info_from_weight(3), len)); + .pre_dispatch( + &1, + CALL, + &info_from_weight(Weight::new().set_computation(3).set_bandwidth(1)), + len + )); assert_eq!( Balances::free_balance(1), 100 // original @@ -1186,7 +1222,7 @@ mod tests { class: info.class, partial_fee: 5 * 2 /* base * weight_fee */ + len as u64 /* len * 1 */ - + info.weight.min(BlockWeights::get().max_block) as u64 * 2 * 3 / 2 /* weight */ + + info.weight.min(BlockWeights::get().max_block).computation() as u64 * 2 * 3 / 2 /* weight */ }, ); @@ -1205,8 +1241,11 @@ mod tests { inclusion_fee: Some(InclusionFee { base_fee: 5 * 2, len_fee: len as u64, - adjusted_weight_fee: info.weight.min(BlockWeights::get().max_block) as u64 * - 2 * 3 / 2 + adjusted_weight_fee: info + .weight + .min(BlockWeights::get().max_block) + .computation() as u64 * 2 * 3 / + 2 }), tip: 0, }, @@ -1232,14 +1271,14 @@ mod tests { // Tip only, no fees works let dispatch_info = DispatchInfo { - weight: 0, + weight: Zero::zero(), class: DispatchClass::Operational, pays_fee: Pays::No, }; assert_eq!(Pallet::::compute_fee(0, &dispatch_info, 10), 10); // No tip, only base fee works let dispatch_info = DispatchInfo { - weight: 0, + weight: Zero::zero(), class: DispatchClass::Operational, pays_fee: Pays::Yes, }; @@ -1250,7 +1289,7 @@ mod tests { assert_eq!(Pallet::::compute_fee(42, &dispatch_info, 0), 520); // Weight fee + base fee works let dispatch_info = DispatchInfo { - weight: 1000, + weight: Weight::new().set_computation(1000).set_bandwidth(1), class: DispatchClass::Operational, pays_fee: Pays::Yes, }; @@ -1270,7 +1309,7 @@ mod tests { >::put(Multiplier::saturating_from_rational(3, 2)); // Base fee is unaffected by multiplier let dispatch_info = DispatchInfo { - weight: 0, + weight: Zero::zero(), class: DispatchClass::Operational, pays_fee: Pays::Yes, }; @@ -1278,7 +1317,7 @@ mod tests { // Everything works together :) let dispatch_info = DispatchInfo { - weight: 123, + weight: Weight::new().set_computation(123).set_bandwidth(1), class: DispatchClass::Operational, pays_fee: Pays::Yes, }; @@ -1303,7 +1342,7 @@ mod tests { // Base fee is unaffected by multiplier. let dispatch_info = DispatchInfo { - weight: 0, + weight: Zero::zero(), class: DispatchClass::Operational, pays_fee: Pays::Yes, }; @@ -1311,7 +1350,7 @@ mod tests { // Everything works together. let dispatch_info = DispatchInfo { - weight: 123, + weight: Weight::new().set_computation(123).set_bandwidth(1), class: DispatchClass::Operational, pays_fee: Pays::Yes, }; @@ -1333,7 +1372,7 @@ mod tests { .execute_with(|| { // Overflow is handled let dispatch_info = DispatchInfo { - weight: Weight::max_value(), + weight: Weight::MAX, class: DispatchClass::Operational, pays_fee: Pays::Yes, }; @@ -1355,7 +1394,12 @@ mod tests { System::set_block_number(10); let len = 10; let pre = ChargeTransactionPayment::::from(5 /* tipped */) - .pre_dispatch(&2, CALL, &info_from_weight(100), len) + .pre_dispatch( + &2, + CALL, + &info_from_weight(Weight::new().set_computation(100).set_bandwidth(1)), + len, + ) .unwrap(); assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 100 - 5); @@ -1365,8 +1409,8 @@ mod tests { assert_ok!(ChargeTransactionPayment::::post_dispatch( Some(pre), - &info_from_weight(100), - &post_info_from_weight(50), + &info_from_weight(Weight::new().set_computation(100).set_bandwidth(1)), + &post_info_from_weight(Weight::new().set_computation(50).set_bandwidth(1)), len, &Ok(()) )); @@ -1393,14 +1437,19 @@ mod tests { .execute_with(|| { let len = 10; let pre = ChargeTransactionPayment::::from(5 /* tipped */) - .pre_dispatch(&2, CALL, &info_from_weight(100), len) + .pre_dispatch( + &2, + CALL, + &info_from_weight(Weight::new().set_computation(100).set_bandwidth(1)), + len, + ) .unwrap(); assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 100 - 5); assert_ok!(ChargeTransactionPayment::::post_dispatch( Some(pre), - &info_from_weight(100), - &post_info_from_weight(101), + &info_from_weight(Weight::new().set_computation(100).set_bandwidth(1)), + &post_info_from_weight(Weight::new().set_computation(101).set_bandwidth(1)), len, &Ok(()) )); @@ -1418,8 +1467,11 @@ mod tests { // So events are emitted System::set_block_number(10); let len = 10; - let dispatch_info = - DispatchInfo { weight: 100, pays_fee: Pays::No, class: DispatchClass::Normal }; + let dispatch_info = DispatchInfo { + weight: Weight::new().set_computation(100).set_bandwidth(1), + pays_fee: Pays::No, + class: DispatchClass::Normal, + }; let user = 69; let pre = ChargeTransactionPayment::::from(0) .pre_dispatch(&user, CALL, &dispatch_info, len) @@ -1445,8 +1497,9 @@ mod tests { .base_weight(7) .build() .execute_with(|| { - let info = info_from_weight(100); - let post_info = post_info_from_weight(33); + let info = info_from_weight(Weight::new().set_computation(100).set_bandwidth(1)); + let post_info = + post_info_from_weight(Weight::new().set_computation(33).set_bandwidth(1)); let prev_balance = Balances::free_balance(2); let len = 10; let tip = 5; @@ -1482,8 +1535,11 @@ mod tests { let len = 10; ExtBuilder::default().balance_factor(100).build().execute_with(|| { - let normal = - DispatchInfo { weight: 100, class: DispatchClass::Normal, pays_fee: Pays::Yes }; + let normal = DispatchInfo { + weight: Weight::new().set_computation(100).set_bandwidth(1), + class: DispatchClass::Normal, + pays_fee: Pays::Yes, + }; let priority = ChargeTransactionPayment::(tip) .validate(&2, CALL, &normal, len) .unwrap() @@ -1501,7 +1557,7 @@ mod tests { ExtBuilder::default().balance_factor(100).build().execute_with(|| { let op = DispatchInfo { - weight: 100, + weight: Weight::new().set_computation(100).set_bandwidth(1), class: DispatchClass::Operational, pays_fee: Pays::Yes, }; @@ -1525,8 +1581,11 @@ mod tests { let len = 10; ExtBuilder::default().balance_factor(100).build().execute_with(|| { - let normal = - DispatchInfo { weight: 100, class: DispatchClass::Normal, pays_fee: Pays::Yes }; + let normal = DispatchInfo { + weight: Weight::new().set_computation(100).set_bandwidth(1), + class: DispatchClass::Normal, + pays_fee: Pays::Yes, + }; let priority = ChargeTransactionPayment::(tip) .validate(&2, CALL, &normal, len) .unwrap() @@ -1537,7 +1596,7 @@ mod tests { ExtBuilder::default().balance_factor(100).build().execute_with(|| { let op = DispatchInfo { - weight: 100, + weight: Weight::new().set_computation(100).set_bandwidth(1), class: DispatchClass::Operational, pays_fee: Pays::Yes, }; @@ -1556,8 +1615,11 @@ mod tests { let mut priority2 = 0; let len = 10; ExtBuilder::default().balance_factor(100).build().execute_with(|| { - let normal = - DispatchInfo { weight: 100, class: DispatchClass::Normal, pays_fee: Pays::Yes }; + let normal = DispatchInfo { + weight: Weight::new().set_computation(100).set_bandwidth(1), + class: DispatchClass::Normal, + pays_fee: Pays::Yes, + }; priority1 = ChargeTransactionPayment::(tip) .validate(&2, CALL, &normal, len) .unwrap() @@ -1566,7 +1628,7 @@ mod tests { ExtBuilder::default().balance_factor(100).build().execute_with(|| { let op = DispatchInfo { - weight: 100, + weight: Weight::new().set_computation(100).set_bandwidth(1), class: DispatchClass::Operational, pays_fee: Pays::Yes, }; @@ -1596,7 +1658,7 @@ mod tests { .base_weight(7) .build() .execute_with(|| { - let info = info_from_weight(100); + let info = info_from_weight(Weight::new().set_computation(100).set_bandwidth(1)); let post_info = post_info_from_pays(Pays::No); let prev_balance = Balances::free_balance(2); let len = 10; diff --git a/frame/transaction-payment/src/types.rs b/frame/transaction-payment/src/types.rs index 3faebfed48946..f7587a074e292 100644 --- a/frame/transaction-payment/src/types.rs +++ b/frame/transaction-payment/src/types.rs @@ -135,12 +135,13 @@ mod tests { #[test] fn should_serialize_and_deserialize_properly_with_string() { let info = RuntimeDispatchInfo { - weight: 5, + weight: Weight::from_computation(5), class: DispatchClass::Normal, partial_fee: 1_000_000_u64, }; - let json_str = r#"{"weight":5,"class":"normal","partialFee":"1000000"}"#; + let json_str = + r#"{"weight":{"computation":5,"bandwidth":0},"class":"normal","partialFee":"1000000"}"#; assert_eq!(serde_json::to_string(&info).unwrap(), json_str); assert_eq!(serde_json::from_str::>(json_str).unwrap(), info); @@ -152,12 +153,12 @@ mod tests { #[test] fn should_serialize_and_deserialize_properly_large_value() { let info = RuntimeDispatchInfo { - weight: 5, + weight: Weight::from_computation(5), class: DispatchClass::Normal, partial_fee: u128::max_value(), }; - let json_str = r#"{"weight":5,"class":"normal","partialFee":"340282366920938463463374607431768211455"}"#; + let json_str = r#"{"weight":{"computation":5,"bandwidth":0},"class":"normal","partialFee":"340282366920938463463374607431768211455"}"#; assert_eq!(serde_json::to_string(&info).unwrap(), json_str); assert_eq!(serde_json::from_str::>(json_str).unwrap(), info); diff --git a/frame/transaction-storage/src/lib.rs b/frame/transaction-storage/src/lib.rs index a63b31f2f1aac..525b2cd401ece 100644 --- a/frame/transaction-storage/src/lib.rs +++ b/frame/transaction-storage/src/lib.rs @@ -144,7 +144,7 @@ pub mod pallet { >::remove(obsolete); } // 2 writes in `on_initialize` and 2 writes + 2 reads in `on_finalize` - T::DbWeight::get().reads_writes(2, 4) + Weight::from_computation(T::DbWeight::get().reads_writes(2, 4)) } fn on_finalize(n: T::BlockNumber) { diff --git a/frame/transaction-storage/src/weights.rs b/frame/transaction-storage/src/weights.rs index 8063783b4cc22..14171f63c7395 100644 --- a/frame/transaction-storage/src/weights.rs +++ b/frame/transaction-storage/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_transaction_storage. diff --git a/frame/treasury/src/lib.rs b/frame/treasury/src/lib.rs index 419970ed18afa..6be5af24d5261 100644 --- a/frame/treasury/src/lib.rs +++ b/frame/treasury/src/lib.rs @@ -304,7 +304,7 @@ pub mod pallet { if (n % T::SpendPeriod::get()).is_zero() { Self::spend_funds() } else { - 0 + Weight::zero() } } } @@ -492,7 +492,9 @@ impl, I: 'static> Pallet { proposals_approvals_len }); - total_weight += T::WeightInfo::on_initialize_proposals(proposals_len); + total_weight = total_weight.saturating_add(Weight::from_computation( + T::WeightInfo::on_initialize_proposals(proposals_len), + )); // Call Runtime hooks to external pallet using treasury to compute spend funds. T::SpendFunds::spend_funds( diff --git a/frame/treasury/src/tests.rs b/frame/treasury/src/tests.rs index b755db29682aa..b3f9d88a58115 100644 --- a/frame/treasury/src/tests.rs +++ b/frame/treasury/src/tests.rs @@ -55,7 +55,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; diff --git a/frame/treasury/src/weights.rs b/frame/treasury/src/weights.rs index 4ae82d3b230d2..2ca15437f86db 100644 --- a/frame/treasury/src/weights.rs +++ b/frame/treasury/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_treasury. diff --git a/frame/uniques/src/migration.rs b/frame/uniques/src/migration.rs index d301f0a3d1eb1..75a75f57e28ba 100644 --- a/frame/uniques/src/migration.rs +++ b/frame/uniques/src/migration.rs @@ -18,8 +18,8 @@ //! Various pieces of common functionality. use super::*; use frame_support::{ + pallet_prelude::Weight, traits::{Get, GetStorageVersion, PalletInfoAccess, StorageVersion}, - weights::Weight, }; /// Migrate the pallet storage to v1. @@ -45,13 +45,13 @@ pub fn migrate_to_v1, I: 'static, P: GetStorageVersion + PalletInfo on_chain_storage_version, ); // calculate and return migration weights - T::DbWeight::get().reads_writes(count as Weight + 1, count as Weight + 1) + Weight::from_computation(T::DbWeight::get().reads_writes(count + 1, count + 1)) } else { log::warn!( target: "runtime::uniques", "Attempted to apply migration to v1 but failed because storage version is {:?}", on_chain_storage_version, ); - T::DbWeight::get().reads(1) + Weight::from_computation(T::DbWeight::get().reads(1)) } } diff --git a/frame/uniques/src/weights.rs b/frame/uniques/src/weights.rs index 127e5ccbb12a3..b3769dc00d99d 100644 --- a/frame/uniques/src/weights.rs +++ b/frame/uniques/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_uniques. diff --git a/frame/utility/src/lib.rs b/frame/utility/src/lib.rs index 9a8384f836f8b..7db5b545a2d0f 100644 --- a/frame/utility/src/lib.rs +++ b/frame/utility/src/lib.rs @@ -61,11 +61,11 @@ use frame_support::{ dispatch::PostDispatchInfo, traits::{IsSubType, OriginTrait, UnfilteredDispatchable}, transactional, - weights::{extract_actual_weight, GetDispatchInfo}, + weights::{extract_actual_weight, GetDispatchInfo, Weight}, }; use sp_core::TypeId; use sp_io::hashing::blake2_256; -use sp_runtime::traits::{Dispatchable, TrailingZeroInput}; +use sp_runtime::traits::{Dispatchable, TrailingZeroInput, Zero}; use sp_std::prelude::*; pub use weights::WeightInfo; @@ -186,8 +186,8 @@ pub mod pallet { let dispatch_infos = calls.iter().map(|call| call.get_dispatch_info()).collect::>(); let dispatch_weight = dispatch_infos.iter() .map(|di| di.weight) - .fold(0, |total: Weight, weight: Weight| total.saturating_add(weight)) - .saturating_add(T::WeightInfo::batch(calls.len() as u32)); + .fold(Zero::zero(), |total: Weight, weight: Weight| total.saturating_add(weight)) + .saturating_add(Weight::from_computation(T::WeightInfo::batch(calls.len() as u32))); let dispatch_class = { let all_operational = dispatch_infos.iter() .map(|di| di.class) @@ -209,7 +209,7 @@ pub mod pallet { ensure!(calls_len <= Self::batched_calls_limit() as usize, Error::::TooManyCalls); // Track the actual weight of each of the batch calls. - let mut weight: Weight = 0; + let mut weight: Weight = Zero::zero(); for (index, call) in calls.into_iter().enumerate() { let info = call.get_dispatch_info(); // If origin is root, don't apply any dispatch filters; root can call anything. @@ -226,14 +226,16 @@ pub mod pallet { error: e.error, }); // Take the weight of this function itself into account. - let base_weight = T::WeightInfo::batch(index.saturating_add(1) as u32); + let base_weight = Weight::from_computation(T::WeightInfo::batch( + index.saturating_add(1) as u32, + )); // Return the actual used weight + base_weight of this call. return Ok(Some(base_weight + weight).into()) } Self::deposit_event(Event::ItemCompleted); } Self::deposit_event(Event::BatchCompleted); - let base_weight = T::WeightInfo::batch(calls_len as u32); + let base_weight = Weight::from_computation(T::WeightInfo::batch(calls_len as u32)); Ok(Some(base_weight + weight).into()) } @@ -253,10 +255,10 @@ pub mod pallet { #[pallet::weight({ let dispatch_info = call.get_dispatch_info(); ( - T::WeightInfo::as_derivative() + Weight::from_computation(T::WeightInfo::as_derivative()) .saturating_add(dispatch_info.weight) // AccountData for inner call origin accountdata. - .saturating_add(T::DbWeight::get().reads_writes(1, 1)), + .saturating_add(Weight::from_computation(T::DbWeight::get().reads_writes(1, 1))), dispatch_info.class, ) })] @@ -272,8 +274,12 @@ pub mod pallet { let info = call.get_dispatch_info(); let result = call.dispatch(origin); // Always take into account the base weight of this call. - let mut weight = T::WeightInfo::as_derivative() - .saturating_add(T::DbWeight::get().reads_writes(1, 1)); + let mut weight = Weight::zero(); + + weight = weight.saturating_add(Weight::from_computation( + T::WeightInfo::as_derivative() + .saturating_add(T::DbWeight::get().reads_writes(1, 1)), + )); // Add the real weight of the dispatch. weight = weight.saturating_add(extract_actual_weight(&result, &info)); result @@ -302,8 +308,8 @@ pub mod pallet { let dispatch_infos = calls.iter().map(|call| call.get_dispatch_info()).collect::>(); let dispatch_weight = dispatch_infos.iter() .map(|di| di.weight) - .fold(0, |total: Weight, weight: Weight| total.saturating_add(weight)) - .saturating_add(T::WeightInfo::batch_all(calls.len() as u32)); + .fold(Zero::zero(), |total: Weight, weight: Weight| total.saturating_add(weight)) + .saturating_add(Weight::from_computation(T::WeightInfo::batch_all(calls.len() as u32))); let dispatch_class = { let all_operational = dispatch_infos.iter() .map(|di| di.class) @@ -326,7 +332,7 @@ pub mod pallet { ensure!(calls_len <= Self::batched_calls_limit() as usize, Error::::TooManyCalls); // Track the actual weight of each of the batch calls. - let mut weight: Weight = 0; + let mut weight = Weight::zero(); for (index, call) in calls.into_iter().enumerate() { let info = call.get_dispatch_info(); // If origin is root, bypass any dispatch filter; root can call anything. @@ -345,7 +351,9 @@ pub mod pallet { weight = weight.saturating_add(extract_actual_weight(&result, &info)); result.map_err(|mut err| { // Take the weight of this function itself into account. - let base_weight = T::WeightInfo::batch_all(index.saturating_add(1) as u32); + let base_weight = Weight::from_computation(T::WeightInfo::batch_all( + index.saturating_add(1) as u32, + )); // Return the actual used weight + base_weight of this call. err.post_info = Some(base_weight + weight).into(); err @@ -353,7 +361,7 @@ pub mod pallet { Self::deposit_event(Event::ItemCompleted); } Self::deposit_event(Event::BatchCompleted); - let base_weight = T::WeightInfo::batch_all(calls_len as u32); + let base_weight = Weight::from_computation(T::WeightInfo::batch_all(calls_len as u32)); Ok(Some(base_weight + weight).into()) } @@ -370,7 +378,7 @@ pub mod pallet { #[pallet::weight({ let dispatch_info = call.get_dispatch_info(); ( - T::WeightInfo::dispatch_as() + Weight::from_computation(T::WeightInfo::dispatch_as()) .saturating_add(dispatch_info.weight), dispatch_info.class, ) @@ -408,8 +416,8 @@ pub mod pallet { let dispatch_infos = calls.iter().map(|call| call.get_dispatch_info()).collect::>(); let dispatch_weight = dispatch_infos.iter() .map(|di| di.weight) - .fold(0, |total: Weight, weight: Weight| total.saturating_add(weight)) - .saturating_add(T::WeightInfo::force_batch(calls.len() as u32)); + .fold(Zero::zero(), |total: Weight, weight: Weight| (total.saturating_add(weight))) + .saturating_add(Weight::from_computation(T::WeightInfo::force_batch(calls.len() as u32))); let dispatch_class = { let all_operational = dispatch_infos.iter() .map(|di| di.class) @@ -431,7 +439,7 @@ pub mod pallet { ensure!(calls_len <= Self::batched_calls_limit() as usize, Error::::TooManyCalls); // Track the actual weight of each of the batch calls. - let mut weight: Weight = 0; + let mut weight = Weight::zero(); // Track failed dispatch occur. let mut has_error: bool = false; for call in calls.into_iter() { @@ -456,7 +464,7 @@ pub mod pallet { } else { Self::deposit_event(Event::BatchCompleted); } - let base_weight = T::WeightInfo::batch(calls_len as u32); + let base_weight = Weight::from_computation(T::WeightInfo::batch(calls_len as u32)); Ok(Some(base_weight + weight).into()) } } diff --git a/frame/utility/src/tests.rs b/frame/utility/src/tests.rs index f53459a707b54..89e4805c0260e 100644 --- a/frame/utility/src/tests.rs +++ b/frame/utility/src/tests.rs @@ -27,7 +27,7 @@ use frame_support::{ dispatch::{DispatchError, DispatchErrorWithPostInfo, Dispatchable}, parameter_types, storage, traits::{ConstU32, ConstU64, Contains}, - weights::{Pays, Weight}, + weights::Pays, }; use sp_core::H256; use sp_runtime::{ @@ -99,7 +99,7 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(Weight::max_value()); + frame_system::limits::BlockWeights::simple_max(Weight::MAX); } impl frame_system::Config for Test { type BaseCallFilter = TestBaseCallFilter; @@ -191,7 +191,7 @@ fn call_transfer(dest: u64, value: u64) -> Call { Call::Balances(BalancesCall::transfer { dest, value }) } -fn call_foobar(err: bool, start_weight: u64, end_weight: Option) -> Call { +fn call_foobar(err: bool, start_weight: Weight, end_weight: Option) -> Call { Call::Example(ExampleCall::foobar { err, start_weight, end_weight }) } @@ -213,8 +213,8 @@ fn as_derivative_works() { #[test] fn as_derivative_handles_weight_refund() { new_test_ext().execute_with(|| { - let start_weight = 100; - let end_weight = 75; + let start_weight = Weight::new().set_computation(100).set_bandwidth(100); + let end_weight = Weight::new().set_computation(75).set_bandwidth(75); let diff = start_weight - end_weight; // Full weight when ok @@ -364,24 +364,24 @@ fn batch_weight_calculation_doesnt_overflow() { use sp_runtime::Perbill; new_test_ext().execute_with(|| { let big_call = Call::System(SystemCall::fill_block { ratio: Perbill::from_percent(50) }); - assert_eq!(big_call.get_dispatch_info().weight, Weight::max_value() / 2); + assert_eq!(big_call.get_dispatch_info().weight, Weight::MAX / 2); // 3 * 50% saturates to 100% let batch_call = Call::Utility(crate::Call::batch { calls: vec![big_call.clone(), big_call.clone(), big_call.clone()], }); - assert_eq!(batch_call.get_dispatch_info().weight, Weight::max_value()); + assert_eq!(batch_call.get_dispatch_info().weight, Weight::MAX); }); } #[test] fn batch_handles_weight_refund() { new_test_ext().execute_with(|| { - let start_weight = 100; - let end_weight = 75; + let start_weight = Weight::new().set_computation(100).set_bandwidth(100); + let end_weight = Weight::new().set_computation(75).set_bandwidth(75); let diff = start_weight - end_weight; - let batch_len: Weight = 4; + let batch_len: u64 = 4; // Full weight when ok let inner_call = call_foobar(false, start_weight, None); @@ -420,7 +420,7 @@ fn batch_handles_weight_refund() { let good_call = call_foobar(false, start_weight, Some(end_weight)); let bad_call = call_foobar(true, start_weight, Some(end_weight)); let batch_calls = vec![good_call, bad_call]; - let batch_len = batch_calls.len() as Weight; + let batch_len = batch_calls.len() as u64; let call = Call::Utility(UtilityCall::batch { calls: batch_calls }); let info = call.get_dispatch_info(); let result = call.dispatch(Origin::signed(1)); @@ -444,7 +444,7 @@ fn batch_handles_weight_refund() { assert_eq!( extract_actual_weight(&result, &info), // Real weight is 2 calls at end_weight - ::WeightInfo::batch(2) + end_weight * 2, + Weight::from_computation(::WeightInfo::batch(2)) + end_weight * 2, ); }); } @@ -479,7 +479,8 @@ fn batch_all_revert() { DispatchErrorWithPostInfo { post_info: PostDispatchInfo { actual_weight: Some( - ::WeightInfo::batch_all(2) + info.weight * 2 + Weight::from_computation(::WeightInfo::batch_all(2)) + + info.weight * 2 ), pays_fee: Pays::Yes }, @@ -494,10 +495,10 @@ fn batch_all_revert() { #[test] fn batch_all_handles_weight_refund() { new_test_ext().execute_with(|| { - let start_weight = 100; - let end_weight = 75; + let start_weight = Weight::new().set_computation(100).set_bandwidth(100); + let end_weight = Weight::new().set_computation(75).set_bandwidth(75); let diff = start_weight - end_weight; - let batch_len: Weight = 4; + let batch_len: u64 = 4; // Full weight when ok let inner_call = call_foobar(false, start_weight, None); @@ -533,7 +534,7 @@ fn batch_all_handles_weight_refund() { let good_call = call_foobar(false, start_weight, Some(end_weight)); let bad_call = call_foobar(true, start_weight, Some(end_weight)); let batch_calls = vec![good_call, bad_call]; - let batch_len = batch_calls.len() as Weight; + let batch_len = batch_calls.len() as u64; let call = Call::Utility(UtilityCall::batch_all { calls: batch_calls }); let info = call.get_dispatch_info(); let result = call.dispatch(Origin::signed(1)); @@ -551,7 +552,7 @@ fn batch_all_handles_weight_refund() { assert_eq!( extract_actual_weight(&result, &info), // Real weight is 2 calls at end_weight - ::WeightInfo::batch_all(2) + end_weight * 2, + Weight::from_computation(::WeightInfo::batch_all(2)) + end_weight * 2, ); }); } @@ -572,7 +573,10 @@ fn batch_all_does_not_nest() { Utility::batch_all(Origin::signed(1), vec![batch_all.clone()]), DispatchErrorWithPostInfo { post_info: PostDispatchInfo { - actual_weight: Some(::WeightInfo::batch_all(1) + info.weight), + actual_weight: Some( + Weight::from_computation(::WeightInfo::batch_all(1)) + + info.weight + ), pays_fee: Pays::Yes }, error: frame_system::Error::::CallFiltered.into(), @@ -616,7 +620,7 @@ fn force_batch_works() { Origin::signed(1), vec![ call_transfer(2, 5), - call_foobar(true, 75, None), + call_foobar(true, Weight::from_computation(75), None), call_transfer(2, 10), call_transfer(2, 5), ] diff --git a/frame/utility/src/weights.rs b/frame/utility/src/weights.rs index d3cd7530c2584..58cea4ee63575 100644 --- a/frame/utility/src/weights.rs +++ b/frame/utility/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_utility. diff --git a/frame/vesting/src/migrations.rs b/frame/vesting/src/migrations.rs index 15668425b4b20..a679338d5e81b 100644 --- a/frame/vesting/src/migrations.rs +++ b/frame/vesting/src/migrations.rs @@ -61,7 +61,7 @@ pub mod v1 { }, ); - T::DbWeight::get().reads_writes(reads_writes, reads_writes) + Weight::from_computation(T::DbWeight::get().reads_writes(reads_writes, reads_writes)) } #[cfg(feature = "try-runtime")] diff --git a/frame/vesting/src/mock.rs b/frame/vesting/src/mock.rs index 9ad8e57500e89..de353fc2ee9ea 100644 --- a/frame/vesting/src/mock.rs +++ b/frame/vesting/src/mock.rs @@ -45,7 +45,10 @@ frame_support::construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; diff --git a/frame/vesting/src/weights.rs b/frame/vesting/src/weights.rs index 356cd003d8848..3e82f1d218f7a 100644 --- a/frame/vesting/src/weights.rs +++ b/frame/vesting/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_vesting. diff --git a/frame/whitelist/src/lib.rs b/frame/whitelist/src/lib.rs index 239f0fd280160..0aac5a5ac62ce 100644 --- a/frame/whitelist/src/lib.rs +++ b/frame/whitelist/src/lib.rs @@ -46,7 +46,7 @@ use frame_support::{ weights::{GetDispatchInfo, PostDispatchInfo, Weight}, }; use scale_info::TypeInfo; -use sp_runtime::traits::{Dispatchable, Hash}; +use sp_runtime::traits::{Dispatchable, Hash, Saturating}; use sp_std::prelude::*; pub use pallet::*; @@ -147,9 +147,10 @@ pub mod pallet { Ok(()) } - #[pallet::weight( - T::WeightInfo::dispatch_whitelisted_call().saturating_add(*call_weight_witness) - )] + #[pallet::weight({ + let benchmarked_weight = Weight::from_computation(T::WeightInfo::dispatch_whitelisted_call()); + benchmarked_weight.saturating_add(*call_weight_witness) + })] pub fn dispatch_whitelisted_call( origin: OriginFor, call_hash: T::Hash, @@ -172,12 +173,17 @@ pub mod pallet { .map_err(|_| Error::::UndecodableCall)?; ensure!( - call.get_dispatch_info().weight <= call_weight_witness, + call.get_dispatch_info() + .weight + .is_strictly_less_than_or_equal(&call_weight_witness), Error::::InvalidCallWeightWitness ); - let actual_weight = Self::clean_and_dispatch(call_hash, call) - .map(|w| w.saturating_add(T::WeightInfo::dispatch_whitelisted_call())); + let actual_weight = Self::clean_and_dispatch(call_hash, call).map(|w| { + w.saturating_add(Weight::from_computation( + T::WeightInfo::dispatch_whitelisted_call(), + )) + }); Ok(actual_weight.into()) } @@ -186,8 +192,8 @@ pub mod pallet { let call_weight = call.get_dispatch_info().weight; let call_len = call.encoded_size() as u32; - T::WeightInfo::dispatch_whitelisted_call_with_preimage(call_len) - .saturating_add(call_weight) + let benchmarked_weight = Weight::from_computation(T::WeightInfo::dispatch_whitelisted_call_with_preimage(call_len)); + benchmarked_weight.saturating_add(call_weight) })] pub fn dispatch_whitelisted_call_with_preimage( origin: OriginFor, @@ -204,7 +210,9 @@ pub mod pallet { let call_len = call.encoded_size() as u32; let actual_weight = Self::clean_and_dispatch(call_hash, *call).map(|w| { - w.saturating_add(T::WeightInfo::dispatch_whitelisted_call_with_preimage(call_len)) + w.saturating_add(Weight::from_computation( + T::WeightInfo::dispatch_whitelisted_call_with_preimage(call_len), + )) }); Ok(actual_weight.into()) diff --git a/frame/whitelist/src/mock.rs b/frame/whitelist/src/mock.rs index 634db53a09a4e..92dc2a5570cba 100644 --- a/frame/whitelist/src/mock.rs +++ b/frame/whitelist/src/mock.rs @@ -51,7 +51,10 @@ construct_runtime!( parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::new() + .set_computation(1024) + .set_bandwidth(1024) + ); } impl frame_system::Config for Test { type BaseCallFilter = Nothing; diff --git a/frame/whitelist/src/tests.rs b/frame/whitelist/src/tests.rs index 67bccaeaeebe1..7c4578f365e0d 100644 --- a/frame/whitelist/src/tests.rs +++ b/frame/whitelist/src/tests.rs @@ -19,8 +19,13 @@ use crate::mock::*; use codec::Encode; -use frame_support::{assert_noop, assert_ok, dispatch::GetDispatchInfo, traits::PreimageProvider}; -use sp_runtime::{traits::Hash, DispatchError}; +use frame_support::{ + assert_noop, assert_ok, dispatch::GetDispatchInfo, traits::PreimageProvider, weights::Weight, +}; +use sp_runtime::{ + traits::{Hash, Zero}, + DispatchError, +}; #[test] fn test_whitelist_call_and_remove() { @@ -94,7 +99,11 @@ fn test_whitelist_call_and_execute() { assert!(Preimage::preimage_requested(&call_hash)); assert_noop!( - Whitelist::dispatch_whitelisted_call(Origin::root(), call_hash, call_weight - 1), + Whitelist::dispatch_whitelisted_call( + Origin::root(), + call_hash, + call_weight - Weight::from_computation(1) + ), crate::Error::::InvalidCallWeightWitness, ); @@ -114,7 +123,7 @@ fn test_whitelist_call_and_execute_failing_call() { new_test_ext().execute_with(|| { let call = Call::Whitelist(crate::Call::dispatch_whitelisted_call { call_hash: Default::default(), - call_weight_witness: 0, + call_weight_witness: Zero::zero(), }); let call_weight = call.get_dispatch_info().weight; let encoded_call = call.encode(); diff --git a/frame/whitelist/src/weights.rs b/frame/whitelist/src/weights.rs index b074cbf00d40d..d9cf1a579b31f 100644 --- a/frame/whitelist/src/weights.rs +++ b/frame/whitelist/src/weights.rs @@ -39,7 +39,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_whitelist. diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index aef061d952a96..767b503b78934 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -36,7 +36,7 @@ use cfg_if::cfg_if; use frame_support::{ parameter_types, traits::{ConstU32, ConstU64, CrateVersion, KeyOwnerProofSystem}, - weights::RuntimeDbWeight, + weights::{RuntimeDbWeight, Weight}, }; use frame_system::limits::{BlockLength, BlockWeights}; use sp_api::{decl_runtime_apis, impl_runtime_apis}; @@ -573,7 +573,10 @@ parameter_types! { pub RuntimeBlockLength: BlockLength = BlockLength::max(4 * 1024 * 1024); pub RuntimeBlockWeights: BlockWeights = - BlockWeights::with_sensible_defaults(4 * 1024 * 1024, Perbill::from_percent(75)); + BlockWeights::with_sensible_defaults(Weight::new() + .set_computation(4 * 1024 * 1024) + .set_bandwidth(5 * 1024 * 1024), + Perbill::from_percent(75)); } impl frame_system::Config for Runtime { diff --git a/utils/frame/benchmarking-cli/src/block/bench.rs b/utils/frame/benchmarking-cli/src/block/bench.rs index e48a7e8b3c6f5..87d8113018dd0 100644 --- a/utils/frame/benchmarking-cli/src/block/bench.rs +++ b/utils/frame/benchmarking-cli/src/block/bench.rs @@ -142,7 +142,7 @@ where let weight = ConsumedWeight::decode_all(&mut raw_weight)?; // Should be divisible, but still use floats in case we ever change that. - Ok((weight.total() as f64 / WEIGHT_PER_NANOS as f64).floor() as NanoSeconds) + Ok((weight.total().computation() as f64 / WEIGHT_PER_NANOS as f64).floor() as NanoSeconds) } /// Prints the weight info of a block to the console. diff --git a/utils/frame/benchmarking-cli/src/overhead/weights.hbs b/utils/frame/benchmarking-cli/src/overhead/weights.hbs index 6d3ae471d1cf2..938b697480f8a 100644 --- a/utils/frame/benchmarking-cli/src/overhead/weights.hbs +++ b/utils/frame/benchmarking-cli/src/overhead/weights.hbs @@ -30,7 +30,7 @@ use frame_support::{ parameter_types, - weights::{constants::WEIGHT_PER_NANOS, Weight}, + weights::{constants::WEIGHT_PER_NANOS, ComputationWeight as Weight}, }; parameter_types! { diff --git a/utils/frame/benchmarking-cli/src/pallet/template.hbs b/utils/frame/benchmarking-cli/src/pallet/template.hbs index ea734e165919a..04a5a0f8105e9 100644 --- a/utils/frame/benchmarking-cli/src/pallet/template.hbs +++ b/utils/frame/benchmarking-cli/src/pallet/template.hbs @@ -14,7 +14,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::Weight}; +use frame_support::{traits::Get, weights::{ComputationWeight as Weight}; use sp_std::marker::PhantomData; /// Weight functions for `{{pallet}}`.