Introduce BlockExecutionWeight and ExtrinsicBaseWeight (#5722)

* Introduce `BlockExectionWeight` and `ExtrinsicBaseWeight`

* Add new traits everywhere

* Missed one update

* fix tests

* Update `check_weight` logic

* introduce `max_extrinsic_weight` function

* fix + add tests

* format nits

* remove println

* make test a bit more clear

* Remove minimum weight

* newlines left over from find/replace

* Fix test, improve clarity

* Fix executor tests

* Extrinsic base weight same as old `MINIMUM_WEIGHT`

* fix example test

* Expose constants

* Add test for full block with operational and normal

* Initiate test environment with `BlockExecutionWeight` weight

* format nit

* Update frame/system/src/lib.rs

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

* Replace `TransactionBaseFee` with `ExtrinsicBaseWeight` (#5761)

* Replace `TransactionBaseFee` with `ExtrinsicBaseFee`

* Fix stuff

* Fix and make tests better

* Forgot to update this test

* Fix priority number in test

* Remove minimum weight from merge

* Fix weight in contracts

* remove `TransactionBaseFee` from contract tests

* Let `register_extra_weight_unchecked` go past `MaximumBlockWeight`

* address feedback

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
This commit is contained in:
Shawn Tabrizi
2020-04-25 07:59:54 +02:00
committed by GitHub
parent 3793fbf9cc
commit 8a33c297b4
74 changed files with 518 additions and 301 deletions
@@ -10,7 +10,6 @@
/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs
use frame_support::{decl_module, decl_storage, decl_event, decl_error, dispatch};
use frame_support::weights::MINIMUM_WEIGHT;
use frame_system::{self as system, ensure_signed};
#[cfg(test)]
@@ -76,7 +75,7 @@ decl_module! {
/// Just a dummy entry point.
/// function that can be called by the external world as an extrinsics call
/// takes a parameter of the type `AccountId`, stores it, and emits an event
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn do_something(origin, something: u32) -> dispatch::DispatchResult {
// Check it was signed and get the signer. See also: ensure_root and ensure_none
let who = ensure_signed(origin)?;
@@ -92,7 +91,7 @@ decl_module! {
/// Another dummy entry point.
/// takes no parameters, attempts to increment storage value, and possibly throws an error
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn cause_error(origin) -> dispatch::DispatchResult {
// Check it was signed and get the signer. See also: ensure_root and ensure_none
let _who = ensure_signed(origin)?;
@@ -37,6 +37,8 @@ impl system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
@@ -123,6 +123,7 @@ parameter_types! {
pub const BlockHashCount: BlockNumber = 250;
/// We allow for 2 seconds of compute with a 6 second average block time.
pub const MaximumBlockWeight: Weight = 2_000_000_000_000;
pub const ExtrinsicBaseWeight: Weight = 10_000_000;
pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);
pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;
pub const Version: RuntimeVersion = VERSION;
@@ -161,6 +162,12 @@ impl system::Trait for Runtime {
type MaximumBlockWeight = MaximumBlockWeight;
/// The weight of database operations that the runtime can invoke.
type DbWeight = DbWeight;
/// The weight of the overhead invoked on the block import process, independent of the
/// extrinsics included in that block.
type BlockExecutionWeight = ();
/// The base weight of any extrinsic processed by the runtime, independent of the
/// logic of that extrinsic. (Signature verification, nonce increment, fee, etc...)
type ExtrinsicBaseWeight = ExtrinsicBaseWeight;
/// Maximum size of all encoded transactions (in bytes) that are allowed in one block.
type MaximumBlockLength = MaximumBlockLength;
/// Portion of the block weight that is available to all normal transactions.
@@ -213,14 +220,12 @@ impl balances::Trait for Runtime {
}
parameter_types! {
pub const TransactionBaseFee: Balance = 0;
pub const TransactionByteFee: Balance = 1;
}
impl transaction_payment::Trait for Runtime {
type Currency = balances::Module<Runtime>;
type OnTransactionPayment = ();
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = ConvertInto;
type FeeMultiplierUpdate = ();
+6 -6
View File
@@ -33,7 +33,7 @@ use frame_system::{self, EventRecord, Phase};
use node_runtime::{
Header, Block, UncheckedExtrinsic, CheckedExtrinsic, Call, Runtime, Balances,
System, TransactionPayment, Event, TransactionBaseFee, TransactionByteFee,
System, TransactionPayment, Event, TransactionByteFee, ExtrinsicBaseWeight,
constants::currency::*,
};
use node_primitives::{Balance, Hash};
@@ -54,11 +54,11 @@ pub const BLOATY_CODE: &[u8] = node_runtime::WASM_BINARY_BLOATY;
fn transfer_fee<E: Encode>(extrinsic: &E, fee_multiplier: Fixed128) -> Balance {
let length_fee = TransactionByteFee::get() * (extrinsic.encode().len() as Balance);
let base_weight = ExtrinsicBaseWeight::get();
let base_fee = <Runtime as pallet_transaction_payment::Trait>::WeightToFee::convert(base_weight);
let weight = default_transfer_call().get_dispatch_info().weight;
let weight_fee = <Runtime as pallet_transaction_payment::Trait>
::WeightToFee::convert(weight);
let weight_fee = <Runtime as pallet_transaction_payment::Trait>::WeightToFee::convert(weight);
let base_fee = TransactionBaseFee::get();
base_fee + fee_multiplier.saturated_multiply_accumulate(length_fee + weight_fee)
}
@@ -338,7 +338,7 @@ fn full_native_block_import_works() {
EventRecord {
phase: Phase::ApplyExtrinsic(0),
event: Event::frame_system(frame_system::RawEvent::ExtrinsicSuccess(
DispatchInfo { weight: 10_000_000, class: DispatchClass::Mandatory, ..Default::default() }
DispatchInfo { weight: 0, class: DispatchClass::Mandatory, ..Default::default() }
)),
topics: vec![],
},
@@ -391,7 +391,7 @@ fn full_native_block_import_works() {
EventRecord {
phase: Phase::ApplyExtrinsic(0),
event: Event::frame_system(frame_system::RawEvent::ExtrinsicSuccess(
DispatchInfo { weight: 10_000_000, class: DispatchClass::Mandatory, pays_fee: Pays::Yes }
DispatchInfo { weight: 0, class: DispatchClass::Mandatory, pays_fee: Pays::Yes }
)),
topics: vec![],
},
+8 -5
View File
@@ -23,9 +23,9 @@ use frame_support::{
use sp_core::{NeverNativeValue, map, storage::Storage};
use sp_runtime::{Fixed128, Perbill, traits::{Convert, BlakeTwo256}};
use node_runtime::{
CheckedExtrinsic, Call, Runtime, Balances, TransactionPayment, TransactionBaseFee,
CheckedExtrinsic, Call, Runtime, Balances, TransactionPayment,
TransactionByteFee, WeightFeeCoefficient,
constants::currency::*,
constants::currency::*, ExtrinsicBaseWeight,
};
use node_runtime::impls::LinearWeightToFee;
use node_primitives::Balance;
@@ -173,15 +173,17 @@ fn transaction_fee_is_correct_ultimate() {
t.execute_with(|| {
assert_eq!(Balances::total_balance(&bob()), (10 + 69) * DOLLARS);
// Components deducted from alice's balances:
// - Base fee
// - Weight fee
// - Length fee
// - Tip
// - Creation-fee of bob's account.
let mut balance_alice = (100 - 69) * DOLLARS;
let length_fee = TransactionBaseFee::get() +
TransactionByteFee::get() *
(xt.clone().encode().len() as Balance);
let base_weight = ExtrinsicBaseWeight::get();
let base_fee = LinearWeightToFee::<WeightFeeCoefficient>::convert(base_weight);
let length_fee = TransactionByteFee::get() * (xt.clone().encode().len() as Balance);
balance_alice -= length_fee;
let weight = default_transfer_call().get_dispatch_info().weight;
@@ -191,6 +193,7 @@ fn transaction_fee_is_correct_ultimate() {
// 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);
balance_alice -= base_fee;
balance_alice -= weight_fee;
balance_alice -= tip;
@@ -229,7 +229,7 @@ fn submitted_transaction_should_be_valid() {
let res = Executive::validate_transaction(source, extrinsic);
assert_eq!(res.unwrap(), ValidTransaction {
priority: 2_411_380_000_000,
priority: 1_411_390_000_000,
requires: vec![],
provides: vec![(address, 0).encode()],
longevity: 128,
+3 -2
View File
@@ -119,6 +119,7 @@ parameter_types! {
pub const BlockHashCount: BlockNumber = 250;
/// We allow for 2 seconds of compute with a 6 second average block time.
pub const MaximumBlockWeight: Weight = 2_000_000_000_000;
pub const ExtrinsicBaseWeight: Weight = 10_000_000;
pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;
pub const Version: RuntimeVersion = VERSION;
pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);
@@ -142,6 +143,8 @@ impl frame_system::Trait for Runtime {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = DbWeight;
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ExtrinsicBaseWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = Version;
@@ -214,7 +217,6 @@ impl pallet_balances::Trait for Runtime {
}
parameter_types! {
pub const TransactionBaseFee: Balance = 1 * CENTS;
pub const TransactionByteFee: Balance = 10 * MILLICENTS;
// In the Substrate node, a weight of 10_000_000 (smallest non-zero weight)
// is mapped to 10_000_000 units of fees, hence:
@@ -226,7 +228,6 @@ parameter_types! {
impl pallet_transaction_payment::Trait for Runtime {
type Currency = Balances;
type OnTransactionPayment = DealWithFees;
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = LinearWeightToFee<WeightFeeCoefficient>;
type FeeMultiplierUpdate = TargetedFeeAdjustment<TargetBlockFullness>;
+8 -7
View File
@@ -133,7 +133,6 @@
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::{Parameter, decl_module, decl_event, decl_storage, decl_error, ensure};
use frame_support::weights::MINIMUM_WEIGHT;
use sp_runtime::traits::{Member, AtLeast32Bit, Zero, StaticLookup};
use frame_system::{self as system, ensure_signed};
use sp_runtime::traits::One;
@@ -158,14 +157,14 @@ decl_module! {
/// Issue a new class of fungible assets. There are, and will only ever be, `total`
/// such assets and they'll all belong to the `origin` initially. It will have an
/// identifier `AssetId` instance: this will be specified in the `Issued` event.
///
///
/// # <weight>
/// - `O(1)`
/// - 1 storage mutation (codec `O(1)`).
/// - 2 storage writes (condec `O(1)`).
/// - 1 event.
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn issue(origin, #[compact] total: T::Balance) {
let origin = ensure_signed(origin)?;
@@ -179,14 +178,14 @@ decl_module! {
}
/// Move some assets from one holder to another.
///
///
/// # <weight>
/// - `O(1)`
/// - 1 static lookup
/// - 2 storage mutations (codec `O(1)`).
/// - 1 event.
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn transfer(origin,
#[compact] id: T::AssetId,
target: <T::Lookup as StaticLookup>::Source,
@@ -205,14 +204,14 @@ decl_module! {
}
/// Destroy any assets of `id` owned by `origin`.
///
///
/// # <weight>
/// - `O(1)`
/// - 1 storage mutation (codec `O(1)`).
/// - 1 storage deletion (codec `O(1)`).
/// - 1 event.
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn destroy(origin, #[compact] id: T::AssetId) {
let origin = ensure_signed(origin)?;
let balance = <Balances<T>>::take((id, &origin));
@@ -315,6 +314,8 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
type Version = ();
+2
View File
@@ -58,6 +58,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
type Version = ();
@@ -155,6 +155,8 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
type Version = ();
+5 -3
View File
@@ -27,7 +27,7 @@ use frame_support::traits::{FindAuthor, VerifySeal, Get};
use codec::{Encode, Decode};
use frame_system::ensure_none;
use sp_runtime::traits::{Header as HeaderT, One, Zero};
use frame_support::weights::{Weight, MINIMUM_WEIGHT, DispatchClass};
use frame_support::weights::{Weight, DispatchClass};
use sp_inherents::{InherentIdentifier, ProvideInherent, InherentData};
use sp_authorship::{INHERENT_IDENTIFIER, UnclesInherentData, InherentError};
@@ -197,7 +197,7 @@ decl_module! {
T::EventHandler::note_author(Self::author());
MINIMUM_WEIGHT
0
}
fn on_finalize() {
@@ -207,7 +207,7 @@ decl_module! {
}
/// Provide a set of uncles.
#[weight = (MINIMUM_WEIGHT, DispatchClass::Mandatory)]
#[weight = (0, DispatchClass::Mandatory)]
fn set_uncles(origin, new_uncles: Vec<T::Header>) -> dispatch::DispatchResult {
ensure_none(origin)?;
ensure!(new_uncles.len() <= MAX_UNCLES, Error::<T>::TooManyUncles);
@@ -430,6 +430,8 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
type Version = ();
+2 -2
View File
@@ -25,7 +25,7 @@ use pallet_timestamp;
use sp_std::{result, prelude::*};
use frame_support::{
decl_storage, decl_module, traits::{FindAuthor, Get, Randomness as RandomnessT},
weights::{Weight, MINIMUM_WEIGHT},
weights::Weight,
};
use sp_timestamp::OnTimestampSet;
use sp_runtime::{generic::DigestItem, ConsensusEngineId, Perbill};
@@ -184,7 +184,7 @@ decl_module! {
fn on_initialize(now: T::BlockNumber) -> Weight {
Self::do_initialize(now);
MINIMUM_WEIGHT
0
}
/// Block finalization
+2
View File
@@ -69,6 +69,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
type ModuleToIndex = ();
+2
View File
@@ -847,6 +847,8 @@ impl<T: Subtrait<I>, I: Instance> frame_system::Trait for ElevatedTrait<T, I> {
type BlockHashCount = T::BlockHashCount;
type MaximumBlockWeight = T::MaximumBlockWeight;
type DbWeight = T::DbWeight;
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = T::MaximumBlockLength;
type AvailableBlockRatio = T::AvailableBlockRatio;
type Version = T::Version;
@@ -68,6 +68,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
@@ -77,13 +79,11 @@ impl frame_system::Trait for Test {
type OnKilledAccount = ();
}
parameter_types! {
pub const TransactionBaseFee: u64 = 0;
pub const TransactionByteFee: u64 = 1;
}
impl pallet_transaction_payment::Trait for Test {
type Currency = Module<Test>;
type OnTransactionPayment = ();
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = ConvertInto;
type FeeMultiplierUpdate = ();
+2 -2
View File
@@ -68,6 +68,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
@@ -77,13 +79,11 @@ impl frame_system::Trait for Test {
type OnKilledAccount = Module<Test>;
}
parameter_types! {
pub const TransactionBaseFee: u64 = 0;
pub const TransactionByteFee: u64 = 1;
}
impl pallet_transaction_payment::Trait for Test {
type Currency = Module<Test>;
type OnTransactionPayment = ();
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = ConvertInto;
type FeeMultiplierUpdate = ();
+13 -14
View File
@@ -21,7 +21,6 @@
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::{decl_module, decl_storage, decl_event, decl_error};
use frame_support::weights::MINIMUM_WEIGHT;
use frame_support::traits::Currency;
use frame_system::{self as system, ensure_signed};
use codec::{Encode, Decode};
@@ -71,7 +70,7 @@ decl_module! {
fn deposit_event() = default;
/// Do nothing.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn do_nothing(_origin, input: u32) {
if input > 0 {
return Ok(());
@@ -83,7 +82,7 @@ decl_module! {
/// storage database, however, the `repeat` calls will all pull from the
/// storage overlay cache. You must consider this when analyzing the
/// results of the benchmark.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn read_value(_origin, repeat: u32) {
for _ in 0..repeat {
MyValue::get();
@@ -91,7 +90,7 @@ decl_module! {
}
/// Put a value into a storage value.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn put_value(_origin, repeat: u32) {
for r in 0..repeat {
MyValue::put(r);
@@ -103,7 +102,7 @@ decl_module! {
/// storage database, however, the `repeat` calls will all pull from the
/// storage overlay cache. You must consider this when analyzing the
/// results of the benchmark.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn exists_value(_origin, repeat: u32) {
for _ in 0..repeat {
MyValue::exists();
@@ -111,7 +110,7 @@ decl_module! {
}
/// Remove a value from storage `repeat` number of times.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn remove_value(_origin, repeat: u32) {
for r in 0..repeat {
MyMap::remove(r);
@@ -119,7 +118,7 @@ decl_module! {
}
/// Read a value from storage map `repeat` number of times.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn read_map(_origin, repeat: u32) {
for r in 0..repeat {
MyMap::get(r);
@@ -127,7 +126,7 @@ decl_module! {
}
/// Insert a value into a map.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn insert_map(_origin, repeat: u32) {
for r in 0..repeat {
MyMap::insert(r, r);
@@ -135,7 +134,7 @@ decl_module! {
}
/// Check is a map contains a value `repeat` number of times.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn contains_key_map(_origin, repeat: u32) {
for r in 0..repeat {
MyMap::contains_key(r);
@@ -143,7 +142,7 @@ decl_module! {
}
/// Read a value from storage `repeat` number of times.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn remove_prefix(_origin, repeat: u32) {
for r in 0..repeat {
MyDoubleMap::remove_prefix(r);
@@ -151,21 +150,21 @@ decl_module! {
}
/// Add user to the list.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn add_member_list(origin) {
let who = ensure_signed(origin)?;
MyMemberList::<T>::mutate(|x| x.push(who));
}
/// Append user to the list.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn append_member_list(origin) {
let who = ensure_signed(origin)?;
MyMemberList::<T>::append(&[who])?;
}
/// Encode a vector of accounts to bytes.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn encode_accounts(_origin, accounts: Vec<T::AccountId>) {
let bytes = accounts.encode();
@@ -177,7 +176,7 @@ decl_module! {
}
/// Decode bytes into a vector of accounts.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn decode_accounts(_origin, bytes: Vec<u8>) {
let accounts: Vec<T::AccountId> = Decode::decode(&mut bytes.as_slice()).map_err(|_| "Could not decode")?;
+4 -3
View File
@@ -24,7 +24,6 @@ use sp_std::prelude::*;
use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::{H256, Header}};
use frame_support::{
dispatch::DispatchResult,
weights::MINIMUM_WEIGHT,
decl_module, decl_storage, impl_outer_origin, assert_ok, assert_err, ensure
};
use frame_system::{RawOrigin, ensure_signed, ensure_none};
@@ -37,14 +36,14 @@ decl_storage! {
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn set_value(origin, n: u32) -> DispatchResult {
let _sender = ensure_signed(origin)?;
Value::put(n);
Ok(())
}
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn dummy(origin, _n: u32) -> DispatchResult {
let _sender = ensure_none(origin)?;
Ok(())
@@ -80,6 +79,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = ();
type MaximumBlockWeight = ();
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = ();
type AvailableBlockRatio = ();
type Version = ();
+2
View File
@@ -554,6 +554,8 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
+5 -8
View File
@@ -112,7 +112,6 @@ use sp_runtime::{
use frame_support::dispatch::{
PostDispatchInfo, DispatchResult, Dispatchable, DispatchResultWithPostInfo
};
use frame_support::weights::MINIMUM_WEIGHT;
use frame_support::{
Parameter, decl_module, decl_event, decl_storage, decl_error,
parameter_types, IsSubType, storage::child::{self, ChildInfo},
@@ -453,7 +452,7 @@ decl_module! {
/// Updates the schedule for metering contracts.
///
/// The schedule must have a greater version than the stored schedule.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn update_schedule(origin, schedule: Schedule) -> DispatchResult {
ensure_root(origin)?;
if <Module<T>>::current_schedule().version >= schedule.version {
@@ -469,7 +468,7 @@ decl_module! {
/// Stores the given binary Wasm code into the chain's storage and returns its `codehash`.
/// You can instantiate contracts only with stored code.
#[weight = FunctionOf(
|args: (&Vec<u8>,)| Module::<T>::calc_code_put_costs(args.0) + MINIMUM_WEIGHT,
|args: (&Vec<u8>,)| Module::<T>::calc_code_put_costs(args.0),
DispatchClass::Normal,
Pays::Yes
)]
@@ -494,8 +493,7 @@ decl_module! {
/// * 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.
#[weight = FunctionOf(
|args: (&<T::Lookup as StaticLookup>::Source, &BalanceOf<T>, &Weight, &Vec<u8>)|
args.2 + MINIMUM_WEIGHT,
|args: (&<T::Lookup as StaticLookup>::Source, &BalanceOf<T>, &Weight, &Vec<u8>)| *args.2,
DispatchClass::Normal,
Pays::Yes
)]
@@ -527,7 +525,7 @@ decl_module! {
/// upon any call received by this account.
/// - The contract is initialized.
#[weight = FunctionOf(
|args: (&BalanceOf<T>, &Weight, &CodeHash<T>, &Vec<u8>)| args.1 + MINIMUM_WEIGHT,
|args: (&BalanceOf<T>, &Weight, &CodeHash<T>, &Vec<u8>)| *args.1,
DispatchClass::Normal,
Pays::Yes
)]
@@ -553,7 +551,7 @@ decl_module! {
///
/// If contract is not evicted as a result of this call, no actions are taken and
/// the sender is not eligible for the reward.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn claim_surcharge(origin, dest: T::AccountId, aux_sender: Option<T::AccountId>) {
let origin = origin.into();
let (signed, rewarded) = match (origin, aux_sender) {
@@ -970,4 +968,3 @@ impl Default for Schedule {
}
}
}
+2 -2
View File
@@ -101,6 +101,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
type Version = ();
@@ -136,7 +138,6 @@ parameter_types! {
}
parameter_types! {
pub const TransactionBaseFee: u64 = 0;
pub const TransactionByteFee: u64 = 0;
}
@@ -149,7 +150,6 @@ impl Convert<Weight, BalanceOf<Self>> for Test {
impl pallet_transaction_payment::Trait for Test {
type Currency = Balances;
type OnTransactionPayment = ();
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = Test;
type FeeMultiplierUpdate = ();
+12 -12
View File
@@ -171,7 +171,7 @@ use sp_runtime::{
use codec::{Ref, Encode, Decode};
use frame_support::{
decl_module, decl_storage, decl_event, decl_error, ensure, Parameter,
weights::{Weight, MINIMUM_WEIGHT, DispatchClass},
weights::{Weight, DispatchClass},
traits::{
Currency, ReservableCurrency, LockableCurrency, WithdrawReason, LockIdentifier, Get,
OnUnbalanced, BalanceStatus, schedule::Named as ScheduleNamed, EnsureOrigin
@@ -528,7 +528,7 @@ decl_module! {
fn on_runtime_upgrade() -> Weight {
Self::migrate();
MINIMUM_WEIGHT
0
}
/// Propose a sensitive action to be taken.
@@ -820,7 +820,7 @@ decl_module! {
/// # <weight>
/// - `O(1)`.
/// # </weight>
#[weight = (MINIMUM_WEIGHT, DispatchClass::Operational)]
#[weight = (0, DispatchClass::Operational)]
fn cancel_referendum(origin, #[compact] ref_index: ReferendumIndex) {
ensure_root(origin)?;
Self::internal_cancel_referendum(ref_index);
@@ -836,7 +836,7 @@ decl_module! {
/// - One DB change.
/// - O(d) where d is the items in the dispatch queue.
/// # </weight>
#[weight = (MINIMUM_WEIGHT, DispatchClass::Operational)]
#[weight = (0, DispatchClass::Operational)]
fn cancel_queued(origin, which: ReferendumIndex) {
ensure_root(origin)?;
T::Scheduler::cancel_named((DEMOCRACY_ID, which))
@@ -848,7 +848,7 @@ decl_module! {
sp_runtime::print(e);
}
MINIMUM_WEIGHT
0
}
/// Specify a proxy that is already open to us. Called by the stash.
@@ -975,7 +975,7 @@ decl_module! {
/// - `O(1)`.
/// - One DB clear.
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn clear_public_proposals(origin) {
ensure_root(origin)?;
@@ -1066,7 +1066,7 @@ decl_module! {
/// # <weight>
/// - One DB clear.
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn reap_preimage(origin, proposal_hash: T::Hash) {
let who = ensure_signed(origin)?;
let (provider, deposit, since, expiry) = <Preimages<T>>::get(&proposal_hash)
@@ -1096,7 +1096,7 @@ decl_module! {
/// # <weight>
/// - `O(1)`.
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn unlock(origin, target: T::AccountId) {
ensure_signed(origin)?;
Self::update_lock(&target);
@@ -1154,7 +1154,7 @@ decl_module! {
/// # <weight>
/// - `O(R + log R)` where R is the number of referenda that `target` has voted on.
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn remove_vote(origin, index: ReferendumIndex) -> DispatchResult {
let who = ensure_signed(origin)?;
Self::try_remove_vote(&who, index, UnvoteScope::Any)
@@ -1176,7 +1176,7 @@ decl_module! {
/// # <weight>
/// - `O(R + log R)` where R is the number of referenda that `target` has voted on.
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn remove_other_vote(origin, target: T::AccountId, index: ReferendumIndex) -> DispatchResult {
let who = ensure_signed(origin)?;
let scope = if target == who { UnvoteScope::Any } else { UnvoteScope::OnlyExpired };
@@ -1251,7 +1251,7 @@ decl_module! {
/// # <weight>
/// - `O(R + log R)` where R is the number of referenda that `target` has voted on.
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn proxy_remove_vote(origin, index: ReferendumIndex) -> DispatchResult {
let who = ensure_signed(origin)?;
let target = Self::proxy(who).and_then(|a| a.as_active()).ok_or(Error::<T>::NotProxy)?;
@@ -1259,7 +1259,7 @@ decl_module! {
}
/// Enact a proposal from a referendum. For now we just make the weight be the maximum.
#[weight = Weight::max_value()]
#[weight = frame_system::Module::<T>::max_extrinsic_weight(DispatchClass::Normal)]
fn enact_proposal(origin, proposal_hash: T::Hash, index: ReferendumIndex) -> DispatchResult {
ensure_root(origin)?;
Self::do_enact_proposal(proposal_hash, index)
+2
View File
@@ -95,6 +95,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
@@ -88,7 +88,7 @@ use sp_runtime::{
};
use frame_support::{
decl_storage, decl_event, ensure, decl_module, decl_error,
weights::{Weight, MINIMUM_WEIGHT, DispatchClass},
weights::{Weight, DispatchClass},
storage::{StorageMap, IterableStorageMap},
traits::{
Currency, Get, LockableCurrency, LockIdentifier, ReservableCurrency, WithdrawReasons,
@@ -269,7 +269,7 @@ decl_module! {
fn on_runtime_upgrade() -> Weight {
migration::migrate::<T>();
MINIMUM_WEIGHT
0
}
const CandidacyBond: BalanceOf<T> = T::CandidacyBond::get();
@@ -339,7 +339,7 @@ decl_module! {
/// Reads: O(1)
/// Writes: O(1)
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn remove_voter(origin) {
let who = ensure_signed(origin)?;
@@ -513,7 +513,7 @@ decl_module! {
print(e);
}
MINIMUM_WEIGHT
0
}
}
}
@@ -915,6 +915,8 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
+6 -6
View File
@@ -30,7 +30,7 @@ use sp_runtime::{
};
use frame_support::{
decl_storage, decl_event, ensure, decl_module, decl_error,
weights::{Weight, MINIMUM_WEIGHT, DispatchClass},
weights::{Weight, DispatchClass},
traits::{
Currency, ExistenceRequirement, Get, LockableCurrency, LockIdentifier, BalanceStatus,
OnUnbalanced, ReservableCurrency, WithdrawReason, WithdrawReasons, ChangeMembers,
@@ -662,7 +662,7 @@ decl_module! {
/// Set the desired member count; if lower than the current count, then seats will not be up
/// election when they expire. If more, then a new vote will be started if one is not
/// already in progress.
#[weight = (MINIMUM_WEIGHT, DispatchClass::Operational)]
#[weight = (0, DispatchClass::Operational)]
fn set_desired_seats(origin, #[compact] count: u32) {
ensure_root(origin)?;
DesiredSeats::put(count);
@@ -672,7 +672,7 @@ decl_module! {
///
/// Note: A tally should happen instantly (if not already in a presentation
/// period) to fill the seat if removal means that the desired members are not met.
#[weight = (MINIMUM_WEIGHT, DispatchClass::Operational)]
#[weight = (0, DispatchClass::Operational)]
fn remove_member(origin, who: <T::Lookup as StaticLookup>::Source) {
ensure_root(origin)?;
let who = T::Lookup::lookup(who)?;
@@ -687,7 +687,7 @@ decl_module! {
/// Set the presentation duration. If there is currently a vote being presented for, will
/// invoke `finalize_vote`.
#[weight = (MINIMUM_WEIGHT, DispatchClass::Operational)]
#[weight = (0, DispatchClass::Operational)]
fn set_presentation_duration(origin, #[compact] count: T::BlockNumber) {
ensure_root(origin)?;
<PresentationDuration<T>>::put(count);
@@ -695,7 +695,7 @@ decl_module! {
/// Set the presentation duration. If there is current a vote being presented for, will
/// invoke `finalize_vote`.
#[weight = (MINIMUM_WEIGHT, DispatchClass::Operational)]
#[weight = (0, DispatchClass::Operational)]
fn set_term_duration(origin, #[compact] count: T::BlockNumber) {
ensure_root(origin)?;
<TermDuration<T>>::put(count);
@@ -706,7 +706,7 @@ decl_module! {
print("Guru meditation");
print(e);
}
MINIMUM_WEIGHT
0
}
}
}
+2
View File
@@ -51,6 +51,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
+4 -4
View File
@@ -25,7 +25,7 @@ pub use crate::backend::{Account, Log, Vicinity, Backend};
use sp_std::{vec::Vec, marker::PhantomData};
use frame_support::{ensure, decl_module, decl_storage, decl_event, decl_error};
use frame_support::weights::{Weight, MINIMUM_WEIGHT, DispatchClass, FunctionOf, Pays};
use frame_support::weights::{Weight, DispatchClass, FunctionOf, Pays};
use frame_support::traits::{Currency, WithdrawReason, ExistenceRequirement, Get};
use frame_system::{self as system, ensure_signed};
use sp_runtime::ModuleId;
@@ -188,11 +188,11 @@ decl_module! {
type Error = Error<T>;
fn deposit_event() = default;
const ModuleId: ModuleId = T::ModuleId::get();
/// Deposit balance from currency/balances module into EVM.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn deposit_balance(origin, value: BalanceOf<T>) {
let sender = ensure_signed(origin)?;
@@ -213,7 +213,7 @@ decl_module! {
}
/// Withdraw balance from EVM into currency/balances module.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn withdraw_balance(origin, value: BalanceOf<T>) {
let sender = ensure_signed(origin)?;
let address = T::ConvertAccountId::convert_account_id(&sender);
@@ -53,7 +53,6 @@ use frame_support::{
debug,
dispatch::DispatchResult, decl_module, decl_storage, decl_event,
traits::Get,
weights::MINIMUM_WEIGHT,
};
use sp_core::crypto::KeyTypeId;
use sp_runtime::{
@@ -189,7 +188,7 @@ decl_module! {
/// working and receives (and provides) meaningful data.
/// This example is not focused on correctness of the oracle itself, but rather its
/// purpose is to showcase offchain worker capabilities.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn submit_price(origin, price: u32) -> DispatchResult {
// Retrieve sender of the transaction.
let who = ensure_signed(origin)?;
@@ -214,7 +213,7 @@ decl_module! {
///
/// This example is not focused on correctness of the oracle itself, but rather its
/// purpose is to showcase offchain worker capabilities.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn submit_price_unsigned(origin, _block_number: T::BlockNumber, price: u32)
-> DispatchResult
{
@@ -228,7 +227,7 @@ decl_module! {
Ok(())
}
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn submit_price_unsigned_with_signed_payload(
origin,
price_payload: PricePayload<T::Public, T::BlockNumber>,
@@ -66,6 +66,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
+6 -4
View File
@@ -256,7 +256,7 @@
use sp_std::marker::PhantomData;
use frame_support::{
dispatch::DispatchResult, decl_module, decl_storage, decl_event,
weights::{DispatchClass, ClassifyDispatch, WeighData, Weight, PaysFee, MINIMUM_WEIGHT, Pays},
weights::{DispatchClass, ClassifyDispatch, WeighData, Weight, PaysFee, Pays},
};
use sp_std::prelude::*;
use frame_system::{self as system, ensure_signed, ensure_root};
@@ -466,7 +466,7 @@ decl_module! {
// weight (a numeric representation of pure execution time and difficulty) of the
// transaction and the latter demonstrates the [`DispatchClass`] of the call. A higher
// weight means a larger transaction (less of which can be placed in a single block).
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn accumulate_dummy(origin, increase_by: T::Balance) -> DispatchResult {
// This is a public call, so we ensure that the origin is some signed account.
let _sender = ensure_signed(origin)?;
@@ -520,7 +520,7 @@ decl_module! {
// Anything that needs to be done at the start of the block.
// We don't do anything here.
MINIMUM_WEIGHT
0
}
// The signature could also look like: `fn on_finalize()`
@@ -751,6 +751,8 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
@@ -845,7 +847,7 @@ mod tests {
let default_call = <Call<Test>>::accumulate_dummy(10);
let info = default_call.get_dispatch_info();
// aka. `let info = <Call<Test> as GetDispatchInfo>::get_dispatch_info(&default_call);`
assert_eq!(info.weight, 10_000_000);
assert_eq!(info.weight, 0);
// must have a custom weight of `100 * arg = 2000`
let custom_call = <Call<Test>>::set_dummy(20);
+47 -28
View File
@@ -192,8 +192,9 @@ where
frame_system::InitKind::Full,
);
<frame_system::Module<System> as OnInitialize<System::BlockNumber>>::on_initialize(*block_number);
let weight = <AllModules as OnInitialize<System::BlockNumber>>::on_initialize(*block_number);
<frame_system::Module<System>>::register_extra_weight_unchecked(weight);
let weight = <AllModules as OnInitialize<System::BlockNumber>>::on_initialize(*block_number)
.saturating_add(<System::BlockExecutionWeight as frame_support::traits::Get<_>>::get());
<frame_system::Module::<System>>::register_extra_weight_unchecked(weight);
frame_system::Module::<System>::note_finished_initialize();
}
@@ -398,12 +399,12 @@ mod tests {
use sp_core::H256;
use sp_runtime::{
generic::Era, Perbill, DispatchError, testing::{Digest, Header, Block},
traits::{Header as HeaderT, BlakeTwo256, IdentityLookup, ConvertInto},
traits::{Header as HeaderT, BlakeTwo256, IdentityLookup, Convert, ConvertInto},
transaction_validity::{InvalidTransaction, UnknownTransaction, TransactionValidityError},
};
use frame_support::{
impl_outer_event, impl_outer_origin, parameter_types, impl_outer_dispatch,
weights::Weight,
weights::{Weight, RuntimeDbWeight},
traits::{Currency, LockIdentifier, LockableCurrency, WithdrawReasons, WithdrawReason},
};
use frame_system::{self as system, Call as SystemCall, ChainContext, LastRuntimeUpgradeInfo};
@@ -475,6 +476,12 @@ mod tests {
pub const MaximumBlockWeight: Weight = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
pub const BlockExecutionWeight: Weight = 10;
pub const ExtrinsicBaseWeight: Weight = 5;
pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight {
read: 10,
write: 100,
};
}
impl frame_system::Trait for Runtime {
type Origin = Origin;
@@ -489,20 +496,24 @@ mod tests {
type Event = MetaEvent;
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type DbWeight = DbWeight;
type BlockExecutionWeight = BlockExecutionWeight;
type ExtrinsicBaseWeight = ExtrinsicBaseWeight;
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
type Version = RuntimeVersion;
type ModuleToIndex = ();
type AccountData = pallet_balances::AccountData<u64>;
type AccountData = pallet_balances::AccountData<Balance>;
type OnNewAccount = ();
type OnKilledAccount = ();
}
type Balance = u64;
parameter_types! {
pub const ExistentialDeposit: u64 = 1;
pub const ExistentialDeposit: Balance = 1;
}
impl pallet_balances::Trait for Runtime {
type Balance = u64;
type Balance = Balance;
type Event = MetaEvent;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
@@ -510,13 +521,11 @@ mod tests {
}
parameter_types! {
pub const TransactionBaseFee: u64 = 10;
pub const TransactionByteFee: u64 = 0;
pub const TransactionByteFee: Balance = 0;
}
impl pallet_transaction_payment::Trait for Runtime {
type Currency = Balances;
type OnTransactionPayment = ();
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = ConvertInto;
type FeeMultiplierUpdate = ();
@@ -563,7 +572,7 @@ mod tests {
type TestXt = sp_runtime::testing::TestXt<Call, SignedExtra>;
type Executive = super::Executive<Runtime, Block<TestXt>, ChainContext<Runtime>, Runtime, AllModules>;
fn extra(nonce: u64, fee: u64) -> SignedExtra {
fn extra(nonce: u64, fee: Balance) -> SignedExtra {
(
frame_system::CheckEra::from(Era::Immortal),
frame_system::CheckNonce::from(nonce),
@@ -572,7 +581,7 @@ mod tests {
)
}
fn sign_extra(who: u64, nonce: u64, fee: u64) -> Option<(u64, SignedExtra)> {
fn sign_extra(who: u64, nonce: u64, fee: Balance) -> Option<(u64, SignedExtra)> {
Some((who, extra(nonce, fee)))
}
@@ -583,7 +592,8 @@ mod tests {
balances: vec![(1, 211)],
}.assimilate_storage(&mut t).unwrap();
let xt = TestXt::new(Call::Balances(BalancesCall::transfer(2, 69)), sign_extra(1, 0, 0));
let weight = xt.get_dispatch_info().weight as u64;
let weight = xt.get_dispatch_info().weight + <Runtime as frame_system::Trait>::ExtrinsicBaseWeight::get();
let fee: Balance = <Runtime as pallet_transaction_payment::Trait>::WeightToFee::convert(weight);
let mut t = sp_io::TestExternalities::new(t);
t.execute_with(|| {
Executive::initialize_block(&Header::new(
@@ -595,12 +605,12 @@ mod tests {
));
let r = Executive::apply_extrinsic(xt);
assert!(r.is_ok());
assert_eq!(<pallet_balances::Module<Runtime>>::total_balance(&1), 142 - 10 - weight);
assert_eq!(<pallet_balances::Module<Runtime>>::total_balance(&1), 142 - fee);
assert_eq!(<pallet_balances::Module<Runtime>>::total_balance(&2), 69);
});
}
fn new_test_ext(balance_factor: u64) -> sp_io::TestExternalities {
fn new_test_ext(balance_factor: Balance) -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default().build_storage::<Runtime>().unwrap();
pallet_balances::GenesisConfig::<Runtime> {
balances: vec![(1, 111 * balance_factor)],
@@ -683,8 +693,10 @@ mod tests {
let xt = TestXt::new(Call::Balances(BalancesCall::transfer(33, 0)), sign_extra(1, 0, 0));
let encoded = xt.encode();
let encoded_len = encoded.len() as Weight;
let limit = AvailableBlockRatio::get() * MaximumBlockWeight::get() - 175;
let num_to_exhaust_block = limit / encoded_len;
// Block execution weight + on_initialize weight
let base_block_weight = 175 + <Runtime as frame_system::Trait>::BlockExecutionWeight::get();
let limit = AvailableBlockRatio::get() * MaximumBlockWeight::get() - base_block_weight;
let num_to_exhaust_block = limit / (encoded_len + 5);
t.execute_with(|| {
Executive::initialize_block(&Header::new(
1,
@@ -693,8 +705,8 @@ mod tests {
[69u8; 32].into(),
Digest::default(),
));
// Initial block weight form the custom module.
assert_eq!(<frame_system::Module<Runtime>>::all_extrinsics_weight(), 175);
// Base block execution weight + `on_initialize` weight from the custom module.
assert_eq!(<frame_system::Module<Runtime>>::all_extrinsics_weight(), base_block_weight);
for nonce in 0..=num_to_exhaust_block {
let xt = TestXt::new(
@@ -705,7 +717,8 @@ mod tests {
assert!(res.is_ok());
assert_eq!(
<frame_system::Module<Runtime>>::all_extrinsics_weight(),
encoded_len * (nonce + 1) + 175,
//--------------------- on_initialize + block_execution + extrinsic_base weight
(encoded_len + 5) * (nonce + 1) + base_block_weight,
);
assert_eq!(<frame_system::Module<Runtime>>::extrinsic_index(), Some(nonce as u32 + 1));
} else {
@@ -731,7 +744,10 @@ mod tests {
assert!(Executive::apply_extrinsic(x2.clone()).unwrap().is_ok());
// default weight for `TestXt` == encoded length.
assert_eq!(<frame_system::Module<Runtime>>::all_extrinsics_weight(), (3 * len) as Weight);
assert_eq!(
<frame_system::Module<Runtime>>::all_extrinsics_weight(),
3 * (len as Weight + <Runtime as frame_system::Trait>::ExtrinsicBaseWeight::get()),
);
assert_eq!(<frame_system::Module<Runtime>>::all_extrinsics_len(), 3 * len);
let _ = <frame_system::Module<Runtime>>::finalize();
@@ -761,7 +777,7 @@ mod tests {
let execute_with_lock = |lock: WithdrawReasons| {
let mut t = new_test_ext(1);
t.execute_with(|| {
<pallet_balances::Module<Runtime> as LockableCurrency<u64>>::set_lock(
<pallet_balances::Module<Runtime> as LockableCurrency<Balance>>::set_lock(
id,
&1,
110,
@@ -771,7 +787,9 @@ mod tests {
Call::System(SystemCall::remark(vec![1u8])),
sign_extra(1, 0, 0),
);
let weight = xt.get_dispatch_info().weight as u64;
let weight = xt.get_dispatch_info().weight
+ <Runtime as frame_system::Trait>::ExtrinsicBaseWeight::get();
let fee: Balance = <Runtime as pallet_transaction_payment::Trait>::WeightToFee::convert(weight);
Executive::initialize_block(&Header::new(
1,
H256::default(),
@@ -783,7 +801,7 @@ mod tests {
if lock == WithdrawReasons::except(WithdrawReason::TransactionPayment) {
assert!(Executive::apply_extrinsic(xt).unwrap().is_ok());
// tx fee has been deducted.
assert_eq!(<pallet_balances::Module<Runtime>>::total_balance(&1), 111 - 10 - weight);
assert_eq!(<pallet_balances::Module<Runtime>>::total_balance(&1), 111 - fee);
} else {
assert_eq!(
Executive::apply_extrinsic(xt),
@@ -803,9 +821,10 @@ mod tests {
new_test_ext(1).execute_with(|| {
Executive::initialize_block(&Header::new_from_number(1));
// NOTE: might need updates over time if system and balance introduce new weights. For
// now only accounts for the custom module.
assert_eq!(<frame_system::Module<Runtime>>::all_extrinsics_weight(), 150 + 25);
// 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!(<frame_system::Module<Runtime>>::all_extrinsics_weight(), 175 + 10);
})
}
+4 -2
View File
@@ -23,7 +23,7 @@ use sp_runtime::traits::{One, Zero, SaturatedConversion};
use sp_std::{prelude::*, result, cmp, vec};
use frame_support::{decl_module, decl_storage, decl_error, ensure};
use frame_support::traits::Get;
use frame_support::weights::{MINIMUM_WEIGHT, DispatchClass};
use frame_support::weights::{DispatchClass};
use frame_system::{ensure_none, Trait as SystemTrait};
use sp_finality_tracker::{INHERENT_IDENTIFIER, FinalizedInherentData};
@@ -77,7 +77,7 @@ decl_module! {
/// Hint that the author of this block thinks the best finalized
/// block is the given number.
#[weight = (MINIMUM_WEIGHT, DispatchClass::Mandatory)]
#[weight = (0, DispatchClass::Mandatory)]
fn final_hint(origin, #[compact] hint: T::BlockNumber) {
ensure_none(origin)?;
ensure!(!<Self as Store>::Update::exists(), Error::<T>::AlreadyUpdated);
@@ -264,6 +264,8 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
type Version = ();
+8 -7
View File
@@ -164,7 +164,6 @@ use sp_std::prelude::*;
use sp_std::{cmp, result, fmt::Debug};
use frame_support::{
decl_event, decl_module, decl_storage, ensure, decl_error,
weights::MINIMUM_WEIGHT,
traits::{
Currency, ExistenceRequirement, Imbalance, LockIdentifier, LockableCurrency, ReservableCurrency,
SignedImbalance, WithdrawReason, WithdrawReasons, TryDrop, BalanceStatus,
@@ -361,14 +360,14 @@ decl_module! {
fn deposit_event() = default;
/// Create a new kind of asset.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn create(origin, options: AssetOptions<T::Balance, T::AccountId>) -> DispatchResult {
let origin = ensure_signed(origin)?;
Self::create_asset(None, Some(origin), options)
}
/// Transfer some liquid free balance to another account.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn transfer(origin, #[compact] asset_id: T::AssetId, to: T::AccountId, #[compact] amount: T::Balance) {
let origin = ensure_signed(origin)?;
ensure!(!amount.is_zero(), Error::<T>::ZeroAmount);
@@ -378,7 +377,7 @@ decl_module! {
/// Updates permission for a given `asset_id` and an account.
///
/// The `origin` must have `update` permission.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn update_permission(
origin,
#[compact] asset_id: T::AssetId,
@@ -401,7 +400,7 @@ decl_module! {
/// Mints an asset, increases its total issuance.
/// The origin must have `mint` permissions.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn mint(origin, #[compact] asset_id: T::AssetId, to: T::AccountId, amount: T::Balance) -> DispatchResult {
let who = ensure_signed(origin)?;
Self::mint_free(&asset_id, &who, &to, &amount)?;
@@ -411,7 +410,7 @@ decl_module! {
/// Burns an asset, decreases its total issuance.
/// The `origin` must have `burn` permissions.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn burn(origin, #[compact] asset_id: T::AssetId, to: T::AccountId, amount: T::Balance) -> DispatchResult {
let who = ensure_signed(origin)?;
Self::burn_free(&asset_id, &who, &to, &amount)?;
@@ -421,7 +420,7 @@ decl_module! {
/// Can be used to create reserved tokens.
/// Requires Root call.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn create_reserved(
origin,
asset_id: T::AssetId,
@@ -1126,6 +1125,8 @@ impl<T: Subtrait> frame_system::Trait for ElevatedTrait<T> {
type BlockHashCount = T::BlockHashCount;
type MaximumBlockWeight = T::MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = T::MaximumBlockLength;
type AvailableBlockRatio = T::AvailableBlockRatio;
type Version = T::Version;
@@ -58,6 +58,8 @@ impl frame_system::Trait for Test {
type Event = TestEvent;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type BlockHashCount = BlockHashCount;
+1 -2
View File
@@ -33,7 +33,6 @@ pub use sp_finality_grandpa as fg_primitives;
use sp_std::prelude::*;
use codec::{self as codec, Encode, Decode};
use frame_support::{decl_event, decl_storage, decl_module, decl_error, storage};
use frame_support::weights::MINIMUM_WEIGHT;
use sp_runtime::{
DispatchResult, generic::{DigestItem, OpaqueDigestItemId}, traits::Zero, Perbill,
};
@@ -185,7 +184,7 @@ decl_module! {
fn deposit_event() = default;
/// Report some misbehavior.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn report_misbehavior(origin, _report: Vec<u8>) {
ensure_signed(origin)?;
// FIXME: https://github.com/paritytech/substrate/issues/1112
+2
View File
@@ -62,6 +62,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
+6 -4
View File
@@ -619,7 +619,7 @@ decl_module! {
/// - One balance reserve operation.
/// - One storage mutation (codec-read `O(X' + R)`, codec-write `O(X + R)`).
/// - One event.
/// - Benchmarks:
/// - Benchmarks:
/// - 136.6 + R * 0.62 + X * 2.62 µs (min squares analysis)
/// - 146.2 + R * 0.372 + X * 2.98 µs (min squares analysis)
/// # </weight>
@@ -684,7 +684,7 @@ decl_module! {
/// - One storage read (codec complexity `O(P)`).
/// - One storage write (codec complexity `O(S)`).
/// - One storage-exists (`IdentityOf::contains_key`).
/// - Benchmarks:
/// - Benchmarks:
/// - 115.2 + P * 5.11 + S * 6.67 µs (min squares analysis)
/// - 121 + P * 4.852 + S * 7.111 µs (min squares analysis)
/// # </weight>
@@ -748,7 +748,7 @@ decl_module! {
/// - One balance-unreserve operation.
/// - `2` storage reads and `S + 2` storage deletions.
/// - One event.
/// - Benchmarks:
/// - Benchmarks:
/// - 152.3 + R * 0.306 + S * 4.967 + X * 1.697 µs (min squares analysis)
/// - 139.5 + R * 0.466 + S * 5.304 + X * 1.895 µs (min squares analysis)
/// # </weight>
@@ -1167,6 +1167,8 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
@@ -1271,7 +1273,7 @@ mod tests {
}
let last_registrar = MaxRegistrars::get() as u64 + 1;
assert_noop!(
Identity::add_registrar(Origin::signed(1), last_registrar),
Identity::add_registrar(Origin::signed(1), last_registrar),
Error::<Test>::TooManyRegistrars
);
});
+2 -4
View File
@@ -43,7 +43,6 @@
//!
//! ```
//! use frame_support::{decl_module, dispatch};
//! use frame_support::weights::MINIMUM_WEIGHT;
//! use frame_system::{self as system, ensure_signed};
//! use pallet_im_online::{self as im_online};
//!
@@ -51,7 +50,7 @@
//!
//! decl_module! {
//! pub struct Module<T: Trait> for enum Call where origin: T::Origin {
//! #[weight = MINIMUM_WEIGHT]
//! #[weight = 0]
//! pub fn is_online(origin, authority_index: u32) -> dispatch::DispatchResult {
//! let _sender = ensure_signed(origin)?;
//! let _is_online = <im_online::Module<T>>::is_online(authority_index);
@@ -95,7 +94,6 @@ use sp_staking::{
use frame_support::{
decl_module, decl_event, decl_storage, Parameter, debug, decl_error,
traits::Get,
weights::MINIMUM_WEIGHT,
};
use frame_system::{self as system, ensure_none};
use frame_system::offchain::{
@@ -315,7 +313,7 @@ decl_module! {
fn deposit_event() = default;
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn heartbeat(
origin,
heartbeat: Heartbeat<T::BlockNumber>,
+2
View File
@@ -116,6 +116,8 @@ impl frame_system::Trait for Runtime {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
+6 -6
View File
@@ -25,7 +25,7 @@ use sp_runtime::traits::{
StaticLookup, Member, LookupError, Zero, One, BlakeTwo256, Hash, Saturating, AtLeast32Bit
};
use frame_support::{Parameter, decl_module, decl_error, decl_event, decl_storage, ensure};
use frame_support::weights::{Weight, MINIMUM_WEIGHT};
use frame_support::weights::Weight;
use frame_support::dispatch::DispatchResult;
use frame_support::traits::{Currency, ReservableCurrency, Get, BalanceStatus::Reserved};
use frame_support::storage::migration::take_storage_value;
@@ -102,7 +102,7 @@ decl_module! {
fn on_initialize() -> Weight {
Self::migrations();
MINIMUM_WEIGHT
0
}
/// Assign an previously unassigned index.
@@ -121,7 +121,7 @@ decl_module! {
/// - One reserve operation.
/// - One event.
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn claim(origin, index: T::AccountIndex) {
let who = ensure_signed(origin)?;
@@ -149,7 +149,7 @@ decl_module! {
/// - One transfer operation.
/// - One event.
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn transfer(origin, new: T::AccountId, index: T::AccountIndex) {
let who = ensure_signed(origin)?;
ensure!(who != new, Error::<T>::NotTransfer);
@@ -180,7 +180,7 @@ decl_module! {
/// - One reserve operation.
/// - One event.
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn free(origin, index: T::AccountIndex) {
let who = ensure_signed(origin)?;
@@ -209,7 +209,7 @@ decl_module! {
/// - Up to one reserve operation.
/// - One event.
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn force_transfer(origin, new: T::AccountId, index: T::AccountIndex) {
ensure_root(origin)?;
+2
View File
@@ -62,6 +62,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
+2
View File
@@ -315,6 +315,8 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
+2
View File
@@ -282,6 +282,8 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
+3 -3
View File
@@ -27,7 +27,7 @@ mod tests;
use sp_std::vec::Vec;
use frame_support::{
decl_module, decl_event, decl_storage, Parameter, debug,
weights::{Weight, MINIMUM_WEIGHT},
weights::Weight,
};
use sp_runtime::{traits::Hash, Perbill};
use sp_staking::{
@@ -104,7 +104,7 @@ decl_module! {
ConcurrentReportsIndex::<T>::remove_all();
ReportsByKindIndex::remove_all();
MINIMUM_WEIGHT
0
}
fn on_initialize(now: T::BlockNumber) -> Weight {
@@ -125,7 +125,7 @@ decl_module! {
})
}
MINIMUM_WEIGHT
0
}
}
}
+2
View File
@@ -101,6 +101,8 @@ impl frame_system::Trait for Runtime {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
@@ -20,7 +20,7 @@
//! function that generates low-influence random values based on the block hashes from the previous
//! `81` blocks. Low-influence randomness can be useful when defending against relatively weak
//! adversaries. Using this pallet as a randomness source is advisable primarily in low-security
//! situations like testing.
//! situations like testing.
//!
//! ## Public Functions
//!
@@ -36,13 +36,13 @@
//! ### Example - Get random seed for the current block
//!
//! ```
//! use frame_support::{decl_module, dispatch, traits::Randomness, weights::MINIMUM_WEIGHT};
//! use frame_support::{decl_module, dispatch, traits::Randomness};
//!
//! pub trait Trait: frame_system::Trait {}
//!
//! decl_module! {
//! pub struct Module<T: Trait> for enum Call where origin: T::Origin {
//! #[weight = MINIMUM_WEIGHT]
//! #[weight = 0]
//! pub fn random_module_example(origin) -> dispatch::DispatchResult {
//! let _random_value = <pallet_randomness_collective_flip::Module<T>>::random(&b"my context"[..]);
//! Ok(())
@@ -58,7 +58,7 @@ use sp_std::{prelude::*, convert::TryInto};
use sp_runtime::traits::Hash;
use frame_support::{
decl_module, decl_storage, traits::Randomness,
weights::{Weight, MINIMUM_WEIGHT}
weights::Weight
};
use safe_mix::TripletMix;
use codec::Encode;
@@ -84,7 +84,7 @@ decl_module! {
values[index] = parent_hash;
});
MINIMUM_WEIGHT
0
}
}
}
@@ -170,6 +170,8 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
type Version = ();
+3 -3
View File
@@ -159,7 +159,7 @@ use codec::{Encode, Decode};
use frame_support::{
decl_module, decl_event, decl_storage, decl_error, ensure,
Parameter, RuntimeDebug, weights::{MINIMUM_WEIGHT, GetDispatchInfo, FunctionOf, Pays},
Parameter, RuntimeDebug, weights::{GetDispatchInfo, FunctionOf, Pays},
traits::{Currency, ReservableCurrency, Get, BalanceStatus},
dispatch::PostDispatchInfo,
};
@@ -365,7 +365,7 @@ decl_module! {
/// - One storage write O(1)
/// - One event
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn set_recovered(origin, lost: T::AccountId, rescuer: T::AccountId) {
ensure_root(origin)?;
// Create the recovery storage item.
@@ -647,7 +647,7 @@ decl_module! {
/// # <weight>
/// - One storage mutation to check account is recovered by `who`. O(1)
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn cancel_recovered(origin, account: T::AccountId) {
let who = ensure_signed(origin)?;
// Check `who` is allowed to make a call on behalf of `account`
+2
View File
@@ -76,6 +76,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
+2
View File
@@ -349,6 +349,8 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
+8 -9
View File
@@ -54,7 +54,6 @@
//!
//! ```
//! use frame_support::{decl_module, dispatch};
//! use frame_support::weights::MINIMUM_WEIGHT;
//! use frame_system::{self as system, ensure_signed};
//! use pallet_scored_pool::{self as scored_pool};
//!
@@ -62,7 +61,7 @@
//!
//! decl_module! {
//! pub struct Module<T: Trait> for enum Call where origin: T::Origin {
//! #[weight = MINIMUM_WEIGHT]
//! #[weight = 0]
//! pub fn candidate(origin) -> dispatch::DispatchResult {
//! let who = ensure_signed(origin)?;
//!
@@ -98,7 +97,7 @@ use sp_std::{
use frame_support::{
decl_module, decl_storage, decl_event, ensure, decl_error,
traits::{EnsureOrigin, ChangeMembers, InitializeMembers, Currency, Get, ReservableCurrency},
weights::{Weight, MINIMUM_WEIGHT},
weights::Weight,
};
use frame_system::{self as system, ensure_root, ensure_signed};
use sp_runtime::{
@@ -253,7 +252,7 @@ decl_module! {
let pool = <Pool<T, I>>::get();
<Module<T, I>>::refresh_members(pool, ChangeReceiver::MembershipChanged);
}
MINIMUM_WEIGHT
0
}
/// Add `origin` to the pool of candidates.
@@ -267,7 +266,7 @@ decl_module! {
///
/// The `index` parameter of this function must be set to
/// the index of the transactor in the `Pool`.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn submit_candidacy(origin) {
let who = ensure_signed(origin)?;
ensure!(!<CandidateExists<T, I>>::contains_key(&who), Error::<T, I>::AlreadyInPool);
@@ -297,7 +296,7 @@ decl_module! {
///
/// The `index` parameter of this function must be set to
/// the index of the transactor in the `Pool`.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn withdraw_candidacy(
origin,
index: u32
@@ -317,7 +316,7 @@ decl_module! {
///
/// The `index` parameter of this function must be set to
/// the index of `dest` in the `Pool`.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn kick(
origin,
dest: <T::Lookup as StaticLookup>::Source,
@@ -342,7 +341,7 @@ decl_module! {
///
/// The `index` parameter of this function must be set to
/// the index of the `dest` in the `Pool`.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn score(
origin,
dest: <T::Lookup as StaticLookup>::Source,
@@ -383,7 +382,7 @@ decl_module! {
/// (this happens each `Period`).
///
/// May only be called from root.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn change_member_count(origin, count: u32) {
ensure_root(origin)?;
<MemberCount<I>>::put(&count);
+2
View File
@@ -67,6 +67,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
@@ -70,6 +70,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = ();
type MaximumBlockWeight = ();
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type AvailableBlockRatio = ();
type MaximumBlockLength = ();
type Version = ();
+2
View File
@@ -185,6 +185,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
type Version = ();
+4 -4
View File
@@ -260,7 +260,7 @@ use sp_runtime::{Percent, ModuleId, RuntimeDebug,
}
};
use frame_support::{decl_error, decl_module, decl_storage, decl_event, ensure, dispatch::DispatchResult};
use frame_support::weights::{Weight, MINIMUM_WEIGHT};
use frame_support::weights::Weight;
use frame_support::traits::{
Currency, ReservableCurrency, Randomness, Get, ChangeMembers, BalanceStatus,
ExistenceRequirement::AllowDeath, EnsureOrigin
@@ -824,7 +824,7 @@ decl_module! {
///
/// Total Complexity: O(1)
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn found(origin, founder: T::AccountId, max_members: u32, rules: Vec<u8>) {
T::FounderSetOrigin::ensure_origin(origin)?;
ensure!(!<Head<T, I>>::exists(), Error::<T, I>::AlreadyFounded);
@@ -1024,7 +1024,7 @@ decl_module! {
///
/// Total Complexity: O(1)
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn set_max_members(origin, max: u32) {
ensure_root(origin)?;
ensure!(max > 1, Error::<T, I>::MaxMembers);
@@ -1050,7 +1050,7 @@ decl_module! {
Self::rotate_challenge(&mut members);
}
MINIMUM_WEIGHT
0
}
}
}
+2
View File
@@ -77,6 +77,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
+4 -5
View File
@@ -150,7 +150,6 @@
//!
//! ```
//! use frame_support::{decl_module, dispatch};
//! use frame_support::weights::MINIMUM_WEIGHT;
//! use frame_system::{self as system, ensure_signed};
//! use pallet_staking::{self as staking};
//!
@@ -159,7 +158,7 @@
//! decl_module! {
//! pub struct Module<T: Trait> for enum Call where origin: T::Origin {
//! /// Reward a validator.
//! #[weight = MINIMUM_WEIGHT]
//! #[weight = 0]
//! pub fn reward_myself(origin) -> dispatch::DispatchResult {
//! let reported = ensure_signed(origin)?;
//! <staking::Module<T>>::reward_by_ids(vec![(reported, 10)]);
@@ -291,7 +290,7 @@ use sp_std::{
use codec::{HasCompact, Encode, Decode};
use frame_support::{
decl_module, decl_event, decl_storage, ensure, decl_error, debug,
weights::{MINIMUM_WEIGHT, Weight, DispatchClass},
weights::{Weight, DispatchClass},
storage::IterableStorageMap,
dispatch::{IsSubType, DispatchResult},
traits::{
@@ -1623,7 +1622,7 @@ decl_module! {
}
/// Force a current staker to become completely unstaked, immediately.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn force_unstake(origin, stash: T::AccountId) {
ensure_root(origin)?;
@@ -1803,7 +1802,7 @@ decl_module! {
/// This can be called from any origin.
///
/// - `stash`: The stash account to reap. Its balance must be zero.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn reap_stash(_origin, stash: T::AccountId) {
ensure!(T::Currency::total_balance(&stash).is_zero(), Error::<T>::FundedTarget);
Self::kill_stash(&stash)?;
+2
View File
@@ -204,6 +204,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
type Version = ();
+3 -4
View File
@@ -52,14 +52,13 @@
//!
//! ```
//! use frame_support::{decl_module, dispatch};
//! use frame_support::weights::MINIMUM_WEIGHT;
//! use frame_system::{self as system, ensure_root};
//!
//! pub trait Trait: frame_system::Trait {}
//!
//! decl_module! {
//! pub struct Module<T: Trait> for enum Call where origin: T::Origin {
//! #[weight = MINIMUM_WEIGHT]
//! #[weight = 0]
//! pub fn privileged_function(origin) -> dispatch::DispatchResult {
//! ensure_root(origin)?;
//!
@@ -93,7 +92,7 @@ use sp_runtime::traits::{StaticLookup, Dispatchable};
use frame_support::{
Parameter, decl_module, decl_event, decl_storage, decl_error, ensure,
};
use frame_support::weights::{MINIMUM_WEIGHT, GetDispatchInfo, FunctionOf, Pays};
use frame_support::weights::{GetDispatchInfo, FunctionOf, Pays};
use frame_system::{self as system, ensure_signed};
pub trait Trait: frame_system::Trait {
@@ -151,7 +150,7 @@ decl_module! {
/// - Limited storage reads.
/// - One DB change.
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn set_key(origin, new: <T::Lookup as StaticLookup>::Source) {
// This is a public call, so we ensure that the origin is some signed account.
let sender = ensure_signed(origin)?;
+11 -14
View File
@@ -70,14 +70,13 @@ impl<T> Parameter for T where T: Codec + EncodeLike + Clone + Eq + fmt::Debug {}
/// # #[macro_use]
/// # extern crate frame_support;
/// # use frame_support::dispatch;
/// # use frame_support::weights::MINIMUM_WEIGHT;
/// # use frame_system::{self as system, Trait, ensure_signed};
/// decl_module! {
/// pub struct Module<T: Trait> for enum Call where origin: T::Origin {
///
/// // Private functions are dispatchable, but not available to other
/// // FRAME pallets.
/// #[weight = MINIMUM_WEIGHT]
/// #[weight = 0]
/// fn my_function(origin, var: u64) -> dispatch::DispatchResult {
/// // Your implementation
/// Ok(())
@@ -85,7 +84,7 @@ impl<T> Parameter for T where T: Codec + EncodeLike + Clone + Eq + fmt::Debug {}
///
/// // Public functions are both dispatchable and available to other
/// // FRAME pallets.
/// #[weight = MINIMUM_WEIGHT]
/// #[weight = 0]
/// pub fn my_public_function(origin) -> dispatch::DispatchResult {
/// // Your implementation
/// Ok(())
@@ -113,17 +112,16 @@ impl<T> Parameter for T where T: Codec + EncodeLike + Clone + Eq + fmt::Debug {}
/// # #[macro_use]
/// # extern crate frame_support;
/// # use frame_support::dispatch;
/// # use frame_support::weights::MINIMUM_WEIGHT;
/// # use frame_system::{self as system, Trait, ensure_signed};
/// decl_module! {
/// pub struct Module<T: Trait> for enum Call where origin: T::Origin {
/// #[weight = MINIMUM_WEIGHT]
/// #[weight = 0]
/// fn my_long_function(origin) -> dispatch::DispatchResult {
/// // Your implementation
/// Ok(())
/// }
///
/// #[weight = MINIMUM_WEIGHT]
/// #[weight = 0]
/// fn my_short_function(origin) {
/// // Your implementation
/// }
@@ -177,11 +175,10 @@ impl<T> Parameter for T where T: Codec + EncodeLike + Clone + Eq + fmt::Debug {}
/// # #[macro_use]
/// # extern crate frame_support;
/// # use frame_support::dispatch;
/// # use frame_support::weights::MINIMUM_WEIGHT;
/// # use frame_system::{self as system, Trait, ensure_signed, ensure_root};
/// decl_module! {
/// pub struct Module<T: Trait> for enum Call where origin: T::Origin {
/// #[weight = MINIMUM_WEIGHT]
/// #[weight = 0]
/// fn my_privileged_function(origin) -> dispatch::DispatchResult {
/// ensure_root(origin)?;
/// // Your implementation
@@ -2045,7 +2042,7 @@ macro_rules! __check_reserved_fn_name {
#[allow(dead_code)]
mod tests {
use super::*;
use crate::weights::{MINIMUM_WEIGHT, DispatchInfo, DispatchClass, Pays};
use crate::weights::{DispatchInfo, DispatchClass, Pays};
use crate::traits::{
CallMetadata, GetCallMetadata, GetCallName, OnInitialize, OnFinalize, OnRuntimeUpgrade
};
@@ -2071,22 +2068,22 @@ mod tests {
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin, T::AccountId: From<u32> {
/// Hi, this is a comment.
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn aux_0(_origin) -> DispatchResult { unreachable!() }
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn aux_1(_origin, #[compact] _data: u32,) -> DispatchResult { unreachable!() }
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn aux_2(_origin, _data: i32, _data2: String) -> DispatchResult { unreachable!() }
#[weight = 3]
fn aux_3(_origin) -> DispatchResult { unreachable!() }
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn aux_4(_origin, _data: i32) -> DispatchResult { unreachable!() }
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn aux_5(_origin, _data: i32, #[compact] _data2: u32,) -> DispatchResult { unreachable!() }
#[weight = (5, DispatchClass::Operational)]
+2 -2
View File
@@ -35,7 +35,7 @@ pub use frame_metadata::{ModuleErrorMetadata, ErrorMetadata, DecodeDifferent};
///
/// ```
/// # use frame_support::{decl_error, decl_module};
/// # use frame_support::weights::MINIMUM_WEIGHT;
/// #
/// decl_error! {
/// /// Errors that can occur in my module.
/// pub enum MyError for Module<T: Trait> {
@@ -55,7 +55,7 @@ pub use frame_metadata::{ModuleErrorMetadata, ErrorMetadata, DecodeDifferent};
/// pub struct Module<T: Trait> for enum Call where origin: T::Origin {
/// type Error = MyError<T>;
///
/// #[weight = MINIMUM_WEIGHT]
/// #[weight = 0]
/// fn do_something(origin) -> frame_support::dispatch::DispatchResult {
/// Err(MyError::<T>::YouAreNotCoolEnough.into())
/// }
+1 -2
View File
@@ -334,7 +334,6 @@ mod tests {
mod event_module {
use crate::dispatch::DispatchResult;
use crate::weights::MINIMUM_WEIGHT;
pub trait Trait: super::system::Trait {
type Balance;
@@ -352,7 +351,7 @@ mod tests {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
type Error = Error<T>;
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn aux_0(_origin) -> DispatchResult { unreachable!() }
}
}
-3
View File
@@ -141,9 +141,6 @@ pub use sp_runtime::transaction_validity::TransactionPriority;
/// Numeric range of a transaction weight.
pub type Weight = u64;
/// The smallest total weight an extrinsic should have.
pub const MINIMUM_WEIGHT: Weight = 10_000_000;
/// Means of weighing some particular kind of data (`T`).
pub trait WeighData<T> {
/// Weigh the data `T` given by `target`. When implementing this for a dispatchable, `T` will be
@@ -18,7 +18,7 @@
use sp_runtime::{generic, traits::{BlakeTwo256, Block as _, Verify}, DispatchError};
use sp_core::{H256, sr25519};
use frame_support::weights::MINIMUM_WEIGHT;
mod system;
@@ -33,7 +33,7 @@ mod module1 {
pub struct Module<T: Trait<I>, I: Instance = DefaultInstance> for enum Call
where origin: <T as system::Trait>::Origin
{
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn fail(_origin) -> frame_support::dispatch::DispatchResult {
Err(Error::<T, I>::Something.into())
}
@@ -60,7 +60,7 @@ mod module2 {
pub struct Module<T: Trait> for enum Call
where origin: <T as system::Trait>::Origin
{
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
pub fn fail(_origin) -> frame_support::dispatch::DispatchResult {
Err(Error::<T>::Something.into())
}
@@ -23,7 +23,6 @@ use frame_support::{
DecodeDifferent, StorageMetadata, StorageEntryModifier, StorageEntryType, DefaultByteGetter,
StorageEntryMetadata, StorageHasher,
},
weights::MINIMUM_WEIGHT,
StorageValue, StorageMap, StorageDoubleMap,
};
use sp_inherents::{ProvideInherent, InherentData, InherentIdentifier, MakeFatalError};
@@ -56,7 +55,7 @@ mod module1 {
fn deposit_event() = default;
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn one(origin) {
system::ensure_root(origin)?;
Self::deposit_event(RawEvent::AnotherVariant(3));
@@ -2,7 +2,7 @@ macro_rules! reserved {
($($reserved:ident)*) => {
$(
mod $reserved {
pub use frame_support::{dispatch, weights::MINIMUM_WEIGHT};
pub use frame_support::dispatch;
pub trait Trait {
type Origin;
@@ -19,7 +19,7 @@ macro_rules! reserved {
frame_support::decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn $reserved(_origin) -> dispatch::DispatchResult { unreachable!() }
}
}
+2
View File
@@ -73,6 +73,8 @@ impl system::Trait for Runtime {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
+190 -51
View File
@@ -68,14 +68,14 @@
//! ### Example - Get extrinsic count and parent hash for the current block
//!
//! ```
//! use frame_support::{decl_module, dispatch, weights::MINIMUM_WEIGHT};
//! use frame_support::{decl_module, dispatch};
//! use frame_system::{self as system, ensure_signed};
//!
//! pub trait Trait: system::Trait {}
//!
//! decl_module! {
//! pub struct Module<T: Trait> for enum Call where origin: T::Origin {
//! #[weight = MINIMUM_WEIGHT]
//! #[weight = 0]
//! pub fn system_module_example(origin) -> dispatch::DispatchResult {
//! let _sender = ensure_signed(origin)?;
//! let _extrinsic_count = <system::Module<T>>::extrinsic_count();
@@ -121,7 +121,7 @@ use frame_support::{
StoredMap, EnsureOrigin,
},
weights::{
Weight, MINIMUM_WEIGHT, RuntimeDbWeight, DispatchInfo, PostDispatchInfo, DispatchClass,
Weight, RuntimeDbWeight, DispatchInfo, PostDispatchInfo, DispatchClass,
FunctionOf, Pays,
}
};
@@ -201,6 +201,12 @@ pub trait Trait: 'static + Eq + Clone {
/// The weight of runtime database operations the runtime can invoke.
type DbWeight: Get<RuntimeDbWeight>;
/// The base weight of executing a block, independent of the transactions in the block.
type BlockExecutionWeight: Get<Weight>;
/// The base weight of an Extrinsic in the block, independent of the of extrinsic being executed.
type ExtrinsicBaseWeight: Get<Weight>;
/// The maximum length of a block (in bytes).
type MaximumBlockLength: Get<u32>;
@@ -478,6 +484,15 @@ decl_module! {
/// The maximum weight of a block.
const MaximumBlockWeight: Weight = T::MaximumBlockWeight::get();
/// The weight of runtime database operations the runtime can invoke.
const DbWeight: RuntimeDbWeight = T::DbWeight::get();
/// The base weight of executing a block, independent of the transactions in the block.
const BlockExecutionWeight: Weight = T::BlockExecutionWeight::get();
/// The base weight of an Extrinsic in the block, independent of the of extrinsic being executed.
const ExtrinsicBaseWeight: Weight = T::ExtrinsicBaseWeight::get();
/// The maximum length of a block (in bytes).
const MaximumBlockLength: u32 = T::MaximumBlockLength::get();
@@ -494,29 +509,29 @@ decl_module! {
}
/// Make some on-chain remark.
///
///
/// # <weight>
/// - `O(1)`
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn remark(origin, _remark: Vec<u8>) {
ensure_signed(origin)?;
}
/// Set the number of pages in the WebAssembly environment's heap.
///
///
/// # <weight>
/// - `O(1)`
/// - 1 storage write.
/// # </weight>
#[weight = (MINIMUM_WEIGHT, DispatchClass::Operational)]
#[weight = (0, DispatchClass::Operational)]
fn set_heap_pages(origin, pages: u64) {
ensure_root(origin)?;
storage::unhashed::put_raw(well_known_keys::HEAP_PAGES, &pages.encode());
}
/// Set the new runtime code.
///
///
/// # <weight>
/// - `O(C + S)` where `C` length of `code` and `S` complexity of `can_set_code`
/// - 1 storage write (codec `O(C)`).
@@ -532,7 +547,7 @@ decl_module! {
}
/// Set the new runtime code without doing any checks of the given `code`.
///
///
/// # <weight>
/// - `O(C)` where `C` length of `code`
/// - 1 storage write (codec `O(C)`).
@@ -546,7 +561,7 @@ decl_module! {
}
/// Set the new changes trie configuration.
///
///
/// # <weight>
/// - `O(D)` where `D` length of `Digest`
/// - 1 storage write or delete (codec `O(1)`).
@@ -570,12 +585,12 @@ decl_module! {
}
/// Set some items of storage.
///
///
/// # <weight>
/// - `O(I)` where `I` length of `items`
/// - `I` storage writes (`O(1)`).
/// # </weight>
#[weight = (MINIMUM_WEIGHT, DispatchClass::Operational)]
#[weight = (0, DispatchClass::Operational)]
fn set_storage(origin, items: Vec<KeyValue>) {
ensure_root(origin)?;
for i in &items {
@@ -584,12 +599,12 @@ decl_module! {
}
/// Kill some items from storage.
///
///
/// # <weight>
/// - `O(VK)` where `V` length of `keys` and `K` length of one key
/// - `V` storage deletions.
/// # </weight>
#[weight = (MINIMUM_WEIGHT, DispatchClass::Operational)]
#[weight = (0, DispatchClass::Operational)]
fn kill_storage(origin, keys: Vec<Key>) {
ensure_root(origin)?;
for key in &keys {
@@ -598,12 +613,12 @@ decl_module! {
}
/// Kill all storage items with a key that starts with the given prefix.
///
///
/// # <weight>
/// - `O(P)` where `P` amount of keys with prefix `prefix`
/// - `P` storage deletions.
/// # </weight>
#[weight = (MINIMUM_WEIGHT, DispatchClass::Operational)]
#[weight = (0, DispatchClass::Operational)]
fn kill_prefix(origin, prefix: Key) {
ensure_root(origin)?;
storage::unhashed::kill_prefix(&prefix);
@@ -611,7 +626,7 @@ decl_module! {
/// Kill the sending account, assuming there are no references outstanding and the composite
/// data is equal to its default value.
///
///
/// # <weight>
/// - `O(K)` with `K` being complexity of `on_killed_account`
/// - 1 storage read and deletion.
@@ -874,6 +889,23 @@ impl<T: Trait> Module<T> {
AllExtrinsicsWeight::get().unwrap_or_default()
}
/// Get the quota ratio of each dispatch class type. This indicates that all operational and mandatory
/// dispatches can use the full capacity of any resource, while user-triggered ones can consume
/// a portion.
pub fn get_dispatch_limit_ratio(class: DispatchClass) -> Perbill {
match class {
DispatchClass::Operational | DispatchClass::Mandatory
=> <Perbill as sp_runtime::PerThing>::one(),
DispatchClass::Normal => T::AvailableBlockRatio::get(),
}
}
/// The maximum weight of an allowable extrinsic. Only one of these could exist in a block.
pub fn max_extrinsic_weight(class: DispatchClass) -> Weight {
let limit = Self::get_dispatch_limit_ratio(class) * T::MaximumBlockWeight::get();
limit - (T::BlockExecutionWeight::get() + T::ExtrinsicBaseWeight::get())
}
pub fn all_extrinsics_len() -> u32 {
AllExtrinsicsLen::get().unwrap_or_default()
}
@@ -897,7 +929,7 @@ impl<T: Trait> Module<T> {
/// If no previous weight exists, the function initializes the weight to zero.
pub fn register_extra_weight_unchecked(weight: Weight) {
let current_weight = AllExtrinsicsWeight::get().unwrap_or_default();
let next_weight = current_weight.saturating_add(weight).min(T::MaximumBlockWeight::get());
let next_weight = current_weight.saturating_add(weight);
AllExtrinsicsWeight::put(next_weight);
}
@@ -974,7 +1006,7 @@ impl<T: Trait> Module<T> {
}
/// Deposits a log and ensures it matches the block's log data.
///
///
/// # <weight>
/// - `O(D)` where `D` length of `Digest`
/// - 1 storage mutation (codec `O(D)`).
@@ -1238,15 +1270,11 @@ pub struct CheckWeight<T: Trait + Send + Sync>(PhantomData<T>);
impl<T: Trait + Send + Sync> CheckWeight<T> where
T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo>
{
/// Get the quota ratio of each dispatch class type. This indicates that all operational
/// Get the quota ratio of each dispatch class type. This indicates that all operational and mandatory
/// dispatches can use the full capacity of any resource, while user-triggered ones can consume
/// a portion.
fn get_dispatch_limit_ratio(class: DispatchClass) -> Perbill {
match class {
DispatchClass::Operational | DispatchClass::Mandatory
=> <Perbill as sp_runtime::PerThing>::one(),
DispatchClass::Normal => T::AvailableBlockRatio::get(),
}
Module::<T>::get_dispatch_limit_ratio(class)
}
/// Checks if the current extrinsic can fit into the block with respect to block weight limits.
@@ -1258,12 +1286,21 @@ impl<T: Trait + Send + Sync> CheckWeight<T> where
let current_weight = Module::<T>::all_extrinsics_weight();
let maximum_weight = T::MaximumBlockWeight::get();
let limit = Self::get_dispatch_limit_ratio(info.class) * maximum_weight;
let added_weight = info.weight.min(limit);
let next_weight = current_weight.saturating_add(added_weight);
if next_weight > limit && info.class != DispatchClass::Mandatory {
Err(InvalidTransaction::ExhaustsResources.into())
} else {
if info.class == DispatchClass::Mandatory {
// If we have a dispatch that must be included in the block, it ignores all the limits.
let extrinsic_weight = info.weight.saturating_add(T::ExtrinsicBaseWeight::get());
let next_weight = current_weight.saturating_add(extrinsic_weight);
Ok(next_weight)
} else {
let extrinsic_weight = info.weight.checked_add(T::ExtrinsicBaseWeight::get())
.ok_or(InvalidTransaction::ExhaustsResources)?;
let next_weight = current_weight.checked_add(extrinsic_weight)
.ok_or(InvalidTransaction::ExhaustsResources)?;
if next_weight > limit {
Err(InvalidTransaction::ExhaustsResources.into())
} else {
Ok(next_weight)
}
}
}
@@ -1659,8 +1696,8 @@ pub(crate) mod tests {
use super::*;
use sp_std::cell::RefCell;
use sp_core::H256;
use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::Header, DispatchError};
use frame_support::{impl_outer_origin, parameter_types};
use sp_runtime::{traits::{BlakeTwo256, IdentityLookup, SignedExtension}, testing::Header, DispatchError};
use frame_support::{impl_outer_origin, parameter_types, assert_ok, assert_err};
impl_outer_origin! {
pub enum Origin for Test where system = super {}
@@ -1683,6 +1720,12 @@ pub(crate) mod tests {
apis: sp_version::create_apis_vec!([]),
transaction_version: 1,
};
pub const BlockExecutionWeight: Weight = 10;
pub const ExtrinsicBaseWeight: Weight = 5;
pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight {
read: 10,
write: 100,
};
}
thread_local!{
@@ -1721,7 +1764,9 @@ pub(crate) mod tests {
type Event = u16;
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type DbWeight = DbWeight;
type BlockExecutionWeight = BlockExecutionWeight;
type ExtrinsicBaseWeight = ExtrinsicBaseWeight;
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
type Version = Version;
@@ -1747,7 +1792,10 @@ pub(crate) mod tests {
const CALL: &<Test as Trait>::Call = &Call;
fn new_test_ext() -> sp_io::TestExternalities {
GenesisConfig::default().build_storage::<Test>().unwrap().into()
let mut ext: sp_io::TestExternalities = GenesisConfig::default().build_storage::<Test>().unwrap().into();
// Add to each test the initial weight of a block
ext.execute_with(|| System::register_extra_weight_unchecked(<Test as Trait>::BlockExecutionWeight::get()));
ext
}
fn normal_weight_limit() -> Weight {
@@ -1962,11 +2010,11 @@ pub(crate) mod tests {
let normal_limit = normal_weight_limit();
let small = DispatchInfo { weight: 100, ..Default::default() };
let medium = DispatchInfo {
weight: normal_limit - 1,
weight: normal_limit - <Test as Trait>::ExtrinsicBaseWeight::get(),
..Default::default()
};
let big = DispatchInfo {
weight: normal_limit + 1,
weight: normal_limit - <Test as Trait>::ExtrinsicBaseWeight::get() + 1,
..Default::default()
};
let len = 0_usize;
@@ -1986,11 +2034,13 @@ pub(crate) mod tests {
#[test]
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), };
let len = 0_usize;
AllExtrinsicsWeight::put(256);
// We allow 75% for normal transaction, so we put 25% - extrinsic base weight
AllExtrinsicsWeight::put(256 - <Test as Trait>::ExtrinsicBaseWeight::get());
let pre = CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, &info, len).unwrap();
assert_eq!(AllExtrinsicsWeight::get().unwrap(), info.weight + 256);
@@ -1999,7 +2049,10 @@ pub(crate) mod tests {
CheckWeight::<Test>::post_dispatch(pre, &info, &post_info, len, &Ok(()))
.is_ok()
);
assert_eq!(AllExtrinsicsWeight::get().unwrap(), post_info.actual_weight.unwrap() + 256);
assert_eq!(
AllExtrinsicsWeight::get().unwrap(),
post_info.actual_weight.unwrap() + 256,
);
})
}
@@ -2013,41 +2066,127 @@ pub(crate) mod tests {
AllExtrinsicsWeight::put(128);
let pre = CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, &info, len).unwrap();
assert_eq!(AllExtrinsicsWeight::get().unwrap(), info.weight + 128);
assert_eq!(
AllExtrinsicsWeight::get().unwrap(),
info.weight + 128 + <Test as Trait>::ExtrinsicBaseWeight::get(),
);
assert!(
CheckWeight::<Test>::post_dispatch(pre, &info, &post_info, len, &Ok(()))
.is_ok()
);
assert_eq!(AllExtrinsicsWeight::get().unwrap(), info.weight + 128);
assert_eq!(
AllExtrinsicsWeight::get().unwrap(),
info.weight + 128 + <Test as Trait>::ExtrinsicBaseWeight::get(),
);
})
}
#[test]
fn signed_ext_check_weight_fee_works() {
fn zero_weight_extrinsic_still_has_base_weight() {
new_test_ext().execute_with(|| {
let free = DispatchInfo { weight: 0, ..Default::default() };
let len = 0_usize;
assert_eq!(System::all_extrinsics_weight(), 0);
// Initial weight from `BlockExecutionWeight`
assert_eq!(System::all_extrinsics_weight(), <Test as Trait>::BlockExecutionWeight::get());
let r = CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, &free, len);
assert!(r.is_ok());
assert_eq!(System::all_extrinsics_weight(), 0);
assert_eq!(
System::all_extrinsics_weight(),
<Test as Trait>::ExtrinsicBaseWeight::get() + <Test as Trait>::BlockExecutionWeight::get()
);
})
}
#[test]
fn signed_ext_check_weight_max_works() {
fn max_extrinsic_weight_is_allowed_but_nothing_more() {
// Dispatch Class Normal
new_test_ext().execute_with(|| {
let max = DispatchInfo { weight: Weight::max_value(), ..Default::default() };
let one = DispatchInfo { weight: 1, ..Default::default() };
let max = DispatchInfo { weight: System::max_extrinsic_weight(DispatchClass::Normal), ..Default::default() };
let len = 0_usize;
let normal_limit = normal_weight_limit();
assert_eq!(System::all_extrinsics_weight(), 0);
let r = CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, &max, len);
assert!(r.is_ok());
assert_eq!(System::all_extrinsics_weight(), normal_limit);
})
assert_ok!(CheckWeight::<Test>::do_pre_dispatch(&max, len));
assert_err!(
CheckWeight::<Test>::do_pre_dispatch(&one, len),
InvalidTransaction::ExhaustsResources,
);
// Weight should be 75% of 1024 (max block weight)
assert_eq!(System::all_extrinsics_weight(), 768);
});
// Dispatch Class Operational
new_test_ext().execute_with(|| {
let one = DispatchInfo {
weight: 1,
class: DispatchClass::Operational,
..Default::default()
};
let max = DispatchInfo {
weight: System::max_extrinsic_weight(DispatchClass::Operational),
class: DispatchClass::Operational,
..Default::default()
};
let len = 0_usize;
assert_ok!(CheckWeight::<Test>::do_pre_dispatch(&max, len));
assert_err!(
CheckWeight::<Test>::do_pre_dispatch(&one, len),
InvalidTransaction::ExhaustsResources,
);
// Weight should be 100% of max block weight
assert_eq!(System::all_extrinsics_weight(), <Test as Trait>::MaximumBlockWeight::get());
});
}
#[test]
fn mandatory_extrinsic_doesnt_care_about_limits() {
new_test_ext().execute_with(|| {
let max = DispatchInfo {
weight: Weight::max_value(),
class: DispatchClass::Mandatory,
..Default::default()
};
let len = 0_usize;
assert_ok!(CheckWeight::<Test>::do_pre_dispatch(&max, len));
assert_eq!(System::all_extrinsics_weight(), Weight::max_value());
assert!(System::all_extrinsics_weight() > <Test as Trait>::MaximumBlockWeight::get());
});
}
#[test]
fn register_extra_weight_unchecked_doesnt_care_about_limits() {
new_test_ext().execute_with(|| {
System::register_extra_weight_unchecked(Weight::max_value());
assert_eq!(System::all_extrinsics_weight(), Weight::max_value());
assert!(System::all_extrinsics_weight() > <Test as Trait>::MaximumBlockWeight::get());
});
}
#[test]
fn full_block_with_normal_and_operational() {
new_test_ext().execute_with(|| {
// Max block is 1024
// Max normal is 768 (75%)
// 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)
assert_eq!(System::max_extrinsic_weight(DispatchClass::Normal), 753);
let max_normal = DispatchInfo { weight: 753, ..Default::default() };
let rest_operational = DispatchInfo { weight: 251, class: DispatchClass::Operational, ..Default::default() };
let len = 0_usize;
assert_ok!(CheckWeight::<Test>::do_pre_dispatch(&max_normal, len));
assert_eq!(System::all_extrinsics_weight(), 768);
assert_ok!(CheckWeight::<Test>::do_pre_dispatch(&rest_operational, len));
assert_eq!(<Test as Trait>::MaximumBlockWeight::get(), 1024);
assert_eq!(System::all_extrinsics_weight(), <Test as Trait>::MaximumBlockWeight::get());
});
}
#[test]
+6 -5
View File
@@ -62,7 +62,6 @@
//!
//! ```
//! use frame_support::{decl_module, dispatch};
//! use frame_support::weights::MINIMUM_WEIGHT;
//! # use pallet_timestamp as timestamp;
//! use frame_system::{self as system, ensure_signed};
//!
@@ -70,7 +69,7 @@
//!
//! decl_module! {
//! pub struct Module<T: Trait> for enum Call where origin: T::Origin {
//! #[weight = MINIMUM_WEIGHT]
//! #[weight = 0]
//! pub fn get_time(origin) -> dispatch::DispatchResult {
//! let _sender = ensure_signed(origin)?;
//! let _now = <timestamp::Module<T>>::get();
@@ -101,7 +100,7 @@ use frame_support::debug;
use frame_support::{
Parameter, decl_storage, decl_module,
traits::{Time, UnixTime, Get},
weights::{MINIMUM_WEIGHT, DispatchClass},
weights::{DispatchClass},
};
use sp_runtime::{
RuntimeString,
@@ -148,13 +147,13 @@ decl_module! {
/// `MinimumPeriod`.
///
/// The dispatch origin for this call must be `Inherent`.
///
///
/// # <weight>
/// - `O(T)` where `T` complexity of `on_timestamp_set`
/// - 2 storage mutations (codec `O(1)`).
/// - 1 event handler `on_timestamp_set` `O(T)`.
/// # </weight>
#[weight = (MINIMUM_WEIGHT, DispatchClass::Mandatory)]
#[weight = (0, DispatchClass::Mandatory)]
fn set(origin, #[compact] now: T::Moment) {
ensure_none(origin)?;
assert!(!<Self as Store>::DidUpdate::exists(), "Timestamp must be updated only once in the block");
@@ -313,6 +312,8 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
type Version = ();
+28 -30
View File
@@ -67,9 +67,6 @@ pub trait Trait: frame_system::Trait {
/// if any.
type OnTransactionPayment: OnUnbalanced<NegativeImbalanceOf<Self>>;
/// The fee to be paid for making a transaction; the base.
type TransactionBaseFee: Get<BalanceOf<Self>>;
/// The fee to be paid for making a transaction; the per-byte portion.
type TransactionByteFee: Get<BalanceOf<Self>>;
@@ -88,9 +85,6 @@ decl_storage! {
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
/// The fee to be paid for making a transaction; the base.
const TransactionBaseFee: BalanceOf<T> = T::TransactionBaseFee::get();
/// The fee to be paid for making a transaction; the per-byte portion.
const TransactionByteFee: BalanceOf<T> = T::TransactionByteFee::get();
@@ -178,7 +172,7 @@ impl<T: Trait> Module<T> {
let targeted_fee_adjustment = NextFeeMultiplier::get();
let adjusted_fee = targeted_fee_adjustment.saturated_multiply_accumulate(adjustable_fee.saturated_into());
let base_fee = T::TransactionBaseFee::get();
let base_fee = Self::weight_to_fee(T::ExtrinsicBaseWeight::get());
base_fee.saturating_add(adjusted_fee.saturated_into()).saturating_add(tip)
} else {
tip
@@ -367,6 +361,15 @@ mod tests {
pub enum Origin for Runtime {}
}
thread_local! {
static EXTRINSIC_BASE_WEIGHT: RefCell<u64> = RefCell::new(0);
}
pub struct ExtrinsicBaseWeight;
impl Get<u64> for ExtrinsicBaseWeight {
fn get() -> u64 { EXTRINSIC_BASE_WEIGHT.with(|v| *v.borrow()) }
}
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: Weight = 1024;
@@ -388,6 +391,8 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ExtrinsicBaseWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
@@ -409,16 +414,10 @@ mod tests {
type AccountStore = System;
}
thread_local! {
static TRANSACTION_BASE_FEE: RefCell<u64> = RefCell::new(0);
static TRANSACTION_BYTE_FEE: RefCell<u64> = RefCell::new(1);
static WEIGHT_TO_FEE: RefCell<u64> = RefCell::new(1);
}
pub struct TransactionBaseFee;
impl Get<u64> for TransactionBaseFee {
fn get() -> u64 { TRANSACTION_BASE_FEE.with(|v| *v.borrow()) }
}
pub struct TransactionByteFee;
impl Get<u64> for TransactionByteFee {
fn get() -> u64 { TRANSACTION_BYTE_FEE.with(|v| *v.borrow()) }
@@ -434,7 +433,6 @@ mod tests {
impl Trait for Runtime {
type Currency = pallet_balances::Module<Runtime>;
type OnTransactionPayment = ();
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = WeightToFee;
type FeeMultiplierUpdate = ();
@@ -446,7 +444,7 @@ mod tests {
pub struct ExtBuilder {
balance_factor: u64,
base_fee: u64,
base_weight: u64,
byte_fee: u64,
weight_to_fee: u64
}
@@ -455,7 +453,7 @@ mod tests {
fn default() -> Self {
Self {
balance_factor: 1,
base_fee: 0,
base_weight: 0,
byte_fee: 1,
weight_to_fee: 1,
}
@@ -463,8 +461,8 @@ mod tests {
}
impl ExtBuilder {
pub fn base_fee(mut self, base_fee: u64) -> Self {
self.base_fee = base_fee;
pub fn base_weight(mut self, base_weight: u64) -> Self {
self.base_weight = base_weight;
self
}
pub fn byte_fee(mut self, byte_fee: u64) -> Self {
@@ -480,7 +478,7 @@ mod tests {
self
}
fn set_constants(&self) {
TRANSACTION_BASE_FEE.with(|v| *v.borrow_mut() = self.base_fee);
EXTRINSIC_BASE_WEIGHT.with(|v| *v.borrow_mut() = self.base_weight);
TRANSACTION_BYTE_FEE.with(|v| *v.borrow_mut() = self.byte_fee);
WEIGHT_TO_FEE.with(|v| *v.borrow_mut() = self.weight_to_fee);
}
@@ -523,7 +521,7 @@ mod tests {
fn signed_extension_transaction_payment_work() {
ExtBuilder::default()
.balance_factor(10)
.base_fee(5)
.base_weight(5)
.build()
.execute_with(||
{
@@ -558,7 +556,7 @@ mod tests {
fn signed_extension_transaction_payment_multiplied_refund_works() {
ExtBuilder::default()
.balance_factor(10)
.base_fee(5)
.base_weight(5)
.build()
.execute_with(||
{
@@ -606,7 +604,7 @@ mod tests {
#[test]
fn signed_extension_allows_free_transactions() {
ExtBuilder::default()
.base_fee(100)
.base_weight(100)
.balance_factor(0)
.build()
.execute_with(||
@@ -645,7 +643,7 @@ mod tests {
#[test]
fn signed_ext_length_fee_is_also_updated_per_congestion() {
ExtBuilder::default()
.base_fee(5)
.base_weight(5)
.balance_factor(10)
.build()
.execute_with(||
@@ -673,7 +671,7 @@ mod tests {
let ext = xt.encode();
let len = ext.len() as u32;
ExtBuilder::default()
.base_fee(5)
.base_weight(5)
.weight_fee(2)
.build()
.execute_with(||
@@ -687,7 +685,7 @@ mod tests {
weight: info.weight,
class: info.class,
partial_fee:
5 /* base */
5 * 2 /* base * weight_fee */
+ (
len as u64 /* len * 1 */
+ info.weight.min(MaximumBlockWeight::get()) as u64 * 2 /* weight * weight_to_fee */
@@ -701,7 +699,7 @@ mod tests {
#[test]
fn compute_fee_works_without_multiplier() {
ExtBuilder::default()
.base_fee(100)
.base_weight(100)
.byte_fee(10)
.balance_factor(0)
.build()
@@ -741,7 +739,7 @@ mod tests {
#[test]
fn compute_fee_works_with_multiplier() {
ExtBuilder::default()
.base_fee(100)
.base_weight(100)
.byte_fee(10)
.balance_factor(0)
.build()
@@ -774,7 +772,7 @@ mod tests {
#[test]
fn compute_fee_does_not_overflow() {
ExtBuilder::default()
.base_fee(100)
.base_weight(100)
.byte_fee(10)
.balance_factor(0)
.build()
@@ -801,7 +799,7 @@ mod tests {
fn refund_does_not_recreate_account() {
ExtBuilder::default()
.balance_factor(10)
.base_fee(5)
.base_weight(5)
.build()
.execute_with(||
{
@@ -828,7 +826,7 @@ mod tests {
fn actual_weight_higher_than_max_refunds_nothing() {
ExtBuilder::default()
.balance_factor(10)
.base_fee(5)
.base_weight(5)
.build()
.execute_with(||
{
+2 -2
View File
@@ -98,7 +98,7 @@ use frame_support::traits::{
use sp_runtime::{Permill, ModuleId, Percent, RuntimeDebug, traits::{
Zero, StaticLookup, AccountIdConversion, Saturating, Hash, BadOrigin
}};
use frame_support::weights::{Weight, MINIMUM_WEIGHT, DispatchClass};
use frame_support::weights::{Weight, DispatchClass};
use frame_support::traits::{Contains, EnsureOrigin};
use codec::{Encode, Decode};
use frame_system::{self as system, ensure_signed, ensure_root};
@@ -561,7 +561,7 @@ decl_module! {
Self::spend_funds();
}
MINIMUM_WEIGHT
0
}
}
}
+2
View File
@@ -72,6 +72,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
type Version = ();
+2
View File
@@ -72,6 +72,8 @@ impl frame_system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
+5 -3
View File
@@ -57,7 +57,7 @@ use frame_support::traits::{
Currency, LockableCurrency, VestingSchedule, WithdrawReason, LockIdentifier,
ExistenceRequirement, Get
};
use frame_support::weights::MINIMUM_WEIGHT;
use frame_system::{self as system, ensure_signed};
mod benchmarking;
@@ -194,7 +194,7 @@ decl_module! {
/// - One storage read (codec `O(1)`) and up to one removal.
/// - One event.
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn vest(origin) -> DispatchResult {
let who = ensure_signed(origin)?;
Self::update_lock(who)
@@ -216,7 +216,7 @@ decl_module! {
/// - One storage read (codec `O(1)`) and up to one removal.
/// - One event.
/// # </weight>
#[weight = MINIMUM_WEIGHT]
#[weight = 0]
fn vest_other(origin, target: <T::Lookup as StaticLookup>::Source) -> DispatchResult {
ensure_signed(origin)?;
Self::update_lock(T::Lookup::lookup(target)?)
@@ -382,6 +382,8 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
+2
View File
@@ -402,6 +402,8 @@ impl frame_system::Trait for Runtime {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();