From 02b6a577ffdd0067b34698e85d4f407c5e0a75f4 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Sat, 28 Mar 2020 22:44:53 +0100 Subject: [PATCH 01/52] Update to u64 --- bin/node-template/runtime/src/lib.rs | 3 ++- bin/node/runtime/src/lib.rs | 3 ++- frame/support/src/weights.rs | 5 ++++- frame/utility/src/lib.rs | 8 ++++---- 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/bin/node-template/runtime/src/lib.rs b/bin/node-template/runtime/src/lib.rs index 94f033fd8f58e..405da07456fcb 100644 --- a/bin/node-template/runtime/src/lib.rs +++ b/bin/node-template/runtime/src/lib.rs @@ -120,7 +120,8 @@ pub fn native_version() -> NativeVersion { parameter_types! { pub const BlockHashCount: BlockNumber = 250; - pub const MaximumBlockWeight: Weight = 1_000_000_000; + /// We allow for 2 seconds of compute with a 6 second average block time. + pub const MaximumBlockWeight: Weight = 2_000_000_000; pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); pub const MaximumBlockLength: u32 = 5 * 1024 * 1024; pub const Version: RuntimeVersion = VERSION; diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 8868f28557e70..1f3dcf7425c88 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -162,7 +162,8 @@ impl OnUnbalanced for DealWithFees { parameter_types! { pub const BlockHashCount: BlockNumber = 250; - pub const MaximumBlockWeight: Weight = 1_000_000_000; + /// We allow for 2 seconds of compute with a average block time of 6 seconds. + pub const MaximumBlockWeight: Weight = 2_000_000_000; pub const MaximumBlockLength: u32 = 5 * 1024 * 1024; pub const Version: RuntimeVersion = VERSION; pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); diff --git a/frame/support/src/weights.rs b/frame/support/src/weights.rs index 7e8174ca7b145..8d536a73c3f5a 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -49,7 +49,10 @@ use sp_runtime::{ pub use sp_runtime::transaction_validity::TransactionPriority; /// Numeric range of a transaction weight. -pub type Weight = u32; +/// +/// FRAME assumes a weight of `1_000_000_000` equals 1 second of compute on a standard +/// machine: (TODO: DEFINE STANDARD MACHINE SPECIFICATIONS) +pub type Weight = u64; /// Means of weighing some particular kind of data (`T`). pub trait WeighData { diff --git a/frame/utility/src/lib.rs b/frame/utility/src/lib.rs index 0b60532c3dd23..12956960451ff 100644 --- a/frame/utility/src/lib.rs +++ b/frame/utility/src/lib.rs @@ -67,7 +67,7 @@ use sp_core::TypeId; use sp_io::hashing::blake2_256; use frame_support::{decl_module, decl_event, decl_error, decl_storage, Parameter, ensure, RuntimeDebug}; use frame_support::{traits::{Get, ReservableCurrency, Currency}, - weights::{GetDispatchInfo, DispatchClass,FunctionOf}, + weights::{Weight, GetDispatchInfo, DispatchClass, FunctionOf}, }; use frame_system::{self as system, ensure_signed}; use sp_runtime::{DispatchError, DispatchResult, traits::Dispatchable}; @@ -311,7 +311,7 @@ decl_module! { /// # #[weight = FunctionOf( |args: (&u16, &Vec, &Option>, &Box<::Call>)| { - args.3.get_dispatch_info().weight + 10_000 * (args.1.len() as u32 + 1) + args.3.get_dispatch_info().weight + 10_000 * (args.1.len() as Weight + 1) }, |args: (&u16, &Vec, &Option>, &Box<::Call>)| { args.3.get_dispatch_info().class @@ -409,7 +409,7 @@ decl_module! { /// # #[weight = FunctionOf( |args: (&u16, &Vec, &Option>, &[u8; 32])| { - 10_000 * (args.1.len() as u32 + 1) + 10_000 * (args.1.len() as Weight + 1) }, DispatchClass::Normal, true @@ -484,7 +484,7 @@ decl_module! { /// # #[weight = FunctionOf( |args: (&u16, &Vec, &Timepoint, &[u8; 32])| { - 10_000 * (args.1.len() as u32 + 1) + 10_000 * (args.1.len() as Weight + 1) }, DispatchClass::Normal, true From 1b8a18183d152128d9a2aa7e7de3c25c46b551ca Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Sun, 29 Mar 2020 07:43:44 +0200 Subject: [PATCH 02/52] Update bin/node/runtime/src/lib.rs --- bin/node/runtime/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 1f3dcf7425c88..d659d308858ec 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -162,7 +162,7 @@ impl OnUnbalanced for DealWithFees { parameter_types! { pub const BlockHashCount: BlockNumber = 250; - /// We allow for 2 seconds of compute with a average block time of 6 seconds. + /// We allow for 2 seconds of compute with a 6 second average block time. pub const MaximumBlockWeight: Weight = 2_000_000_000; pub const MaximumBlockLength: u32 = 5 * 1024 * 1024; pub const Version: RuntimeVersion = VERSION; From f204dcbaf4df3984a0b67a04dcf5e652cd3aaa1d Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Sun, 29 Mar 2020 07:44:29 +0200 Subject: [PATCH 03/52] Update weights --- frame/balances/src/lib.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index b83530d6352eb..945a3e40c31e9 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -437,7 +437,7 @@ decl_module! { /// check that the transfer will not kill the origin account. /// /// # - #[weight = SimpleDispatchInfo::FixedNormal(1_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(800_000)] pub fn transfer( origin, dest: ::Source, @@ -461,7 +461,7 @@ decl_module! { /// - Independent of the arguments. /// - Contains a limited number of reads and writes. /// # - #[weight = SimpleDispatchInfo::FixedOperational(50_000)] + #[weight = SimpleDispatchInfo::FixedOperational(400_000)] fn set_balance( origin, who: ::Source, @@ -499,7 +499,7 @@ decl_module! { /// Exactly as `transfer`, except the origin must be root and the source account may be /// specified. - #[weight = SimpleDispatchInfo::FixedNormal(1_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(800_000)] pub fn force_transfer( origin, source: ::Source, @@ -518,7 +518,7 @@ decl_module! { /// 99% of the time you want [`transfer`] instead. /// /// [`transfer`]: struct.Module.html#method.transfer - #[weight = SimpleDispatchInfo::FixedNormal(1_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(800_000)] pub fn transfer_keep_alive( origin, dest: ::Source, From 6d60384eae0abac9d08e0dd53113de3538ebd9be Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Sun, 29 Mar 2020 07:53:32 +0200 Subject: [PATCH 04/52] Fix test --- frame/support/src/weights.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/support/src/weights.rs b/frame/support/src/weights.rs index 8d536a73c3f5a..f1aaa2d4e1d61 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -326,7 +326,7 @@ mod tests { fn f0(_origin) { unimplemented!(); } // weight = a x 10 + b - #[weight = FunctionOf(|args: (&u32, &u32)| args.0 * 10 + args.1, DispatchClass::Normal, true)] + #[weight = FunctionOf(|args: (&u32, &u32)| (args.0 * 10 + args.1) as Weight, DispatchClass::Normal, true)] fn f11(_origin, _a: u32, _eb: u32) { unimplemented!(); } #[weight = FunctionOf(|_: (&u32, &u32)| 0, DispatchClass::Operational, true)] From 010fccb4ba80efb957640e22f12bf3fd934dd112 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Wed, 8 Apr 2020 12:02:32 +0200 Subject: [PATCH 05/52] Extra zeros to make gas 1:1 with weight --- bin/node-template/runtime/src/lib.rs | 2 +- bin/node/runtime/src/lib.rs | 2 +- frame/support/src/weights.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/bin/node-template/runtime/src/lib.rs b/bin/node-template/runtime/src/lib.rs index 405da07456fcb..6af2dcce0fcea 100644 --- a/bin/node-template/runtime/src/lib.rs +++ b/bin/node-template/runtime/src/lib.rs @@ -121,7 +121,7 @@ pub fn native_version() -> NativeVersion { 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; + pub const MaximumBlockWeight: Weight = 2_000_000_000_000; pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); pub const MaximumBlockLength: u32 = 5 * 1024 * 1024; pub const Version: RuntimeVersion = VERSION; diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index d659d308858ec..e0150bc88329a 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -163,7 +163,7 @@ impl OnUnbalanced for DealWithFees { 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; + pub const MaximumBlockWeight: Weight = 2_000_000_000_000; pub const MaximumBlockLength: u32 = 5 * 1024 * 1024; pub const Version: RuntimeVersion = VERSION; pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); diff --git a/frame/support/src/weights.rs b/frame/support/src/weights.rs index f1aaa2d4e1d61..8dc4cf3978e3f 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -50,7 +50,7 @@ pub use sp_runtime::transaction_validity::TransactionPriority; /// Numeric range of a transaction weight. /// -/// FRAME assumes a weight of `1_000_000_000` equals 1 second of compute on a standard +/// FRAME assumes a weight of `1_000_000_000_000` equals 1 second of compute on a standard /// machine: (TODO: DEFINE STANDARD MACHINE SPECIFICATIONS) pub type Weight = u64; From 25f8dd405bd13862c3a7d6b4b398ad1fe57d95c2 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Wed, 8 Apr 2020 21:46:26 +0200 Subject: [PATCH 06/52] initial impl DbWeight --- frame/balances/src/lib.rs | 2 +- frame/balances/src/tests_composite.rs | 2 + frame/balances/src/tests_local.rs | 2 + frame/support/src/weights.rs | 75 ++++++++++++++++++++++++++- frame/system/src/lib.rs | 7 ++- test-utils/runtime/src/lib.rs | 11 +++- 6 files changed, 94 insertions(+), 5 deletions(-) diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 2249d7c694a68..9d65d8068ca9b 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -433,7 +433,7 @@ decl_module! { /// check that the transfer will not kill the origin account. /// /// # - #[weight = SimpleDispatchInfo::FixedNormal(800_000)] + #[weight = T::DbWeight::get() * (1, 24, 0, 1, 12, 0)] pub fn transfer( origin, dest: ::Source, diff --git a/frame/balances/src/tests_composite.rs b/frame/balances/src/tests_composite.rs index 59c520f4b55b3..bb8302511d895 100644 --- a/frame/balances/src/tests_composite.rs +++ b/frame/balances/src/tests_composite.rs @@ -51,6 +51,7 @@ pub struct Test; parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 1024; + pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight::default(); pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } @@ -67,6 +68,7 @@ impl frame_system::Trait for Test { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = DbWeight; type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/balances/src/tests_local.rs b/frame/balances/src/tests_local.rs index 3a9bfb30cecd8..14ef8da967243 100644 --- a/frame/balances/src/tests_local.rs +++ b/frame/balances/src/tests_local.rs @@ -51,6 +51,7 @@ pub struct Test; parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 1024; + pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight::default(); pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } @@ -67,6 +68,7 @@ impl frame_system::Trait for Test { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = DbWeight; type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/support/src/weights.rs b/frame/support/src/weights.rs index 6c989a9e08ba9..feb57bddfa659 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -37,6 +37,7 @@ #[cfg(feature = "std")] use serde::{Serialize, Deserialize}; +use core::ops::Mul; use codec::{Encode, Decode}; use sp_arithmetic::traits::Bounded; use sp_runtime::{ @@ -378,24 +379,86 @@ impl GetDispatchInfo for sp_runtime::testing::TestX } } +/// The weight of various database operations that the runtime can invoke. +#[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)] +pub struct RuntimeDbWeight { + pub read: Weight, + pub read_repeat: Weight, + pub read_none: Weight, + pub write: Weight, + pub write_repeat: Weight, + pub write_none: Weight, +} + +impl Mul<(Weight, Weight, Weight, Weight, Weight, Weight)> for RuntimeDbWeight { + type Output = Self; + + fn mul(self, rhs: (Weight, Weight, Weight, Weight, Weight, Weight)) -> Self::Output { + RuntimeDbWeight { + read: self.read.saturating_mul(rhs.0), + read_repeat: self.read_repeat.saturating_mul(rhs.1), + read_none: self.read_none.saturating_mul(rhs.2), + write: self.write.saturating_mul(rhs.3), + write_repeat: self.write_repeat.saturating_mul(rhs.4), + write_none: self.write_none.saturating_mul(rhs.5), + } + } +} + +impl WeighData for RuntimeDbWeight { + fn weigh_data(&self, _: T) -> Weight { + return self.read + .saturating_add(self.read_repeat) + .saturating_add(self.read_none) + .saturating_add(self.write) + .saturating_add(self.write_repeat) + .saturating_add(self.write_none) + } +} + +impl ClassifyDispatch for RuntimeDbWeight { + fn classify_dispatch(&self, _: T) -> DispatchClass { + DispatchClass::Normal + } +} + +impl PaysFee for RuntimeDbWeight { + fn pays_fee(&self, _: T) -> bool { + true + } +} + #[cfg(test)] #[allow(dead_code)] mod tests { - use crate::decl_module; + use crate::{decl_module, parameter_types, traits::Get}; use super::*; pub trait Trait { type Origin; type Balance; type BlockNumber; + type DbWeight: Get; } pub struct TraitImpl {} + parameter_types! { + pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 100, + read_repeat: 10, + read_none: 100, + write: 1000, + write_repeat: 20, + write_none: 1000, + }; + } + impl Trait for TraitImpl { type Origin = u32; type BlockNumber = u32; type Balance = u32; + type DbWeight = DbWeight; } decl_module! { @@ -410,13 +473,21 @@ mod tests { #[weight = FunctionOf(|_: (&u32, &u32)| 0, DispatchClass::Operational, true)] fn f12(_origin, _a: u32, _eb: u32) { unimplemented!(); } + + #[weight = T::DbWeight::get() * (1, 2, 0, 1, 2, 0)] + fn f2(_origin) { unimplemented!(); } + } } #[test] fn weights_are_correct() { + assert_eq!(Call::::f0().get_dispatch_info().weight, 1000); assert_eq!(Call::::f11(10, 20).get_dispatch_info().weight, 120); assert_eq!(Call::::f11(10, 20).get_dispatch_info().class, DispatchClass::Normal); - assert_eq!(Call::::f0().get_dispatch_info().weight, 1000); + assert_eq!(Call::::f12(10, 20).get_dispatch_info().weight, 0); + assert_eq!(Call::::f12(10, 20).get_dispatch_info().class, DispatchClass::Operational); + assert_eq!(Call::::f2().get_dispatch_info().weight, 1160); + assert_eq!(Call::::f2().get_dispatch_info().class, DispatchClass::Normal); } } diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index a38a8854c75c3..803f118ea915b 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -120,7 +120,7 @@ use frame_support::{ Contains, Get, ModuleToIndex, OnNewAccount, OnKilledAccount, IsDeadAccount, Happened, StoredMap, EnsureOrigin, }, - weights::{Weight, DispatchInfo, DispatchClass, SimpleDispatchInfo, FunctionOf} + weights::{Weight, RuntimeDbWeight, DispatchInfo, DispatchClass, SimpleDispatchInfo, FunctionOf} }; use codec::{Encode, Decode, FullCodec, EncodeLike}; @@ -195,6 +195,9 @@ pub trait Trait: 'static + Eq + Clone { /// The maximum weight of a block. type MaximumBlockWeight: Get; + /// The weight of runtime database operations. + type DbWeight: Get; + /// The maximum length of a block (in bytes). type MaximumBlockLength: Get; @@ -1597,6 +1600,7 @@ mod tests { parameter_types! { pub const BlockHashCount: u64 = 10; pub const MaximumBlockWeight: Weight = 1024; + pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight::default(); pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); pub const MaximumBlockLength: u32 = 1024; pub const Version: RuntimeVersion = RuntimeVersion { @@ -1644,6 +1648,7 @@ mod tests { type Event = u16; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = DbWeight; type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = Version; diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index c0aea9a2ab599..099e509c64ccb 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -47,7 +47,7 @@ use sp_version::RuntimeVersion; pub use sp_core::hash::H256; #[cfg(any(feature = "std", test))] use sp_version::NativeVersion; -use frame_support::{impl_outer_origin, parameter_types, weights::Weight}; +use frame_support::{impl_outer_origin, parameter_types, weights::{Weight, RuntimeDbWeight}}; use sp_inherents::{CheckInherentsResult, InherentData}; use cfg_if::cfg_if; use sp_core::storage::ChildType; @@ -380,6 +380,14 @@ parameter_types! { pub const BlockHashCount: BlockNumber = 250; pub const MinimumPeriod: u64 = 5; pub const MaximumBlockWeight: Weight = 4 * 1024 * 1024; + pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 100, + read_repeat: 10, + read_none: 100, + write: 1000, + write_repeat: 20, + write_none: 1000, + }; pub const MaximumBlockLength: u32 = 4 * 1024 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); } @@ -397,6 +405,7 @@ impl frame_system::Trait for Runtime { type Event = Event; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = DbWeight; type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); From 6ed3496f34552d9df88b1b09e03a99cdf72cbe32 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Thu, 9 Apr 2020 19:10:20 +0200 Subject: [PATCH 07/52] Update weights for balances --- frame/balances/src/lib.rs | 13 ++++-- frame/balances/src/tests_composite.rs | 2 +- frame/balances/src/tests_local.rs | 2 +- frame/support/src/weights.rs | 58 ++++++++++++++++----------- 4 files changed, 45 insertions(+), 30 deletions(-) diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 9d65d8068ca9b..0b58e57689cfb 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -433,7 +433,7 @@ decl_module! { /// check that the transfer will not kill the origin account. /// /// # - #[weight = T::DbWeight::get() * (1, 24, 0, 1, 12, 0)] + #[weight = T::DbWeight::get() * (1, 1) + 200_000_000] pub fn transfer( origin, dest: ::Source, @@ -457,7 +457,7 @@ decl_module! { /// - Independent of the arguments. /// - Contains a limited number of reads and writes. /// # - #[weight = SimpleDispatchInfo::FixedOperational(400_000)] + #[weight = T::DbWeight::get() * (1, 1) + 100_000_000] fn set_balance( origin, who: ::Source, @@ -495,7 +495,11 @@ decl_module! { /// Exactly as `transfer`, except the origin must be root and the source account may be /// specified. - #[weight = SimpleDispatchInfo::FixedNormal(800_000)] + /// # + /// - Same as transfer, but additional read and write because the source account is + /// not assumed to be in the overlay. + /// # + #[weight = T::DbWeight::get() * (2, 2) + 200_000_000] pub fn force_transfer( origin, source: ::Source, @@ -514,7 +518,7 @@ decl_module! { /// 99% of the time you want [`transfer`] instead. /// /// [`transfer`]: struct.Module.html#method.transfer - #[weight = SimpleDispatchInfo::FixedNormal(800_000)] + #[weight = T::DbWeight::get() * (1, 1) + 150_000_000] pub fn transfer_keep_alive( origin, dest: ::Source, @@ -842,6 +846,7 @@ impl, I: Instance> frame_system::Trait for ElevatedTrait { type Event = (); type BlockHashCount = T::BlockHashCount; type MaximumBlockWeight = T::MaximumBlockWeight; + type DbWeight = T::DbWeight; type MaximumBlockLength = T::MaximumBlockLength; type AvailableBlockRatio = T::AvailableBlockRatio; type Version = T::Version; diff --git a/frame/balances/src/tests_composite.rs b/frame/balances/src/tests_composite.rs index bb8302511d895..ff54c9cc70300 100644 --- a/frame/balances/src/tests_composite.rs +++ b/frame/balances/src/tests_composite.rs @@ -27,7 +27,7 @@ use sp_core::H256; use sp_io; use frame_support::{impl_outer_origin, parameter_types}; use frame_support::traits::Get; -use frame_support::weights::{Weight, DispatchInfo}; +use frame_support::weights::{Weight, RuntimeDbWeight, DispatchInfo}; use std::cell::RefCell; use crate::{GenesisConfig, Module, Trait, decl_tests, tests::CallWithDispatchInfo}; diff --git a/frame/balances/src/tests_local.rs b/frame/balances/src/tests_local.rs index 14ef8da967243..e892e5b4ec540 100644 --- a/frame/balances/src/tests_local.rs +++ b/frame/balances/src/tests_local.rs @@ -27,7 +27,7 @@ use sp_core::H256; use sp_io; use frame_support::{impl_outer_origin, parameter_types}; use frame_support::traits::{Get, StorageMapShim}; -use frame_support::weights::{Weight, DispatchInfo}; +use frame_support::weights::{Weight, RuntimeDbWeight, DispatchInfo}; use std::cell::RefCell; use crate::{GenesisConfig, Module, Trait, decl_tests, tests::CallWithDispatchInfo}; diff --git a/frame/support/src/weights.rs b/frame/support/src/weights.rs index feb57bddfa659..0b741d3177cde 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -37,7 +37,7 @@ #[cfg(feature = "std")] use serde::{Serialize, Deserialize}; -use core::ops::Mul; +use core::ops::{Add, Mul}; use codec::{Encode, Decode}; use sp_arithmetic::traits::Bounded; use sp_runtime::{ @@ -110,6 +110,25 @@ impl Default for DispatchClass { } } +// Implement traits for raw Weight value +impl WeighData for Weight { + fn weigh_data(&self, _: T) -> Weight { + return *self + } +} + +impl ClassifyDispatch for Weight { + fn classify_dispatch(&self, _: T) -> DispatchClass { + DispatchClass::default() + } +} + +impl PaysFee for Weight { + fn pays_fee(&self, _: T) -> bool { + true + } +} + impl From for DispatchClass { fn from(tx: SimpleDispatchInfo) -> Self { match tx { @@ -383,36 +402,31 @@ impl GetDispatchInfo for sp_runtime::testing::TestX #[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)] pub struct RuntimeDbWeight { pub read: Weight, - pub read_repeat: Weight, - pub read_none: Weight, pub write: Weight, - pub write_repeat: Weight, - pub write_none: Weight, } -impl Mul<(Weight, Weight, Weight, Weight, Weight, Weight)> for RuntimeDbWeight { +impl Mul<(Weight, Weight)> for RuntimeDbWeight { type Output = Self; - fn mul(self, rhs: (Weight, Weight, Weight, Weight, Weight, Weight)) -> Self::Output { + fn mul(self, rhs: (Weight, Weight)) -> Self::Output { RuntimeDbWeight { read: self.read.saturating_mul(rhs.0), - read_repeat: self.read_repeat.saturating_mul(rhs.1), - read_none: self.read_none.saturating_mul(rhs.2), - write: self.write.saturating_mul(rhs.3), - write_repeat: self.write_repeat.saturating_mul(rhs.4), - write_none: self.write_none.saturating_mul(rhs.5), + write: self.write.saturating_mul(rhs.1), } } } +impl Add for RuntimeDbWeight { + type Output = Weight; + + fn add(self, rhs: Weight) -> Self::Output { + return self.weigh_data(()) + rhs + } +} + impl WeighData for RuntimeDbWeight { fn weigh_data(&self, _: T) -> Weight { - return self.read - .saturating_add(self.read_repeat) - .saturating_add(self.read_none) - .saturating_add(self.write) - .saturating_add(self.write_repeat) - .saturating_add(self.write_none) + return self.read.saturating_add(self.write) } } @@ -446,11 +460,7 @@ mod tests { parameter_types! { pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 100, - read_repeat: 10, - read_none: 100, write: 1000, - write_repeat: 20, - write_none: 1000, }; } @@ -474,7 +484,7 @@ mod tests { #[weight = FunctionOf(|_: (&u32, &u32)| 0, DispatchClass::Operational, true)] fn f12(_origin, _a: u32, _eb: u32) { unimplemented!(); } - #[weight = T::DbWeight::get() * (1, 2, 0, 1, 2, 0)] + #[weight = T::DbWeight::get() * (3, 2) + 10_000] fn f2(_origin) { unimplemented!(); } } @@ -487,7 +497,7 @@ mod tests { assert_eq!(Call::::f11(10, 20).get_dispatch_info().class, DispatchClass::Normal); assert_eq!(Call::::f12(10, 20).get_dispatch_info().weight, 0); assert_eq!(Call::::f12(10, 20).get_dispatch_info().class, DispatchClass::Operational); - assert_eq!(Call::::f2().get_dispatch_info().weight, 1160); + assert_eq!(Call::::f2().get_dispatch_info().weight, 12300); assert_eq!(Call::::f2().get_dispatch_info().class, DispatchClass::Normal); } } From d239667135c2b560be461bc6dca481e47836aa4e Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Thu, 9 Apr 2020 19:32:50 +0200 Subject: [PATCH 08/52] multiply all weights by 1_000 --- bin/node/runtime/src/lib.rs | 2 +- frame/authorship/src/lib.rs | 2 +- frame/collective/src/lib.rs | 10 ++--- frame/democracy/src/lib.rs | 56 ++++++++++++------------ frame/elections-phragmen/src/lib.rs | 12 ++--- frame/elections/src/lib.rs | 20 ++++----- frame/evm/src/lib.rs | 4 +- frame/example-offchain-worker/src/lib.rs | 4 +- frame/example/src/lib.rs | 2 +- frame/finality-tracker/src/lib.rs | 2 +- frame/identity/src/lib.rs | 22 +++++----- frame/membership/src/lib.rs | 14 +++--- frame/nicks/src/lib.rs | 8 ++-- frame/recovery/src/lib.rs | 14 +++--- frame/session/src/lib.rs | 4 +- frame/society/src/lib.rs | 24 +++++----- frame/staking/src/lib.rs | 46 +++++++++---------- frame/support/src/weights.rs | 2 +- frame/system/src/lib.rs | 18 ++++---- frame/timestamp/src/lib.rs | 2 +- frame/treasury/src/lib.rs | 16 +++---- frame/vesting/src/lib.rs | 2 +- 22 files changed, 143 insertions(+), 143 deletions(-) diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index f453e05951047..cb5d4f41e8102 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -256,7 +256,7 @@ parameter_types! { pub const TransactionBaseFee: Balance = 1 * CENTS; pub const TransactionByteFee: Balance = 10 * MILLICENTS; // setting this to zero will disable the weight fee. - pub const WeightFeeCoefficient: Balance = 1_000; + pub const WeightFeeCoefficient: Balance = 1_000_000; // for a sane configuration, this should always be less than `AvailableBlockRatio`. pub const TargetBlockFullness: Perbill = Perbill::from_percent(25); } diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index e6249849bf40c..af273e60b5d0d 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -207,7 +207,7 @@ decl_module! { } /// Provide a set of uncles. - #[weight = SimpleDispatchInfo::FixedMandatory(10_000)] + #[weight = SimpleDispatchInfo::FixedMandatory(10_000_000)] fn set_uncles(origin, new_uncles: Vec) -> dispatch::DispatchResult { ensure_none(origin)?; ensure!(new_uncles.len() <= MAX_UNCLES, Error::::TooManyUncles); diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 53e9853221f21..46140a378486f 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -187,7 +187,7 @@ decl_module! { /// - `prime`: The prime member whose vote sets the default. /// /// Requires root origin. - #[weight = SimpleDispatchInfo::FixedOperational(100_000)] + #[weight = SimpleDispatchInfo::FixedOperational(100_000_000)] fn set_members(origin, new_members: Vec, prime: Option) { ensure_root(origin)?; let mut new_members = new_members; @@ -200,7 +200,7 @@ decl_module! { /// Dispatch a proposal from a member using the `Member` origin. /// /// Origin must be a member of the collective. - #[weight = SimpleDispatchInfo::FixedOperational(100_000)] + #[weight = SimpleDispatchInfo::FixedOperational(100_000_000)] fn execute(origin, proposal: Box<>::Proposal>) { let who = ensure_signed(origin)?; ensure!(Self::is_member(&who), Error::::NotMember); @@ -214,7 +214,7 @@ decl_module! { /// - Bounded storage reads and writes. /// - Argument `threshold` has bearing on weight. /// # - #[weight = SimpleDispatchInfo::FixedOperational(5_000_000)] + #[weight = SimpleDispatchInfo::FixedOperational(5_000_000_000)] fn propose(origin, #[compact] threshold: MemberCount, proposal: Box<>::Proposal>) { let who = ensure_signed(origin)?; ensure!(Self::is_member(&who), Error::::NotMember); @@ -244,7 +244,7 @@ decl_module! { /// - Bounded storage read and writes. /// - Will be slightly heavier if the proposal is approved / disapproved after the vote. /// # - #[weight = SimpleDispatchInfo::FixedOperational(200_000)] + #[weight = SimpleDispatchInfo::FixedOperational(200_000_000)] fn vote(origin, proposal: T::Hash, #[compact] index: ProposalIndex, approve: bool) { let who = ensure_signed(origin)?; ensure!(Self::is_member(&who), Error::::NotMember); @@ -303,7 +303,7 @@ decl_module! { /// - `M` is number of members, /// - `P` is number of active proposals, /// - `L` is the encoded length of `proposal` preimage. - #[weight = SimpleDispatchInfo::FixedOperational(200_000)] + #[weight = SimpleDispatchInfo::FixedOperational(200_000_000)] fn close(origin, proposal: T::Hash, #[compact] index: ProposalIndex) { let _ = ensure_signed(origin)?; diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index b09f305c64247..0caa63a561076 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -546,7 +546,7 @@ decl_module! { /// - P is the number proposals in the `PublicProps` vec. /// - Two DB changes, one DB entry. /// # - #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(5_000_000_000)] fn propose(origin, proposal_hash: T::Hash, #[compact] value: BalanceOf @@ -577,7 +577,7 @@ decl_module! { /// - S is the number of seconds a proposal already has. /// - One DB entry. /// # - #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(5_000_000_000)] fn second(origin, #[compact] proposal: PropIndex) { let who = ensure_signed(origin)?; let mut deposit = Self::deposit_of(proposal) @@ -600,7 +600,7 @@ decl_module! { /// - R is the number of referendums the voter has voted on. /// - One DB change, one DB entry. /// # - #[weight = SimpleDispatchInfo::FixedNormal(200_000)] + #[weight = SimpleDispatchInfo::FixedNormal(200_000_000)] fn vote(origin, #[compact] ref_index: ReferendumIndex, vote: AccountVote>, @@ -621,7 +621,7 @@ decl_module! { /// - `O(1)`. /// - One DB change, one DB entry. /// # - #[weight = SimpleDispatchInfo::FixedNormal(200_000)] + #[weight = SimpleDispatchInfo::FixedNormal(200_000_000)] fn proxy_vote(origin, #[compact] ref_index: ReferendumIndex, vote: AccountVote>, @@ -641,7 +641,7 @@ decl_module! { /// # /// - `O(1)`. /// # - #[weight = SimpleDispatchInfo::FixedOperational(500_000)] + #[weight = SimpleDispatchInfo::FixedOperational(500_000_000)] fn emergency_cancel(origin, ref_index: ReferendumIndex) { T::CancellationOrigin::ensure_origin(origin)?; @@ -664,7 +664,7 @@ decl_module! { /// - `O(1)`. /// - One DB change. /// # - #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(5_000_000_000)] fn external_propose(origin, proposal_hash: T::Hash) { T::ExternalOrigin::ensure_origin(origin)?; ensure!(!>::exists(), Error::::DuplicateProposal); @@ -691,7 +691,7 @@ decl_module! { /// - `O(1)`. /// - One DB change. /// # - #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(5_000_000_000)] fn external_propose_majority(origin, proposal_hash: T::Hash) { T::ExternalMajorityOrigin::ensure_origin(origin)?; >::put((proposal_hash, VoteThreshold::SimpleMajority)); @@ -711,7 +711,7 @@ decl_module! { /// - `O(1)`. /// - One DB change. /// # - #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(5_000_000_000)] fn external_propose_default(origin, proposal_hash: T::Hash) { T::ExternalDefaultOrigin::ensure_origin(origin)?; >::put((proposal_hash, VoteThreshold::SuperMajorityAgainst)); @@ -736,7 +736,7 @@ decl_module! { /// - One DB change. /// - One extra DB entry. /// # - #[weight = SimpleDispatchInfo::FixedNormal(200_000)] + #[weight = SimpleDispatchInfo::FixedNormal(200_000_000)] fn fast_track(origin, proposal_hash: T::Hash, voting_period: T::BlockNumber, @@ -787,7 +787,7 @@ decl_module! { /// be very large. /// - O(log v), v is number of `existing_vetoers` /// # - #[weight = SimpleDispatchInfo::FixedNormal(200_000)] + #[weight = SimpleDispatchInfo::FixedNormal(200_000_000)] fn veto_external(origin, proposal_hash: T::Hash) { let who = T::VetoOrigin::ensure_origin(origin)?; @@ -820,7 +820,7 @@ decl_module! { /// # /// - `O(1)`. /// # - #[weight = SimpleDispatchInfo::FixedOperational(10_000)] + #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] 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 = SimpleDispatchInfo::FixedOperational(10_000)] + #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] fn cancel_queued(origin, which: ReferendumIndex) { ensure_root(origin)?; T::Scheduler::cancel_named((DEMOCRACY_ID, which)) @@ -862,7 +862,7 @@ decl_module! { /// # /// - One extra DB entry. /// # - #[weight = SimpleDispatchInfo::FixedNormal(100_000)] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000)] fn activate_proxy(origin, proxy: T::AccountId) { let who = ensure_signed(origin)?; Proxy::::try_mutate(&proxy, |a| match a.take() { @@ -885,7 +885,7 @@ decl_module! { /// # /// - One DB clear. /// # - #[weight = SimpleDispatchInfo::FixedNormal(100_000)] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000)] fn close_proxy(origin) { let who = ensure_signed(origin)?; Proxy::::mutate(&who, |a| { @@ -909,7 +909,7 @@ decl_module! { /// # /// - One DB clear. /// # - #[weight = SimpleDispatchInfo::FixedNormal(100_000)] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000)] fn deactivate_proxy(origin, proxy: T::AccountId) { let who = ensure_signed(origin)?; Proxy::::try_mutate(&proxy, |a| match a.take() { @@ -942,7 +942,7 @@ decl_module! { /// /// # /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] pub fn delegate(origin, to: T::AccountId, conviction: Conviction, balance: BalanceOf) { let who = ensure_signed(origin)?; Self::try_delegate(who, to, conviction, balance)?; @@ -961,7 +961,7 @@ decl_module! { /// # /// - O(1). /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] fn undelegate(origin) { let who = ensure_signed(origin)?; Self::try_undelegate(who)?; @@ -975,7 +975,7 @@ decl_module! { /// - `O(1)`. /// - One DB clear. /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn clear_public_proposals(origin) { ensure_root(origin)?; @@ -995,7 +995,7 @@ decl_module! { /// - Dependent on the size of `encoded_proposal` but protected by a /// required deposit. /// # - #[weight = SimpleDispatchInfo::FixedNormal(100_000)] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000)] fn note_preimage(origin, encoded_proposal: Vec) { let who = ensure_signed(origin)?; let proposal_hash = T::Hashing::hash(&encoded_proposal[..]); @@ -1030,7 +1030,7 @@ decl_module! { /// # /// - Dependent on the size of `encoded_proposal` and length of dispatch queue. /// # - #[weight = SimpleDispatchInfo::FixedNormal(100_000)] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000)] fn note_imminent_preimage(origin, encoded_proposal: Vec) { let who = ensure_signed(origin)?; let proposal_hash = T::Hashing::hash(&encoded_proposal[..]); @@ -1066,7 +1066,7 @@ decl_module! { /// # /// - One DB clear. /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn reap_preimage(origin, proposal_hash: T::Hash) { let who = ensure_signed(origin)?; let (provider, deposit, since, expiry) = >::get(&proposal_hash) @@ -1096,7 +1096,7 @@ decl_module! { /// # /// - `O(1)`. /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn unlock(origin, target: T::AccountId) { ensure_signed(origin)?; Self::update_lock(&target); @@ -1115,7 +1115,7 @@ decl_module! { /// # /// - One extra DB entry. /// # - #[weight = SimpleDispatchInfo::FixedNormal(100_000)] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000)] fn open_proxy(origin, target: T::AccountId) { let who = ensure_signed(origin)?; Proxy::::mutate(&who, |a| { @@ -1154,7 +1154,7 @@ decl_module! { /// # /// - `O(R + log R)` where R is the number of referenda that `target` has voted on. /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] 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! { /// # /// - `O(R + log R)` where R is the number of referenda that `target` has voted on. /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] 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 }; @@ -1207,7 +1207,7 @@ decl_module! { /// /// # /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] pub fn proxy_delegate(origin, to: T::AccountId, conviction: Conviction, @@ -1231,7 +1231,7 @@ decl_module! { /// # /// - O(1). /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] fn proxy_undelegate(origin) { let who = ensure_signed(origin)?; let target = Self::proxy(who).and_then(|a| a.as_active()).ok_or(Error::::NotProxy)?; @@ -1251,7 +1251,7 @@ decl_module! { /// # /// - `O(R + log R)` where R is the number of referenda that `target` has voted on. /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] 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::::NotProxy)?; diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 036a5f492c19c..0467f110e6865 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -291,7 +291,7 @@ decl_module! { /// Reads: O(1) /// Writes: O(V) given `V` votes. V is bounded by 16. /// # - #[weight = SimpleDispatchInfo::FixedNormal(100_000)] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000)] fn vote(origin, votes: Vec, #[compact] value: BalanceOf) { let who = ensure_signed(origin)?; @@ -336,7 +336,7 @@ decl_module! { /// Reads: O(1) /// Writes: O(1) /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn remove_voter(origin) { let who = ensure_signed(origin)?; @@ -358,7 +358,7 @@ decl_module! { /// Reads: O(NLogM) given M current candidates and N votes for `target`. /// Writes: O(1) /// # - #[weight = SimpleDispatchInfo::FixedNormal(1_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(1_000_000_000)] fn report_defunct_voter(origin, target: ::Source) { let reporter = ensure_signed(origin)?; let target = T::Lookup::lookup(target)?; @@ -401,7 +401,7 @@ decl_module! { /// Reads: O(LogN) Given N candidates. /// Writes: O(1) /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] fn submit_candidacy(origin) { let who = ensure_signed(origin)?; @@ -428,7 +428,7 @@ decl_module! { /// - `origin` is a current member. In this case, the bond is unreserved and origin is /// removed as a member, consequently not being a candidate for the next round anymore. /// Similar to [`remove_voter`], if replacement runners exists, they are immediately used. - #[weight = SimpleDispatchInfo::FixedOperational(2_000_000)] + #[weight = SimpleDispatchInfo::FixedOperational(2_000_000_000)] fn renounce_candidacy(origin) { let who = ensure_signed(origin)?; @@ -487,7 +487,7 @@ decl_module! { /// Reads: O(do_phragmen) /// Writes: O(do_phragmen) /// # - #[weight = SimpleDispatchInfo::FixedOperational(2_000_000)] + #[weight = SimpleDispatchInfo::FixedOperational(2_000_000_000)] fn remove_member(origin, who: ::Source) -> DispatchResult { ensure_root(origin)?; let who = T::Lookup::lookup(who)?; diff --git a/frame/elections/src/lib.rs b/frame/elections/src/lib.rs index a8ea0b8c2e455..478ead6156ee2 100644 --- a/frame/elections/src/lib.rs +++ b/frame/elections/src/lib.rs @@ -405,7 +405,7 @@ decl_module! { /// - Two extra DB entries, one DB change. /// - Argument `votes` is limited in length to number of candidates. /// # - #[weight = SimpleDispatchInfo::FixedNormal(2_500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(2_500_000_000)] fn set_approvals( origin, votes: Vec, @@ -423,7 +423,7 @@ decl_module! { /// # /// - Same as `set_approvals` with one additional storage read. /// # - #[weight = SimpleDispatchInfo::FixedNormal(2_500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(2_500_000_000)] fn proxy_set_approvals(origin, votes: Vec, #[compact] index: VoteIndex, @@ -446,7 +446,7 @@ decl_module! { /// - O(1). /// - Two fewer DB entries, one DB change. /// # - #[weight = SimpleDispatchInfo::FixedNormal(2_500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(2_500_000_000)] fn reap_inactive_voter( origin, #[compact] reporter_index: u32, @@ -520,7 +520,7 @@ decl_module! { /// - O(1). /// - Two fewer DB entries, one DB change. /// # - #[weight = SimpleDispatchInfo::FixedNormal(1_250_000)] + #[weight = SimpleDispatchInfo::FixedNormal(1_250_000_000)] fn retract_voter(origin, #[compact] index: u32) { let who = ensure_signed(origin)?; @@ -548,7 +548,7 @@ decl_module! { /// - Independent of input. /// - Three DB changes. /// # - #[weight = SimpleDispatchInfo::FixedNormal(2_500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(2_500_000_000)] fn submit_candidacy(origin, #[compact] slot: u32) { let who = ensure_signed(origin)?; @@ -585,7 +585,7 @@ decl_module! { /// - O(voters) compute. /// - One DB change. /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000_000)] fn present_winner( origin, candidate: ::Source, @@ -659,7 +659,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 = SimpleDispatchInfo::FixedOperational(10_000)] + #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] fn set_desired_seats(origin, #[compact] count: u32) { ensure_root(origin)?; DesiredSeats::put(count); @@ -669,7 +669,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 = SimpleDispatchInfo::FixedOperational(10_000)] + #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] fn remove_member(origin, who: ::Source) { ensure_root(origin)?; let who = T::Lookup::lookup(who)?; @@ -684,7 +684,7 @@ decl_module! { /// Set the presentation duration. If there is currently a vote being presented for, will /// invoke `finalize_vote`. - #[weight = SimpleDispatchInfo::FixedOperational(10_000)] + #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] fn set_presentation_duration(origin, #[compact] count: T::BlockNumber) { ensure_root(origin)?; >::put(count); @@ -692,7 +692,7 @@ decl_module! { /// Set the presentation duration. If there is current a vote being presented for, will /// invoke `finalize_vote`. - #[weight = SimpleDispatchInfo::FixedOperational(10_000)] + #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] fn set_term_duration(origin, #[compact] count: T::BlockNumber) { ensure_root(origin)?; >::put(count); diff --git a/frame/evm/src/lib.rs b/frame/evm/src/lib.rs index a50c545a461c1..84f7cda95adc1 100644 --- a/frame/evm/src/lib.rs +++ b/frame/evm/src/lib.rs @@ -191,7 +191,7 @@ decl_module! { fn deposit_event() = default; /// Deposit balance from currency/balances module into EVM. - #[weight = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn deposit_balance(origin, value: BalanceOf) { let sender = ensure_signed(origin)?; @@ -212,7 +212,7 @@ decl_module! { } /// Withdraw balance from EVM into currency/balances module. - #[weight = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn withdraw_balance(origin, value: BalanceOf) { let sender = ensure_signed(origin)?; let address = T::ConvertAccountId::convert_account_id(&sender); diff --git a/frame/example-offchain-worker/src/lib.rs b/frame/example-offchain-worker/src/lib.rs index ac9ac2d1eea4f..741cc7dd0db8b 100644 --- a/frame/example-offchain-worker/src/lib.rs +++ b/frame/example-offchain-worker/src/lib.rs @@ -157,7 +157,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 = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn submit_price(origin, price: u32) -> DispatchResult { // Retrieve sender of the transaction. let who = ensure_signed(origin)?; @@ -182,7 +182,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 = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn submit_price_unsigned(origin, _block_number: T::BlockNumber, price: u32) -> DispatchResult { diff --git a/frame/example/src/lib.rs b/frame/example/src/lib.rs index 13985671c2e79..f2cf09809ecb6 100644 --- a/frame/example/src/lib.rs +++ b/frame/example/src/lib.rs @@ -468,7 +468,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 = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] 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)?; diff --git a/frame/finality-tracker/src/lib.rs b/frame/finality-tracker/src/lib.rs index 8200543ffa171..7248280c2184a 100644 --- a/frame/finality-tracker/src/lib.rs +++ b/frame/finality-tracker/src/lib.rs @@ -76,7 +76,7 @@ decl_module! { /// Hint that the author of this block thinks the best finalized /// block is the given number. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedMandatory(10_000)] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedMandatory(10_000_000)] fn final_hint(origin, #[compact] hint: T::BlockNumber) { ensure_none(origin)?; ensure!(!::Update::exists(), Error::::AlreadyUpdated); diff --git a/frame/identity/src/lib.rs b/frame/identity/src/lib.rs index 2a2d1c9cf8404..d8f10bafd170b 100644 --- a/frame/identity/src/lib.rs +++ b/frame/identity/src/lib.rs @@ -474,7 +474,7 @@ decl_module! { /// - One storage mutation (codec `O(R)`). /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn add_registrar(origin, account: T::AccountId) { T::RegistrarOrigin::try_origin(origin) .map(|_| ()) @@ -506,7 +506,7 @@ decl_module! { /// - One storage mutation (codec-read `O(X' + R)`, codec-write `O(X + R)`). /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn set_identity(origin, info: IdentityInfo) { let sender = ensure_signed(origin)?; let extra_fields = info.additional.len() as u32; @@ -552,7 +552,7 @@ decl_module! { /// - At most O(2 * S + 1) storage mutations; codec complexity `O(1 * S + S * 1)`); /// one storage-exists. /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn set_subs(origin, subs: Vec<(T::AccountId, Data)>) { let sender = ensure_signed(origin)?; ensure!(>::contains_key(&sender), Error::::NotFound); @@ -599,7 +599,7 @@ decl_module! { /// - `S + 2` storage deletions. /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn clear_identity(origin) { let sender = ensure_signed(origin)?; @@ -638,7 +638,7 @@ decl_module! { /// - Storage: 1 read `O(R)`, 1 mutate `O(X + R)`. /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn request_judgement(origin, #[compact] reg_index: RegistrarIndex, #[compact] max_fee: BalanceOf, @@ -684,7 +684,7 @@ decl_module! { /// - One storage mutation `O(R + X)`. /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn cancel_request(origin, reg_index: RegistrarIndex) { let sender = ensure_signed(origin)?; let mut id = >::get(&sender).ok_or(Error::::NoIdentity)?; @@ -715,7 +715,7 @@ decl_module! { /// - `O(R)`. /// - One storage mutation `O(R)`. /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn set_fee(origin, #[compact] index: RegistrarIndex, #[compact] fee: BalanceOf, @@ -742,7 +742,7 @@ decl_module! { /// - `O(R)`. /// - One storage mutation `O(R)`. /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn set_account_id(origin, #[compact] index: RegistrarIndex, new: T::AccountId, @@ -769,7 +769,7 @@ decl_module! { /// - `O(R)`. /// - One storage mutation `O(R)`. /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn set_fields(origin, #[compact] index: RegistrarIndex, fields: IdentityFields, @@ -803,7 +803,7 @@ decl_module! { /// - Storage: 1 read `O(R)`, 1 mutate `O(R + X)`. /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn provide_judgement(origin, #[compact] reg_index: RegistrarIndex, target: ::Source, @@ -852,7 +852,7 @@ decl_module! { /// - `S + 2` storage mutations. /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(100_000)] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000)] fn kill_identity(origin, target: ::Source) { T::ForceOrigin::try_origin(origin) .map(|_| ()) diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index 8f086fa2f3211..6710a7050f9bb 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -118,7 +118,7 @@ decl_module! { /// Add a member `who` to the set. /// /// May only be called from `AddOrigin` or root. - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn add_member(origin, who: T::AccountId) { T::AddOrigin::try_origin(origin) .map(|_| ()) @@ -137,7 +137,7 @@ decl_module! { /// Remove a member `who` from the set. /// /// May only be called from `RemoveOrigin` or root. - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn remove_member(origin, who: T::AccountId) { T::RemoveOrigin::try_origin(origin) .map(|_| ()) @@ -159,7 +159,7 @@ decl_module! { /// May only be called from `SwapOrigin` or root. /// /// Prime membership is *not* passed from `remove` to `add`, if extant. - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn swap_member(origin, remove: T::AccountId, add: T::AccountId) { T::SwapOrigin::try_origin(origin) .map(|_| ()) @@ -188,7 +188,7 @@ decl_module! { /// pass `members` pre-sorted. /// /// May only be called from `ResetOrigin` or root. - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn reset_members(origin, members: Vec) { T::ResetOrigin::try_origin(origin) .map(|_| ()) @@ -211,7 +211,7 @@ decl_module! { /// May only be called from `Signed` origin of a current member. /// /// Prime membership is passed from the origin account to `new`, if extant. - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn change_key(origin, new: T::AccountId) { let remove = ensure_signed(origin)?; @@ -239,7 +239,7 @@ decl_module! { } /// Set the prime member. Must be a current member. - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn set_prime(origin, who: T::AccountId) { T::PrimeOrigin::try_origin(origin) .map(|_| ()) @@ -250,7 +250,7 @@ decl_module! { } /// Remove the prime member if it exists. - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn clear_prime(origin) { T::PrimeOrigin::try_origin(origin) .map(|_| ()) diff --git a/frame/nicks/src/lib.rs b/frame/nicks/src/lib.rs index ae005e2500b85..ae3061995f6a8 100644 --- a/frame/nicks/src/lib.rs +++ b/frame/nicks/src/lib.rs @@ -141,7 +141,7 @@ decl_module! { /// - One storage read/write. /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn set_name(origin, name: Vec) { let sender = ensure_signed(origin)?; @@ -171,7 +171,7 @@ decl_module! { /// - One storage read/write. /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(70_000)] + #[weight = SimpleDispatchInfo::FixedNormal(70_000_000)] fn clear_name(origin) { let sender = ensure_signed(origin)?; @@ -195,7 +195,7 @@ decl_module! { /// - One storage read/write. /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(70_000)] + #[weight = SimpleDispatchInfo::FixedNormal(70_000_000)] fn kill_name(origin, target: ::Source) { T::ForceOrigin::try_origin(origin) .map(|_| ()) @@ -223,7 +223,7 @@ decl_module! { /// - One storage read/write. /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(70_000)] + #[weight = SimpleDispatchInfo::FixedNormal(70_000_000)] fn force_name(origin, target: ::Source, name: Vec) { T::ForceOrigin::try_origin(origin) .map(|_| ()) diff --git a/frame/recovery/src/lib.rs b/frame/recovery/src/lib.rs index c055f2bd97c67..cd3b0e340555b 100644 --- a/frame/recovery/src/lib.rs +++ b/frame/recovery/src/lib.rs @@ -365,7 +365,7 @@ decl_module! { /// - One storage write O(1) /// - One event /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn set_recovered(origin, lost: T::AccountId, rescuer: T::AccountId) { ensure_root(origin)?; // Create the recovery storage item. @@ -400,7 +400,7 @@ decl_module! { /// /// Total Complexity: O(F + X) /// # - #[weight = SimpleDispatchInfo::FixedNormal(100_000)] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000)] fn create_recovery(origin, friends: Vec, threshold: u16, @@ -460,7 +460,7 @@ decl_module! { /// /// Total Complexity: O(F + X) /// # - #[weight = SimpleDispatchInfo::FixedNormal(100_000)] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000)] fn initiate_recovery(origin, account: T::AccountId) { let who = ensure_signed(origin)?; // Check that the account is recoverable @@ -506,7 +506,7 @@ decl_module! { /// /// Total Complexity: O(F + logF + V + logV) /// # - #[weight = SimpleDispatchInfo::FixedNormal(100_000)] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000)] fn vouch_recovery(origin, lost: T::AccountId, rescuer: T::AccountId) { let who = ensure_signed(origin)?; // Get the recovery configuration for the lost account. @@ -545,7 +545,7 @@ decl_module! { /// /// Total Complexity: O(F + V) /// # - #[weight = SimpleDispatchInfo::FixedNormal(100_000)] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000)] fn claim_recovery(origin, account: T::AccountId) { let who = ensure_signed(origin)?; // Get the recovery configuration for the lost account @@ -590,7 +590,7 @@ decl_module! { /// /// Total Complexity: O(V + X) /// # - #[weight = SimpleDispatchInfo::FixedNormal(30_000)] + #[weight = SimpleDispatchInfo::FixedNormal(30_000_000)] fn close_recovery(origin, rescuer: T::AccountId) { let who = ensure_signed(origin)?; // Take the active recovery process started by the rescuer for this account. @@ -622,7 +622,7 @@ decl_module! { /// /// Total Complexity: O(F + X) /// # - #[weight = SimpleDispatchInfo::FixedNormal(30_000)] + #[weight = SimpleDispatchInfo::FixedNormal(30_000_000)] fn remove_recovery(origin) { let who = ensure_signed(origin)?; // Check there are no active recoveries diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index 9346b060fa48a..e14b502bddc64 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -498,7 +498,7 @@ decl_module! { /// - Increases system account refs by one on success iff there were previously no keys set. /// In this case, purge_keys will need to be called before the account can be removed. /// # - #[weight = SimpleDispatchInfo::FixedNormal(150_000)] + #[weight = SimpleDispatchInfo::FixedNormal(150_000_000)] pub fn set_keys(origin, keys: T::Keys, proof: Vec) -> dispatch::DispatchResult { let who = ensure_signed(origin)?; @@ -519,7 +519,7 @@ decl_module! { /// - Removes N + 1 DB entries. /// - Reduces system account refs by one on success. /// # - #[weight = SimpleDispatchInfo::FixedNormal(150_000)] + #[weight = SimpleDispatchInfo::FixedNormal(150_000_000)] pub fn purge_keys(origin) { let who = ensure_signed(origin)?; Self::do_purge_keys(&who)?; diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index 2061c21d9c5f9..13ddd68550369 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -527,7 +527,7 @@ decl_module! { /// /// Total Complexity: O(M + B + C + logM + logB + X) /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] pub fn bid(origin, value: BalanceOf) -> DispatchResult { let who = ensure_signed(origin)?; ensure!(!>::contains_key(&who), Error::::Suspended); @@ -566,7 +566,7 @@ decl_module! { /// /// Total Complexity: O(B + X) /// # - #[weight = SimpleDispatchInfo::FixedNormal(20_000)] + #[weight = SimpleDispatchInfo::FixedNormal(20_000_000)] pub fn unbid(origin, pos: u32) -> DispatchResult { let who = ensure_signed(origin)?; @@ -636,7 +636,7 @@ decl_module! { /// /// Total Complexity: O(M + B + C + logM + logB + X) /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] pub fn vouch(origin, who: T::AccountId, value: BalanceOf, tip: BalanceOf) -> DispatchResult { let voucher = ensure_signed(origin)?; // Check user is not suspended. @@ -677,7 +677,7 @@ decl_module! { /// /// Total Complexity: O(B) /// # - #[weight = SimpleDispatchInfo::FixedNormal(20_000)] + #[weight = SimpleDispatchInfo::FixedNormal(20_000_000)] pub fn unvouch(origin, pos: u32) -> DispatchResult { let voucher = ensure_signed(origin)?; ensure!(Self::vouching(&voucher) == Some(VouchingStatus::Vouching), Error::::NotVouching); @@ -715,7 +715,7 @@ decl_module! { /// /// Total Complexity: O(M + logM + C) /// # - #[weight = SimpleDispatchInfo::FixedNormal(30_000)] + #[weight = SimpleDispatchInfo::FixedNormal(30_000_000)] pub fn vote(origin, candidate: ::Source, approve: bool) { let voter = ensure_signed(origin)?; let candidate = T::Lookup::lookup(candidate)?; @@ -746,7 +746,7 @@ decl_module! { /// /// Total Complexity: O(M + logM) /// # - #[weight = SimpleDispatchInfo::FixedNormal(20_000)] + #[weight = SimpleDispatchInfo::FixedNormal(20_000_000)] pub fn defender_vote(origin, approve: bool) { let voter = ensure_signed(origin)?; let members = >::get(); @@ -778,7 +778,7 @@ decl_module! { /// /// Total Complexity: O(M + logM + P + X) /// # - #[weight = SimpleDispatchInfo::FixedNormal(30_000)] + #[weight = SimpleDispatchInfo::FixedNormal(30_000_000)] pub fn payout(origin) { let who = ensure_signed(origin)?; @@ -820,7 +820,7 @@ decl_module! { /// /// Total Complexity: O(1) /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn found(origin, founder: T::AccountId, max_members: u32, rules: Vec) { T::FounderSetOrigin::ensure_origin(origin)?; ensure!(!>::exists(), Error::::AlreadyFounded); @@ -847,7 +847,7 @@ decl_module! { /// /// Total Complexity: O(1) /// # - #[weight = SimpleDispatchInfo::FixedNormal(20_000)] + #[weight = SimpleDispatchInfo::FixedNormal(20_000_000)] fn unfound(origin) { let founder = ensure_signed(origin)?; ensure!(Founder::::get() == Some(founder.clone()), Error::::NotFounder); @@ -889,7 +889,7 @@ decl_module! { /// /// Total Complexity: O(M + logM + B) /// # - #[weight = SimpleDispatchInfo::FixedNormal(30_000)] + #[weight = SimpleDispatchInfo::FixedNormal(30_000_000)] fn judge_suspended_member(origin, who: T::AccountId, forgive: bool) { T::SuspensionJudgementOrigin::ensure_origin(origin)?; ensure!(>::contains_key(&who), Error::::NotSuspended); @@ -960,7 +960,7 @@ decl_module! { /// /// Total Complexity: O(M + logM + B + X) /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn judge_suspended_candidate(origin, who: T::AccountId, judgement: Judgement) { T::SuspensionJudgementOrigin::ensure_origin(origin)?; if let Some((value, kind)) = >::get(&who) { @@ -1020,7 +1020,7 @@ decl_module! { /// /// Total Complexity: O(1) /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn set_max_members(origin, max: u32) { ensure_root(origin)?; ensure!(max > 1, Error::::MaxMembers); diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index da860bd63e943..d1cd21cdf2d3f 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -1251,7 +1251,7 @@ decl_module! { /// NOTE: Two of the storage writes (`Self::bonded`, `Self::payee`) are _never_ cleaned /// unless the `origin` falls below _existential deposit_ and gets removed as dust. /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] pub fn bond(origin, controller: ::Source, #[compact] value: BalanceOf, @@ -1315,7 +1315,7 @@ decl_module! { /// - O(1). /// - One DB entry. /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] fn bond_extra(origin, #[compact] max_additional: BalanceOf) { ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed); let stash = ensure_signed(origin)?; @@ -1361,7 +1361,7 @@ decl_module! { /// `withdraw_unbonded`. /// - One DB entry. /// - #[weight = SimpleDispatchInfo::FixedNormal(400_000)] + #[weight = SimpleDispatchInfo::FixedNormal(400_000_000)] fn unbond(origin, #[compact] value: BalanceOf) { ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed); let controller = ensure_signed(origin)?; @@ -1409,7 +1409,7 @@ decl_module! { /// - Contains a limited number of reads, yet the size of which could be large based on `ledger`. /// - Writes are limited to the `origin` account key. /// # - #[weight = SimpleDispatchInfo::FixedNormal(400_000)] + #[weight = SimpleDispatchInfo::FixedNormal(400_000_000)] fn withdraw_unbonded(origin) { ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed); let controller = ensure_signed(origin)?; @@ -1452,7 +1452,7 @@ decl_module! { /// - Contains a limited number of reads. /// - Writes are limited to the `origin` account key. /// # - #[weight = SimpleDispatchInfo::FixedNormal(750_000)] + #[weight = SimpleDispatchInfo::FixedNormal(750_000_000)] pub fn validate(origin, prefs: ValidatorPrefs) { ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed); let controller = ensure_signed(origin)?; @@ -1475,7 +1475,7 @@ decl_module! { /// which is capped at CompactAssignments::LIMIT. /// - Both the reads and writes follow a similar pattern. /// # - #[weight = SimpleDispatchInfo::FixedNormal(750_000)] + #[weight = SimpleDispatchInfo::FixedNormal(750_000_000)] pub fn nominate(origin, targets: Vec<::Source>) { ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed); let controller = ensure_signed(origin)?; @@ -1510,7 +1510,7 @@ decl_module! { /// - Contains one read. /// - Writes are limited to the `origin` account key. /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] fn chill(origin) { ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed); let controller = ensure_signed(origin)?; @@ -1529,7 +1529,7 @@ decl_module! { /// - Contains a limited number of reads. /// - Writes are limited to the `origin` account key. /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] fn set_payee(origin, payee: RewardDestination) { let controller = ensure_signed(origin)?; let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; @@ -1548,7 +1548,7 @@ decl_module! { /// - Contains a limited number of reads. /// - Writes are limited to the `origin` account key. /// # - #[weight = SimpleDispatchInfo::FixedNormal(750_000)] + #[weight = SimpleDispatchInfo::FixedNormal(750_000_000)] fn set_controller(origin, controller: ::Source) { let stash = ensure_signed(origin)?; let old_controller = Self::bonded(&stash).ok_or(Error::::NotStash)?; @@ -1565,7 +1565,7 @@ decl_module! { } /// The ideal number of validators. - #[weight = SimpleDispatchInfo::FixedNormal(5_000)] + #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] fn set_validator_count(origin, #[compact] new: u32) { ensure_root(origin)?; ValidatorCount::put(new); @@ -1576,7 +1576,7 @@ decl_module! { /// # /// - No arguments. /// # - #[weight = SimpleDispatchInfo::FixedNormal(5_000)] + #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] fn force_no_eras(origin) { ensure_root(origin)?; ForceEra::put(Forcing::ForceNone); @@ -1588,21 +1588,21 @@ decl_module! { /// # /// - No arguments. /// # - #[weight = SimpleDispatchInfo::FixedNormal(5_000)] + #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] fn force_new_era(origin) { ensure_root(origin)?; ForceEra::put(Forcing::ForceNew); } /// Set the validators who cannot be slashed (if any). - #[weight = SimpleDispatchInfo::FixedNormal(5_000)] + #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] fn set_invulnerables(origin, validators: Vec) { ensure_root(origin)?; >::put(validators); } /// Force a current staker to become completely unstaked, immediately. - #[weight = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn force_unstake(origin, stash: T::AccountId) { ensure_root(origin)?; @@ -1618,7 +1618,7 @@ decl_module! { /// # /// - One storage write /// # - #[weight = SimpleDispatchInfo::FixedNormal(5_000)] + #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] fn force_new_era_always(origin) { ensure_root(origin)?; ForceEra::put(Forcing::ForceAlways); @@ -1631,7 +1631,7 @@ decl_module! { /// # /// - One storage write. /// # - #[weight = SimpleDispatchInfo::FixedNormal(1_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(1_000_000_000)] fn cancel_deferred_slash(origin, era: EraIndex, slash_indices: Vec) { T::SlashCancelOrigin::try_origin(origin) .map(|_| ()) @@ -1682,7 +1682,7 @@ decl_module! { /// maximum number of validators that may be nominated by a single nominator, it is /// bounded only economically (all nominators are required to place a minimum stake). /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] fn payout_nominator(origin, era: EraIndex, validators: Vec<(T::AccountId, u32)>) -> DispatchResult { @@ -1709,7 +1709,7 @@ decl_module! { /// - Time complexity: O(1). /// - Contains a limited number of reads and writes. /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] fn payout_validator(origin, era: EraIndex) -> DispatchResult { let ctrl = ensure_signed(origin)?; Self::do_payout_validator(ctrl, era) @@ -1730,7 +1730,7 @@ decl_module! { /// - Time complexity: at most O(MaxNominatorRewardedPerValidator). /// - Contains a limited number of reads and writes. /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] fn payout_stakers(origin, validator_stash: T::AccountId, era: EraIndex) -> DispatchResult { ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed); ensure_signed(origin)?; @@ -1746,7 +1746,7 @@ decl_module! { /// - Time complexity: O(1). Bounded by `MAX_UNLOCKING_CHUNKS`. /// - Storage changes: Can't increase storage, only decrease it. /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] fn rebond(origin, #[compact] value: BalanceOf) { ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed); let controller = ensure_signed(origin)?; @@ -1760,7 +1760,7 @@ decl_module! { /// Set history_depth value. /// /// Origin must be root. - #[weight = SimpleDispatchInfo::FixedOperational(500_000)] + #[weight = SimpleDispatchInfo::FixedOperational(500_000_000)] fn set_history_depth(origin, #[compact] new_history_depth: EraIndex) { ensure_root(origin)?; if let Some(current_era) = Self::current_era() { @@ -1863,7 +1863,7 @@ decl_module! { /// /// The weight of this call is 1/10th of the blocks total weight. /// # - #[weight = SimpleDispatchInfo::FixedNormal(100_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000_000)] pub fn submit_election_solution( origin, winners: Vec, @@ -1886,7 +1886,7 @@ decl_module! { /// Note that this must pass the [`ValidateUnsigned`] check which only allows transactions /// from the local node to be included. In other words, only the block author can include a /// transaction in the block. - #[weight = SimpleDispatchInfo::FixedNormal(100_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000_000)] pub fn submit_election_solution_unsigned( origin, winners: Vec, diff --git a/frame/support/src/weights.rs b/frame/support/src/weights.rs index 0b741d3177cde..cb9d5be555e6b 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -292,7 +292,7 @@ impl PaysFee for SimpleDispatchInfo { impl Default for SimpleDispatchInfo { fn default() -> Self { // Default weight of all transactions. - SimpleDispatchInfo::FixedNormal(10_000) + SimpleDispatchInfo::FixedNormal(10_000_000) } } diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index 803f118ea915b..ed7dad7bd9e55 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -485,20 +485,20 @@ decl_module! { } /// Make some on-chain remark. - #[weight = SimpleDispatchInfo::FixedNormal(10_000)] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn remark(origin, _remark: Vec) { ensure_signed(origin)?; } /// Set the number of pages in the WebAssembly environment's heap. - #[weight = SimpleDispatchInfo::FixedOperational(10_000)] + #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] 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 = SimpleDispatchInfo::FixedOperational(200_000)] + #[weight = SimpleDispatchInfo::FixedOperational(200_000_000)] pub fn set_code(origin, code: Vec) { Self::can_set_code(origin, &code)?; @@ -507,7 +507,7 @@ decl_module! { } /// Set the new runtime code without doing any checks of the given `code`. - #[weight = SimpleDispatchInfo::FixedOperational(200_000)] + #[weight = SimpleDispatchInfo::FixedOperational(200_000_000)] pub fn set_code_without_checks(origin, code: Vec) { ensure_root(origin)?; storage::unhashed::put_raw(well_known_keys::CODE, &code); @@ -515,7 +515,7 @@ decl_module! { } /// Set the new changes trie configuration. - #[weight = SimpleDispatchInfo::FixedOperational(20_000)] + #[weight = SimpleDispatchInfo::FixedOperational(20_000_000)] pub fn set_changes_trie_config(origin, changes_trie_config: Option) { ensure_root(origin)?; match changes_trie_config.clone() { @@ -533,7 +533,7 @@ decl_module! { } /// Set some items of storage. - #[weight = SimpleDispatchInfo::FixedOperational(10_000)] + #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] fn set_storage(origin, items: Vec) { ensure_root(origin)?; for i in &items { @@ -542,7 +542,7 @@ decl_module! { } /// Kill some items from storage. - #[weight = SimpleDispatchInfo::FixedOperational(10_000)] + #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] fn kill_storage(origin, keys: Vec) { ensure_root(origin)?; for key in &keys { @@ -551,7 +551,7 @@ decl_module! { } /// Kill all storage items with a key that starts with the given prefix. - #[weight = SimpleDispatchInfo::FixedOperational(10_000)] + #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] fn kill_prefix(origin, prefix: Key) { ensure_root(origin)?; storage::unhashed::kill_prefix(&prefix); @@ -559,7 +559,7 @@ decl_module! { /// Kill the sending account, assuming there are no references outstanding and the composite /// data is equal to its default value. - #[weight = SimpleDispatchInfo::FixedOperational(25_000)] + #[weight = SimpleDispatchInfo::FixedOperational(25_000_000)] fn suicide(origin) { let who = ensure_signed(origin)?; let account = Account::::get(&who); diff --git a/frame/timestamp/src/lib.rs b/frame/timestamp/src/lib.rs index 6df8b46065650..269fe845635ff 100644 --- a/frame/timestamp/src/lib.rs +++ b/frame/timestamp/src/lib.rs @@ -147,7 +147,7 @@ decl_module! { /// `MinimumPeriod`. /// /// The dispatch origin for this call must be `Inherent`. - #[weight = SimpleDispatchInfo::FixedMandatory(10_000)] + #[weight = SimpleDispatchInfo::FixedMandatory(10_000_000)] fn set(origin, #[compact] now: T::Moment) { ensure_none(origin)?; assert!(!::DidUpdate::exists(), "Timestamp must be updated only once in the block"); diff --git a/frame/treasury/src/lib.rs b/frame/treasury/src/lib.rs index f07b9b511e168..08afec217e840 100644 --- a/frame/treasury/src/lib.rs +++ b/frame/treasury/src/lib.rs @@ -327,7 +327,7 @@ decl_module! { /// - Limited storage reads. /// - One DB change, one extra DB entry. /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000)] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] fn propose_spend( origin, #[compact] value: BalanceOf, @@ -354,7 +354,7 @@ decl_module! { /// - Limited storage reads. /// - One DB clear. /// # - #[weight = SimpleDispatchInfo::FixedOperational(100_000)] + #[weight = SimpleDispatchInfo::FixedOperational(100_000_000)] fn reject_proposal(origin, #[compact] proposal_id: ProposalIndex) { T::RejectOrigin::try_origin(origin) .map(|_| ()) @@ -376,7 +376,7 @@ decl_module! { /// - Limited storage reads. /// - One DB change. /// # - #[weight = SimpleDispatchInfo::FixedOperational(100_000)] + #[weight = SimpleDispatchInfo::FixedOperational(100_000_000)] fn approve_proposal(origin, #[compact] proposal_id: ProposalIndex) { T::ApproveOrigin::try_origin(origin) .map(|_| ()) @@ -405,7 +405,7 @@ decl_module! { /// - One storage mutation (codec `O(R)`). /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(100_000)] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000)] fn report_awesome(origin, reason: Vec, who: T::AccountId) { let finder = ensure_signed(origin)?; @@ -447,7 +447,7 @@ decl_module! { /// - Two storage removals (one read, codec `O(T)`). /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn retract_tip(origin, hash: T::Hash) { let who = ensure_signed(origin)?; let tip = Tips::::get(&hash).ok_or(Error::::UnknownTip)?; @@ -479,7 +479,7 @@ decl_module! { /// - Two storage insertions (codecs `O(R)`, `O(T)`), one read `O(1)`. /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(150_000)] + #[weight = SimpleDispatchInfo::FixedNormal(150_000_000)] fn tip_new(origin, reason: Vec, who: T::AccountId, tip_value: BalanceOf) { let tipper = ensure_signed(origin)?; ensure!(T::Tippers::contains(&tipper), BadOrigin); @@ -513,7 +513,7 @@ decl_module! { /// - One storage mutation (codec `O(T)`), one storage read `O(1)`. /// - Up to one event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn tip(origin, hash: T::Hash, tip_value: BalanceOf) { let tipper = ensure_signed(origin)?; ensure!(T::Tippers::contains(&tipper), BadOrigin); @@ -539,7 +539,7 @@ decl_module! { /// - One storage retrieval (codec `O(T)`) and two removals. /// - Up to three balance operations. /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000)] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn close_tip(origin, hash: T::Hash) { ensure_signed(origin)?; diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index b0c98e78bd6f7..230c9c4bd4906 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -236,7 +236,7 @@ decl_module! { /// - Creates a new storage entry, but is protected by a minimum transfer /// amount needed to succeed. /// # - #[weight = SimpleDispatchInfo::FixedNormal(1_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(1_000_000_000)] pub fn vested_transfer( origin, target: ::Source, From 04ff18d700dd7bb7e9d242f027b48cc25233efce Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Thu, 9 Apr 2020 19:36:09 +0200 Subject: [PATCH 09/52] Fix tests --- test-utils/runtime/src/lib.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index 099e509c64ccb..97354ee5da865 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -382,11 +382,7 @@ parameter_types! { pub const MaximumBlockWeight: Weight = 4 * 1024 * 1024; pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 100, - read_repeat: 10, - read_none: 100, write: 1000, - write_repeat: 20, - write_none: 1000, }; pub const MaximumBlockLength: u32 = 4 * 1024 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); From 189cbb16ac04b789957f35880f215f1047a47997 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Thu, 9 Apr 2020 20:05:38 +0200 Subject: [PATCH 10/52] backfill trait --- bin/node-template/pallets/template/src/mock.rs | 1 + bin/node/runtime/src/lib.rs | 1 + frame/assets/src/lib.rs | 1 + frame/aura/src/mock.rs | 1 + frame/authority-discovery/src/lib.rs | 1 + frame/authorship/src/lib.rs | 1 + frame/babe/src/mock.rs | 1 + frame/balances/src/lib.rs | 2 +- frame/balances/src/tests_composite.rs | 3 +-- frame/balances/src/tests_local.rs | 3 +-- frame/collective/src/lib.rs | 1 + frame/contracts/src/tests.rs | 1 + frame/democracy/src/tests.rs | 1 + frame/elections-phragmen/src/lib.rs | 1 + frame/elections/src/mock.rs | 1 + frame/example-offchain-worker/src/tests.rs | 1 + frame/example/src/lib.rs | 1 + frame/executive/src/lib.rs | 1 + frame/finality-tracker/src/lib.rs | 1 + frame/generic-asset/src/mock.rs | 1 + frame/grandpa/src/mock.rs | 1 + frame/identity/src/lib.rs | 1 + frame/im-online/src/mock.rs | 1 + frame/indices/src/mock.rs | 1 + frame/membership/src/lib.rs | 1 + frame/nicks/src/lib.rs | 1 + frame/offences/src/mock.rs | 1 + frame/randomness-collective-flip/src/lib.rs | 1 + frame/recovery/src/mock.rs | 1 + frame/scheduler/src/lib.rs | 1 + frame/scored-pool/src/mock.rs | 1 + frame/session/src/mock.rs | 1 + frame/society/src/mock.rs | 1 + frame/staking/src/mock.rs | 1 + frame/support/src/dispatch.rs | 2 +- frame/system/benches/bench.rs | 1 + frame/system/src/lib.rs | 3 +-- frame/timestamp/src/lib.rs | 1 + frame/transaction-payment/src/lib.rs | 1 + frame/treasury/src/tests.rs | 1 + frame/utility/src/tests.rs | 1 + frame/vesting/src/lib.rs | 1 + test-utils/runtime/src/lib.rs | 2 +- 43 files changed, 43 insertions(+), 9 deletions(-) diff --git a/bin/node-template/pallets/template/src/mock.rs b/bin/node-template/pallets/template/src/mock.rs index a93ac0359e3a2..fdabf7d03a490 100644 --- a/bin/node-template/pallets/template/src/mock.rs +++ b/bin/node-template/pallets/template/src/mock.rs @@ -36,6 +36,7 @@ impl system::Trait for Test { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index cb5d4f41e8102..ca8fd04fdb070 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -181,6 +181,7 @@ impl frame_system::Trait for Runtime { type Event = Event; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = Version; diff --git a/frame/assets/src/lib.rs b/frame/assets/src/lib.rs index 388eb7780bd6d..9385656203e9c 100644 --- a/frame/assets/src/lib.rs +++ b/frame/assets/src/lib.rs @@ -292,6 +292,7 @@ mod tests { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); diff --git a/frame/aura/src/mock.rs b/frame/aura/src/mock.rs index 05a161ee49c3d..2716806b6eddd 100644 --- a/frame/aura/src/mock.rs +++ b/frame/aura/src/mock.rs @@ -57,6 +57,7 @@ impl frame_system::Trait for Test { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); diff --git a/frame/authority-discovery/src/lib.rs b/frame/authority-discovery/src/lib.rs index b8f28b432ba75..b3edce481868d 100644 --- a/frame/authority-discovery/src/lib.rs +++ b/frame/authority-discovery/src/lib.rs @@ -154,6 +154,7 @@ mod tests { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index af273e60b5d0d..24cd8a1a05ec2 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -429,6 +429,7 @@ mod tests { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); diff --git a/frame/babe/src/mock.rs b/frame/babe/src/mock.rs index ea802b268e399..1c7d02a56c981 100644 --- a/frame/babe/src/mock.rs +++ b/frame/babe/src/mock.rs @@ -68,6 +68,7 @@ impl frame_system::Trait for Test { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type ModuleToIndex = (); diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 0b58e57689cfb..7e438b1ad7e2a 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -159,7 +159,7 @@ use sp_std::{cmp, result, mem, fmt::Debug, ops::BitOr, convert::Infallible}; use codec::{Codec, Encode, Decode}; use frame_support::{ StorageValue, Parameter, decl_event, decl_storage, decl_module, decl_error, ensure, - weights::SimpleDispatchInfo, traits::{ + traits::{ Currency, OnKilledAccount, OnUnbalanced, TryDrop, StoredMap, WithdrawReason, WithdrawReasons, LockIdentifier, LockableCurrency, ExistenceRequirement, Imbalance, SignedImbalance, ReservableCurrency, Get, ExistenceRequirement::KeepAlive, diff --git a/frame/balances/src/tests_composite.rs b/frame/balances/src/tests_composite.rs index ff54c9cc70300..dcfe7994418d1 100644 --- a/frame/balances/src/tests_composite.rs +++ b/frame/balances/src/tests_composite.rs @@ -51,7 +51,6 @@ pub struct Test; parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 1024; - pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight::default(); pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } @@ -68,7 +67,7 @@ impl frame_system::Trait for Test { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; - type DbWeight = DbWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/balances/src/tests_local.rs b/frame/balances/src/tests_local.rs index e892e5b4ec540..5ed4decdc9442 100644 --- a/frame/balances/src/tests_local.rs +++ b/frame/balances/src/tests_local.rs @@ -51,7 +51,6 @@ pub struct Test; parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 1024; - pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight::default(); pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } @@ -68,7 +67,7 @@ impl frame_system::Trait for Test { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; - type DbWeight = DbWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 46140a378486f..b5626ae4a6814 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -553,6 +553,7 @@ mod tests { type Event = Event; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index 1a5aa08454d14..2bcd708904b41 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -111,6 +111,7 @@ impl frame_system::Trait for Test { type Event = MetaEvent; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); diff --git a/frame/democracy/src/tests.rs b/frame/democracy/src/tests.rs index e7320da082801..4d540f63d5080 100644 --- a/frame/democracy/src/tests.rs +++ b/frame/democracy/src/tests.rs @@ -80,6 +80,7 @@ impl frame_system::Trait for Test { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 0467f110e6865..c0a8f3a45906d 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -907,6 +907,7 @@ mod tests { type Event = Event; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/elections/src/mock.rs b/frame/elections/src/mock.rs index 2898be26ca300..a304478abbf34 100644 --- a/frame/elections/src/mock.rs +++ b/frame/elections/src/mock.rs @@ -50,6 +50,7 @@ impl frame_system::Trait for Test { type Event = Event; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/example-offchain-worker/src/tests.rs b/frame/example-offchain-worker/src/tests.rs index 727c4942f6882..59da11ae5bd72 100644 --- a/frame/example-offchain-worker/src/tests.rs +++ b/frame/example-offchain-worker/src/tests.rs @@ -61,6 +61,7 @@ impl frame_system::Trait for Test { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/example/src/lib.rs b/frame/example/src/lib.rs index f2cf09809ecb6..b577667ea8241 100644 --- a/frame/example/src/lib.rs +++ b/frame/example/src/lib.rs @@ -753,6 +753,7 @@ mod tests { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index 20c79fe4a5cac..99f934afd247b 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -476,6 +476,7 @@ mod tests { type Event = MetaEvent; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = RuntimeVersion; diff --git a/frame/finality-tracker/src/lib.rs b/frame/finality-tracker/src/lib.rs index 7248280c2184a..f80ea1707acdd 100644 --- a/frame/finality-tracker/src/lib.rs +++ b/frame/finality-tracker/src/lib.rs @@ -260,6 +260,7 @@ mod tests { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); diff --git a/frame/generic-asset/src/mock.rs b/frame/generic-asset/src/mock.rs index c805b793bc7b4..2cd779da03078 100644 --- a/frame/generic-asset/src/mock.rs +++ b/frame/generic-asset/src/mock.rs @@ -57,6 +57,7 @@ impl frame_system::Trait for Test { type Header = Header; type Event = TestEvent; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type BlockHashCount = BlockHashCount; diff --git a/frame/grandpa/src/mock.rs b/frame/grandpa/src/mock.rs index 8b94becd5aa6a..90b7c97437a27 100644 --- a/frame/grandpa/src/mock.rs +++ b/frame/grandpa/src/mock.rs @@ -61,6 +61,7 @@ impl frame_system::Trait for Test { type Event = TestEvent; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/identity/src/lib.rs b/frame/identity/src/lib.rs index d8f10bafd170b..1eb3cc410aaf0 100644 --- a/frame/identity/src/lib.rs +++ b/frame/identity/src/lib.rs @@ -930,6 +930,7 @@ mod tests { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/im-online/src/mock.rs b/frame/im-online/src/mock.rs index 73ccaf3f707cb..d620bb51b7436 100644 --- a/frame/im-online/src/mock.rs +++ b/frame/im-online/src/mock.rs @@ -114,6 +114,7 @@ impl frame_system::Trait for Runtime { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/indices/src/mock.rs b/frame/indices/src/mock.rs index 355b3cc792c94..b8786c2dc82e8 100644 --- a/frame/indices/src/mock.rs +++ b/frame/indices/src/mock.rs @@ -61,6 +61,7 @@ impl frame_system::Trait for Test { type Event = MetaEvent; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index 6710a7050f9bb..e968be19a6be1 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -315,6 +315,7 @@ mod tests { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/nicks/src/lib.rs b/frame/nicks/src/lib.rs index ae3061995f6a8..b8a2359450458 100644 --- a/frame/nicks/src/lib.rs +++ b/frame/nicks/src/lib.rs @@ -282,6 +282,7 @@ mod tests { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/offences/src/mock.rs b/frame/offences/src/mock.rs index e464200396ebd..7eda40cbbbd7c 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -100,6 +100,7 @@ impl frame_system::Trait for Runtime { type Event = TestEvent; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/randomness-collective-flip/src/lib.rs b/frame/randomness-collective-flip/src/lib.rs index fdc465b4dc3bb..1117f69960788 100644 --- a/frame/randomness-collective-flip/src/lib.rs +++ b/frame/randomness-collective-flip/src/lib.rs @@ -195,6 +195,7 @@ mod tests { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); diff --git a/frame/recovery/src/mock.rs b/frame/recovery/src/mock.rs index 9327ece572212..ccc80730a19e6 100644 --- a/frame/recovery/src/mock.rs +++ b/frame/recovery/src/mock.rs @@ -75,6 +75,7 @@ impl frame_system::Trait for Test { type Event = TestEvent; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/scheduler/src/lib.rs b/frame/scheduler/src/lib.rs index f70204cb1a6b7..3e53b7a505b1e 100644 --- a/frame/scheduler/src/lib.rs +++ b/frame/scheduler/src/lib.rs @@ -348,6 +348,7 @@ mod tests { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/scored-pool/src/mock.rs b/frame/scored-pool/src/mock.rs index a28b7891370ea..07bd8cffbfbcb 100644 --- a/frame/scored-pool/src/mock.rs +++ b/frame/scored-pool/src/mock.rs @@ -66,6 +66,7 @@ impl frame_system::Trait for Test { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/session/src/mock.rs b/frame/session/src/mock.rs index a888dcfb28e99..9e8c77edf3eb6 100644 --- a/frame/session/src/mock.rs +++ b/frame/session/src/mock.rs @@ -184,6 +184,7 @@ impl frame_system::Trait for Test { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); diff --git a/frame/society/src/mock.rs b/frame/society/src/mock.rs index a66a5e6e047d4..a410fdbd04240 100644 --- a/frame/society/src/mock.rs +++ b/frame/society/src/mock.rs @@ -75,6 +75,7 @@ impl frame_system::Trait for Test { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index 6332486b65099..00d417a469472 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -203,6 +203,7 @@ impl frame_system::Trait for Test { type Event = MetaEvent; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index aadcec67a3606..6ed5d63e1bb16 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -2294,7 +2294,7 @@ mod tests { // default weight. assert_eq!( Call::::aux_0().get_dispatch_info(), - DispatchInfo { weight: 10_000, class: DispatchClass::Normal, pays_fee: true }, + DispatchInfo { weight: 10_000_000, class: DispatchClass::Normal, pays_fee: true }, ); // custom basic assert_eq!( diff --git a/frame/system/benches/bench.rs b/frame/system/benches/bench.rs index 90a4ad1d34de8..36711d3177790 100644 --- a/frame/system/benches/bench.rs +++ b/frame/system/benches/bench.rs @@ -72,6 +72,7 @@ impl system::Trait for Runtime { type Event = Event; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index ed7dad7bd9e55..29e5034ecb4f6 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -1600,7 +1600,6 @@ mod tests { parameter_types! { pub const BlockHashCount: u64 = 10; pub const MaximumBlockWeight: Weight = 1024; - pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight::default(); pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); pub const MaximumBlockLength: u32 = 1024; pub const Version: RuntimeVersion = RuntimeVersion { @@ -1648,7 +1647,7 @@ mod tests { type Event = u16; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; - type DbWeight = DbWeight; + type DbWeight = (); type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = Version; diff --git a/frame/timestamp/src/lib.rs b/frame/timestamp/src/lib.rs index 269fe845635ff..13337833fbe4f 100644 --- a/frame/timestamp/src/lib.rs +++ b/frame/timestamp/src/lib.rs @@ -301,6 +301,7 @@ mod tests { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index 7cf364d700f42..94135c04e6095 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -312,6 +312,7 @@ mod tests { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/treasury/src/tests.rs b/frame/treasury/src/tests.rs index 5ad78dcad7935..132690d29f3f6 100644 --- a/frame/treasury/src/tests.rs +++ b/frame/treasury/src/tests.rs @@ -56,6 +56,7 @@ impl frame_system::Trait for Test { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); diff --git a/frame/utility/src/tests.rs b/frame/utility/src/tests.rs index 68bdabd6d9b7f..1b26bb5d5b1fa 100644 --- a/frame/utility/src/tests.rs +++ b/frame/utility/src/tests.rs @@ -71,6 +71,7 @@ impl frame_system::Trait for Test { type Event = TestEvent; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index 230c9c4bd4906..6408691b2e123 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -381,6 +381,7 @@ mod tests { type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index 97354ee5da865..a853912893d36 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -401,7 +401,7 @@ impl frame_system::Trait for Runtime { type Event = Event; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; - type DbWeight = DbWeight; + type DbWeight = (); type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); From 42814c01b9990c2b20b2f05f72364246771bf463 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Thu, 9 Apr 2020 20:10:18 +0200 Subject: [PATCH 11/52] Missed one --- frame/generic-asset/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/frame/generic-asset/src/lib.rs b/frame/generic-asset/src/lib.rs index b16666cb6b7e1..d8c91aff65438 100644 --- a/frame/generic-asset/src/lib.rs +++ b/frame/generic-asset/src/lib.rs @@ -1124,6 +1124,7 @@ impl frame_system::Trait for ElevatedTrait { type Event = (); type BlockHashCount = T::BlockHashCount; type MaximumBlockWeight = T::MaximumBlockWeight; + type DbWeight = (); type MaximumBlockLength = T::MaximumBlockLength; type AvailableBlockRatio = T::AvailableBlockRatio; type Version = T::Version; From f65bbd4b425ae4167437999d06c7333e4afac1dc Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Thu, 9 Apr 2020 20:22:04 +0200 Subject: [PATCH 12/52] more fixes --- bin/node-template/runtime/src/lib.rs | 2 ++ frame/balances/src/tests_composite.rs | 2 +- frame/balances/src/tests_local.rs | 2 +- frame/benchmarking/src/tests.rs | 1 + frame/evm/src/lib.rs | 6 +++--- frame/session/benchmarking/src/mock.rs | 1 + frame/support/src/weights.rs | 2 +- frame/system/src/lib.rs | 2 +- frame/transaction-payment/src/lib.rs | 2 +- 9 files changed, 12 insertions(+), 8 deletions(-) diff --git a/bin/node-template/runtime/src/lib.rs b/bin/node-template/runtime/src/lib.rs index 6af2dcce0fcea..6238ffda1a0c9 100644 --- a/bin/node-template/runtime/src/lib.rs +++ b/bin/node-template/runtime/src/lib.rs @@ -152,6 +152,8 @@ impl system::Trait for Runtime { type BlockHashCount = BlockHashCount; /// Maximum weight of each block. type MaximumBlockWeight = MaximumBlockWeight; + /// The weight of database operations that the runtime can invoke. + type DbWeight = (); /// 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. diff --git a/frame/balances/src/tests_composite.rs b/frame/balances/src/tests_composite.rs index dcfe7994418d1..72668ad0d853d 100644 --- a/frame/balances/src/tests_composite.rs +++ b/frame/balances/src/tests_composite.rs @@ -27,7 +27,7 @@ use sp_core::H256; use sp_io; use frame_support::{impl_outer_origin, parameter_types}; use frame_support::traits::Get; -use frame_support::weights::{Weight, RuntimeDbWeight, DispatchInfo}; +use frame_support::weights::{Weight, DispatchInfo}; use std::cell::RefCell; use crate::{GenesisConfig, Module, Trait, decl_tests, tests::CallWithDispatchInfo}; diff --git a/frame/balances/src/tests_local.rs b/frame/balances/src/tests_local.rs index 5ed4decdc9442..aab275c781a4c 100644 --- a/frame/balances/src/tests_local.rs +++ b/frame/balances/src/tests_local.rs @@ -27,7 +27,7 @@ use sp_core::H256; use sp_io; use frame_support::{impl_outer_origin, parameter_types}; use frame_support::traits::{Get, StorageMapShim}; -use frame_support::weights::{Weight, RuntimeDbWeight, DispatchInfo}; +use frame_support::weights::{Weight, DispatchInfo}; use std::cell::RefCell; use crate::{GenesisConfig, Module, Trait, decl_tests, tests::CallWithDispatchInfo}; diff --git a/frame/benchmarking/src/tests.rs b/frame/benchmarking/src/tests.rs index 50a39d0fcf1be..a84604f0fd549 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -78,6 +78,7 @@ impl frame_system::Trait for Test { type Event = (); type BlockHashCount = (); type MaximumBlockWeight = (); + type DbWeight = (); type MaximumBlockLength = (); type AvailableBlockRatio = (); type Version = (); diff --git a/frame/evm/src/lib.rs b/frame/evm/src/lib.rs index 84f7cda95adc1..e198c8c7aa1e0 100644 --- a/frame/evm/src/lib.rs +++ b/frame/evm/src/lib.rs @@ -236,7 +236,7 @@ decl_module! { } /// Issue an EVM call operation. This is similar to a message call transaction in Ethereum. - #[weight = FunctionOf(|(_, _, _, gas_limit, gas_price, _): (&H160, &Vec, &U256, &u32, &U256, &Option)| (*gas_price).saturated_into::().saturating_mul(*gas_limit), DispatchClass::Normal, true)] + #[weight = FunctionOf(|(_, _, _, gas_limit, gas_price, _): (&H160, &Vec, &U256, &u32, &U256, &Option)| (*gas_price).saturated_into::().saturating_mul(*gas_limit as Weight), DispatchClass::Normal, true)] fn call( origin, target: H160, @@ -267,7 +267,7 @@ decl_module! { /// Issue an EVM create operation. This is similar to a contract creation transaction in /// Ethereum. - #[weight = FunctionOf(|(_, _, gas_limit, gas_price, _): (&Vec, &U256, &u32, &U256, &Option)| (*gas_price).saturated_into::().saturating_mul(*gas_limit), DispatchClass::Normal, true)] + #[weight = FunctionOf(|(_, _, gas_limit, gas_price, _): (&Vec, &U256, &u32, &U256, &Option)| (*gas_price).saturated_into::().saturating_mul(*gas_limit as Weight), DispatchClass::Normal, true)] fn create( origin, init: Vec, @@ -302,7 +302,7 @@ decl_module! { } /// Issue an EVM create2 operation. - #[weight = FunctionOf(|(_, _, _, gas_limit, gas_price, _): (&Vec, &H256, &U256, &u32, &U256, &Option)| (*gas_price).saturated_into::().saturating_mul(*gas_limit), DispatchClass::Normal, true)] + #[weight = FunctionOf(|(_, _, _, gas_limit, gas_price, _): (&Vec, &H256, &U256, &u32, &U256, &Option)| (*gas_price).saturated_into::().saturating_mul(*gas_limit as Weight), DispatchClass::Normal, true)] fn create2( origin, init: Vec, diff --git a/frame/session/benchmarking/src/mock.rs b/frame/session/benchmarking/src/mock.rs index ff7965efcaceb..4c022eb8b89b6 100644 --- a/frame/session/benchmarking/src/mock.rs +++ b/frame/session/benchmarking/src/mock.rs @@ -69,6 +69,7 @@ impl frame_system::Trait for Test { type Event = (); type BlockHashCount = (); type MaximumBlockWeight = (); + type DbWeight = (); type AvailableBlockRatio = (); type MaximumBlockLength = (); type Version = (); diff --git a/frame/support/src/weights.rs b/frame/support/src/weights.rs index cb9d5be555e6b..c80c721c4e041 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -398,7 +398,7 @@ impl GetDispatchInfo for sp_runtime::testing::TestX } } -/// The weight of various database operations that the runtime can invoke. +/// The weight of database operations that the runtime can invoke. #[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)] pub struct RuntimeDbWeight { pub read: Weight, diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index 29e5034ecb4f6..cd1ad6b5913c1 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -195,7 +195,7 @@ pub trait Trait: 'static + Eq + Clone { /// The maximum weight of a block. type MaximumBlockWeight: Get; - /// The weight of runtime database operations. + /// The weight of runtime database operations the runtime can invoke. type DbWeight: Get; /// The maximum length of a block (in bytes). diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index 94135c04e6095..1153b947789e8 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -661,7 +661,7 @@ mod tests { { // Overflow is handled let dispatch_info = DispatchInfo { - weight: ::max_value(), + weight: Weight::max_value(), class: DispatchClass::Operational, pays_fee: true, }; From a16ae55fda90541f4131ae2dc20373c1c2244e77 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Thu, 9 Apr 2020 23:11:24 +0200 Subject: [PATCH 13/52] Fix tests --- bin/node/executor/tests/basic.rs | 12 +++++------- bin/node/executor/tests/fees.rs | 2 +- bin/node/executor/tests/submit_transaction.rs | 2 +- bin/node/runtime/src/impls.rs | 3 +-- bin/node/runtime/src/lib.rs | 5 +++-- 5 files changed, 11 insertions(+), 13 deletions(-) diff --git a/bin/node/executor/tests/basic.rs b/bin/node/executor/tests/basic.rs index fccf4a62cc21d..8da14111f29b4 100644 --- a/bin/node/executor/tests/basic.rs +++ b/bin/node/executor/tests/basic.rs @@ -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: 10000, class: DispatchClass::Mandatory, pays_fee: true } + DispatchInfo { weight: 10_000_000, class: DispatchClass::Mandatory, pays_fee: true } )), topics: vec![], }, @@ -359,7 +359,7 @@ fn full_native_block_import_works() { EventRecord { phase: Phase::ApplyExtrinsic(1), event: Event::frame_system(frame_system::RawEvent::ExtrinsicSuccess( - DispatchInfo { weight: 1000000, class: DispatchClass::Normal, pays_fee: true } + DispatchInfo { weight: 200_000_000, class: DispatchClass::Normal, pays_fee: true } )), 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: 10000, class: DispatchClass::Mandatory, pays_fee: true } + DispatchInfo { weight: 10_000_000, class: DispatchClass::Mandatory, pays_fee: true } )), topics: vec![], }, @@ -414,7 +414,7 @@ fn full_native_block_import_works() { EventRecord { phase: Phase::ApplyExtrinsic(1), event: Event::frame_system(frame_system::RawEvent::ExtrinsicSuccess( - DispatchInfo { weight: 1000000, class: DispatchClass::Normal, pays_fee: true } + DispatchInfo { weight: 200_000_000, class: DispatchClass::Normal, pays_fee: true } )), topics: vec![], }, @@ -437,7 +437,7 @@ fn full_native_block_import_works() { EventRecord { phase: Phase::ApplyExtrinsic(2), event: Event::frame_system(frame_system::RawEvent::ExtrinsicSuccess( - DispatchInfo { weight: 1000000, class: DispatchClass::Normal, pays_fee: true } + DispatchInfo { weight: 200_000_000, class: DispatchClass::Normal, pays_fee: true } )), topics: vec![], }, @@ -817,5 +817,3 @@ fn should_import_block_with_test_client() { client.import(BlockOrigin::Own, block).unwrap(); } - - diff --git a/bin/node/executor/tests/fees.rs b/bin/node/executor/tests/fees.rs index ea9d740a05ef8..4731c6f09c329 100644 --- a/bin/node/executor/tests/fees.rs +++ b/bin/node/executor/tests/fees.rs @@ -188,7 +188,7 @@ fn transaction_fee_is_correct_ultimate() { let weight_fee = LinearWeightToFee::::convert(weight); // we know that weight to fee multiplier is effect-less in block 1. - assert_eq!(weight_fee as Balance, MILLICENTS); + assert_eq!(weight_fee as Balance, MILLICENTS / 5); balance_alice -= weight_fee; balance_alice -= tip; diff --git a/bin/node/executor/tests/submit_transaction.rs b/bin/node/executor/tests/submit_transaction.rs index 536cf486e38ae..d92f3e3202f6e 100644 --- a/bin/node/executor/tests/submit_transaction.rs +++ b/bin/node/executor/tests/submit_transaction.rs @@ -178,7 +178,7 @@ fn submitted_transaction_should_be_valid() { let res = Executive::validate_transaction(source, extrinsic); assert_eq!(res.unwrap(), ValidTransaction { - priority: 2_411_002_000_000, + priority: 2_410_600_000_000, requires: vec![], provides: vec![(address, 0).encode()], longevity: 128, diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index 646dc24f578de..49eefc09a2dfc 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -51,8 +51,7 @@ pub struct LinearWeightToFee(sp_std::marker::PhantomData); impl> Convert for LinearWeightToFee { fn convert(w: Weight) -> Balance { - // substrate-node a weight of 10_000 (smallest non-zero weight) to be mapped to 10^7 units of - // fees, hence: + // setting this to zero will disable the weight fee. let coefficient = C::get(); Balance::from(w).saturating_mul(coefficient) } diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index ca8fd04fdb070..604e76f1d6777 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -256,8 +256,9 @@ impl pallet_balances::Trait for Runtime { parameter_types! { pub const TransactionBaseFee: Balance = 1 * CENTS; pub const TransactionByteFee: Balance = 10 * MILLICENTS; - // setting this to zero will disable the weight fee. - pub const WeightFeeCoefficient: Balance = 1_000_000; + // In the Substrate node, a weight of 10_000_000 (smallest non-zero weight) + // is mapped to 10_000_000 units of fees, hence: + pub const WeightFeeCoefficient: Balance = 1; // for a sane configuration, this should always be less than `AvailableBlockRatio`. pub const TargetBlockFullness: Perbill = Perbill::from_percent(25); } From c3ad5fb6bac37c13413f772ee795fa08e5b8ea23 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Fri, 10 Apr 2020 13:14:57 +0200 Subject: [PATCH 14/52] update fixed 64 docs --- primitives/arithmetic/src/fixed64.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/primitives/arithmetic/src/fixed64.rs b/primitives/arithmetic/src/fixed64.rs index 6b399b6aa5106..9c7c71e96727b 100644 --- a/primitives/arithmetic/src/fixed64.rs +++ b/primitives/arithmetic/src/fixed64.rs @@ -26,8 +26,10 @@ use crate::{ } }; -/// An unsigned fixed point number. Can hold any value in the range [-9_223_372_036, 9_223_372_036] -/// with fixed point accuracy of one billion. +/// An signed fixed point number. Can represent any value in the range [-9.223372036, 9.223372036] +/// with fixed point accuracy of nine decimal points. +/// +/// This fixed point number is represented as an i64 divided by a billion. #[derive(Encode, Decode, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct Fixed64(i64); From 428ec844ccdbc88aa4922e8bfbdee6f087286785 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Fri, 10 Apr 2020 14:54:06 +0200 Subject: [PATCH 15/52] introduce fixed 128 --- primitives/arithmetic/src/fixed128.rs | 352 ++++++++++++++++++++++++++ primitives/arithmetic/src/fixed64.rs | 14 +- primitives/arithmetic/src/lib.rs | 2 + 3 files changed, 364 insertions(+), 4 deletions(-) create mode 100644 primitives/arithmetic/src/fixed128.rs diff --git a/primitives/arithmetic/src/fixed128.rs b/primitives/arithmetic/src/fixed128.rs new file mode 100644 index 0000000000000..53f2dc4e415b3 --- /dev/null +++ b/primitives/arithmetic/src/fixed128.rs @@ -0,0 +1,352 @@ +// Copyright 2020 Parity Technologies (UK) Ltd. +// This file is part of Substrate. + +// Substrate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Substrate is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Substrate. If not, see . + +use sp_std::{ + ops, prelude::*, + convert::{TryFrom, TryInto}, +}; +use codec::{Encode, Decode}; +use crate::{ + Perquintill, + traits::{ + SaturatedConversion, CheckedSub, CheckedAdd, CheckedDiv, Bounded, UniqueSaturatedInto, Saturating + }, + helpers_128bit::multiply_by_rational, +}; + +/// A signed fixed point number. Can hold any value in the range +/// [-170_141_183_460_469_231_731, 170_141_183_460_469_231_731] +/// with an additional fixed point accuracy of 18 decimal points. +/// i.e. 170000000000000000000.000000000000000001 can be represented by Fixed128. +#[derive(Encode, Decode, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct Fixed128(i128); + +/// The accuracy of the `Fixed128` type. +const DIV: i128 = 1_000_000_000_000_000_000; +const U_DIV: u128 = 1_000_000_000_000_000_000; + +impl Fixed128 { + /// creates self from a natural number. + /// + /// Note that this might be lossy. + pub fn from_natural(int: i128) -> Self { + Self(int.saturating_mul(DIV)) + } + + /// Return the accuracy of the type. Given that this function returns the value `X`, it means + /// that an instance composed of `X` parts (`Fixed128::from_parts(X)`) is equal to `1`. + pub fn accuracy() -> i128 { + DIV + } + + /// Consume self and return the inner value. + /// + /// This should only be used for testing. + #[cfg(any(feature = "std", test))] + pub fn into_inner(self) -> i128 { self.0 } + + /// Raw constructor. Equal to `parts / 1_000_000_000_000_000_000`. + pub fn from_parts(parts: i128) -> Self { + Self(parts) + } + + /// creates self from a rational number. Equal to `n/d`. + /// + /// Note that this might be lossy. + pub fn from_rational(n: i128, d: u128) -> Self { + // Turn n into a positive number, and track the original sign. + // This lossy by 1 if n is exactly i128.min_value() + let (n, sign): (u128, i128) = if n == i128::min_value() { + (i128::max_value().try_into().expect("i128 max value can fit into u128"), -1) + } else if n.is_negative() { + ((n * -1).try_into().expect("positive i128 can always fit into u128"), -1) + } else { + (n.try_into().expect("positive i128 can always fit into u128"), 1) + }; + // This should never fail, but if it does, it is because value was too big for u128 + // so we map to u128 max value. TODO: Can we expect here that value is always smaller? + let result = multiply_by_rational(n, U_DIV, d.max(1)).unwrap_or(u128::max_value()); + // If the u128 result wont fit in i128, we do i128 max. TODO: Can we expect value is always smaller? + let signed_result: i128 = sign * result.try_into().unwrap_or(i128::max_value()); + Self(signed_result) + } + + /// Performs a saturated multiply and accumulate by unsigned number. + /// + /// Returns a saturated `int + (self * int)`. + pub fn saturated_multiply_accumulate(self, int: N) -> N + where + N: TryFrom + From + UniqueSaturatedInto + Bounded + Clone + Saturating + + ops::Rem + ops::Div + ops::Mul + + ops::Add, + { + let div = DIV as u128; + let positive = self.0 > 0; + // safe to convert as absolute value. + let parts = self.0.checked_abs().map(|v| v as u128).unwrap_or(i128::max_value() as u128 + 1); + + + // will always fit. + let natural_parts = parts / div; + // might saturate. + let natural_parts: N = natural_parts.saturated_into(); + // fractional parts can always fit into u64. + let perquintill_parts = (parts % div) as u64; + + let n = int.clone().saturating_mul(natural_parts); + let p = Perquintill::from_parts(perquintill_parts) * int.clone(); + + // everything that needs to be either added or subtracted from the original weight. + let excess = n.saturating_add(p); + + if positive { + int.saturating_add(excess) + } else { + int.saturating_sub(excess) + } + } +} + +impl Saturating for Fixed128 { + fn saturating_add(self, rhs: Self) -> Self { + Self(self.0.saturating_add(rhs.0)) + } + + fn saturating_mul(self, rhs: Self) -> Self { + Self(self.0.saturating_mul(rhs.0) / DIV) + } + + fn saturating_sub(self, rhs: Self) -> Self { + Self(self.0.saturating_sub(rhs.0)) + } + + fn saturating_pow(self, exp: usize) -> Self { + Self(self.0.saturating_pow(exp as u32)) + } +} + +/// Note that this is a standard, _potentially-panicking_, implementation. Use `Saturating` trait +/// for safe addition. +impl ops::Add for Fixed128 { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self(self.0 + rhs.0) + } +} + +/// Note that this is a standard, _potentially-panicking_, implementation. Use `Saturating` trait +/// for safe subtraction. +impl ops::Sub for Fixed128 { + type Output = Self; + + fn sub(self, rhs: Self) -> Self::Output { + Self(self.0 - rhs.0) + } +} + +/// Note that this is a standard, _potentially-panicking_, implementation. Use `CheckedDiv` trait +/// for safe division. +impl ops::Div for Fixed128 { + type Output = Self; + + fn div(self, rhs: Self) -> Self::Output { + if rhs.0 == 0 { + let zero = 0; + return Fixed128::from_parts( self.0 / zero); + } + let (n, d) = if rhs.0 < 0 { + (-self.0, rhs.0.abs() as u128) + } else { + (self.0, rhs.0 as u128) + }; + Fixed128::from_rational(n, d) + } +} + +impl CheckedSub for Fixed128 { + fn checked_sub(&self, rhs: &Self) -> Option { + self.0.checked_sub(rhs.0).map(Self) + } +} + +impl CheckedAdd for Fixed128 { + fn checked_add(&self, rhs: &Self) -> Option { + self.0.checked_add(rhs.0).map(Self) + } +} + +impl CheckedDiv for Fixed128 { + fn checked_div(&self, rhs: &Self) -> Option { + if rhs.0 == 0 { + None + } else { + Some(*self / *rhs) + } + } +} + +impl sp_std::fmt::Debug for Fixed128 { + #[cfg(feature = "std")] + fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + write!(f, "Fixed128({},{})", self.0 / DIV, (self.0 % DIV) / 1000) + } + + #[cfg(not(feature = "std"))] + fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn max() -> Fixed128 { + Fixed128::from_parts(i128::max_value()) + } + fn min() -> Fixed128 { + Fixed128::from_parts(i128::min_value()) + } + + #[test] + fn fixed128_semantics() { + assert_eq!(Fixed128::from_rational(5, 2).0, 5 * 1_000_000_000_000_000_000 / 2); + assert_eq!(Fixed128::from_rational(5, 2), Fixed128::from_rational(10, 4)); + assert_eq!(Fixed128::from_rational(5, 0), Fixed128::from_rational(5, 1)); + + // biggest value that can be created. + assert_ne!(max(), Fixed128::from_natural(170141183460469231731)); + assert_eq!(max(), Fixed128::from_natural(170141183460469231732)); + // smallest value that can be created + assert_ne!(min(), Fixed128::from_natural(-170141183460469231731)); + assert_eq!(min(), Fixed128::from_natural(-170141183460469231732)); + } + + #[test] + fn fixed_128_growth_decrease_curve() { + let test_set = vec![0u64, 1, 10, 1000, 1_000_000_000, 1_000_000_000_000_000_000]; + + // negative (1/2) + let mut fm = Fixed128::from_rational(-1, 2); + test_set.clone().into_iter().for_each(|i| { + assert_eq!(fm.saturated_multiply_accumulate(i) as i64, i as i64 - i as i64 / 2); + }); + + // unit (1) multiplier + fm = Fixed128::from_parts(0); + test_set.clone().into_iter().for_each(|i| { + assert_eq!(fm.saturated_multiply_accumulate(i), i); + }); + + // i.5 multiplier + fm = Fixed128::from_rational(1, 2); + test_set.clone().into_iter().for_each(|i| { + assert_eq!(fm.saturated_multiply_accumulate(i), i * 3 / 2); + }); + + // dual multiplier + fm = Fixed128::from_rational(1, 1); + test_set.clone().into_iter().for_each(|i| { + assert_eq!(fm.saturated_multiply_accumulate(i), i * 2); + }); + } + + macro_rules! saturating_mul_acc_test { + ($num_type:tt) => { + assert_eq!( + Fixed128::from_rational(100, 1).saturated_multiply_accumulate(10 as $num_type), + 1010, + ); + assert_eq!( + Fixed128::from_rational(100, 2).saturated_multiply_accumulate(10 as $num_type), + 510, + ); + assert_eq!( + Fixed128::from_rational(100, 3).saturated_multiply_accumulate(0 as $num_type), + 0, + ); + assert_eq!( + Fixed128::from_rational(5, 1).saturated_multiply_accumulate($num_type::max_value()), + $num_type::max_value() + ); + assert_eq!( + max().saturated_multiply_accumulate($num_type::max_value()), + $num_type::max_value() + ); + } + } + + #[test] + fn fixed128_multiply_accumulate_works() { + saturating_mul_acc_test!(u64); + saturating_mul_acc_test!(u128); + saturating_mul_acc_test!(u128); + } + + #[test] + fn div_works() { + let a = Fixed128::from_rational(12, 10); + let b = Fixed128::from_rational(10, 1); + assert_eq!(a / b, Fixed128::from_rational(12, 100)); + + let a = Fixed128::from_rational(12, 10); + let b = Fixed128::from_rational(1, 100); + assert_eq!(a / b, Fixed128::from_rational(120, 1)); + + let a = Fixed128::from_rational(12, 100); + let b = Fixed128::from_rational(10, 1); + assert_eq!(a / b, Fixed128::from_rational(12, 1000)); + + let a = Fixed128::from_rational(12, 100); + let b = Fixed128::from_rational(1, 100); + assert_eq!(a / b, Fixed128::from_rational(12, 1)); + + let a = Fixed128::from_rational(-12, 10); + let b = Fixed128::from_rational(10, 1); + assert_eq!(a / b, Fixed128::from_rational(-12, 100)); + + let a = Fixed128::from_rational(12, 10); + let b = Fixed128::from_rational(-10, 1); + assert_eq!(a / b, Fixed128::from_rational(-12, 100)); + + let a = Fixed128::from_rational(-12, 10); + let b = Fixed128::from_rational(-10, 1); + assert_eq!(a / b, Fixed128::from_rational(12, 100)); + } + + #[test] + #[should_panic(expected = "attempt to divide by zero")] + fn div_zero() { + let a = Fixed128::from_rational(12, 10); + let b = Fixed128::from_natural(0); + let _ = a / b; + } + + #[test] + fn checked_div_zero() { + let a = Fixed128::from_rational(12, 10); + let b = Fixed128::from_natural(0); + assert_eq!(a.checked_div(&b), None); + } + + #[test] + fn checked_div_non_zero() { + let a = Fixed128::from_rational(12, 10); + let b = Fixed128::from_rational(1, 100); + assert_eq!(a.checked_div(&b), Some(Fixed128::from_rational(120, 1))); + } +} diff --git a/primitives/arithmetic/src/fixed64.rs b/primitives/arithmetic/src/fixed64.rs index 9c7c71e96727b..834fa8505cf8d 100644 --- a/primitives/arithmetic/src/fixed64.rs +++ b/primitives/arithmetic/src/fixed64.rs @@ -26,10 +26,9 @@ use crate::{ } }; -/// An signed fixed point number. Can represent any value in the range [-9.223372036, 9.223372036] -/// with fixed point accuracy of nine decimal points. -/// -/// This fixed point number is represented as an i64 divided by a billion. +/// A signed fixed point number. Can hold any value in the range [-9_223_372_036, 9_223_372_036] +/// with an additional fixed point accuracy of one billion. i.e. 9000000000.000000001 can be +/// represented by Fixed64. #[derive(Encode, Decode, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct Fixed64(i64); @@ -207,6 +206,10 @@ mod tests { Fixed64::from_parts(i64::max_value()) } + fn min() -> Fixed64 { + Fixed64::from_parts(i64::min_value()) + } + #[test] fn fixed64_semantics() { assert_eq!(Fixed64::from_rational(5, 2).0, 5 * 1_000_000_000 / 2); @@ -216,6 +219,9 @@ mod tests { // biggest value that can be created. assert_ne!(max(), Fixed64::from_natural(9_223_372_036)); assert_eq!(max(), Fixed64::from_natural(9_223_372_037)); + // smallest value that can be created. + assert_ne!(min(), Fixed64::from_natural(-9_223_372_036)); + assert_eq!(min(), Fixed64::from_natural(-9_223_372_037)); } #[test] diff --git a/primitives/arithmetic/src/lib.rs b/primitives/arithmetic/src/lib.rs index f6d8b53e3499b..fb70b13a15312 100644 --- a/primitives/arithmetic/src/lib.rs +++ b/primitives/arithmetic/src/lib.rs @@ -37,9 +37,11 @@ pub mod helpers_128bit; pub mod traits; mod per_things; mod fixed64; +mod fixed128; mod rational128; pub use fixed64::Fixed64; +pub use fixed128::Fixed128; pub use per_things::{PerThing, Percent, PerU16, Permill, Perbill, Perquintill}; pub use rational128::Rational128; From 30e4a210959c12a6e6439d1dd59b091a807bd4e6 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Fri, 10 Apr 2020 15:15:36 +0200 Subject: [PATCH 16/52] Revert "introduce fixed 128" This reverts commit 428ec844ccdbc88aa4922e8bfbdee6f087286785. --- primitives/arithmetic/src/fixed128.rs | 352 -------------------------- primitives/arithmetic/src/fixed64.rs | 14 +- primitives/arithmetic/src/lib.rs | 2 - 3 files changed, 4 insertions(+), 364 deletions(-) delete mode 100644 primitives/arithmetic/src/fixed128.rs diff --git a/primitives/arithmetic/src/fixed128.rs b/primitives/arithmetic/src/fixed128.rs deleted file mode 100644 index 53f2dc4e415b3..0000000000000 --- a/primitives/arithmetic/src/fixed128.rs +++ /dev/null @@ -1,352 +0,0 @@ -// Copyright 2020 Parity Technologies (UK) Ltd. -// This file is part of Substrate. - -// Substrate is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Substrate is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Substrate. If not, see . - -use sp_std::{ - ops, prelude::*, - convert::{TryFrom, TryInto}, -}; -use codec::{Encode, Decode}; -use crate::{ - Perquintill, - traits::{ - SaturatedConversion, CheckedSub, CheckedAdd, CheckedDiv, Bounded, UniqueSaturatedInto, Saturating - }, - helpers_128bit::multiply_by_rational, -}; - -/// A signed fixed point number. Can hold any value in the range -/// [-170_141_183_460_469_231_731, 170_141_183_460_469_231_731] -/// with an additional fixed point accuracy of 18 decimal points. -/// i.e. 170000000000000000000.000000000000000001 can be represented by Fixed128. -#[derive(Encode, Decode, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] -pub struct Fixed128(i128); - -/// The accuracy of the `Fixed128` type. -const DIV: i128 = 1_000_000_000_000_000_000; -const U_DIV: u128 = 1_000_000_000_000_000_000; - -impl Fixed128 { - /// creates self from a natural number. - /// - /// Note that this might be lossy. - pub fn from_natural(int: i128) -> Self { - Self(int.saturating_mul(DIV)) - } - - /// Return the accuracy of the type. Given that this function returns the value `X`, it means - /// that an instance composed of `X` parts (`Fixed128::from_parts(X)`) is equal to `1`. - pub fn accuracy() -> i128 { - DIV - } - - /// Consume self and return the inner value. - /// - /// This should only be used for testing. - #[cfg(any(feature = "std", test))] - pub fn into_inner(self) -> i128 { self.0 } - - /// Raw constructor. Equal to `parts / 1_000_000_000_000_000_000`. - pub fn from_parts(parts: i128) -> Self { - Self(parts) - } - - /// creates self from a rational number. Equal to `n/d`. - /// - /// Note that this might be lossy. - pub fn from_rational(n: i128, d: u128) -> Self { - // Turn n into a positive number, and track the original sign. - // This lossy by 1 if n is exactly i128.min_value() - let (n, sign): (u128, i128) = if n == i128::min_value() { - (i128::max_value().try_into().expect("i128 max value can fit into u128"), -1) - } else if n.is_negative() { - ((n * -1).try_into().expect("positive i128 can always fit into u128"), -1) - } else { - (n.try_into().expect("positive i128 can always fit into u128"), 1) - }; - // This should never fail, but if it does, it is because value was too big for u128 - // so we map to u128 max value. TODO: Can we expect here that value is always smaller? - let result = multiply_by_rational(n, U_DIV, d.max(1)).unwrap_or(u128::max_value()); - // If the u128 result wont fit in i128, we do i128 max. TODO: Can we expect value is always smaller? - let signed_result: i128 = sign * result.try_into().unwrap_or(i128::max_value()); - Self(signed_result) - } - - /// Performs a saturated multiply and accumulate by unsigned number. - /// - /// Returns a saturated `int + (self * int)`. - pub fn saturated_multiply_accumulate(self, int: N) -> N - where - N: TryFrom + From + UniqueSaturatedInto + Bounded + Clone + Saturating + - ops::Rem + ops::Div + ops::Mul + - ops::Add, - { - let div = DIV as u128; - let positive = self.0 > 0; - // safe to convert as absolute value. - let parts = self.0.checked_abs().map(|v| v as u128).unwrap_or(i128::max_value() as u128 + 1); - - - // will always fit. - let natural_parts = parts / div; - // might saturate. - let natural_parts: N = natural_parts.saturated_into(); - // fractional parts can always fit into u64. - let perquintill_parts = (parts % div) as u64; - - let n = int.clone().saturating_mul(natural_parts); - let p = Perquintill::from_parts(perquintill_parts) * int.clone(); - - // everything that needs to be either added or subtracted from the original weight. - let excess = n.saturating_add(p); - - if positive { - int.saturating_add(excess) - } else { - int.saturating_sub(excess) - } - } -} - -impl Saturating for Fixed128 { - fn saturating_add(self, rhs: Self) -> Self { - Self(self.0.saturating_add(rhs.0)) - } - - fn saturating_mul(self, rhs: Self) -> Self { - Self(self.0.saturating_mul(rhs.0) / DIV) - } - - fn saturating_sub(self, rhs: Self) -> Self { - Self(self.0.saturating_sub(rhs.0)) - } - - fn saturating_pow(self, exp: usize) -> Self { - Self(self.0.saturating_pow(exp as u32)) - } -} - -/// Note that this is a standard, _potentially-panicking_, implementation. Use `Saturating` trait -/// for safe addition. -impl ops::Add for Fixed128 { - type Output = Self; - - fn add(self, rhs: Self) -> Self::Output { - Self(self.0 + rhs.0) - } -} - -/// Note that this is a standard, _potentially-panicking_, implementation. Use `Saturating` trait -/// for safe subtraction. -impl ops::Sub for Fixed128 { - type Output = Self; - - fn sub(self, rhs: Self) -> Self::Output { - Self(self.0 - rhs.0) - } -} - -/// Note that this is a standard, _potentially-panicking_, implementation. Use `CheckedDiv` trait -/// for safe division. -impl ops::Div for Fixed128 { - type Output = Self; - - fn div(self, rhs: Self) -> Self::Output { - if rhs.0 == 0 { - let zero = 0; - return Fixed128::from_parts( self.0 / zero); - } - let (n, d) = if rhs.0 < 0 { - (-self.0, rhs.0.abs() as u128) - } else { - (self.0, rhs.0 as u128) - }; - Fixed128::from_rational(n, d) - } -} - -impl CheckedSub for Fixed128 { - fn checked_sub(&self, rhs: &Self) -> Option { - self.0.checked_sub(rhs.0).map(Self) - } -} - -impl CheckedAdd for Fixed128 { - fn checked_add(&self, rhs: &Self) -> Option { - self.0.checked_add(rhs.0).map(Self) - } -} - -impl CheckedDiv for Fixed128 { - fn checked_div(&self, rhs: &Self) -> Option { - if rhs.0 == 0 { - None - } else { - Some(*self / *rhs) - } - } -} - -impl sp_std::fmt::Debug for Fixed128 { - #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { - write!(f, "Fixed128({},{})", self.0 / DIV, (self.0 % DIV) / 1000) - } - - #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn max() -> Fixed128 { - Fixed128::from_parts(i128::max_value()) - } - fn min() -> Fixed128 { - Fixed128::from_parts(i128::min_value()) - } - - #[test] - fn fixed128_semantics() { - assert_eq!(Fixed128::from_rational(5, 2).0, 5 * 1_000_000_000_000_000_000 / 2); - assert_eq!(Fixed128::from_rational(5, 2), Fixed128::from_rational(10, 4)); - assert_eq!(Fixed128::from_rational(5, 0), Fixed128::from_rational(5, 1)); - - // biggest value that can be created. - assert_ne!(max(), Fixed128::from_natural(170141183460469231731)); - assert_eq!(max(), Fixed128::from_natural(170141183460469231732)); - // smallest value that can be created - assert_ne!(min(), Fixed128::from_natural(-170141183460469231731)); - assert_eq!(min(), Fixed128::from_natural(-170141183460469231732)); - } - - #[test] - fn fixed_128_growth_decrease_curve() { - let test_set = vec![0u64, 1, 10, 1000, 1_000_000_000, 1_000_000_000_000_000_000]; - - // negative (1/2) - let mut fm = Fixed128::from_rational(-1, 2); - test_set.clone().into_iter().for_each(|i| { - assert_eq!(fm.saturated_multiply_accumulate(i) as i64, i as i64 - i as i64 / 2); - }); - - // unit (1) multiplier - fm = Fixed128::from_parts(0); - test_set.clone().into_iter().for_each(|i| { - assert_eq!(fm.saturated_multiply_accumulate(i), i); - }); - - // i.5 multiplier - fm = Fixed128::from_rational(1, 2); - test_set.clone().into_iter().for_each(|i| { - assert_eq!(fm.saturated_multiply_accumulate(i), i * 3 / 2); - }); - - // dual multiplier - fm = Fixed128::from_rational(1, 1); - test_set.clone().into_iter().for_each(|i| { - assert_eq!(fm.saturated_multiply_accumulate(i), i * 2); - }); - } - - macro_rules! saturating_mul_acc_test { - ($num_type:tt) => { - assert_eq!( - Fixed128::from_rational(100, 1).saturated_multiply_accumulate(10 as $num_type), - 1010, - ); - assert_eq!( - Fixed128::from_rational(100, 2).saturated_multiply_accumulate(10 as $num_type), - 510, - ); - assert_eq!( - Fixed128::from_rational(100, 3).saturated_multiply_accumulate(0 as $num_type), - 0, - ); - assert_eq!( - Fixed128::from_rational(5, 1).saturated_multiply_accumulate($num_type::max_value()), - $num_type::max_value() - ); - assert_eq!( - max().saturated_multiply_accumulate($num_type::max_value()), - $num_type::max_value() - ); - } - } - - #[test] - fn fixed128_multiply_accumulate_works() { - saturating_mul_acc_test!(u64); - saturating_mul_acc_test!(u128); - saturating_mul_acc_test!(u128); - } - - #[test] - fn div_works() { - let a = Fixed128::from_rational(12, 10); - let b = Fixed128::from_rational(10, 1); - assert_eq!(a / b, Fixed128::from_rational(12, 100)); - - let a = Fixed128::from_rational(12, 10); - let b = Fixed128::from_rational(1, 100); - assert_eq!(a / b, Fixed128::from_rational(120, 1)); - - let a = Fixed128::from_rational(12, 100); - let b = Fixed128::from_rational(10, 1); - assert_eq!(a / b, Fixed128::from_rational(12, 1000)); - - let a = Fixed128::from_rational(12, 100); - let b = Fixed128::from_rational(1, 100); - assert_eq!(a / b, Fixed128::from_rational(12, 1)); - - let a = Fixed128::from_rational(-12, 10); - let b = Fixed128::from_rational(10, 1); - assert_eq!(a / b, Fixed128::from_rational(-12, 100)); - - let a = Fixed128::from_rational(12, 10); - let b = Fixed128::from_rational(-10, 1); - assert_eq!(a / b, Fixed128::from_rational(-12, 100)); - - let a = Fixed128::from_rational(-12, 10); - let b = Fixed128::from_rational(-10, 1); - assert_eq!(a / b, Fixed128::from_rational(12, 100)); - } - - #[test] - #[should_panic(expected = "attempt to divide by zero")] - fn div_zero() { - let a = Fixed128::from_rational(12, 10); - let b = Fixed128::from_natural(0); - let _ = a / b; - } - - #[test] - fn checked_div_zero() { - let a = Fixed128::from_rational(12, 10); - let b = Fixed128::from_natural(0); - assert_eq!(a.checked_div(&b), None); - } - - #[test] - fn checked_div_non_zero() { - let a = Fixed128::from_rational(12, 10); - let b = Fixed128::from_rational(1, 100); - assert_eq!(a.checked_div(&b), Some(Fixed128::from_rational(120, 1))); - } -} diff --git a/primitives/arithmetic/src/fixed64.rs b/primitives/arithmetic/src/fixed64.rs index 834fa8505cf8d..9c7c71e96727b 100644 --- a/primitives/arithmetic/src/fixed64.rs +++ b/primitives/arithmetic/src/fixed64.rs @@ -26,9 +26,10 @@ use crate::{ } }; -/// A signed fixed point number. Can hold any value in the range [-9_223_372_036, 9_223_372_036] -/// with an additional fixed point accuracy of one billion. i.e. 9000000000.000000001 can be -/// represented by Fixed64. +/// An signed fixed point number. Can represent any value in the range [-9.223372036, 9.223372036] +/// with fixed point accuracy of nine decimal points. +/// +/// This fixed point number is represented as an i64 divided by a billion. #[derive(Encode, Decode, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct Fixed64(i64); @@ -206,10 +207,6 @@ mod tests { Fixed64::from_parts(i64::max_value()) } - fn min() -> Fixed64 { - Fixed64::from_parts(i64::min_value()) - } - #[test] fn fixed64_semantics() { assert_eq!(Fixed64::from_rational(5, 2).0, 5 * 1_000_000_000 / 2); @@ -219,9 +216,6 @@ mod tests { // biggest value that can be created. assert_ne!(max(), Fixed64::from_natural(9_223_372_036)); assert_eq!(max(), Fixed64::from_natural(9_223_372_037)); - // smallest value that can be created. - assert_ne!(min(), Fixed64::from_natural(-9_223_372_036)); - assert_eq!(min(), Fixed64::from_natural(-9_223_372_037)); } #[test] diff --git a/primitives/arithmetic/src/lib.rs b/primitives/arithmetic/src/lib.rs index fb70b13a15312..f6d8b53e3499b 100644 --- a/primitives/arithmetic/src/lib.rs +++ b/primitives/arithmetic/src/lib.rs @@ -37,11 +37,9 @@ pub mod helpers_128bit; pub mod traits; mod per_things; mod fixed64; -mod fixed128; mod rational128; pub use fixed64::Fixed64; -pub use fixed128::Fixed128; pub use per_things::{PerThing, Percent, PerU16, Permill, Perbill, Perquintill}; pub use rational128::Rational128; From bec986ce7a2fd1cc752027e8154b76058d850106 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Fri, 10 Apr 2020 15:15:39 +0200 Subject: [PATCH 17/52] Revert "update fixed 64 docs" This reverts commit c3ad5fb6bac37c13413f772ee795fa08e5b8ea23. --- primitives/arithmetic/src/fixed64.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/primitives/arithmetic/src/fixed64.rs b/primitives/arithmetic/src/fixed64.rs index 9c7c71e96727b..6b399b6aa5106 100644 --- a/primitives/arithmetic/src/fixed64.rs +++ b/primitives/arithmetic/src/fixed64.rs @@ -26,10 +26,8 @@ use crate::{ } }; -/// An signed fixed point number. Can represent any value in the range [-9.223372036, 9.223372036] -/// with fixed point accuracy of nine decimal points. -/// -/// This fixed point number is represented as an i64 divided by a billion. +/// An unsigned fixed point number. Can hold any value in the range [-9_223_372_036, 9_223_372_036] +/// with fixed point accuracy of one billion. #[derive(Encode, Decode, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct Fixed64(i64); From 06197b487b9e2b7d6e81808e1ec4f8c8be181344 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Mon, 13 Apr 2020 12:48:41 +0200 Subject: [PATCH 18/52] Add fixed 128 --- bin/node/runtime/src/impls.rs | 2 + primitives/arithmetic/Cargo.toml | 3 +- primitives/arithmetic/src/fixed128.rs | 647 ++++++++++++++++++++++++++ primitives/arithmetic/src/fixed64.rs | 12 +- primitives/arithmetic/src/lib.rs | 2 + primitives/runtime/src/lib.rs | 2 +- 6 files changed, 665 insertions(+), 3 deletions(-) create mode 100644 primitives/arithmetic/src/fixed128.rs diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index 49eefc09a2dfc..3fd191a474028 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -344,6 +344,8 @@ mod tests { run_with_system_weight(i, || { let next = TargetedFeeAdjustment::::convert(Fixed64::default()); let truth = fee_multiplier_update(i, Fixed64::default()); + println!("Real: {:?}", next); + println!("Truth: {:?}", truth); assert_eq_error_rate!(truth.into_inner(), next.into_inner(), 5); }); }); diff --git a/primitives/arithmetic/Cargo.toml b/primitives/arithmetic/Cargo.toml index 208525f6c193b..71479e4eb0f16 100644 --- a/primitives/arithmetic/Cargo.toml +++ b/primitives/arithmetic/Cargo.toml @@ -17,9 +17,9 @@ num-traits = { version = "0.2.8", default-features = false } sp-std = { version = "2.0.0-alpha.5", default-features = false, path = "../std" } serde = { version = "1.0.101", optional = true, features = ["derive"] } sp-debug-derive = { version = "2.0.0-alpha.5", default-features = false, path = "../../primitives/debug-derive" } +primitive-types = { version = "0.7.0", default-features = false } [dev-dependencies] -primitive-types = "0.7.0" rand = "0.7.2" criterion = "0.3" @@ -31,6 +31,7 @@ std = [ "sp-std/std", "serde", "sp-debug-derive/std", + "primitive-types/std", ] [[bench]] diff --git a/primitives/arithmetic/src/fixed128.rs b/primitives/arithmetic/src/fixed128.rs new file mode 100644 index 0000000000000..f2b2cc6d6104b --- /dev/null +++ b/primitives/arithmetic/src/fixed128.rs @@ -0,0 +1,647 @@ +// Copyright 2020 Parity Technologies (UK) Ltd. +// This file is part of Substrate. + +// Substrate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Substrate is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Substrate. If not, see . + +use codec::{Decode, Encode}; +use primitive_types::U256; +use crate::{ + traits::{Bounded, Saturating, UniqueSaturatedInto, SaturatedConversion}, + PerThing, +}; +use sp_std::{ + convert::{Into, TryFrom, TryInto}, + fmt, + num::NonZeroI128, +}; + +#[cfg(feature = "std")] +use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; + +/// A signed fixed-point number. +/// Can hold any value in the range [-170_141_183_460_469_231_731, 170_141_183_460_469_231_731] +/// with fixed-point accuracy of 10 ** 18. +#[derive(Encode, Decode, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct Fixed128(i128); + +const DIV: i128 = 1_000_000_000_000_000_000; + +impl Fixed128 { + /// Create self from a natural number. + /// + /// Note that this might be lossy. + pub fn from_natural(int: i128) -> Self { + Self(int.saturating_mul(DIV)) + } + + /// Accuracy of `Fixed128`. + pub const fn accuracy() -> i128 { + DIV + } + + /// Raw constructor. Equal to `parts / DIV`. + pub fn from_parts(parts: i128) -> Self { + Self(parts) + } + + /// Creates self from a rational number. Equal to `n/d`. + /// + /// Note that this might be lossy. + pub fn from_rational>(n: N, d: NonZeroI128) -> Self { + let n = n.unique_saturated_into(); + Self(n.saturating_mul(DIV.into()) / d.get()) + } + + /// Consume self and return the inner raw `i128` value. + /// + /// Note this is a low level function, as the returned value is represented with accuracy. + pub fn deconstruct(self) -> i128 { + self.0 + } + + /// Takes the reciprocal(inverse) of Fixed128, 1/x + pub fn recip(&self) -> Option { + Self::from_natural(1i128).checked_div(self) + } + + /// Checked add. Same semantic to `num_traits::CheckedAdd`. + pub fn checked_add(&self, rhs: &Self) -> Option { + self.0.checked_add(rhs.0).map(Self) + } + + /// Checked sub. Same semantic to `num_traits::CheckedSub`. + pub fn checked_sub(&self, rhs: &Self) -> Option { + self.0.checked_sub(rhs.0).map(Self) + } + + /// Checked mul. Same semantic to `num_traits::CheckedMul`. + pub fn checked_mul(&self, rhs: &Self) -> Option { + let signum = self.0.signum() * rhs.0.signum(); + let mut lhs = self.0; + if lhs.is_negative() { + lhs = lhs.saturating_mul(-1); + } + let mut rhs: i128 = rhs.0.saturated_into(); + if rhs.is_negative() { + rhs = rhs.saturating_mul(-1); + } + + U256::from(lhs) + .checked_mul(U256::from(rhs)) + .and_then(|n| n.checked_div(U256::from(DIV))) + .and_then(|n| TryInto::::try_into(n).ok()) + .map(|n| Self(n * signum)) + } + + /// Checked div. Same semantic to `num_traits::CheckedDiv`. + pub fn checked_div(&self, rhs: &Self) -> Option { + if rhs.0.signum() == 0 { + return None; + } + if self.0 == 0 { + return Some(*self); + } + + let signum = self.0.signum() / rhs.0.signum(); + let mut lhs: i128 = self.0; + if lhs.is_negative() { + lhs = lhs.saturating_mul(-1); + } + let mut rhs: i128 = rhs.0.saturated_into(); + if rhs.is_negative() { + rhs = rhs.saturating_mul(-1); + } + + U256::from(lhs) + .checked_mul(U256::from(DIV)) + .and_then(|n| n.checked_div(U256::from(rhs))) + .and_then(|n| TryInto::::try_into(n).ok()) + .map(|n| Self(n * signum)) + } + + /// Checked mul for int type `N`. + pub fn checked_mul_int(&self, other: &N) -> Option + where + N: Copy + TryFrom + TryInto, + { + N::try_into(*other).ok().and_then(|rhs| { + let mut lhs = self.0; + if lhs.is_negative() { + lhs = lhs.saturating_mul(-1); + } + let mut rhs: i128 = rhs.saturated_into(); + let signum = self.0.signum() * rhs.signum(); + if rhs.is_negative() { + rhs = rhs.saturating_mul(-1); + } + + U256::from(lhs) + .checked_mul(U256::from(rhs)) + .and_then(|n| n.checked_div(U256::from(DIV))) + .and_then(|n| TryInto::::try_into(n).ok()) + .and_then(|n| TryInto::::try_into(n * signum).ok()) + }) + } + + /// Checked mul for int type `N`. + pub fn saturating_mul_int(&self, other: &N) -> N + where + N: Copy + TryFrom + TryInto + Bounded, + { + self.checked_mul_int(other).unwrap_or_else(|| { + N::try_into(*other) + .map(|n| n.signum()) + .map(|n| n * self.0.signum()) + .map(|signum| { + if signum.is_negative() { + Bounded::min_value() + } else { + Bounded::max_value() + } + }) + .unwrap_or(Bounded::max_value()) + }) + } + + /// Checked div for int type `N`. + pub fn checked_div_int(&self, other: &N) -> Option + where + N: Copy + TryFrom + TryInto, + { + N::try_into(*other) + .ok() + .and_then(|n| self.0.checked_div(n)) + .and_then(|n| n.checked_div(DIV)) + .and_then(|n| TryInto::::try_into(n).ok()) + } + + pub fn zero() -> Self { + Self(0) + } + + pub fn is_zero(&self) -> bool { + self.0 == 0 + } + + /// Saturating absolute value. Returning MAX if `parts` == i128::MIN instead of overflowing. + pub fn saturating_abs(&self) -> Self { + if self.0 == i128::min_value() { + return Fixed128::max_value(); + } + + if self.0.is_negative() { + Fixed128::from_parts(self.0 * -1) + } else { + *self + } + } + + pub fn is_positive(&self) -> bool { + self.0.is_positive() + } + + pub fn is_negative(&self) -> bool { + self.0.is_negative() + } +} + +impl Saturating for Fixed128 { + fn saturating_add(self, rhs: Self) -> Self { + Self(self.0.saturating_add(rhs.0)) + } + + fn saturating_sub(self, rhs: Self) -> Self { + Self(self.0.saturating_sub(rhs.0)) + } + + fn saturating_mul(self, rhs: Self) -> Self { + self.checked_mul(&rhs).unwrap_or_else(|| { + if (self.0.signum() * rhs.0.signum()).is_negative() { + Bounded::min_value() + } else { + Bounded::max_value() + } + }) + } + + fn saturating_pow(self, exp: usize) -> Self { + let prev_pow_2 = exp.checked_next_power_of_two().map(|val| val / 2).unwrap_or(usize::max_value()); + let count = prev_pow_2.trailing_zeros() as usize; + let mut val = self; + for _ in 0..count { + val = val.saturating_mul(val); + } + let remain = exp % count; + for _ in 0..remain { + val = val.saturating_mul(self) + } + val + } +} + +impl Bounded for Fixed128 { + fn min_value() -> Self { + Self(Bounded::min_value()) + } + + fn max_value() -> Self { + Self(Bounded::max_value()) + } +} + +impl fmt::Debug for Fixed128 { + #[cfg(feature = "std")] + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let integral = { + let int = self.0 / DIV; + let signum_for_zero = if int == 0 && self.is_negative() { "-" } else { "" }; + format!("{}{}", signum_for_zero, int) + }; + let fractional = format!("{:0>18}", (self.0 % DIV).abs()); + write!(f, "Fixed128({}.{})", integral, fractional) + } + + #[cfg(not(feature = "std"))] + fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { + Ok(()) + } +} + +impl From

for Fixed128 { + fn from(val: P) -> Self { + let accuracy = P::ACCURACY.saturated_into().max(1) as i128; + let value = val.deconstruct().saturated_into() as i128; + Fixed128::from_rational(value, NonZeroI128::new(accuracy).unwrap()) + } +} + +#[cfg(feature = "std")] +impl Fixed128 { + fn i128_str(&self) -> String { + format!("{}", &self.0) + } + + fn try_from_i128_str(s: &str) -> Result { + let parts: i128 = s.parse().map_err(|_| "invalid string input")?; + Ok(Self::from_parts(parts)) + } +} + +// Manual impl `Serialize` as serde_json does not support i128. +// TODO: remove impl if issue https://github.com/serde-rs/json/issues/548 fixed. +#[cfg(feature = "std")] +impl Serialize for Fixed128 { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&self.i128_str()) + } +} + +// Manual impl `Serialize` as serde_json does not support i128. +// TODO: remove impl if issue https://github.com/serde-rs/json/issues/548 fixed. +#[cfg(feature = "std")] +impl<'de> Deserialize<'de> for Fixed128 { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + Fixed128::try_from_i128_str(&s).map_err(|err_str| de::Error::custom(err_str)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Perbill, Percent, Permill, Perquintill}; + + fn max() -> Fixed128 { + Fixed128::max_value() + } + + fn min() -> Fixed128 { + Fixed128::min_value() + } + + #[test] + fn fixed128_semantics() { + let a = Fixed128::from_rational(5, NonZeroI128::new(2).unwrap()); + let b = Fixed128::from_rational(10, NonZeroI128::new(4).unwrap()); + assert_eq!(a.0, 5 * DIV / 2); + assert_eq!(a, b); + + let a = Fixed128::from_rational(-5, NonZeroI128::new(1).unwrap()); + assert_eq!(a, Fixed128::from_natural(-5)); + + let a = Fixed128::from_rational(5, NonZeroI128::new(-1).unwrap()); + assert_eq!(a, Fixed128::from_natural(-5)); + + // biggest value that can be created. + assert_ne!(max(), Fixed128::from_natural(170_141_183_460_469_231_731)); + assert_eq!(max(), Fixed128::from_natural(170_141_183_460_469_231_732)); + + // the smallest value that can be created. + assert_ne!(min(), Fixed128::from_natural(-170_141_183_460_469_231_731)); + assert_eq!(min(), Fixed128::from_natural(-170_141_183_460_469_231_732)); + } + + #[test] + fn fixed128_operation() { + let a = Fixed128::from_natural(2); + let b = Fixed128::from_natural(1); + assert_eq!(a.checked_add(&b), Some(Fixed128::from_natural(1 + 2))); + assert_eq!(a.checked_sub(&b), Some(Fixed128::from_natural(2 - 1))); + assert_eq!(a.checked_mul(&b), Some(Fixed128::from_natural(1 * 2))); + assert_eq!( + a.checked_div(&b), + Some(Fixed128::from_rational(2, NonZeroI128::new(1).unwrap())) + ); + + let a = Fixed128::from_rational(5, NonZeroI128::new(2).unwrap()); + let b = Fixed128::from_rational(3, NonZeroI128::new(2).unwrap()); + assert_eq!( + a.checked_add(&b), + Some(Fixed128::from_rational(8, NonZeroI128::new(2).unwrap())) + ); + assert_eq!( + a.checked_sub(&b), + Some(Fixed128::from_rational(2, NonZeroI128::new(2).unwrap())) + ); + assert_eq!( + a.checked_mul(&b), + Some(Fixed128::from_rational(15, NonZeroI128::new(4).unwrap())) + ); + assert_eq!( + a.checked_div(&b), + Some(Fixed128::from_rational(10, NonZeroI128::new(6).unwrap())) + ); + + let a = Fixed128::from_natural(120); + assert_eq!(a.checked_div_int(&2i32), Some(60)); + + let a = Fixed128::from_rational(20, NonZeroI128::new(1).unwrap()); + assert_eq!(a.checked_div_int(&2i32), Some(10)); + + let a = Fixed128::from_natural(120); + assert_eq!(a.checked_mul_int(&2i32), Some(240)); + + let a = Fixed128::from_rational(1, NonZeroI128::new(2).unwrap()); + assert_eq!(a.checked_mul_int(&20i32), Some(10)); + + let a = Fixed128::from_rational(-1, NonZeroI128::new(2).unwrap()); + assert_eq!(a.checked_mul_int(&20i32), Some(-10)); + } + + #[test] + fn saturating_mul_should_work() { + let a = Fixed128::from_natural(-1); + assert_eq!(min().saturating_mul(a), max()); + + assert_eq!(Fixed128::from_natural(125).saturating_mul(a).deconstruct(), -125 * DIV); + + let a = Fixed128::from_rational(1, NonZeroI128::new(5).unwrap()); + assert_eq!(Fixed128::from_natural(125).saturating_mul(a).deconstruct(), 25 * DIV); + } + + #[test] + fn saturating_mul_int_works() { + let a = Fixed128::from_rational(10, NonZeroI128::new(1).unwrap()); + assert_eq!(a.saturating_mul_int(&i32::max_value()), i32::max_value()); + + let a = Fixed128::from_rational(-10, NonZeroI128::new(1).unwrap()); + assert_eq!(a.saturating_mul_int(&i32::max_value()), i32::min_value()); + + let a = Fixed128::from_rational(3, NonZeroI128::new(1).unwrap()); + assert_eq!(a.saturating_mul_int(&100i8), i8::max_value()); + + let a = Fixed128::from_rational(10, NonZeroI128::new(1).unwrap()); + assert_eq!(a.saturating_mul_int(&123i128), 1230); + + let a = Fixed128::from_rational(-10, NonZeroI128::new(1).unwrap()); + assert_eq!(a.saturating_mul_int(&123i128), -1230); + + assert_eq!(max().saturating_mul_int(&2i128), 340_282_366_920_938_463_463); + + assert_eq!(max().saturating_mul_int(&i128::min_value()), i128::min_value()); + + assert_eq!(min().saturating_mul_int(&i128::max_value()), i128::min_value()); + + assert_eq!(min().saturating_mul_int(&i128::min_value()), i128::max_value()); + } + + #[test] + fn zero_works() { + assert_eq!(Fixed128::zero(), Fixed128::from_natural(0)); + } + + #[test] + fn is_zero_works() { + assert!(Fixed128::zero().is_zero()); + assert!(!Fixed128::from_natural(1).is_zero()); + } + + #[test] + fn checked_div_with_zero_should_be_none() { + let a = Fixed128::from_natural(1); + let b = Fixed128::from_natural(0); + assert_eq!(a.checked_div(&b), None); + assert_eq!(b.checked_div(&a), Some(b)); + } + + #[test] + fn checked_div_int_with_zero_should_be_none() { + let a = Fixed128::from_natural(1); + assert_eq!(a.checked_div_int(&0i32), None); + let a = Fixed128::from_natural(0); + assert_eq!(a.checked_div_int(&1i32), Some(0)); + } + + #[test] + fn checked_div_with_zero_dividend_should_be_zero() { + let a = Fixed128::zero(); + let b = Fixed128::from_parts(1); + + assert_eq!(a.checked_div(&b), Some(Fixed128::zero())); + } + + #[test] + fn under_flow_should_be_none() { + let b = Fixed128::from_natural(1); + assert_eq!(min().checked_sub(&b), None); + } + + #[test] + fn over_flow_should_be_none() { + let a = Fixed128::from_parts(i128::max_value() - 1); + let b = Fixed128::from_parts(2); + assert_eq!(a.checked_add(&b), None); + + let a = Fixed128::max_value(); + let b = Fixed128::from_rational(2, NonZeroI128::new(1).unwrap()); + assert_eq!(a.checked_mul(&b), None); + + let a = Fixed128::from_natural(255); + let b = 2u8; + assert_eq!(a.checked_mul_int(&b), None); + + let a = Fixed128::from_natural(256); + let b = 1u8; + assert_eq!(a.checked_div_int(&b), None); + + let a = Fixed128::from_natural(256); + let b = -1i8; + assert_eq!(a.checked_div_int(&b), None); + } + + #[test] + fn checked_div_int_should_work() { + // 256 / 10 = 25 (25.6 as int = 25) + let a = Fixed128::from_natural(256); + let result = a.checked_div_int(&10i128).unwrap(); + assert_eq!(result, 25); + + // 256 / 100 = 2 (2.56 as int = 2) + let a = Fixed128::from_natural(256); + let result = a.checked_div_int(&100i128).unwrap(); + assert_eq!(result, 2); + + // 256 / 1000 = 0 (0.256 as int = 0) + let a = Fixed128::from_natural(256); + let result = a.checked_div_int(&1000i128).unwrap(); + assert_eq!(result, 0); + + // 256 / -1 = -256 + let a = Fixed128::from_natural(256); + let result = a.checked_div_int(&-1i128).unwrap(); + assert_eq!(result, -256); + + // -256 / -1 = 256 + let a = Fixed128::from_natural(-256); + let result = a.checked_div_int(&-1i128).unwrap(); + assert_eq!(result, 256); + + // 10 / -5 = -2 + let a = Fixed128::from_rational(20, NonZeroI128::new(2).unwrap()); + let result = a.checked_div_int(&-5i128).unwrap(); + assert_eq!(result, -2); + + // -170_141_183_460_469_231_731 / -2 = 85_070_591_730_234_615_865 + let result = min().checked_div_int(&-2i128).unwrap(); + assert_eq!(result, 85_070_591_730_234_615_865); + + // 85_070_591_730_234_615_865 * -2 = -170_141_183_460_469_231_730 + let result = Fixed128::from_natural(result).checked_mul_int(&-2i128).unwrap(); + assert_eq!(result, -170_141_183_460_469_231_730); + } + + #[test] + fn perthing_into_fixed_i128() { + let ten_percent_percent: Fixed128 = Percent::from_percent(10).into(); + assert_eq!(ten_percent_percent.deconstruct(), DIV / 10); + + let ten_percent_permill: Fixed128 = Permill::from_percent(10).into(); + assert_eq!(ten_percent_permill.deconstruct(), DIV / 10); + + let ten_percent_perbill: Fixed128 = Perbill::from_percent(10).into(); + assert_eq!(ten_percent_perbill.deconstruct(), DIV / 10); + + let ten_percent_perquintill: Fixed128 = Perquintill::from_percent(10).into(); + assert_eq!(ten_percent_perquintill.deconstruct(), DIV / 10); + } + + #[test] + fn recip_should_work() { + let a = Fixed128::from_natural(2); + assert_eq!( + a.recip(), + Some(Fixed128::from_rational(1, NonZeroI128::new(2).unwrap())) + ); + + let a = Fixed128::from_natural(2); + assert_eq!(a.recip().unwrap().checked_mul_int(&4i32), Some(2i32)); + + let a = Fixed128::from_rational(100, NonZeroI128::new(121).unwrap()); + assert_eq!( + a.recip(), + Some(Fixed128::from_rational(121, NonZeroI128::new(100).unwrap())) + ); + + let a = Fixed128::from_rational(1, NonZeroI128::new(2).unwrap()); + assert_eq!(a.recip().unwrap().checked_mul(&a), Some(Fixed128::from_natural(1))); + + let a = Fixed128::from_natural(0); + assert_eq!(a.recip(), None); + + let a = Fixed128::from_rational(-1, NonZeroI128::new(2).unwrap()); + assert_eq!(a.recip(), Some(Fixed128::from_natural(-2))); + } + + #[test] + fn serialize_deserialize_should_work() { + let two_point_five = Fixed128::from_rational(5, NonZeroI128::new(2).unwrap()); + let serialized = serde_json::to_string(&two_point_five).unwrap(); + assert_eq!(serialized, "\"2500000000000000000\""); + let deserialized: Fixed128 = serde_json::from_str(&serialized).unwrap(); + assert_eq!(deserialized, two_point_five); + + let minus_two_point_five = Fixed128::from_rational(-5, NonZeroI128::new(2).unwrap()); + let serialized = serde_json::to_string(&minus_two_point_five).unwrap(); + assert_eq!(serialized, "\"-2500000000000000000\""); + let deserialized: Fixed128 = serde_json::from_str(&serialized).unwrap(); + assert_eq!(deserialized, minus_two_point_five); + } + + #[test] + fn saturating_abs_should_work() { + // normal + assert_eq!(Fixed128::from_parts(1).saturating_abs(), Fixed128::from_parts(1)); + assert_eq!(Fixed128::from_parts(-1).saturating_abs(), Fixed128::from_parts(1)); + + // saturating + assert_eq!(Fixed128::min_value().saturating_abs(), Fixed128::max_value()); + } + + #[test] + fn is_positive_negative_should_work() { + let positive = Fixed128::from_parts(1); + assert!(positive.is_positive()); + assert!(!positive.is_negative()); + + let negative = Fixed128::from_parts(-1); + assert!(!negative.is_positive()); + assert!(negative.is_negative()); + + let zero = Fixed128::zero(); + assert!(!zero.is_positive()); + assert!(!zero.is_negative()); + } + + #[test] + fn fmt_should_work() { + let positive = Fixed128::from_parts(1000000000000000001); + assert_eq!(format!("{:?}", positive), "Fixed128(1.000000000000000001)"); + let negative = Fixed128::from_parts(-1000000000000000001); + assert_eq!(format!("{:?}", negative), "Fixed128(-1.000000000000000001)"); + + let positive_fractional = Fixed128::from_parts(1); + assert_eq!(format!("{:?}", positive_fractional), "Fixed128(0.000000000000000001)"); + let negative_fractional = Fixed128::from_parts(-1); + assert_eq!(format!("{:?}", negative_fractional), "Fixed128(-0.000000000000000001)"); + + let zero = Fixed128::zero(); + assert_eq!(format!("{:?}", zero), "Fixed128(0.000000000000000000)"); + } +} diff --git a/primitives/arithmetic/src/fixed64.rs b/primitives/arithmetic/src/fixed64.rs index 6b399b6aa5106..1f551c1604de7 100644 --- a/primitives/arithmetic/src/fixed64.rs +++ b/primitives/arithmetic/src/fixed64.rs @@ -104,6 +104,10 @@ impl Fixed64 { int.saturating_sub(excess) } } + + pub fn is_negative(&self) -> bool { + self.0.is_negative() + } } impl Saturating for Fixed64 { @@ -188,7 +192,13 @@ impl CheckedDiv for Fixed64 { impl sp_std::fmt::Debug for Fixed64 { #[cfg(feature = "std")] fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { - write!(f, "Fixed64({},{})", self.0 / DIV, (self.0 % DIV) / 1000) + let integral = { + let int = self.0 / DIV; + let signum_for_zero = if int == 0 && self.is_negative() { "-" } else { "" }; + format!("{}{}", signum_for_zero, int) + }; + let fractional = format!("{:0>9}", (self.0 % DIV).abs()); + write!(f, "Fixed64({}.{})", integral, fractional) } #[cfg(not(feature = "std"))] diff --git a/primitives/arithmetic/src/lib.rs b/primitives/arithmetic/src/lib.rs index f6d8b53e3499b..fb70b13a15312 100644 --- a/primitives/arithmetic/src/lib.rs +++ b/primitives/arithmetic/src/lib.rs @@ -37,9 +37,11 @@ pub mod helpers_128bit; pub mod traits; mod per_things; mod fixed64; +mod fixed128; mod rational128; pub use fixed64::Fixed64; +pub use fixed128::Fixed128; pub use per_things::{PerThing, Percent, PerU16, Permill, Perbill, Perquintill}; pub use rational128::Rational128; diff --git a/primitives/runtime/src/lib.rs b/primitives/runtime/src/lib.rs index c80971b576df2..d037c0234842f 100644 --- a/primitives/runtime/src/lib.rs +++ b/primitives/runtime/src/lib.rs @@ -70,7 +70,7 @@ pub use sp_core::RuntimeDebug; /// Re-export top-level arithmetic stuff. pub use sp_arithmetic::{ Perquintill, Perbill, Permill, Percent, PerU16, Rational128, Fixed64, PerThing, - traits::SaturatedConversion, + traits::SaturatedConversion, Fixed128, }; /// Re-export 128 bit helpers. pub use sp_arithmetic::helpers_128bit; From 0c94fc9c52ed9d5b020dc5d6c90b0826fe33af1a Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Mon, 13 Apr 2020 13:39:25 +0200 Subject: [PATCH 19/52] fix types --- bin/node/runtime/src/impls.rs | 108 +++++++++++++------------- bin/node/runtime/src/lib.rs | 4 +- frame/transaction-payment/src/lib.rs | 16 ++-- primitives/arithmetic/src/fixed128.rs | 39 +++++++++- 4 files changed, 102 insertions(+), 65 deletions(-) diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index 3fd191a474028..2f988bb6d0f6e 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -16,9 +16,10 @@ //! Some configurable implementations as associated type for the substrate runtime. +use core::num::NonZeroI128; use node_primitives::Balance; use sp_runtime::traits::{Convert, Saturating}; -use sp_runtime::{Fixed64, Perbill}; +use sp_runtime::{Fixed128, Perquintill}; use frame_support::{traits::{OnUnbalanced, Currency, Get}, weights::Weight}; use crate::{Balances, System, Authorship, MaximumBlockWeight, NegativeImbalance}; @@ -67,8 +68,8 @@ impl> Convert for LinearWeightToFee { /// https://research.web3.foundation/en/latest/polkadot/Token%20Economics/#relay-chain-transaction-fees pub struct TargetedFeeAdjustment(sp_std::marker::PhantomData); -impl> Convert for TargetedFeeAdjustment { - fn convert(multiplier: Fixed64) -> Fixed64 { +impl> Convert for TargetedFeeAdjustment { + fn convert(multiplier: Fixed128) -> Fixed128 { let block_weight = System::all_extrinsics_weight(); let max_weight = MaximumBlockWeight::get(); let target_weight = (T::get() * max_weight) as u128; @@ -77,15 +78,15 @@ impl> Convert for TargetedFeeAdjustment { // determines if the first_term is positive let positive = block_weight >= target_weight; let diff_abs = block_weight.max(target_weight) - block_weight.min(target_weight); - // diff is within u32, safe. - let diff = Fixed64::from_rational(diff_abs as i64, max_weight as u64); + // diff is within u64, safe. + let diff = Fixed128::from_rational(diff_abs as i64, NonZeroI128::new(max_weight.max(1) as i128).unwrap()); let diff_squared = diff.saturating_mul(diff); // 0.00004 = 4/100_000 = 40_000/10^9 - let v = Fixed64::from_rational(4, 100_000); + let v = Fixed128::from_rational(4, NonZeroI128::new(100_000).unwrap()); // 0.00004^2 = 16/10^10 ~= 2/10^9. Taking the future /2 into account, then it is just 1 // parts from a billionth. - let v_squared_2 = Fixed64::from_rational(1, 1_000_000_000); + let v_squared_2 = Fixed128::from_rational(1, NonZeroI128::new(1_000_000_000).unwrap()); let first_term = v.saturating_mul(diff); // It is very unlikely that this will exist (in our poor perbill estimate) but we are giving @@ -99,14 +100,14 @@ impl> Convert for TargetedFeeAdjustment { multiplier.saturating_add(excess) } else { // Proof: first_term > second_term. Safe subtraction. - let negative = first_term - second_term; + let negative = first_term.saturating_sub(second_term); multiplier.saturating_sub(negative) // despite the fact that apply_to saturates weight (final fee cannot go below 0) // it is crucially important to stop here and don't further reduce the weight fee // multiplier. While at -1, it means that the network is so un-congested that all // transactions have no weight fee. We stop here and only increase if the network // became more busy. - .max(Fixed64::from_rational(-1, 1)) + .max(Fixed128::from_rational(-1, NonZeroI128::new(1).unwrap())) } } } @@ -118,6 +119,7 @@ mod tests { use crate::{MaximumBlockWeight, AvailableBlockRatio, Runtime}; use crate::{constants::currency::*, TransactionPayment, TargetBlockFullness}; use frame_support::weights::Weight; + use core::num::NonZeroI128; fn max() -> Weight { MaximumBlockWeight::get() @@ -128,24 +130,24 @@ mod tests { } // poc reference implementation. - fn fee_multiplier_update(block_weight: Weight, previous: Fixed64) -> Fixed64 { - let block_weight = block_weight as f32; - let v: f32 = 0.00004; + fn fee_multiplier_update(block_weight: Weight, previous: Fixed128) -> Fixed128 { + let block_weight = block_weight as f64; + let v: f64 = 0.00004; // maximum tx weight - let m = max() as f32; + let m = max() as f64; // Ideal saturation in terms of weight - let ss = target() as f32; + let ss = target() as f64; // Current saturation in terms of weight let s = block_weight; let fm = v * (s/m - ss/m) + v.powi(2) * (s/m - ss/m).powi(2) / 2.0; - let addition_fm = Fixed64::from_parts((fm * 1_000_000_000_f32).round() as i64); + let addition_fm = Fixed128::from_parts((fm * Fixed128::accuracy() as f64).round() as i128); previous.saturating_add(addition_fm) } - fn feemul(parts: i64) -> Fixed64 { - Fixed64::from_parts(parts) + fn feemul(n: i128, d: NonZeroI128) -> Fixed128 { + Fixed128::from_rational(n, d) } fn run_with_system_weight(w: Weight, assertions: F) where F: Fn() -> () { @@ -159,7 +161,7 @@ mod tests { #[test] fn fee_multiplier_update_poc_works() { - let fm = Fixed64::from_rational(0, 1); + let fm = Fixed128::from_rational(0, NonZeroI128::new(1).unwrap()); let test_set = vec![ (0, fm.clone()), (100, fm.clone()), @@ -170,9 +172,9 @@ mod tests { test_set.into_iter().for_each(|(w, fm)| { run_with_system_weight(w, || { assert_eq_error_rate!( - fee_multiplier_update(w, fm).into_inner(), - TargetedFeeAdjustment::::convert(fm).into_inner(), - 5, + fee_multiplier_update(w, fm).deconstruct(), + TargetedFeeAdjustment::::convert(fm).deconstruct(), + 5_000_000_000i128, ); }) }) @@ -183,12 +185,12 @@ mod tests { // just a few txs per_block. let block_weight = 0; run_with_system_weight(block_weight, || { - let mut fm = Fixed64::default(); + let mut fm = Fixed128::default(); let mut iterations: u64 = 0; loop { let next = TargetedFeeAdjustment::::convert(fm); fm = next; - if fm == Fixed64::from_rational(-1, 1) { break; } + if fm == Fixed128::from_rational(-1, NonZeroI128::new(1).unwrap()) { break; } iterations += 1; } println!("iteration {}, new fm = {:?}. Weight fee is now zero", iterations, fm); @@ -216,7 +218,7 @@ mod tests { run_with_system_weight(block_weight, || { // initial value configured on module - let mut fm = Fixed64::default(); + let mut fm = Fixed128::default(); assert_eq!(fm, TransactionPayment::next_fee_multiplier()); let mut iterations: u64 = 0; @@ -247,30 +249,30 @@ mod tests { run_with_system_weight(target() / 4, || { // Light block. Fee is reduced a little. assert_eq!( - TargetedFeeAdjustment::::convert(Fixed64::default()), - feemul(-7500), + TargetedFeeAdjustment::::convert(Fixed128::default()), + feemul(-7500, NonZeroI128::new(1_000_000_000).unwrap()), ); }); run_with_system_weight(target() / 2, || { // a bit more. Fee is decreased less, meaning that the fee increases as the block grows. assert_eq!( - TargetedFeeAdjustment::::convert(Fixed64::default()), - feemul(-5000), + TargetedFeeAdjustment::::convert(Fixed128::default()), + feemul(-5000, NonZeroI128::new(1_000_000_000).unwrap()), ); }); run_with_system_weight(target(), || { // ideal. Original fee. No changes. assert_eq!( - TargetedFeeAdjustment::::convert(Fixed64::default()), - feemul(0), + TargetedFeeAdjustment::::convert(Fixed128::default()), + feemul(0, NonZeroI128::new(1_000_000_000).unwrap()), ); }); run_with_system_weight(target() * 2, || { // // More than ideal. Fee is increased. assert_eq!( - TargetedFeeAdjustment::::convert(Fixed64::default()), - feemul(10000), + TargetedFeeAdjustment::::convert(Fixed128::default()), + feemul(10000, NonZeroI128::new(1_000_000_000).unwrap()), ); }); } @@ -279,21 +281,21 @@ mod tests { fn stateful_weight_mul_grow_to_infinity() { run_with_system_weight(target() * 2, || { assert_eq!( - TargetedFeeAdjustment::::convert(Fixed64::default()), - feemul(10000) + TargetedFeeAdjustment::::convert(Fixed128::default()), + feemul(10000, NonZeroI128::new(1_000_000_000).unwrap()) ); assert_eq!( - TargetedFeeAdjustment::::convert(feemul(10000)), - feemul(20000) + TargetedFeeAdjustment::::convert(feemul(10000, NonZeroI128::new(1_000_000_000).unwrap())), + feemul(20000, NonZeroI128::new(1_000_000_000).unwrap()) ); assert_eq!( - TargetedFeeAdjustment::::convert(feemul(20000)), - feemul(30000) + TargetedFeeAdjustment::::convert(feemul(20000, NonZeroI128::new(1_000_000_000).unwrap())), + feemul(30000, NonZeroI128::new(1_000_000_000).unwrap()) ); // ... assert_eq!( - TargetedFeeAdjustment::::convert(feemul(1_000_000_000)), - feemul(1_000_000_000 + 10000) + TargetedFeeAdjustment::::convert(feemul(1_000_000_000, NonZeroI128::new(1_000_000_000).unwrap())), + feemul(1_000_000_000 + 10000, NonZeroI128::new(1_000_000_000).unwrap()) ); }); } @@ -302,21 +304,21 @@ mod tests { fn stateful_weight_mil_collapse_to_minus_one() { run_with_system_weight(0, || { assert_eq!( - TargetedFeeAdjustment::::convert(Fixed64::default()), - feemul(-10000) + TargetedFeeAdjustment::::convert(Fixed128::default()), + feemul(-10000, NonZeroI128::new(1_000_000_000).unwrap()) ); assert_eq!( - TargetedFeeAdjustment::::convert(feemul(-10000)), - feemul(-20000) + TargetedFeeAdjustment::::convert(feemul(-10000, NonZeroI128::new(1_000_000_000).unwrap())), + feemul(-20000, NonZeroI128::new(1_000_000_000).unwrap()) ); assert_eq!( - TargetedFeeAdjustment::::convert(feemul(-20000)), - feemul(-30000) + TargetedFeeAdjustment::::convert(feemul(-20000, NonZeroI128::new(1_000_000_000).unwrap())), + feemul(-30000, NonZeroI128::new(1_000_000_000).unwrap()) ); // ... assert_eq!( - TargetedFeeAdjustment::::convert(feemul(1_000_000_000 * -1)), - feemul(-1_000_000_000) + TargetedFeeAdjustment::::convert(feemul(1_000_000_000 * -1, NonZeroI128::new(1_000_000_000).unwrap())), + feemul(-1_000_000_000, NonZeroI128::new(1_000_000_000).unwrap()) ); }) } @@ -325,7 +327,7 @@ mod tests { fn weight_to_fee_should_not_overflow_on_large_weights() { let kb = 1024 as Weight; let mb = kb * kb; - let max_fm = Fixed64::from_natural(i64::max_value()); + let max_fm = Fixed128::from_natural(i128::max_value()); // check that for all values it can compute, correctly. vec![ @@ -342,11 +344,11 @@ mod tests { Weight::max_value(), ].into_iter().for_each(|i| { run_with_system_weight(i, || { - let next = TargetedFeeAdjustment::::convert(Fixed64::default()); - let truth = fee_multiplier_update(i, Fixed64::default()); - println!("Real: {:?}", next); + let next = TargetedFeeAdjustment::::convert(Fixed128::default()); + let truth = fee_multiplier_update(i, Fixed128::default()); + println!("Next: {:?}", next); println!("Truth: {:?}", truth); - assert_eq_error_rate!(truth.into_inner(), next.into_inner(), 5); + assert_eq_error_rate!(truth.deconstruct(), next.deconstruct(), 5_000_000_000i128); }); }); diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 604e76f1d6777..51c9f125e48f0 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -31,7 +31,7 @@ pub use node_primitives::{AccountId, Signature}; use node_primitives::{AccountIndex, Balance, BlockNumber, Hash, Index, Moment}; use sp_api::impl_runtime_apis; use sp_runtime::{ - Permill, Perbill, Percent, ApplyExtrinsicResult, + Permill, Perbill, Perquintill, Percent, ApplyExtrinsicResult, impl_opaque_keys, generic, create_runtime_str, }; use sp_runtime::curve::PiecewiseLinear; @@ -260,7 +260,7 @@ parameter_types! { // is mapped to 10_000_000 units of fees, hence: pub const WeightFeeCoefficient: Balance = 1; // for a sane configuration, this should always be less than `AvailableBlockRatio`. - pub const TargetBlockFullness: Perbill = Perbill::from_percent(25); + pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(25); } impl pallet_transaction_payment::Trait for Runtime { diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index ed14b523c482d..3ae52286029b0 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -40,7 +40,7 @@ use frame_support::{ dispatch::DispatchResult, }; use sp_runtime::{ - Fixed64, + Fixed128, transaction_validity::{ TransactionPriority, ValidTransaction, InvalidTransaction, TransactionValidityError, TransactionValidity, @@ -52,7 +52,7 @@ use sp_runtime::{ }; use pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo; -type Multiplier = Fixed64; +type Multiplier = Fixed128; type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; type NegativeImbalanceOf = @@ -178,10 +178,10 @@ impl ChargeTransactionPayment where let adjustable_fee = len_fee.saturating_add(weight_fee); let targeted_fee_adjustment = NextFeeMultiplier::get(); // adjusted_fee = adjustable_fee + (adjustable_fee * targeted_fee_adjustment) - let adjusted_fee = targeted_fee_adjustment.saturated_multiply_accumulate(adjustable_fee); + let adjusted_fee = targeted_fee_adjustment.saturated_multiply_accumulate(adjustable_fee.saturated_into()); let base_fee = T::TransactionBaseFee::get(); - base_fee.saturating_add(adjusted_fee).saturating_add(tip) + base_fee.saturating_add(adjusted_fee.saturated_into()).saturating_add(tip) } else { tip } @@ -578,7 +578,7 @@ mod tests { .execute_with(|| { // all fees should be x1.5 - NextFeeMultiplier::put(Fixed64::from_rational(1, 2)); + NextFeeMultiplier::put(Fixed128::from_rational(1, 2)); let len = 10; assert!( @@ -606,7 +606,7 @@ mod tests { .execute_with(|| { // all fees should be x1.5 - NextFeeMultiplier::put(Fixed64::from_rational(1, 2)); + NextFeeMultiplier::put(Fixed128::from_rational(1, 2)); assert_eq!( TransactionPayment::query_info(xt, len), @@ -635,7 +635,7 @@ mod tests { .execute_with(|| { // Next fee multiplier is zero - assert_eq!(NextFeeMultiplier::get(), Fixed64::from_natural(0)); + assert_eq!(NextFeeMultiplier::get(), Fixed128::from_natural(0)); // Tip only, no fees works let dispatch_info = DispatchInfo { @@ -675,7 +675,7 @@ mod tests { .execute_with(|| { // Add a next fee multiplier - NextFeeMultiplier::put(Fixed64::from_rational(1, 2)); // = 1/2 = .5 + NextFeeMultiplier::put(Fixed128::from_rational(1, 2)); // = 1/2 = .5 // Base fee is unaffected by multiplier let dispatch_info = DispatchInfo { weight: 0, diff --git a/primitives/arithmetic/src/fixed128.rs b/primitives/arithmetic/src/fixed128.rs index f2b2cc6d6104b..9081cff7b4df3 100644 --- a/primitives/arithmetic/src/fixed128.rs +++ b/primitives/arithmetic/src/fixed128.rs @@ -18,11 +18,11 @@ use codec::{Decode, Encode}; use primitive_types::U256; use crate::{ traits::{Bounded, Saturating, UniqueSaturatedInto, SaturatedConversion}, - PerThing, + PerThing, Perquintill, }; use sp_std::{ convert::{Into, TryFrom, TryInto}, - fmt, + fmt, ops, num::NonZeroI128, }; @@ -214,6 +214,41 @@ impl Fixed128 { pub fn is_negative(&self) -> bool { self.0.is_negative() } + + /// Performs a saturated multiply and accumulate by unsigned number. + /// + /// Returns a saturated `int + (self * int)`. + pub fn saturated_multiply_accumulate(self, int: N) -> N + where + N: TryFrom + From + UniqueSaturatedInto + Bounded + Clone + Saturating + + ops::Rem + ops::Div + ops::Mul + + ops::Add, + { + let div = DIV as u128; + let positive = self.0 > 0; + // safe to convert as absolute value. + let parts = self.0.checked_abs().map(|v| v as u128).unwrap_or(i128::max_value() as u128 + 1); + + + // will always fit. + let natural_parts = parts / div; + // might saturate. + let natural_parts: N = natural_parts.saturated_into(); + // fractional parts can always fit into u64. + let perquintill_parts = (parts % div) as u64; + + let n = int.clone().saturating_mul(natural_parts); + let p = Perquintill::from_parts(perquintill_parts) * int.clone(); + + // everything that needs to be either added or subtracted from the original weight. + let excess = n.saturating_add(p); + + if positive { + int.saturating_add(excess) + } else { + int.saturating_sub(excess) + } + } } impl Saturating for Fixed128 { From d3f4b4b305c7ef7ec6bbf84729889e39e59492ea Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Mon, 13 Apr 2020 14:19:26 +0200 Subject: [PATCH 20/52] Fix test --- bin/node/runtime/src/impls.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index 2f988bb6d0f6e..16840f5830213 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -340,15 +340,15 @@ mod tests { 100 * kb, mb, 10 * mb, - Weight::max_value() / 2, - Weight::max_value(), + 2147483647, + 4294967295, + MaximumBlockWeight::get() / 2, + MaximumBlockWeight::get(), ].into_iter().for_each(|i| { run_with_system_weight(i, || { let next = TargetedFeeAdjustment::::convert(Fixed128::default()); let truth = fee_multiplier_update(i, Fixed128::default()); - println!("Next: {:?}", next); - println!("Truth: {:?}", truth); - assert_eq_error_rate!(truth.deconstruct(), next.deconstruct(), 5_000_000_000i128); + assert_eq_error_rate!(truth.deconstruct(), next.deconstruct(), 500_000_000i128); }); }); From 62f6a9bdd911685887139fde5d27aa78c7763bda Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Mon, 13 Apr 2020 16:36:54 +0200 Subject: [PATCH 21/52] Fix tests --- Cargo.lock | 1 + bin/node/runtime/src/impls.rs | 79 ++++++++++++++----------- primitives/arithmetic/Cargo.toml | 1 + primitives/arithmetic/src/fixed128.rs | 22 ++++++- primitives/arithmetic/src/per_things.rs | 2 +- 5 files changed, 68 insertions(+), 37 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index affa982bd3856..2728bc21f725d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7186,6 +7186,7 @@ dependencies = [ "primitive-types", "rand 0.7.3", "serde", + "serde_json", "sp-debug-derive", "sp-std", ] diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index 16840f5830213..4e0337bb386ae 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -86,7 +86,7 @@ impl> Convert for TargetedFeeAdjustment< let v = Fixed128::from_rational(4, NonZeroI128::new(100_000).unwrap()); // 0.00004^2 = 16/10^10 ~= 2/10^9. Taking the future /2 into account, then it is just 1 // parts from a billionth. - let v_squared_2 = Fixed128::from_rational(1, NonZeroI128::new(1_000_000_000).unwrap()); + let v_squared_2 = Fixed128::from_rational(1, NonZeroI128::new(800_000_000).unwrap()); let first_term = v.saturating_mul(diff); // It is very unlikely that this will exist (in our poor perbill estimate) but we are giving @@ -129,6 +129,8 @@ mod tests { TargetBlockFullness::get() * max() } + const ERROR_RATE: Fixed128 = Fixed128::from_parts(500_000_000); + // poc reference implementation. fn fee_multiplier_update(block_weight: Weight, previous: Fixed128) -> Fixed128 { let block_weight = block_weight as f64; @@ -146,10 +148,6 @@ mod tests { previous.saturating_add(addition_fm) } - fn feemul(n: i128, d: NonZeroI128) -> Fixed128 { - Fixed128::from_rational(n, d) - } - fn run_with_system_weight(w: Weight, assertions: F) where F: Fn() -> () { let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::default().build_storage::().unwrap().into(); @@ -248,31 +246,35 @@ mod tests { fn stateless_weight_mul() { run_with_system_weight(target() / 4, || { // Light block. Fee is reduced a little. - assert_eq!( + assert_eq_error_rate!( TargetedFeeAdjustment::::convert(Fixed128::default()), - feemul(-7500, NonZeroI128::new(1_000_000_000).unwrap()), + Fixed128::from_rational(-7500, NonZeroI128::new(1_000_000_000).unwrap()), + ERROR_RATE, ); }); run_with_system_weight(target() / 2, || { // a bit more. Fee is decreased less, meaning that the fee increases as the block grows. - assert_eq!( + assert_eq_error_rate!( TargetedFeeAdjustment::::convert(Fixed128::default()), - feemul(-5000, NonZeroI128::new(1_000_000_000).unwrap()), + Fixed128::from_rational(-5000, NonZeroI128::new(1_000_000_000).unwrap()), + ERROR_RATE, ); }); run_with_system_weight(target(), || { // ideal. Original fee. No changes. - assert_eq!( + assert_eq_error_rate!( TargetedFeeAdjustment::::convert(Fixed128::default()), - feemul(0, NonZeroI128::new(1_000_000_000).unwrap()), + Fixed128::from_rational(0, NonZeroI128::new(1_000_000_000).unwrap()), + ERROR_RATE, ); }); run_with_system_weight(target() * 2, || { // // More than ideal. Fee is increased. - assert_eq!( + assert_eq_error_rate!( TargetedFeeAdjustment::::convert(Fixed128::default()), - feemul(10000, NonZeroI128::new(1_000_000_000).unwrap()), + Fixed128::from_rational(10000, NonZeroI128::new(1_000_000_000).unwrap()), + ERROR_RATE, ); }); } @@ -280,22 +282,26 @@ mod tests { #[test] fn stateful_weight_mul_grow_to_infinity() { run_with_system_weight(target() * 2, || { - assert_eq!( + assert_eq_error_rate!( TargetedFeeAdjustment::::convert(Fixed128::default()), - feemul(10000, NonZeroI128::new(1_000_000_000).unwrap()) + Fixed128::from_rational(10000, NonZeroI128::new(1_000_000_000).unwrap()), + ERROR_RATE, ); - assert_eq!( - TargetedFeeAdjustment::::convert(feemul(10000, NonZeroI128::new(1_000_000_000).unwrap())), - feemul(20000, NonZeroI128::new(1_000_000_000).unwrap()) + assert_eq_error_rate!( + TargetedFeeAdjustment::::convert(Fixed128::from_rational(10000, NonZeroI128::new(1_000_000_000).unwrap())), + Fixed128::from_rational(20000, NonZeroI128::new(1_000_000_000).unwrap()), + ERROR_RATE, ); - assert_eq!( - TargetedFeeAdjustment::::convert(feemul(20000, NonZeroI128::new(1_000_000_000).unwrap())), - feemul(30000, NonZeroI128::new(1_000_000_000).unwrap()) + assert_eq_error_rate!( + TargetedFeeAdjustment::::convert(Fixed128::from_rational(20000, NonZeroI128::new(1_000_000_000).unwrap())), + Fixed128::from_rational(30000, NonZeroI128::new(1_000_000_000).unwrap()), + ERROR_RATE, ); // ... - assert_eq!( - TargetedFeeAdjustment::::convert(feemul(1_000_000_000, NonZeroI128::new(1_000_000_000).unwrap())), - feemul(1_000_000_000 + 10000, NonZeroI128::new(1_000_000_000).unwrap()) + assert_eq_error_rate!( + TargetedFeeAdjustment::::convert(Fixed128::from_rational(1_000_000_000, NonZeroI128::new(1_000_000_000).unwrap())), + Fixed128::from_rational(1_000_000_000 + 10000, NonZeroI128::new(1_000_000_000).unwrap()), + ERROR_RATE, ); }); } @@ -303,22 +309,25 @@ mod tests { #[test] fn stateful_weight_mil_collapse_to_minus_one() { run_with_system_weight(0, || { - assert_eq!( + assert_eq_error_rate!( TargetedFeeAdjustment::::convert(Fixed128::default()), - feemul(-10000, NonZeroI128::new(1_000_000_000).unwrap()) + Fixed128::from_rational(-10000, NonZeroI128::new(1_000_000_000).unwrap()), + ERROR_RATE, ); - assert_eq!( - TargetedFeeAdjustment::::convert(feemul(-10000, NonZeroI128::new(1_000_000_000).unwrap())), - feemul(-20000, NonZeroI128::new(1_000_000_000).unwrap()) + assert_eq_error_rate!( + TargetedFeeAdjustment::::convert(Fixed128::from_rational(-10000, NonZeroI128::new(1_000_000_000).unwrap())), + Fixed128::from_rational(-20000, NonZeroI128::new(1_000_000_000).unwrap()), + ERROR_RATE, ); - assert_eq!( - TargetedFeeAdjustment::::convert(feemul(-20000, NonZeroI128::new(1_000_000_000).unwrap())), - feemul(-30000, NonZeroI128::new(1_000_000_000).unwrap()) + assert_eq_error_rate!( + TargetedFeeAdjustment::::convert(Fixed128::from_rational(-20000, NonZeroI128::new(1_000_000_000).unwrap())), + Fixed128::from_rational(-30000, NonZeroI128::new(1_000_000_000).unwrap()), + ERROR_RATE, ); // ... assert_eq!( - TargetedFeeAdjustment::::convert(feemul(1_000_000_000 * -1, NonZeroI128::new(1_000_000_000).unwrap())), - feemul(-1_000_000_000, NonZeroI128::new(1_000_000_000).unwrap()) + TargetedFeeAdjustment::::convert(Fixed128::from_rational(MaximumBlockWeight::get() as i128 * -1, NonZeroI128::new(1_000_000_000).unwrap())), + Fixed128::from_natural(-1) ); }) } @@ -348,7 +357,7 @@ mod tests { run_with_system_weight(i, || { let next = TargetedFeeAdjustment::::convert(Fixed128::default()); let truth = fee_multiplier_update(i, Fixed128::default()); - assert_eq_error_rate!(truth.deconstruct(), next.deconstruct(), 500_000_000i128); + assert_eq_error_rate!(truth, next, ERROR_RATE); }); }); diff --git a/primitives/arithmetic/Cargo.toml b/primitives/arithmetic/Cargo.toml index 71479e4eb0f16..b8eaa721d6923 100644 --- a/primitives/arithmetic/Cargo.toml +++ b/primitives/arithmetic/Cargo.toml @@ -22,6 +22,7 @@ primitive-types = { version = "0.7.0", default-features = false } [dev-dependencies] rand = "0.7.2" criterion = "0.3" +serde_json = "1.0" [features] default = ["std"] diff --git a/primitives/arithmetic/src/fixed128.rs b/primitives/arithmetic/src/fixed128.rs index 9081cff7b4df3..74ad09ceaaa23 100644 --- a/primitives/arithmetic/src/fixed128.rs +++ b/primitives/arithmetic/src/fixed128.rs @@ -51,7 +51,7 @@ impl Fixed128 { } /// Raw constructor. Equal to `parts / DIV`. - pub fn from_parts(parts: i128) -> Self { + pub const fn from_parts(parts: i128) -> Self { Self(parts) } @@ -251,6 +251,26 @@ impl Fixed128 { } } +/// Note that this is a standard, _potentially-panicking_, implementation. Use `Saturating` trait +/// for safe addition. +impl ops::Add for Fixed128 { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self(self.0 + rhs.0) + } +} + +/// Note that this is a standard, _potentially-panicking_, implementation. Use `Saturating` trait +/// for safe subtraction. +impl ops::Sub for Fixed128 { + type Output = Self; + + fn sub(self, rhs: Self) -> Self::Output { + Self(self.0 - rhs.0) + } +} + impl Saturating for Fixed128 { fn saturating_add(self, rhs: Self) -> Self { Self(self.0.saturating_add(rhs.0)) diff --git a/primitives/arithmetic/src/per_things.rs b/primitives/arithmetic/src/per_things.rs index ad529fbf32e24..56fc562cd1a92 100644 --- a/primitives/arithmetic/src/per_things.rs +++ b/primitives/arithmetic/src/per_things.rs @@ -1096,7 +1096,7 @@ macro_rules! implement_per_thing { <$type>::max_value(), super::Rounding::Nearest, ), - (<$type>::max_value() - 1).into(), + <$upper_type>::from((<$type>::max_value() - 1)), ); // (max % 2) * max / 2 == max / 2 assert_eq!( From 0ce0870f946d698bfd6a7aa484c2140eb0030b16 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Mon, 13 Apr 2020 16:38:15 +0200 Subject: [PATCH 22/52] Update impls.rs --- bin/node/runtime/src/impls.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index 4e0337bb386ae..2b76c421f8317 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -129,6 +129,7 @@ mod tests { TargetBlockFullness::get() * max() } + // This is an error rate of 5 x 10 ^ -10 with Fixed128 const ERROR_RATE: Fixed128 = Fixed128::from_parts(500_000_000); // poc reference implementation. From ab5b865b5def2b33b281966353831924dc74a4bf Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Mon, 13 Apr 2020 20:50:00 +0200 Subject: [PATCH 23/52] fix tests --- bin/node/runtime/src/impls.rs | 143 ++++++++++++++++++++-------------- 1 file changed, 83 insertions(+), 60 deletions(-) diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index 2b76c421f8317..6570f6cf38af0 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -60,9 +60,9 @@ impl> Convert for LinearWeightToFee { /// Update the given multiplier based on the following formula /// -/// diff = (previous_block_weight - target_weight) +/// diff = (previous_block_weight - target_weight)/max_weight /// v = 0.00004 -/// next_weight = weight * (1 + (v . diff) + (v . diff)^2 / 2) +/// next_weight = weight * (1 + (v * diff) + (v * diff)^2 / 2) /// /// Where `target_weight` must be given as the `Get` implementation of the `T` generic type. /// https://research.web3.foundation/en/latest/polkadot/Token%20Economics/#relay-chain-transaction-fees @@ -78,19 +78,17 @@ impl> Convert for TargetedFeeAdjustment< // determines if the first_term is positive let positive = block_weight >= target_weight; let diff_abs = block_weight.max(target_weight) - block_weight.min(target_weight); - // diff is within u64, safe. + // TODO: This is not always safe! Diff can be larger than what fits into i64 + // It is safe as long as `block_weight` is less than `max_weight` let diff = Fixed128::from_rational(diff_abs as i64, NonZeroI128::new(max_weight.max(1) as i128).unwrap()); let diff_squared = diff.saturating_mul(diff); // 0.00004 = 4/100_000 = 40_000/10^9 let v = Fixed128::from_rational(4, NonZeroI128::new(100_000).unwrap()); - // 0.00004^2 = 16/10^10 ~= 2/10^9. Taking the future /2 into account, then it is just 1 - // parts from a billionth. - let v_squared_2 = Fixed128::from_rational(1, NonZeroI128::new(800_000_000).unwrap()); + // 0.00004^2 = 16/10^10 Taking the future /2 into account... 8/10^10 + let v_squared_2 = Fixed128::from_rational(8, NonZeroI128::new(10_000_000_000).unwrap()); let first_term = v.saturating_mul(diff); - // It is very unlikely that this will exist (in our poor perbill estimate) but we are giving - // it a shot. let second_term = v_squared_2.saturating_mul(diff_squared); if positive { @@ -107,7 +105,7 @@ impl> Convert for TargetedFeeAdjustment< // multiplier. While at -1, it means that the network is so un-congested that all // transactions have no weight fee. We stop here and only increase if the network // became more busy. - .max(Fixed128::from_rational(-1, NonZeroI128::new(1).unwrap())) + .max(Fixed128::from_natural(-1)) } } } @@ -129,9 +127,6 @@ mod tests { TargetBlockFullness::get() * max() } - // This is an error rate of 5 x 10 ^ -10 with Fixed128 - const ERROR_RATE: Fixed128 = Fixed128::from_parts(500_000_000); - // poc reference implementation. fn fee_multiplier_update(block_weight: Weight, previous: Fixed128) -> Fixed128 { let block_weight = block_weight as f64; @@ -171,9 +166,10 @@ mod tests { test_set.into_iter().for_each(|(w, fm)| { run_with_system_weight(w, || { assert_eq_error_rate!( - fee_multiplier_update(w, fm).deconstruct(), - TargetedFeeAdjustment::::convert(fm).deconstruct(), - 5_000_000_000i128, + fee_multiplier_update(w, fm), + TargetedFeeAdjustment::::convert(fm), + // Error is only 1 in 10^18 + Fixed128::from_parts(1), ); }) }) @@ -247,35 +243,46 @@ mod tests { fn stateless_weight_mul() { run_with_system_weight(target() / 4, || { // Light block. Fee is reduced a little. - assert_eq_error_rate!( + // Target = 25%, Weight is Target / 4 = 6.25%, Diff = -18.75%, V = 4/10^5 + // So first term is -75/10^7 + let first_term = Fixed128::from_rational(-75, NonZeroI128::new(10_000_000).unwrap()); + // Diff^2 = .03515625, V^2 = 8/10^10... So second_term = 28125/10^15 + let second_term = Fixed128::from_parts(28_125_000); + assert_eq!( TargetedFeeAdjustment::::convert(Fixed128::default()), - Fixed128::from_rational(-7500, NonZeroI128::new(1_000_000_000).unwrap()), - ERROR_RATE, + first_term + second_term, ); }); run_with_system_weight(target() / 2, || { // a bit more. Fee is decreased less, meaning that the fee increases as the block grows. - assert_eq_error_rate!( + // Target = 25%, Weight is Target / 2 = 12.5%, Diff = -12.5%, V = 4/10^5 + // So first term is -5/10^6 + let first_term = Fixed128::from_rational(-5, NonZeroI128::new(1_000_000).unwrap()); + // Diff^2 = .015625, V^2 = 8/10^10... So second_term = 125/10^13 + let second_term = Fixed128::from_parts(12_500_000); + assert_eq!( TargetedFeeAdjustment::::convert(Fixed128::default()), - Fixed128::from_rational(-5000, NonZeroI128::new(1_000_000_000).unwrap()), - ERROR_RATE, + first_term + second_term ); }); run_with_system_weight(target(), || { // ideal. Original fee. No changes. - assert_eq_error_rate!( + assert_eq!( TargetedFeeAdjustment::::convert(Fixed128::default()), - Fixed128::from_rational(0, NonZeroI128::new(1_000_000_000).unwrap()), - ERROR_RATE, + Fixed128::from_natural(0), ); }); run_with_system_weight(target() * 2, || { - // // More than ideal. Fee is increased. - assert_eq_error_rate!( + // More than ideal. Fee is increased. + // Target = 25%, Weight is Target * 2 = 50%, Diff = 25%, V = 4/10^5 + // So first term is 1/10^5 + let first_term = Fixed128::from_rational(1, NonZeroI128::new(100_000).unwrap()); + // Diff^2 = .0625, V^2 = 8/10^10... So second_term = 5/10^11 + let second_term = Fixed128::from_parts(50_000_000); + assert_eq!( TargetedFeeAdjustment::::convert(Fixed128::default()), - Fixed128::from_rational(10000, NonZeroI128::new(1_000_000_000).unwrap()), - ERROR_RATE, + first_term + second_term, ); }); } @@ -283,26 +290,32 @@ mod tests { #[test] fn stateful_weight_mul_grow_to_infinity() { run_with_system_weight(target() * 2, || { - assert_eq_error_rate!( - TargetedFeeAdjustment::::convert(Fixed128::default()), - Fixed128::from_rational(10000, NonZeroI128::new(1_000_000_000).unwrap()), - ERROR_RATE, + // Target = 25%, Weight is Target * 2 = 50%, Diff = 25%, V = 4/10^5 + // So first term is 1/10^5 + let first_term = Fixed128::from_rational(1, NonZeroI128::new(100_000).unwrap()); + // Diff^2 = .0625, V^2 = 8/10^10... So second_term = 5/10^11 + let second_term = Fixed128::from_rational(5, NonZeroI128::new(100_000_000_000).unwrap()); + + // We should see the fee in each of these tests increase by first_term + second_term in all cases. + let original = Fixed128::default(); // 0 + assert_eq!( + TargetedFeeAdjustment::::convert(original), + original + first_term + second_term, ); - assert_eq_error_rate!( - TargetedFeeAdjustment::::convert(Fixed128::from_rational(10000, NonZeroI128::new(1_000_000_000).unwrap())), - Fixed128::from_rational(20000, NonZeroI128::new(1_000_000_000).unwrap()), - ERROR_RATE, + let original = Fixed128::from_rational(1, NonZeroI128::new(100).unwrap()); + assert_eq!( + TargetedFeeAdjustment::::convert(original), + original + first_term + second_term, ); - assert_eq_error_rate!( - TargetedFeeAdjustment::::convert(Fixed128::from_rational(20000, NonZeroI128::new(1_000_000_000).unwrap())), - Fixed128::from_rational(30000, NonZeroI128::new(1_000_000_000).unwrap()), - ERROR_RATE, + let original = Fixed128::from_rational(3, NonZeroI128::new(100).unwrap()); + assert_eq!( + TargetedFeeAdjustment::::convert(original), + original + first_term + second_term, ); - // ... - assert_eq_error_rate!( - TargetedFeeAdjustment::::convert(Fixed128::from_rational(1_000_000_000, NonZeroI128::new(1_000_000_000).unwrap())), - Fixed128::from_rational(1_000_000_000 + 10000, NonZeroI128::new(1_000_000_000).unwrap()), - ERROR_RATE, + // ... keeps going up till infinity + assert_eq!( + TargetedFeeAdjustment::::convert(Fixed128::from_natural(1)), + Fixed128::from_natural(1) + first_term + second_term ); }); } @@ -310,24 +323,31 @@ mod tests { #[test] fn stateful_weight_mil_collapse_to_minus_one() { run_with_system_weight(0, || { - assert_eq_error_rate!( - TargetedFeeAdjustment::::convert(Fixed128::default()), - Fixed128::from_rational(-10000, NonZeroI128::new(1_000_000_000).unwrap()), - ERROR_RATE, + // Target = 25%, Weight = 0%, Diff = -25%, V = 4/10^5 + // So first term is -1/10^5 + let first_term = Fixed128::from_rational(-1, NonZeroI128::new(100_000).unwrap()); + // Diff^2 = .0625, V^2 = 8/10^10... So second_term = 5/10^11 + let second_term = Fixed128::from_rational(5, NonZeroI128::new(100_000_000_000).unwrap()); + + // We should see the fee in each of these tests decrease by first_term - second_term until it hits -1. + let original = Fixed128::default(); // 0 + assert_eq!( + TargetedFeeAdjustment::::convert(original), + original + first_term + second_term, ); - assert_eq_error_rate!( - TargetedFeeAdjustment::::convert(Fixed128::from_rational(-10000, NonZeroI128::new(1_000_000_000).unwrap())), - Fixed128::from_rational(-20000, NonZeroI128::new(1_000_000_000).unwrap()), - ERROR_RATE, + let original = Fixed128::from_rational(-1, NonZeroI128::new(100).unwrap()); + assert_eq!( + TargetedFeeAdjustment::::convert(original), + original + first_term + second_term, ); - assert_eq_error_rate!( - TargetedFeeAdjustment::::convert(Fixed128::from_rational(-20000, NonZeroI128::new(1_000_000_000).unwrap())), - Fixed128::from_rational(-30000, NonZeroI128::new(1_000_000_000).unwrap()), - ERROR_RATE, + let original = Fixed128::from_rational(-3, NonZeroI128::new(100).unwrap()); + assert_eq!( + TargetedFeeAdjustment::::convert(original), + original + first_term + second_term, ); - // ... + // ... stops going down at -1 assert_eq!( - TargetedFeeAdjustment::::convert(Fixed128::from_rational(MaximumBlockWeight::get() as i128 * -1, NonZeroI128::new(1_000_000_000).unwrap())), + TargetedFeeAdjustment::::convert(Fixed128::from_natural(-1)), Fixed128::from_natural(-1) ); }) @@ -354,11 +374,14 @@ mod tests { 4294967295, MaximumBlockWeight::get() / 2, MaximumBlockWeight::get(), + // TODO these are not safe + // Weight::max_value() / 2, + // Weight::max_value(), ].into_iter().for_each(|i| { run_with_system_weight(i, || { let next = TargetedFeeAdjustment::::convert(Fixed128::default()); let truth = fee_multiplier_update(i, Fixed128::default()); - assert_eq_error_rate!(truth, next, ERROR_RATE); + assert_eq_error_rate!(truth, next, Fixed128::from_parts(50_000_000)); }); }); From b704be96b08e98fab67c380d6dac32fc0937ac09 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Mon, 13 Apr 2020 20:54:26 +0200 Subject: [PATCH 24/52] better comment --- bin/node/executor/tests/fees.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/bin/node/executor/tests/fees.rs b/bin/node/executor/tests/fees.rs index 4731c6f09c329..b53f22b1306b0 100644 --- a/bin/node/executor/tests/fees.rs +++ b/bin/node/executor/tests/fees.rs @@ -188,6 +188,8 @@ fn transaction_fee_is_correct_ultimate() { let weight_fee = LinearWeightToFee::::convert(weight); // we know that weight to fee multiplier is effect-less in block 1. + // current weight of transfer = 200_000_000 + // 1_000_000_000 = 1 MILLICENT... thus assert_eq!(weight_fee as Balance, MILLICENTS / 5); balance_alice -= weight_fee; balance_alice -= tip; From 275d40d63ae96ba6fa5c1853d0d5f92c966ece5e Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Mon, 13 Apr 2020 21:08:08 +0200 Subject: [PATCH 25/52] types update --- bin/node/executor/tests/basic.rs | 4 ++-- bin/node/executor/tests/fees.rs | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/bin/node/executor/tests/basic.rs b/bin/node/executor/tests/basic.rs index 005b31f3fc49e..7fdf4e9c596a4 100644 --- a/bin/node/executor/tests/basic.rs +++ b/bin/node/executor/tests/basic.rs @@ -24,7 +24,7 @@ use sp_core::{ NeverNativeValue, map, traits::Externalities, storage::{well_known_keys, Storage}, }; use sp_runtime::{ - ApplyExtrinsicResult, Fixed64, + ApplyExtrinsicResult, Fixed128, traits::{Hash as HashT, Convert, BlakeTwo256}, transaction_validity::InvalidTransaction, }; @@ -51,7 +51,7 @@ use self::common::{*, sign}; pub const BLOATY_CODE: &[u8] = node_runtime::WASM_BINARY_BLOATY; /// Default transfer fee -fn transfer_fee(extrinsic: &E, fee_multiplier: Fixed64) -> Balance { +fn transfer_fee(extrinsic: &E, fee_multiplier: Fixed128) -> Balance { let length_fee = TransactionByteFee::get() * (extrinsic.encode().len() as Balance); let weight = default_transfer_call().get_dispatch_info().weight; diff --git a/bin/node/executor/tests/fees.rs b/bin/node/executor/tests/fees.rs index b53f22b1306b0..e1270832e374e 100644 --- a/bin/node/executor/tests/fees.rs +++ b/bin/node/executor/tests/fees.rs @@ -21,7 +21,7 @@ use frame_support::{ weights::GetDispatchInfo, }; use sp_core::{NeverNativeValue, map, storage::Storage}; -use sp_runtime::{Fixed64, Perbill, traits::{Convert, BlakeTwo256}}; +use sp_runtime::{Fixed128, Perbill, traits::{Convert, BlakeTwo256}}; use node_runtime::{ CheckedExtrinsic, Call, Runtime, Balances, TransactionPayment, TransactionBaseFee, TransactionByteFee, WeightFeeCoefficient, @@ -39,7 +39,7 @@ fn fee_multiplier_increases_and_decreases_on_big_weight() { let mut t = new_test_ext(COMPACT_CODE, false); // initial fee multiplier must be zero - let mut prev_multiplier = Fixed64::from_parts(0); + let mut prev_multiplier = Fixed128::from_parts(0); t.execute_with(|| { assert_eq!(TransactionPayment::next_fee_multiplier(), prev_multiplier); @@ -189,8 +189,8 @@ fn transaction_fee_is_correct_ultimate() { // we know that weight to fee multiplier is effect-less in block 1. // current weight of transfer = 200_000_000 - // 1_000_000_000 = 1 MILLICENT... thus - assert_eq!(weight_fee as Balance, MILLICENTS / 5); + // Linear weight to fee is 1:1 right now (1 weight = 1 unit of balance) + assert_eq!(weight_fee as Balance, 200_000_000); balance_alice -= weight_fee; balance_alice -= tip; From d07a62340376834a8f1a01a499ce50137e2c8bf7 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Mon, 13 Apr 2020 21:18:38 +0200 Subject: [PATCH 26/52] Use new fixed128 api --- frame/transaction-payment/src/lib.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index 3ae52286029b0..7d3b673bad025 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -578,7 +578,7 @@ mod tests { .execute_with(|| { // all fees should be x1.5 - NextFeeMultiplier::put(Fixed128::from_rational(1, 2)); + NextFeeMultiplier::put(Fixed128::from_rational(1, NonZeroI128::new(2).unwrap())); let len = 10; assert!( @@ -606,7 +606,7 @@ mod tests { .execute_with(|| { // all fees should be x1.5 - NextFeeMultiplier::put(Fixed128::from_rational(1, 2)); + NextFeeMultiplier::put(Fixed128::from_rational(1, NonZeroI128::new(2).unwrap())); assert_eq!( TransactionPayment::query_info(xt, len), @@ -675,7 +675,7 @@ mod tests { .execute_with(|| { // Add a next fee multiplier - NextFeeMultiplier::put(Fixed128::from_rational(1, 2)); // = 1/2 = .5 + NextFeeMultiplier::put(Fixed128::from_rational(1, NonZeroI128::new(2).unwrap())); // = 1/2 = .5 // Base fee is unaffected by multiplier let dispatch_info = DispatchInfo { weight: 0, From ec2f0c82f4643135c68b12c510d02d4dee218cd0 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Mon, 13 Apr 2020 21:21:18 +0200 Subject: [PATCH 27/52] import in test --- frame/transaction-payment/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index 7d3b673bad025..e6c428e0adfcd 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -307,6 +307,7 @@ impl SignedExtension for ChargeTransactionPayment whe #[cfg(test)] mod tests { use super::*; + use core::num::NonZeroI128; use codec::Encode; use frame_support::{ impl_outer_dispatch, impl_outer_origin, parameter_types, From 2ccd439db66ce96b6d9318ffb02fae2d2ce523e1 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Mon, 13 Apr 2020 21:28:12 +0200 Subject: [PATCH 28/52] another type update --- frame/balances/src/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frame/balances/src/tests.rs b/frame/balances/src/tests.rs index 14caf41c1eec6..7ff7ec0fc45c5 100644 --- a/frame/balances/src/tests.rs +++ b/frame/balances/src/tests.rs @@ -36,7 +36,7 @@ macro_rules! decl_tests { ($test:ty, $ext_builder:ty, $existential_deposit:expr) => { use crate::*; - use sp_runtime::{Fixed64, traits::{SignedExtension, BadOrigin}}; + use sp_runtime::{Fixed128, traits::{SignedExtension, BadOrigin}}; use frame_support::{ assert_noop, assert_ok, assert_err, traits::{ @@ -153,7 +153,7 @@ macro_rules! decl_tests { .monied(true) .build() .execute_with(|| { - pallet_transaction_payment::NextFeeMultiplier::put(Fixed64::from_natural(1)); + pallet_transaction_payment::NextFeeMultiplier::put(Fixed128::from_natural(1)); Balances::set_lock(ID_1, &1, 10, WithdrawReason::Reserve.into()); assert_noop!( >::transfer(&1, &2, 1, AllowDeath), From 5329496418d82ab740fac7c621f225c81f923ac9 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Mon, 13 Apr 2020 22:04:43 +0200 Subject: [PATCH 29/52] fix test in example --- frame/example/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/example/src/lib.rs b/frame/example/src/lib.rs index b577667ea8241..c95240ce50839 100644 --- a/frame/example/src/lib.rs +++ b/frame/example/src/lib.rs @@ -848,7 +848,7 @@ mod tests { let default_call = >::accumulate_dummy(10); let info = default_call.get_dispatch_info(); // aka. `let info = as GetDispatchInfo>::get_dispatch_info(&default_call);` - assert_eq!(info.weight, 10_000); + assert_eq!(info.weight, 10_000_000); // must have a custom weight of `100 * arg = 2000` let custom_call = >::set_dummy(20); From d078d31a2dc4ceb614e3daad49771da381bfc2c5 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Mon, 13 Apr 2020 22:20:43 +0200 Subject: [PATCH 30/52] remove weight test --- frame/example-offchain-worker/src/tests.rs | 9 --------- 1 file changed, 9 deletions(-) diff --git a/frame/example-offchain-worker/src/tests.rs b/frame/example-offchain-worker/src/tests.rs index 59da11ae5bd72..299fbd673611f 100644 --- a/frame/example-offchain-worker/src/tests.rs +++ b/frame/example-offchain-worker/src/tests.rs @@ -193,15 +193,6 @@ fn should_submit_unsigned_transaction_on_chain() { }); } -#[test] -fn weights_work() { - // must have a default weight. - let default_call = >::submit_price(10); - let info = default_call.get_dispatch_info(); - // aka. `let info = as GetDispatchInfo>::get_dispatch_info(&default_call);` - assert_eq!(info.weight, 10_000); -} - fn price_oracle_response(state: &mut testing::OffchainState) { state.expect_request(0, testing::PendingRequest { method: "GET".into(), From b371c239354e26bb5c8b78a778807c5bda6ad482 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Mon, 13 Apr 2020 22:48:08 +0200 Subject: [PATCH 31/52] fix warning --- frame/example-offchain-worker/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/example-offchain-worker/src/tests.rs b/frame/example-offchain-worker/src/tests.rs index 299fbd673611f..279de7ef4a382 100644 --- a/frame/example-offchain-worker/src/tests.rs +++ b/frame/example-offchain-worker/src/tests.rs @@ -19,7 +19,7 @@ use crate::*; use codec::Decode; use frame_support::{ assert_ok, impl_outer_origin, parameter_types, - weights::{GetDispatchInfo, Weight}, + weights::Weight, }; use sp_core::{ H256, From f0187d91bf8064152243885598cc13cbff5cb3be Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Tue, 14 Apr 2020 02:12:56 +0200 Subject: [PATCH 32/52] Simplify RuntimeDbWeight --- bin/node/runtime/src/impls.rs | 2 +- frame/support/src/weights.rs | 37 +++++------------------------------ 2 files changed, 6 insertions(+), 33 deletions(-) diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index 6570f6cf38af0..80b6eecedf94c 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -185,7 +185,7 @@ mod tests { loop { let next = TargetedFeeAdjustment::::convert(fm); fm = next; - if fm == Fixed128::from_rational(-1, NonZeroI128::new(1).unwrap()) { break; } + if fm == Fixed128::from_natural(-1) { break; } iterations += 1; } println!("iteration {}, new fm = {:?}. Weight fee is now zero", iterations, fm); diff --git a/frame/support/src/weights.rs b/frame/support/src/weights.rs index 9132600d6f678..940dfb7ec4d7d 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -37,7 +37,7 @@ #[cfg(feature = "std")] use serde::{Serialize, Deserialize}; -use core::ops::{Add, Mul}; +use core::ops::Mul; use codec::{Encode, Decode}; use sp_arithmetic::traits::Bounded; use sp_runtime::{ @@ -421,39 +421,12 @@ pub struct RuntimeDbWeight { } impl Mul<(Weight, Weight)> for RuntimeDbWeight { - type Output = Self; - - fn mul(self, rhs: (Weight, Weight)) -> Self::Output { - RuntimeDbWeight { - read: self.read.saturating_mul(rhs.0), - write: self.write.saturating_mul(rhs.1), - } - } -} - -impl Add for RuntimeDbWeight { type Output = Weight; - fn add(self, rhs: Weight) -> Self::Output { - return self.weigh_data(()) + rhs - } -} - -impl WeighData for RuntimeDbWeight { - fn weigh_data(&self, _: T) -> Weight { - return self.read.saturating_add(self.write) - } -} - -impl ClassifyDispatch for RuntimeDbWeight { - fn classify_dispatch(&self, _: T) -> DispatchClass { - DispatchClass::Normal - } -} - -impl PaysFee for RuntimeDbWeight { - fn pays_fee(&self, _: T) -> bool { - true + fn mul(self, rhs: (Weight, Weight)) -> Self::Output { + let read_weight = self.read.saturating_mul(rhs.0); + let write_weight = self.write.saturating_mul(rhs.1); + read_weight.saturating_add(write_weight) } } From 96b217ab97400a13da2eb39a1c0e38fb5720f4e7 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Tue, 14 Apr 2020 09:59:27 +0200 Subject: [PATCH 33/52] Update bin/node/runtime/src/impls.rs Co-Authored-By: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- bin/node/runtime/src/impls.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index 80b6eecedf94c..98b6eed1985e6 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -97,7 +97,7 @@ impl> Convert for TargetedFeeAdjustment< let excess = first_term.saturating_add(second_term); multiplier.saturating_add(excess) } else { - // Proof: first_term > second_term. Safe subtraction. + // Defensive-only: first_term > second_term. Safe subtraction. let negative = first_term.saturating_sub(second_term); multiplier.saturating_sub(negative) // despite the fact that apply_to saturates weight (final fee cannot go below 0) From fef18aab7d6145320a07d78a0c4a56b923d455fc Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Tue, 14 Apr 2020 10:00:34 +0200 Subject: [PATCH 34/52] Apply suggestions from code review Co-Authored-By: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- bin/node/runtime/src/impls.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index 98b6eed1985e6..92b258b962142 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -297,17 +297,17 @@ mod tests { let second_term = Fixed128::from_rational(5, NonZeroI128::new(100_000_000_000).unwrap()); // We should see the fee in each of these tests increase by first_term + second_term in all cases. - let original = Fixed128::default(); // 0 + let mut original = Fixed128::default(); // 0 assert_eq!( TargetedFeeAdjustment::::convert(original), original + first_term + second_term, ); - let original = Fixed128::from_rational(1, NonZeroI128::new(100).unwrap()); + original = Fixed128::from_rational(1, NonZeroI128::new(100).unwrap()); assert_eq!( TargetedFeeAdjustment::::convert(original), original + first_term + second_term, ); - let original = Fixed128::from_rational(3, NonZeroI128::new(100).unwrap()); + original = Fixed128::from_rational(3, NonZeroI128::new(100).unwrap()); assert_eq!( TargetedFeeAdjustment::::convert(original), original + first_term + second_term, From 0e77b6f894337d2365b1be531bec44881d2be871 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Tue, 14 Apr 2020 12:07:06 +0200 Subject: [PATCH 35/52] improved api @apopiak --- frame/balances/src/lib.rs | 8 ++++---- frame/support/src/weights.rs | 23 ++++++++++++++++------- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 7e438b1ad7e2a..98d6a93738147 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -433,7 +433,7 @@ decl_module! { /// check that the transfer will not kill the origin account. /// /// # - #[weight = T::DbWeight::get() * (1, 1) + 200_000_000] + #[weight = T::DbWeight::get().reads_writes(1, 1) + 200_000_000] pub fn transfer( origin, dest: ::Source, @@ -457,7 +457,7 @@ decl_module! { /// - Independent of the arguments. /// - Contains a limited number of reads and writes. /// # - #[weight = T::DbWeight::get() * (1, 1) + 100_000_000] + #[weight = T::DbWeight::get().reads_writes(1, 1) + 100_000_000] fn set_balance( origin, who: ::Source, @@ -499,7 +499,7 @@ decl_module! { /// - Same as transfer, but additional read and write because the source account is /// not assumed to be in the overlay. /// # - #[weight = T::DbWeight::get() * (2, 2) + 200_000_000] + #[weight = T::DbWeight::get().reads_writes(2, 2) + 200_000_000] pub fn force_transfer( origin, source: ::Source, @@ -518,7 +518,7 @@ decl_module! { /// 99% of the time you want [`transfer`] instead. /// /// [`transfer`]: struct.Module.html#method.transfer - #[weight = T::DbWeight::get() * (1, 1) + 150_000_000] + #[weight = T::DbWeight::get().reads_writes(1, 1) + 150_000_000] pub fn transfer_keep_alive( origin, dest: ::Source, diff --git a/frame/support/src/weights.rs b/frame/support/src/weights.rs index 940dfb7ec4d7d..c09ea984b2a8d 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -37,7 +37,6 @@ #[cfg(feature = "std")] use serde::{Serialize, Deserialize}; -use core::ops::Mul; use codec::{Encode, Decode}; use sp_arithmetic::traits::Bounded; use sp_runtime::{ @@ -420,12 +419,18 @@ pub struct RuntimeDbWeight { pub write: Weight, } -impl Mul<(Weight, Weight)> for RuntimeDbWeight { - type Output = Weight; +impl RuntimeDbWeight { + pub fn reads(self, r: Weight) -> Weight { + self.read.saturating_mul(r) + } + + pub fn writes(self, w: Weight) -> Weight { + self.write.saturating_mul(w) + } - fn mul(self, rhs: (Weight, Weight)) -> Self::Output { - let read_weight = self.read.saturating_mul(rhs.0); - let write_weight = self.write.saturating_mul(rhs.1); + pub fn reads_writes(self, r: Weight, w: Weight) -> Weight { + let read_weight = self.read.saturating_mul(r); + let write_weight = self.write.saturating_mul(w); read_weight.saturating_add(write_weight) } } @@ -472,9 +477,12 @@ mod tests { #[weight = FunctionOf(|_: (&u32, &u32)| 0, DispatchClass::Operational, true)] fn f12(_origin, _a: u32, _eb: u32) { unimplemented!(); } - #[weight = T::DbWeight::get() * (3, 2) + 10_000] + #[weight = T::DbWeight::get().reads(3) + T::DbWeight::get().writes(2) + 10_000] fn f2(_origin) { unimplemented!(); } + #[weight = T::DbWeight::get().reads_writes(6, 5) + 40_000] + fn f21(_origin) { unimplemented!(); } + } } @@ -486,6 +494,7 @@ mod tests { assert_eq!(Call::::f12(10, 20).get_dispatch_info().weight, 0); assert_eq!(Call::::f12(10, 20).get_dispatch_info().class, DispatchClass::Operational); assert_eq!(Call::::f2().get_dispatch_info().weight, 12300); + assert_eq!(Call::::f21().get_dispatch_info().weight, 45600); assert_eq!(Call::::f2().get_dispatch_info().class, DispatchClass::Normal); } } From c7af45393c3814db830d2c3e0301280781cce356 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Tue, 14 Apr 2020 19:18:31 +0200 Subject: [PATCH 36/52] Remove `SimpleDispatchInfo::default()` --- bin/node-template/pallets/template/src/lib.rs | 4 +-- frame/assets/src/lib.rs | 6 ++--- frame/authorship/src/lib.rs | 2 +- frame/babe/src/lib.rs | 2 +- frame/benchmark/src/lib.rs | 26 +++++++++---------- frame/benchmarking/src/tests.rs | 4 +-- frame/contracts/src/lib.rs | 10 +++---- frame/democracy/src/lib.rs | 4 +-- frame/elections-phragmen/src/lib.rs | 4 +-- frame/elections/src/lib.rs | 2 +- frame/example/src/lib.rs | 2 +- frame/generic-asset/src/lib.rs | 12 ++++----- frame/grandpa/src/lib.rs | 2 +- frame/im-online/src/lib.rs | 4 +-- frame/indices/src/lib.rs | 10 +++---- frame/offences/src/lib.rs | 4 +-- frame/randomness-collective-flip/src/lib.rs | 4 +-- frame/recovery/src/lib.rs | 2 +- frame/scored-pool/src/lib.rs | 14 +++++----- frame/session/src/lib.rs | 2 +- frame/society/src/lib.rs | 2 +- frame/staking/src/lib.rs | 4 +-- frame/sudo/src/lib.rs | 4 +-- frame/support/src/dispatch.rs | 20 +++++++------- frame/support/src/error.rs | 2 +- frame/support/src/metadata.rs | 2 +- frame/support/src/weights.rs | 7 ----- frame/support/test/tests/decl_error.rs | 4 +-- frame/support/test/tests/instance.rs | 2 +- .../tests/reserved_keyword/on_initialize.rs | 2 +- frame/system/src/lib.rs | 2 +- frame/timestamp/src/lib.rs | 2 +- frame/treasury/src/lib.rs | 2 +- frame/vesting/src/lib.rs | 4 +-- 34 files changed, 86 insertions(+), 93 deletions(-) diff --git a/bin/node-template/pallets/template/src/lib.rs b/bin/node-template/pallets/template/src/lib.rs index a0daecfb72c9a..2ac78cf141138 100644 --- a/bin/node-template/pallets/template/src/lib.rs +++ b/bin/node-template/pallets/template/src/lib.rs @@ -75,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 = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] 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)?; @@ -91,7 +91,7 @@ decl_module! { /// Another dummy entry point. /// takes no parameters, attempts to increment storage value, and possibly throws an error - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] 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)?; diff --git a/frame/assets/src/lib.rs b/frame/assets/src/lib.rs index 9385656203e9c..94c1e7cf8080c 100644 --- a/frame/assets/src/lib.rs +++ b/frame/assets/src/lib.rs @@ -157,7 +157,7 @@ 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 = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn issue(origin, #[compact] total: T::Balance) { let origin = ensure_signed(origin)?; @@ -171,7 +171,7 @@ decl_module! { } /// Move some assets from one holder to another. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn transfer(origin, #[compact] id: T::AssetId, target: ::Source, @@ -190,7 +190,7 @@ decl_module! { } /// Destroy any assets of `id` owned by `origin`. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn destroy(origin, #[compact] id: T::AssetId) { let origin = ensure_signed(origin)?; let balance = >::take((id, &origin)); diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index 24cd8a1a05ec2..ec4675eed8045 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -197,7 +197,7 @@ decl_module! { T::EventHandler::note_author(Self::author()); - SimpleDispatchInfo::default().weigh_data(()) + SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) } fn on_finalize() { diff --git a/frame/babe/src/lib.rs b/frame/babe/src/lib.rs index 5f85b91088067..a836fe7851484 100644 --- a/frame/babe/src/lib.rs +++ b/frame/babe/src/lib.rs @@ -184,7 +184,7 @@ decl_module! { fn on_initialize(now: T::BlockNumber) -> Weight { Self::do_initialize(now); - SimpleDispatchInfo::default().weigh_data(()) + SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) } /// Block finalization diff --git a/frame/benchmark/src/lib.rs b/frame/benchmark/src/lib.rs index b571ffb5b9cab..67d374ed9a913 100644 --- a/frame/benchmark/src/lib.rs +++ b/frame/benchmark/src/lib.rs @@ -70,7 +70,7 @@ decl_module! { fn deposit_event() = default; /// Do nothing. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn do_nothing(_origin, input: u32) { if input > 0 { return Ok(()); @@ -82,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 = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn read_value(_origin, repeat: u32) { for _ in 0..repeat { MyValue::get(); @@ -90,7 +90,7 @@ decl_module! { } /// Put a value into a storage value. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn put_value(_origin, repeat: u32) { for r in 0..repeat { MyValue::put(r); @@ -102,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 = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn exists_value(_origin, repeat: u32) { for _ in 0..repeat { MyValue::exists(); @@ -110,7 +110,7 @@ decl_module! { } /// Remove a value from storage `repeat` number of times. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn remove_value(_origin, repeat: u32) { for r in 0..repeat { MyMap::remove(r); @@ -118,7 +118,7 @@ decl_module! { } /// Read a value from storage map `repeat` number of times. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn read_map(_origin, repeat: u32) { for r in 0..repeat { MyMap::get(r); @@ -126,7 +126,7 @@ decl_module! { } /// Insert a value into a map. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn insert_map(_origin, repeat: u32) { for r in 0..repeat { MyMap::insert(r, r); @@ -134,7 +134,7 @@ decl_module! { } /// Check is a map contains a value `repeat` number of times. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn contains_key_map(_origin, repeat: u32) { for r in 0..repeat { MyMap::contains_key(r); @@ -142,7 +142,7 @@ decl_module! { } /// Read a value from storage `repeat` number of times. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn remove_prefix(_origin, repeat: u32) { for r in 0..repeat { MyDoubleMap::remove_prefix(r); @@ -150,21 +150,21 @@ decl_module! { } /// Add user to the list. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn add_member_list(origin) { let who = ensure_signed(origin)?; MyMemberList::::mutate(|x| x.push(who)); } /// Append user to the list. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn append_member_list(origin) { let who = ensure_signed(origin)?; MyMemberList::::append(&[who])?; } /// Encode a vector of accounts to bytes. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn encode_accounts(_origin, accounts: Vec) { let bytes = accounts.encode(); @@ -176,7 +176,7 @@ decl_module! { } /// Decode bytes into a vector of accounts. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn decode_accounts(_origin, bytes: Vec) { let accounts: Vec = Decode::decode(&mut bytes.as_slice()).map_err(|_| "Could not decode")?; diff --git a/frame/benchmarking/src/tests.rs b/frame/benchmarking/src/tests.rs index a84604f0fd549..0a0620a16ea69 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -36,14 +36,14 @@ decl_storage! { decl_module! { pub struct Module for enum Call where origin: T::Origin { - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn set_value(origin, n: u32) -> DispatchResult { let _sender = ensure_signed(origin)?; Value::put(n); Ok(()) } - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn dummy(origin, _n: u32) -> DispatchResult { let _sender = ensure_none(origin)?; Ok(()) diff --git a/frame/contracts/src/lib.rs b/frame/contracts/src/lib.rs index 10938bb7debc1..49ae2dc4272f2 100644 --- a/frame/contracts/src/lib.rs +++ b/frame/contracts/src/lib.rs @@ -550,7 +550,7 @@ decl_module! { /// Updates the schedule for metering contracts. /// /// The schedule must have a greater version than the stored schedule. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn update_schedule(origin, schedule: Schedule) -> DispatchResult { ensure_root(origin)?; if >::current_schedule().version >= schedule.version { @@ -565,7 +565,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 = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn put_code( origin, #[compact] gas_limit: Gas, @@ -593,7 +593,7 @@ decl_module! { /// * If the account is a regular account, any value will be transferred. /// * If no account exists and the call value is not less than `existential_deposit`, /// a regular account will be created and any value will be transferred. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn call( origin, dest: ::Source, @@ -619,7 +619,7 @@ decl_module! { /// after the execution is saved as the `code` of the account. That code will be invoked /// upon any call received by this account. /// - The contract is initialized. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn instantiate( origin, #[compact] endowment: BalanceOf, @@ -642,7 +642,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 = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn claim_surcharge(origin, dest: T::AccountId, aux_sender: Option) { let origin = origin.into(); let (signed, rewarded) = match (origin, aux_sender) { diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index 0caa63a561076..4f50aa65df673 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -528,7 +528,7 @@ decl_module! { fn on_runtime_upgrade() -> Weight { Self::migrate(); - SimpleDispatchInfo::default().weigh_data(()) + SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) } /// Propose a sensitive action to be taken. @@ -848,7 +848,7 @@ decl_module! { sp_runtime::print(e); } - SimpleDispatchInfo::default().weigh_data(()) + SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) } /// Specify a proxy that is already open to us. Called by the stash. diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index e7e4158ba4839..bab00e4c124f9 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -267,7 +267,7 @@ decl_module! { fn on_runtime_upgrade() -> Weight { migration::migrate::(); - SimpleDispatchInfo::default().weigh_data(()) + SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) } const CandidacyBond: BalanceOf = T::CandidacyBond::get(); @@ -510,7 +510,7 @@ decl_module! { print(e); } - SimpleDispatchInfo::default().weigh_data(()) + SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) } } } diff --git a/frame/elections/src/lib.rs b/frame/elections/src/lib.rs index 478ead6156ee2..29055c3f37419 100644 --- a/frame/elections/src/lib.rs +++ b/frame/elections/src/lib.rs @@ -703,7 +703,7 @@ decl_module! { print("Guru meditation"); print(e); } - SimpleDispatchInfo::default().weigh_data(()) + SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) } } } diff --git a/frame/example/src/lib.rs b/frame/example/src/lib.rs index c95240ce50839..1d720af708d30 100644 --- a/frame/example/src/lib.rs +++ b/frame/example/src/lib.rs @@ -523,7 +523,7 @@ decl_module! { // Anything that needs to be done at the start of the block. // We don't do anything here. - SimpleDispatchInfo::default().weigh_data(()) + SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) } // The signature could also look like: `fn on_finalize()` diff --git a/frame/generic-asset/src/lib.rs b/frame/generic-asset/src/lib.rs index d8c91aff65438..fc650039e5c1a 100644 --- a/frame/generic-asset/src/lib.rs +++ b/frame/generic-asset/src/lib.rs @@ -360,14 +360,14 @@ decl_module! { fn deposit_event() = default; /// Create a new kind of asset. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn create(origin, options: AssetOptions) -> DispatchResult { let origin = ensure_signed(origin)?; Self::create_asset(None, Some(origin), options) } /// Transfer some liquid free balance to another account. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] 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::::ZeroAmount); @@ -377,7 +377,7 @@ decl_module! { /// Updates permission for a given `asset_id` and an account. /// /// The `origin` must have `update` permission. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn update_permission( origin, #[compact] asset_id: T::AssetId, @@ -400,7 +400,7 @@ decl_module! { /// Mints an asset, increases its total issuance. /// The origin must have `mint` permissions. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] 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)?; @@ -410,7 +410,7 @@ decl_module! { /// Burns an asset, decreases its total issuance. /// The `origin` must have `burn` permissions. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] 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)?; @@ -420,7 +420,7 @@ decl_module! { /// Can be used to create reserved tokens. /// Requires Root call. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn create_reserved( origin, asset_id: T::AssetId, diff --git a/frame/grandpa/src/lib.rs b/frame/grandpa/src/lib.rs index 030699b525872..4cff4408b865e 100644 --- a/frame/grandpa/src/lib.rs +++ b/frame/grandpa/src/lib.rs @@ -184,7 +184,7 @@ decl_module! { fn deposit_event() = default; /// Report some misbehavior. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn report_misbehavior(origin, _report: Vec) { ensure_signed(origin)?; // FIXME: https://github.com/paritytech/substrate/issues/1112 diff --git a/frame/im-online/src/lib.rs b/frame/im-online/src/lib.rs index 9c2b55a5c037e..cf9635c19b201 100644 --- a/frame/im-online/src/lib.rs +++ b/frame/im-online/src/lib.rs @@ -50,7 +50,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = frame_support::weights::SimpleDispatchInfo::default()] +//! #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] //! pub fn is_online(origin, authority_index: u32) -> dispatch::DispatchResult { //! let _sender = ensure_signed(origin)?; //! let _is_online = >::is_online(authority_index); @@ -316,7 +316,7 @@ decl_module! { fn deposit_event() = default; - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn heartbeat( origin, heartbeat: Heartbeat, diff --git a/frame/indices/src/lib.rs b/frame/indices/src/lib.rs index d2ba664d425ff..2b9319c8535de 100644 --- a/frame/indices/src/lib.rs +++ b/frame/indices/src/lib.rs @@ -102,7 +102,7 @@ decl_module! { fn on_initialize() -> Weight { Self::migrations(); - SimpleDispatchInfo::default().weigh_data(()) + SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) } /// Assign an previously unassigned index. @@ -121,7 +121,7 @@ decl_module! { /// - One reserve operation. /// - One event. /// # - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn claim(origin, index: T::AccountIndex) { let who = ensure_signed(origin)?; @@ -149,7 +149,7 @@ decl_module! { /// - One transfer operation. /// - One event. /// # - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn transfer(origin, new: T::AccountId, index: T::AccountIndex) { let who = ensure_signed(origin)?; ensure!(who != new, Error::::NotTransfer); @@ -180,7 +180,7 @@ decl_module! { /// - One reserve operation. /// - One event. /// # - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] 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 = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn force_transfer(origin, new: T::AccountId, index: T::AccountIndex) { ensure_root(origin)?; diff --git a/frame/offences/src/lib.rs b/frame/offences/src/lib.rs index 40f39ab5f2a0b..e9ee5cbc6200a 100644 --- a/frame/offences/src/lib.rs +++ b/frame/offences/src/lib.rs @@ -104,7 +104,7 @@ decl_module! { ConcurrentReportsIndex::::remove_all(); ReportsByKindIndex::remove_all(); - SimpleDispatchInfo::default().weigh_data(()) + SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) } fn on_initialize(now: T::BlockNumber) -> Weight { @@ -125,7 +125,7 @@ decl_module! { }) } - SimpleDispatchInfo::default().weigh_data(()) + SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) } } } diff --git a/frame/randomness-collective-flip/src/lib.rs b/frame/randomness-collective-flip/src/lib.rs index 1117f69960788..c9cee27275f1e 100644 --- a/frame/randomness-collective-flip/src/lib.rs +++ b/frame/randomness-collective-flip/src/lib.rs @@ -41,7 +41,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = SimpleDispatchInfo::default()] +//! #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] //! pub fn random_module_example(origin) -> dispatch::DispatchResult { //! let _random_seed = >::random_seed(); //! Ok(()) @@ -83,7 +83,7 @@ decl_module! { values[index] = parent_hash; }); - SimpleDispatchInfo::default().weigh_data(()) + SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) } } } diff --git a/frame/recovery/src/lib.rs b/frame/recovery/src/lib.rs index cd3b0e340555b..9862aef69fe6d 100644 --- a/frame/recovery/src/lib.rs +++ b/frame/recovery/src/lib.rs @@ -647,7 +647,7 @@ decl_module! { /// # /// - One storage mutation to check account is recovered by `who`. O(1) /// # - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn cancel_recovered(origin, account: T::AccountId) { let who = ensure_signed(origin)?; // Check `who` is allowed to make a call on behalf of `account` diff --git a/frame/scored-pool/src/lib.rs b/frame/scored-pool/src/lib.rs index 2602d389626a7..020408c46a623 100644 --- a/frame/scored-pool/src/lib.rs +++ b/frame/scored-pool/src/lib.rs @@ -61,7 +61,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = frame_support::weights::SimpleDispatchInfo::default()] +//! #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] //! pub fn candidate(origin) -> dispatch::DispatchResult { //! let who = ensure_signed(origin)?; //! @@ -252,7 +252,7 @@ decl_module! { let pool = >::get(); >::refresh_members(pool, ChangeReceiver::MembershipChanged); } - SimpleDispatchInfo::default().weigh_data(()) + SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) } /// Add `origin` to the pool of candidates. @@ -266,7 +266,7 @@ decl_module! { /// /// The `index` parameter of this function must be set to /// the index of the transactor in the `Pool`. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn submit_candidacy(origin) { let who = ensure_signed(origin)?; ensure!(!>::contains_key(&who), Error::::AlreadyInPool); @@ -296,7 +296,7 @@ decl_module! { /// /// The `index` parameter of this function must be set to /// the index of the transactor in the `Pool`. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn withdraw_candidacy( origin, index: u32 @@ -316,7 +316,7 @@ decl_module! { /// /// The `index` parameter of this function must be set to /// the index of `dest` in the `Pool`. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn kick( origin, dest: ::Source, @@ -341,7 +341,7 @@ decl_module! { /// /// The `index` parameter of this function must be set to /// the index of the `dest` in the `Pool`. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn score( origin, dest: ::Source, @@ -382,7 +382,7 @@ decl_module! { /// (this happens each `Period`). /// /// May only be called from root. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn change_member_count(origin, count: u32) { ensure_root(origin)?; >::put(&count); diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index e14b502bddc64..5156fa38f2ae8 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -532,7 +532,7 @@ decl_module! { Self::rotate_session(); } - SimpleDispatchInfo::default().weigh_data(()) + SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) } } } diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index 13ddd68550369..17fe8765c1467 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -1046,7 +1046,7 @@ decl_module! { Self::rotate_challenge(&mut members); } - SimpleDispatchInfo::default().weigh_data(()) + SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) } } } diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index 6acf026273602..29686c565a902 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -158,7 +158,7 @@ //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { //! /// Reward a validator. -//! #[weight = frame_support::weights::SimpleDispatchInfo::default()] +//! #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] //! pub fn reward_myself(origin) -> dispatch::DispatchResult { //! let reported = ensure_signed(origin)?; //! >::reward_by_ids(vec![(reported, 10)]); @@ -1781,7 +1781,7 @@ decl_module! { /// This can be called from any origin. /// /// - `stash`: The stash account to reap. Its balance must be zero. - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn reap_stash(_origin, stash: T::AccountId) { ensure!(T::Currency::total_balance(&stash).is_zero(), Error::::FundedTarget); Self::kill_stash(&stash)?; diff --git a/frame/sudo/src/lib.rs b/frame/sudo/src/lib.rs index 3f2eacdbf8139..7dc1edf718f74 100644 --- a/frame/sudo/src/lib.rs +++ b/frame/sudo/src/lib.rs @@ -58,7 +58,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = frame_support::weights::SimpleDispatchInfo::default()] +//! #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] //! pub fn privileged_function(origin) -> dispatch::DispatchResult { //! ensure_root(origin)?; //! @@ -150,7 +150,7 @@ decl_module! { /// - Limited storage reads. /// - One DB change. /// # - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn set_key(origin, new: ::Source) { // This is a public call, so we ensure that the origin is some signed account. let sender = ensure_signed(origin)?; diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index 6ed5d63e1bb16..78800422a5bb9 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -81,7 +81,7 @@ impl Parameter for T where T: Codec + EncodeLike + Clone + Eq + fmt::Debug {} /// /// // Private functions are dispatchable, but not available to other /// // FRAME pallets. -/// #[weight = SimpleDispatchInfo::default()] +/// #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] /// fn my_function(origin, var: u64) -> dispatch::DispatchResult { /// // Your implementation /// Ok(()) @@ -89,7 +89,7 @@ impl Parameter for T where T: Codec + EncodeLike + Clone + Eq + fmt::Debug {} /// /// // Public functions are both dispatchable and available to other /// // FRAME pallets. -/// #[weight = SimpleDispatchInfo::default()] +/// #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] /// pub fn my_public_function(origin) -> dispatch::DispatchResult { /// // Your implementation /// Ok(()) @@ -121,13 +121,13 @@ impl Parameter for T where T: Codec + EncodeLike + Clone + Eq + fmt::Debug {} /// # use frame_system::{self as system, Trait, ensure_signed}; /// decl_module! { /// pub struct Module for enum Call where origin: T::Origin { -/// #[weight = SimpleDispatchInfo::default()] +/// #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] /// fn my_long_function(origin) -> dispatch::DispatchResult { /// // Your implementation /// Ok(()) /// } /// -/// #[weight = SimpleDispatchInfo::default()] +/// #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] /// fn my_short_function(origin) { /// // Your implementation /// } @@ -186,7 +186,7 @@ impl Parameter for T where T: Codec + EncodeLike + Clone + Eq + fmt::Debug {} /// # use frame_system::{self as system, Trait, ensure_signed, ensure_root}; /// decl_module! { /// pub struct Module for enum Call where origin: T::Origin { -/// #[weight = SimpleDispatchInfo::default()] +/// #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] /// fn my_privileged_function(origin) -> dispatch::DispatchResult { /// ensure_root(origin)?; /// // Your implementation @@ -2112,22 +2112,22 @@ mod tests { decl_module! { pub struct Module for enum Call where origin: T::Origin, T::AccountId: From { /// Hi, this is a comment. - #[weight = SimpleDispatchInfo::default()] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn aux_0(_origin) -> DispatchResult { unreachable!() } - #[weight = SimpleDispatchInfo::default()] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn aux_1(_origin, #[compact] _data: u32,) -> DispatchResult { unreachable!() } - #[weight = SimpleDispatchInfo::default()] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn aux_2(_origin, _data: i32, _data2: String) -> DispatchResult { unreachable!() } #[weight = SimpleDispatchInfo::FixedNormal(3)] fn aux_3(_origin) -> DispatchResult { unreachable!() } - #[weight = SimpleDispatchInfo::default()] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn aux_4(_origin, _data: i32) -> DispatchResult { unreachable!() } - #[weight = SimpleDispatchInfo::default()] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn aux_5(_origin, _data: i32, #[compact] _data2: u32,) -> DispatchResult { unreachable!() } #[weight = SimpleDispatchInfo::FixedOperational(5)] diff --git a/frame/support/src/error.rs b/frame/support/src/error.rs index f619250726ded..05a1f446a2c8f 100644 --- a/frame/support/src/error.rs +++ b/frame/support/src/error.rs @@ -55,7 +55,7 @@ pub use frame_metadata::{ModuleErrorMetadata, ErrorMetadata, DecodeDifferent}; /// pub struct Module for enum Call where origin: T::Origin { /// type Error = MyError; /// -/// #[weight = SimpleDispatchInfo::default()] +/// #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] /// fn do_something(origin) -> frame_support::dispatch::DispatchResult { /// Err(MyError::::YouAreNotCoolEnough.into()) /// } diff --git a/frame/support/src/metadata.rs b/frame/support/src/metadata.rs index 3d99ddaa84ff4..5d2f851520681 100644 --- a/frame/support/src/metadata.rs +++ b/frame/support/src/metadata.rs @@ -352,7 +352,7 @@ mod tests { pub struct Module for enum Call where origin: T::Origin { type Error = Error; - #[weight = SimpleDispatchInfo::default()] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn aux_0(_origin) -> DispatchResult { unreachable!() } } } diff --git a/frame/support/src/weights.rs b/frame/support/src/weights.rs index c09ea984b2a8d..a85e215c01392 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -303,13 +303,6 @@ impl PaysFee for SimpleDispatchInfo { } } -impl Default for SimpleDispatchInfo { - fn default() -> Self { - // Default weight of all transactions. - SimpleDispatchInfo::FixedNormal(10_000_000) - } -} - impl SimpleDispatchInfo { /// An _additive zero_ variant of SimpleDispatchInfo. pub fn zero() -> Self { diff --git a/frame/support/test/tests/decl_error.rs b/frame/support/test/tests/decl_error.rs index 4191e79f2417c..adb67a5ca586f 100644 --- a/frame/support/test/tests/decl_error.rs +++ b/frame/support/test/tests/decl_error.rs @@ -32,7 +32,7 @@ mod module1 { pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: ::Origin { - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { Err(Error::::Something.into()) } @@ -59,7 +59,7 @@ mod module2 { pub struct Module for enum Call where origin: ::Origin { - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { Err(Error::::Something.into()) } diff --git a/frame/support/test/tests/instance.rs b/frame/support/test/tests/instance.rs index ea5d32fea3b22..e53a5ec03c584 100644 --- a/frame/support/test/tests/instance.rs +++ b/frame/support/test/tests/instance.rs @@ -55,7 +55,7 @@ mod module1 { fn deposit_event() = default; - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn one(origin) { system::ensure_root(origin)?; Self::deposit_event(RawEvent::AnotherVariant(3)); diff --git a/frame/support/test/tests/reserved_keyword/on_initialize.rs b/frame/support/test/tests/reserved_keyword/on_initialize.rs index 8eacc836c4868..54e28f228bd9d 100644 --- a/frame/support/test/tests/reserved_keyword/on_initialize.rs +++ b/frame/support/test/tests/reserved_keyword/on_initialize.rs @@ -19,7 +19,7 @@ macro_rules! reserved { frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin { - #[weight = frame_support::weights::SimpleDispatchInfo::default()] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] fn $reserved(_origin) -> dispatch::DispatchResult { unreachable!() } } } diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index 618e63b3e7ce6..59d3b100b3328 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -75,7 +75,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = SimpleDispatchInfo::default()] +//! #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] //! pub fn system_module_example(origin) -> dispatch::DispatchResult { //! let _sender = ensure_signed(origin)?; //! let _extrinsic_count = >::extrinsic_count(); diff --git a/frame/timestamp/src/lib.rs b/frame/timestamp/src/lib.rs index 13337833fbe4f..0d7fd59fe8999 100644 --- a/frame/timestamp/src/lib.rs +++ b/frame/timestamp/src/lib.rs @@ -69,7 +69,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = frame_support::weights::SimpleDispatchInfo::default()] +//! #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] //! pub fn get_time(origin) -> dispatch::DispatchResult { //! let _sender = ensure_signed(origin)?; //! let _now = >::get(); diff --git a/frame/treasury/src/lib.rs b/frame/treasury/src/lib.rs index 08afec217e840..8707182073eb1 100644 --- a/frame/treasury/src/lib.rs +++ b/frame/treasury/src/lib.rs @@ -558,7 +558,7 @@ decl_module! { Self::spend_funds(); } - SimpleDispatchInfo::default().weigh_data(()) + SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) } } } diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index 6408691b2e123..39c1cd7797576 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -194,7 +194,7 @@ decl_module! { /// - One storage read (codec `O(1)`) and up to one removal. /// - One event. /// # - #[weight = SimpleDispatchInfo::default()] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] 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 = SimpleDispatchInfo::default()] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] fn vest_other(origin, target: ::Source) -> DispatchResult { ensure_signed(origin)?; Self::update_lock(T::Lookup::lookup(target)?) From 21f91f1f3f109e377cf8838f1540ff4e9488506e Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Tue, 14 Apr 2020 19:26:50 +0200 Subject: [PATCH 37/52] little more clean up of default weight --- frame/example/src/lib.rs | 2 +- frame/support/src/dispatch.rs | 5 ----- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/frame/example/src/lib.rs b/frame/example/src/lib.rs index 1d720af708d30..94e9329a5080a 100644 --- a/frame/example/src/lib.rs +++ b/frame/example/src/lib.rs @@ -844,7 +844,7 @@ mod tests { #[test] fn weights_work() { - // must have a default weight. + // must have a defined weight. let default_call = >::accumulate_dummy(10); let info = default_call.get_dispatch_info(); // aka. `let info = as GetDispatchInfo>::get_dispatch_info(&default_call);` diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index 78800422a5bb9..4eba1c5e2f5e4 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -2291,11 +2291,6 @@ mod tests { Call::::operational().get_dispatch_info(), DispatchInfo { weight: 5, class: DispatchClass::Operational, pays_fee: true }, ); - // default weight. - assert_eq!( - Call::::aux_0().get_dispatch_info(), - DispatchInfo { weight: 10_000_000, class: DispatchClass::Normal, pays_fee: true }, - ); // custom basic assert_eq!( Call::::aux_3().get_dispatch_info(), From 3b5790970a990aa88c3b3b7b9b381fcbce7d5fa6 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Tue, 14 Apr 2020 20:03:58 +0200 Subject: [PATCH 38/52] Introduce MINIMUM_WEIGHT const --- bin/node-template/pallets/template/src/lib.rs | 5 ++-- frame/assets/src/lib.rs | 7 +++-- frame/authorship/src/lib.rs | 6 ++-- frame/babe/src/lib.rs | 4 +-- frame/benchmark/src/lib.rs | 27 +++++++++--------- frame/benchmarking/src/tests.rs | 9 +++--- frame/contracts/src/lib.rs | 11 ++++---- frame/democracy/src/lib.rs | 22 +++++++-------- frame/elections-phragmen/src/lib.rs | 8 +++--- frame/elections/src/lib.rs | 12 ++++---- frame/evm/src/lib.rs | 6 ++-- frame/example-offchain-worker/src/lib.rs | 6 ++-- frame/example/src/lib.rs | 5 ++-- frame/finality-tracker/src/lib.rs | 3 +- frame/generic-asset/src/lib.rs | 13 +++++---- frame/grandpa/src/lib.rs | 3 +- frame/identity/src/lib.rs | 4 +-- frame/im-online/src/lib.rs | 6 ++-- frame/indices/src/lib.rs | 12 ++++---- frame/offences/src/lib.rs | 6 ++-- frame/randomness-collective-flip/src/lib.rs | 8 +++--- frame/recovery/src/lib.rs | 6 ++-- frame/scored-pool/src/lib.rs | 17 +++++------ frame/session/src/lib.rs | 4 +-- frame/society/src/lib.rs | 8 +++--- frame/staking/src/lib.rs | 9 +++--- frame/sudo/src/lib.rs | 7 +++-- frame/support/src/dispatch.rs | 28 +++++++++---------- frame/support/src/error.rs | 4 +-- frame/support/src/metadata.rs | 4 +-- frame/support/src/weights.rs | 3 ++ frame/support/test/tests/decl_error.rs | 4 +-- frame/support/test/tests/instance.rs | 3 +- .../tests/reserved_keyword/on_initialize.rs | 2 +- frame/system/src/lib.rs | 14 +++++----- frame/timestamp/src/lib.rs | 6 ++-- frame/treasury/src/lib.rs | 4 +-- frame/vesting/src/lib.rs | 6 ++-- 38 files changed, 165 insertions(+), 147 deletions(-) diff --git a/bin/node-template/pallets/template/src/lib.rs b/bin/node-template/pallets/template/src/lib.rs index 2ac78cf141138..adddbac21b554 100644 --- a/bin/node-template/pallets/template/src/lib.rs +++ b/bin/node-template/pallets/template/src/lib.rs @@ -10,6 +10,7 @@ /// 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::{SimpleDispatchInfo, MINIMUM_WEIGHT}; use frame_system::{self as system, ensure_signed}; #[cfg(test)] @@ -75,7 +76,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 = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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)?; @@ -91,7 +92,7 @@ decl_module! { /// Another dummy entry point. /// takes no parameters, attempts to increment storage value, and possibly throws an error - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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)?; diff --git a/frame/assets/src/lib.rs b/frame/assets/src/lib.rs index 94c1e7cf8080c..15726c9bcb1e9 100644 --- a/frame/assets/src/lib.rs +++ b/frame/assets/src/lib.rs @@ -133,6 +133,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use frame_support::{Parameter, decl_module, decl_event, decl_storage, decl_error, ensure}; +use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; use sp_runtime::traits::{Member, AtLeast32Bit, Zero, StaticLookup}; use frame_system::{self as system, ensure_signed}; use sp_runtime::traits::One; @@ -157,7 +158,7 @@ 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 = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn issue(origin, #[compact] total: T::Balance) { let origin = ensure_signed(origin)?; @@ -171,7 +172,7 @@ decl_module! { } /// Move some assets from one holder to another. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn transfer(origin, #[compact] id: T::AssetId, target: ::Source, @@ -190,7 +191,7 @@ decl_module! { } /// Destroy any assets of `id` owned by `origin`. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn destroy(origin, #[compact] id: T::AssetId) { let origin = ensure_signed(origin)?; let balance = >::take((id, &origin)); diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index ec4675eed8045..7d2d33da1cdf6 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -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, SimpleDispatchInfo, WeighData}; +use frame_support::weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo, WeighData}; 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()); - SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) + SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) } fn on_finalize() { @@ -207,7 +207,7 @@ decl_module! { } /// Provide a set of uncles. - #[weight = SimpleDispatchInfo::FixedMandatory(10_000_000)] + #[weight = SimpleDispatchInfo::FixedMandatory(MINIMUM_WEIGHT)] fn set_uncles(origin, new_uncles: Vec) -> dispatch::DispatchResult { ensure_none(origin)?; ensure!(new_uncles.len() <= MAX_UNCLES, Error::::TooManyUncles); diff --git a/frame/babe/src/lib.rs b/frame/babe/src/lib.rs index a836fe7851484..7b16e3006dd18 100644 --- a/frame/babe/src/lib.rs +++ b/frame/babe/src/lib.rs @@ -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, SimpleDispatchInfo, WeighData}, + weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo, WeighData}, }; 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); - SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) + SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) } /// Block finalization diff --git a/frame/benchmark/src/lib.rs b/frame/benchmark/src/lib.rs index 67d374ed9a913..24b0e433101be 100644 --- a/frame/benchmark/src/lib.rs +++ b/frame/benchmark/src/lib.rs @@ -21,6 +21,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use frame_support::{decl_module, decl_storage, decl_event, decl_error}; +use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; use frame_support::traits::Currency; use frame_system::{self as system, ensure_signed}; use codec::{Encode, Decode}; @@ -70,7 +71,7 @@ decl_module! { fn deposit_event() = default; /// Do nothing. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn do_nothing(_origin, input: u32) { if input > 0 { return Ok(()); @@ -82,7 +83,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 = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn read_value(_origin, repeat: u32) { for _ in 0..repeat { MyValue::get(); @@ -90,7 +91,7 @@ decl_module! { } /// Put a value into a storage value. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn put_value(_origin, repeat: u32) { for r in 0..repeat { MyValue::put(r); @@ -102,7 +103,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 = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn exists_value(_origin, repeat: u32) { for _ in 0..repeat { MyValue::exists(); @@ -110,7 +111,7 @@ decl_module! { } /// Remove a value from storage `repeat` number of times. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn remove_value(_origin, repeat: u32) { for r in 0..repeat { MyMap::remove(r); @@ -118,7 +119,7 @@ decl_module! { } /// Read a value from storage map `repeat` number of times. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn read_map(_origin, repeat: u32) { for r in 0..repeat { MyMap::get(r); @@ -126,7 +127,7 @@ decl_module! { } /// Insert a value into a map. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn insert_map(_origin, repeat: u32) { for r in 0..repeat { MyMap::insert(r, r); @@ -134,7 +135,7 @@ decl_module! { } /// Check is a map contains a value `repeat` number of times. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn contains_key_map(_origin, repeat: u32) { for r in 0..repeat { MyMap::contains_key(r); @@ -142,7 +143,7 @@ decl_module! { } /// Read a value from storage `repeat` number of times. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn remove_prefix(_origin, repeat: u32) { for r in 0..repeat { MyDoubleMap::remove_prefix(r); @@ -150,21 +151,21 @@ decl_module! { } /// Add user to the list. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn add_member_list(origin) { let who = ensure_signed(origin)?; MyMemberList::::mutate(|x| x.push(who)); } /// Append user to the list. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn append_member_list(origin) { let who = ensure_signed(origin)?; MyMemberList::::append(&[who])?; } /// Encode a vector of accounts to bytes. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn encode_accounts(_origin, accounts: Vec) { let bytes = accounts.encode(); @@ -176,7 +177,7 @@ decl_module! { } /// Decode bytes into a vector of accounts. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn decode_accounts(_origin, bytes: Vec) { let accounts: Vec = Decode::decode(&mut bytes.as_slice()).map_err(|_| "Could not decode")?; diff --git a/frame/benchmarking/src/tests.rs b/frame/benchmarking/src/tests.rs index 0a0620a16ea69..4b26ec732d296 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -23,8 +23,9 @@ use codec::Decode; use sp_std::prelude::*; use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::{H256, Header}}; use frame_support::{ - dispatch::DispatchResult, decl_module, decl_storage, impl_outer_origin, - assert_ok, assert_err, ensure + dispatch::DispatchResult, + weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}, + decl_module, decl_storage, impl_outer_origin, assert_ok, assert_err, ensure }; use frame_system::{RawOrigin, ensure_signed, ensure_none}; @@ -36,14 +37,14 @@ decl_storage! { decl_module! { pub struct Module for enum Call where origin: T::Origin { - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn set_value(origin, n: u32) -> DispatchResult { let _sender = ensure_signed(origin)?; Value::put(n); Ok(()) } - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn dummy(origin, _n: u32) -> DispatchResult { let _sender = ensure_none(origin)?; Ok(()) diff --git a/frame/contracts/src/lib.rs b/frame/contracts/src/lib.rs index 49ae2dc4272f2..91f06d5607c8b 100644 --- a/frame/contracts/src/lib.rs +++ b/frame/contracts/src/lib.rs @@ -123,6 +123,7 @@ use sp_runtime::{ RuntimeDebug, }; use frame_support::dispatch::{DispatchResult, Dispatchable}; +use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; use frame_support::{ Parameter, decl_module, decl_event, decl_storage, decl_error, storage::child, parameter_types, IsSubType, @@ -550,7 +551,7 @@ decl_module! { /// Updates the schedule for metering contracts. /// /// The schedule must have a greater version than the stored schedule. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn update_schedule(origin, schedule: Schedule) -> DispatchResult { ensure_root(origin)?; if >::current_schedule().version >= schedule.version { @@ -565,7 +566,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 = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn put_code( origin, #[compact] gas_limit: Gas, @@ -593,7 +594,7 @@ decl_module! { /// * If the account is a regular account, any value will be transferred. /// * If no account exists and the call value is not less than `existential_deposit`, /// a regular account will be created and any value will be transferred. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn call( origin, dest: ::Source, @@ -619,7 +620,7 @@ decl_module! { /// after the execution is saved as the `code` of the account. That code will be invoked /// upon any call received by this account. /// - The contract is initialized. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn instantiate( origin, #[compact] endowment: BalanceOf, @@ -642,7 +643,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 = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn claim_surcharge(origin, dest: T::AccountId, aux_sender: Option) { let origin = origin.into(); let (signed, rewarded) = match (origin, aux_sender) { diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index 4f50aa65df673..fd7cb72dbd627 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -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::{SimpleDispatchInfo, Weight, WeighData}, + weights::{SimpleDispatchInfo, Weight, MINIMUM_WEIGHT, WeighData}, 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(); - SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) + SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) } /// Propose a sensitive action to be taken. @@ -820,7 +820,7 @@ decl_module! { /// # /// - `O(1)`. /// # - #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] + #[weight = SimpleDispatchInfo::FixedOperational(MINIMUM_WEIGHT)] 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 = SimpleDispatchInfo::FixedOperational(10_000_000)] + #[weight = SimpleDispatchInfo::FixedOperational(MINIMUM_WEIGHT)] 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); } - SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) + SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) } /// 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 = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn clear_public_proposals(origin) { ensure_root(origin)?; @@ -1066,7 +1066,7 @@ decl_module! { /// # /// - One DB clear. /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn reap_preimage(origin, proposal_hash: T::Hash) { let who = ensure_signed(origin)?; let (provider, deposit, since, expiry) = >::get(&proposal_hash) @@ -1096,7 +1096,7 @@ decl_module! { /// # /// - `O(1)`. /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn unlock(origin, target: T::AccountId) { ensure_signed(origin)?; Self::update_lock(&target); @@ -1154,7 +1154,7 @@ decl_module! { /// # /// - `O(R + log R)` where R is the number of referenda that `target` has voted on. /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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! { /// # /// - `O(R + log R)` where R is the number of referenda that `target` has voted on. /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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! { /// # /// - `O(R + log R)` where R is the number of referenda that `target` has voted on. /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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::::NotProxy)?; diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index bab00e4c124f9..040c3e716c4ab 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -88,7 +88,7 @@ use sp_runtime::{ }; use frame_support::{ decl_storage, decl_event, ensure, decl_module, decl_error, - weights::{SimpleDispatchInfo, Weight, WeighData}, storage::{StorageMap, IterableStorageMap}, + weights::{SimpleDispatchInfo, Weight, MINIMUM_WEIGHT, WeighData}, storage::{StorageMap, IterableStorageMap}, traits::{ Currency, Get, LockableCurrency, LockIdentifier, ReservableCurrency, WithdrawReasons, ChangeMembers, OnUnbalanced, WithdrawReason, Contains, BalanceStatus, InitializeMembers, @@ -267,7 +267,7 @@ decl_module! { fn on_runtime_upgrade() -> Weight { migration::migrate::(); - SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) + SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) } const CandidacyBond: BalanceOf = T::CandidacyBond::get(); @@ -336,7 +336,7 @@ decl_module! { /// Reads: O(1) /// Writes: O(1) /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn remove_voter(origin) { let who = ensure_signed(origin)?; @@ -510,7 +510,7 @@ decl_module! { print(e); } - SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) + SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) } } } diff --git a/frame/elections/src/lib.rs b/frame/elections/src/lib.rs index 29055c3f37419..2ab76bd769bae 100644 --- a/frame/elections/src/lib.rs +++ b/frame/elections/src/lib.rs @@ -30,7 +30,7 @@ use sp_runtime::{ }; use frame_support::{ decl_storage, decl_event, ensure, decl_module, decl_error, - weights::{Weight, SimpleDispatchInfo, WeighData}, + weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo, WeighData}, traits::{ Currency, ExistenceRequirement, Get, LockableCurrency, LockIdentifier, BalanceStatus, OnUnbalanced, ReservableCurrency, WithdrawReason, WithdrawReasons, ChangeMembers @@ -659,7 +659,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 = SimpleDispatchInfo::FixedOperational(10_000_000)] + #[weight = SimpleDispatchInfo::FixedOperational(MINIMUM_WEIGHT)] fn set_desired_seats(origin, #[compact] count: u32) { ensure_root(origin)?; DesiredSeats::put(count); @@ -669,7 +669,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 = SimpleDispatchInfo::FixedOperational(10_000_000)] + #[weight = SimpleDispatchInfo::FixedOperational(MINIMUM_WEIGHT)] fn remove_member(origin, who: ::Source) { ensure_root(origin)?; let who = T::Lookup::lookup(who)?; @@ -684,7 +684,7 @@ decl_module! { /// Set the presentation duration. If there is currently a vote being presented for, will /// invoke `finalize_vote`. - #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] + #[weight = SimpleDispatchInfo::FixedOperational(MINIMUM_WEIGHT)] fn set_presentation_duration(origin, #[compact] count: T::BlockNumber) { ensure_root(origin)?; >::put(count); @@ -692,7 +692,7 @@ decl_module! { /// Set the presentation duration. If there is current a vote being presented for, will /// invoke `finalize_vote`. - #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] + #[weight = SimpleDispatchInfo::FixedOperational(MINIMUM_WEIGHT)] fn set_term_duration(origin, #[compact] count: T::BlockNumber) { ensure_root(origin)?; >::put(count); @@ -703,7 +703,7 @@ decl_module! { print("Guru meditation"); print(e); } - SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) + SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) } } } diff --git a/frame/evm/src/lib.rs b/frame/evm/src/lib.rs index e198c8c7aa1e0..f67ab767ed320 100644 --- a/frame/evm/src/lib.rs +++ b/frame/evm/src/lib.rs @@ -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, DispatchClass, FunctionOf}; +use frame_support::weights::{Weight, MINIMUM_WEIGHT, DispatchClass, FunctionOf}; use frame_support::traits::{Currency, WithdrawReason, ExistenceRequirement}; use frame_system::{self as system, ensure_signed}; use sp_runtime::ModuleId; @@ -191,7 +191,7 @@ decl_module! { fn deposit_event() = default; /// Deposit balance from currency/balances module into EVM. - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn deposit_balance(origin, value: BalanceOf) { let sender = ensure_signed(origin)?; @@ -212,7 +212,7 @@ decl_module! { } /// Withdraw balance from EVM into currency/balances module. - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn withdraw_balance(origin, value: BalanceOf) { let sender = ensure_signed(origin)?; let address = T::ConvertAccountId::convert_account_id(&sender); diff --git a/frame/example-offchain-worker/src/lib.rs b/frame/example-offchain-worker/src/lib.rs index 741cc7dd0db8b..29a4859c78e21 100644 --- a/frame/example-offchain-worker/src/lib.rs +++ b/frame/example-offchain-worker/src/lib.rs @@ -44,7 +44,7 @@ use frame_support::{ debug, dispatch::DispatchResult, decl_module, decl_storage, decl_event, traits::Get, - weights::SimpleDispatchInfo, + weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}, }; use frame_system::{self as system, ensure_signed, ensure_none, offchain}; use sp_core::crypto::KeyTypeId; @@ -157,7 +157,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 = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn submit_price(origin, price: u32) -> DispatchResult { // Retrieve sender of the transaction. let who = ensure_signed(origin)?; @@ -182,7 +182,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 = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn submit_price_unsigned(origin, _block_number: T::BlockNumber, price: u32) -> DispatchResult { diff --git a/frame/example/src/lib.rs b/frame/example/src/lib.rs index 94e9329a5080a..991120cbe5254 100644 --- a/frame/example/src/lib.rs +++ b/frame/example/src/lib.rs @@ -258,6 +258,7 @@ use frame_support::{ dispatch::DispatchResult, decl_module, decl_storage, decl_event, weights::{ SimpleDispatchInfo, DispatchClass, ClassifyDispatch, WeighData, Weight, PaysFee, + MINIMUM_WEIGHT, }, }; use sp_std::prelude::*; @@ -468,7 +469,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 = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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)?; @@ -523,7 +524,7 @@ decl_module! { // Anything that needs to be done at the start of the block. // We don't do anything here. - SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) + SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) } // The signature could also look like: `fn on_finalize()` diff --git a/frame/finality-tracker/src/lib.rs b/frame/finality-tracker/src/lib.rs index f80ea1707acdd..54506784a9f1b 100644 --- a/frame/finality-tracker/src/lib.rs +++ b/frame/finality-tracker/src/lib.rs @@ -23,6 +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::{SimpleDispatchInfo, MINIMUM_WEIGHT}; use frame_system::{ensure_none, Trait as SystemTrait}; use sp_finality_tracker::{INHERENT_IDENTIFIER, FinalizedInherentData}; @@ -76,7 +77,7 @@ decl_module! { /// Hint that the author of this block thinks the best finalized /// block is the given number. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedMandatory(10_000_000)] + #[weight = SimpleDispatchInfo::FixedMandatory(MINIMUM_WEIGHT)] fn final_hint(origin, #[compact] hint: T::BlockNumber) { ensure_none(origin)?; ensure!(!::Update::exists(), Error::::AlreadyUpdated); diff --git a/frame/generic-asset/src/lib.rs b/frame/generic-asset/src/lib.rs index fc650039e5c1a..720ccd85cccc6 100644 --- a/frame/generic-asset/src/lib.rs +++ b/frame/generic-asset/src/lib.rs @@ -164,6 +164,7 @@ use sp_std::prelude::*; use sp_std::{cmp, result, fmt::Debug}; use frame_support::{ decl_event, decl_module, decl_storage, ensure, decl_error, + weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}, traits::{ Currency, ExistenceRequirement, Imbalance, LockIdentifier, LockableCurrency, ReservableCurrency, SignedImbalance, WithdrawReason, WithdrawReasons, TryDrop, BalanceStatus, @@ -360,14 +361,14 @@ decl_module! { fn deposit_event() = default; /// Create a new kind of asset. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn create(origin, options: AssetOptions) -> DispatchResult { let origin = ensure_signed(origin)?; Self::create_asset(None, Some(origin), options) } /// Transfer some liquid free balance to another account. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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::::ZeroAmount); @@ -377,7 +378,7 @@ decl_module! { /// Updates permission for a given `asset_id` and an account. /// /// The `origin` must have `update` permission. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn update_permission( origin, #[compact] asset_id: T::AssetId, @@ -400,7 +401,7 @@ decl_module! { /// Mints an asset, increases its total issuance. /// The origin must have `mint` permissions. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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)?; @@ -410,7 +411,7 @@ decl_module! { /// Burns an asset, decreases its total issuance. /// The `origin` must have `burn` permissions. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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)?; @@ -420,7 +421,7 @@ decl_module! { /// Can be used to create reserved tokens. /// Requires Root call. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn create_reserved( origin, asset_id: T::AssetId, diff --git a/frame/grandpa/src/lib.rs b/frame/grandpa/src/lib.rs index 4cff4408b865e..10cc8162db3a7 100644 --- a/frame/grandpa/src/lib.rs +++ b/frame/grandpa/src/lib.rs @@ -33,6 +33,7 @@ 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::{SimpleDispatchInfo, MINIMUM_WEIGHT}; use sp_runtime::{ DispatchResult, generic::{DigestItem, OpaqueDigestItemId}, traits::Zero, Perbill, }; @@ -184,7 +185,7 @@ decl_module! { fn deposit_event() = default; /// Report some misbehavior. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn report_misbehavior(origin, _report: Vec) { ensure_signed(origin)?; // FIXME: https://github.com/paritytech/substrate/issues/1112 diff --git a/frame/identity/src/lib.rs b/frame/identity/src/lib.rs index 1eb3cc410aaf0..ddb9bdcce2163 100644 --- a/frame/identity/src/lib.rs +++ b/frame/identity/src/lib.rs @@ -74,7 +74,7 @@ use sp_runtime::traits::{StaticLookup, Zero, AppendZerosInput}; use frame_support::{ decl_module, decl_event, decl_storage, ensure, decl_error, traits::{Currency, ReservableCurrency, OnUnbalanced, Get, BalanceStatus, EnsureOrigin}, - weights::SimpleDispatchInfo, + weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}, }; use frame_system::{self as system, ensure_signed, ensure_root}; @@ -474,7 +474,7 @@ decl_module! { /// - One storage mutation (codec `O(R)`). /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn add_registrar(origin, account: T::AccountId) { T::RegistrarOrigin::try_origin(origin) .map(|_| ()) diff --git a/frame/im-online/src/lib.rs b/frame/im-online/src/lib.rs index cf9635c19b201..1137fc2699fe3 100644 --- a/frame/im-online/src/lib.rs +++ b/frame/im-online/src/lib.rs @@ -43,6 +43,7 @@ //! //! ``` //! use frame_support::{decl_module, dispatch}; +//! use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; //! use frame_system::{self as system, ensure_signed}; //! use pallet_im_online::{self as im_online}; //! @@ -50,7 +51,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] +//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] //! pub fn is_online(origin, authority_index: u32) -> dispatch::DispatchResult { //! let _sender = ensure_signed(origin)?; //! let _is_online = >::is_online(authority_index); @@ -94,6 +95,7 @@ use sp_staking::{ use frame_support::{ decl_module, decl_event, decl_storage, Parameter, debug, decl_error, traits::Get, + weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}, }; use frame_system::{self as system, ensure_none}; use frame_system::offchain::SubmitUnsignedTransaction; @@ -316,7 +318,7 @@ decl_module! { fn deposit_event() = default; - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn heartbeat( origin, heartbeat: Heartbeat, diff --git a/frame/indices/src/lib.rs b/frame/indices/src/lib.rs index 2b9319c8535de..d75bfb04b59fb 100644 --- a/frame/indices/src/lib.rs +++ b/frame/indices/src/lib.rs @@ -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, SimpleDispatchInfo, WeighData}; +use frame_support::weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo, WeighData}; 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(); - SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) + SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) } /// Assign an previously unassigned index. @@ -121,7 +121,7 @@ decl_module! { /// - One reserve operation. /// - One event. /// # - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn claim(origin, index: T::AccountIndex) { let who = ensure_signed(origin)?; @@ -149,7 +149,7 @@ decl_module! { /// - One transfer operation. /// - One event. /// # - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn transfer(origin, new: T::AccountId, index: T::AccountIndex) { let who = ensure_signed(origin)?; ensure!(who != new, Error::::NotTransfer); @@ -180,7 +180,7 @@ decl_module! { /// - One reserve operation. /// - One event. /// # - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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 = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn force_transfer(origin, new: T::AccountId, index: T::AccountIndex) { ensure_root(origin)?; diff --git a/frame/offences/src/lib.rs b/frame/offences/src/lib.rs index e9ee5cbc6200a..0d08565c17f25 100644 --- a/frame/offences/src/lib.rs +++ b/frame/offences/src/lib.rs @@ -27,7 +27,7 @@ mod tests; use sp_std::vec::Vec; use frame_support::{ decl_module, decl_event, decl_storage, Parameter, debug, - weights::{Weight, SimpleDispatchInfo, WeighData}, + weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo, WeighData}, }; use sp_runtime::{traits::Hash, Perbill}; use sp_staking::{ @@ -104,7 +104,7 @@ decl_module! { ConcurrentReportsIndex::::remove_all(); ReportsByKindIndex::remove_all(); - SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) + SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) } fn on_initialize(now: T::BlockNumber) -> Weight { @@ -125,7 +125,7 @@ decl_module! { }) } - SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) + SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) } } } diff --git a/frame/randomness-collective-flip/src/lib.rs b/frame/randomness-collective-flip/src/lib.rs index c9cee27275f1e..f1e51eb1da3b7 100644 --- a/frame/randomness-collective-flip/src/lib.rs +++ b/frame/randomness-collective-flip/src/lib.rs @@ -35,13 +35,13 @@ //! ### Example - Get random seed for the current block //! //! ``` -//! use frame_support::{decl_module, dispatch, traits::Randomness, weights::SimpleDispatchInfo}; +//! use frame_support::{decl_module, dispatch, traits::Randomness, weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}}; //! //! pub trait Trait: frame_system::Trait {} //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] +//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] //! pub fn random_module_example(origin) -> dispatch::DispatchResult { //! let _random_seed = >::random_seed(); //! Ok(()) @@ -57,7 +57,7 @@ use sp_std::{prelude::*, convert::TryInto}; use sp_runtime::traits::Hash; use frame_support::{ decl_module, decl_storage, traits::Randomness, - weights::{Weight, SimpleDispatchInfo, WeighData} + weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo, WeighData} }; use safe_mix::TripletMix; use codec::Encode; @@ -83,7 +83,7 @@ decl_module! { values[index] = parent_hash; }); - SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) + SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) } } } diff --git a/frame/recovery/src/lib.rs b/frame/recovery/src/lib.rs index 9862aef69fe6d..e50a811290037 100644 --- a/frame/recovery/src/lib.rs +++ b/frame/recovery/src/lib.rs @@ -159,7 +159,7 @@ use codec::{Encode, Decode}; use frame_support::{ decl_module, decl_event, decl_storage, decl_error, ensure, - Parameter, RuntimeDebug, weights::{GetDispatchInfo, SimpleDispatchInfo, FunctionOf}, + Parameter, RuntimeDebug, weights::{MINIMUM_WEIGHT, GetDispatchInfo, SimpleDispatchInfo, FunctionOf}, traits::{Currency, ReservableCurrency, Get, BalanceStatus}, dispatch::PostDispatchInfo, }; @@ -365,7 +365,7 @@ decl_module! { /// - One storage write O(1) /// - One event /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn set_recovered(origin, lost: T::AccountId, rescuer: T::AccountId) { ensure_root(origin)?; // Create the recovery storage item. @@ -647,7 +647,7 @@ decl_module! { /// # /// - One storage mutation to check account is recovered by `who`. O(1) /// # - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn cancel_recovered(origin, account: T::AccountId) { let who = ensure_signed(origin)?; // Check `who` is allowed to make a call on behalf of `account` diff --git a/frame/scored-pool/src/lib.rs b/frame/scored-pool/src/lib.rs index 020408c46a623..6e4fd2b06176e 100644 --- a/frame/scored-pool/src/lib.rs +++ b/frame/scored-pool/src/lib.rs @@ -54,6 +54,7 @@ //! //! ``` //! use frame_support::{decl_module, dispatch}; +//! use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; //! use frame_system::{self as system, ensure_signed}; //! use pallet_scored_pool::{self as scored_pool}; //! @@ -61,7 +62,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] +//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] //! pub fn candidate(origin) -> dispatch::DispatchResult { //! let who = ensure_signed(origin)?; //! @@ -97,7 +98,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, SimpleDispatchInfo, WeighData}, + weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo, WeighData}, }; use frame_system::{self as system, ensure_root, ensure_signed}; use sp_runtime::{ @@ -252,7 +253,7 @@ decl_module! { let pool = >::get(); >::refresh_members(pool, ChangeReceiver::MembershipChanged); } - SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) + SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) } /// Add `origin` to the pool of candidates. @@ -266,7 +267,7 @@ decl_module! { /// /// The `index` parameter of this function must be set to /// the index of the transactor in the `Pool`. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn submit_candidacy(origin) { let who = ensure_signed(origin)?; ensure!(!>::contains_key(&who), Error::::AlreadyInPool); @@ -296,7 +297,7 @@ decl_module! { /// /// The `index` parameter of this function must be set to /// the index of the transactor in the `Pool`. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn withdraw_candidacy( origin, index: u32 @@ -316,7 +317,7 @@ decl_module! { /// /// The `index` parameter of this function must be set to /// the index of `dest` in the `Pool`. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn kick( origin, dest: ::Source, @@ -341,7 +342,7 @@ decl_module! { /// /// The `index` parameter of this function must be set to /// the index of the `dest` in the `Pool`. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn score( origin, dest: ::Source, @@ -382,7 +383,7 @@ decl_module! { /// (this happens each `Period`). /// /// May only be called from root. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn change_member_count(origin, count: u32) { ensure_root(origin)?; >::put(&count); diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index 5156fa38f2ae8..10af4430c8cd8 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -110,7 +110,7 @@ use frame_support::{ Get, FindAuthor, ValidatorRegistration, EstimateNextSessionRotation, EstimateNextNewSession, }, dispatch::{self, DispatchResult, DispatchError}, - weights::{Weight, SimpleDispatchInfo, WeighData}, + weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo, WeighData}, }; use frame_system::{self as system, ensure_signed}; @@ -532,7 +532,7 @@ decl_module! { Self::rotate_session(); } - SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) + SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) } } } diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index 17fe8765c1467..41ecc8d36aabf 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -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::{SimpleDispatchInfo, Weight, WeighData}; +use frame_support::weights::{SimpleDispatchInfo, Weight, MINIMUM_WEIGHT, WeighData}; use frame_support::traits::{ Currency, ReservableCurrency, Randomness, Get, ChangeMembers, BalanceStatus, ExistenceRequirement::AllowDeath, EnsureOrigin @@ -820,7 +820,7 @@ decl_module! { /// /// Total Complexity: O(1) /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn found(origin, founder: T::AccountId, max_members: u32, rules: Vec) { T::FounderSetOrigin::ensure_origin(origin)?; ensure!(!>::exists(), Error::::AlreadyFounded); @@ -1020,7 +1020,7 @@ decl_module! { /// /// Total Complexity: O(1) /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn set_max_members(origin, max: u32) { ensure_root(origin)?; ensure!(max > 1, Error::::MaxMembers); @@ -1046,7 +1046,7 @@ decl_module! { Self::rotate_challenge(&mut members); } - SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) + SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) } } } diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index 29686c565a902..597bace187b8c 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -150,6 +150,7 @@ //! //! ``` //! use frame_support::{decl_module, dispatch}; +//! use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; //! use frame_system::{self as system, ensure_signed}; //! use pallet_staking::{self as staking}; //! @@ -158,7 +159,7 @@ //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { //! /// Reward a validator. -//! #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] +//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] //! pub fn reward_myself(origin) -> dispatch::DispatchResult { //! let reported = ensure_signed(origin)?; //! >::reward_by_ids(vec![(reported, 10)]); @@ -274,7 +275,7 @@ use sp_std::{ use codec::{HasCompact, Encode, Decode}; use frame_support::{ decl_module, decl_event, decl_storage, ensure, decl_error, debug, - weights::{SimpleDispatchInfo, Weight}, + weights::{SimpleDispatchInfo, MINIMUM_WEIGHT, Weight}, storage::IterableStorageMap, dispatch::{IsSubType, DispatchResult}, traits::{ @@ -1601,7 +1602,7 @@ decl_module! { } /// Force a current staker to become completely unstaked, immediately. - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn force_unstake(origin, stash: T::AccountId) { ensure_root(origin)?; @@ -1781,7 +1782,7 @@ decl_module! { /// This can be called from any origin. /// /// - `stash`: The stash account to reap. Its balance must be zero. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn reap_stash(_origin, stash: T::AccountId) { ensure!(T::Currency::total_balance(&stash).is_zero(), Error::::FundedTarget); Self::kill_stash(&stash)?; diff --git a/frame/sudo/src/lib.rs b/frame/sudo/src/lib.rs index 7dc1edf718f74..441a22d6efa8e 100644 --- a/frame/sudo/src/lib.rs +++ b/frame/sudo/src/lib.rs @@ -52,13 +52,14 @@ //! //! ``` //! use frame_support::{decl_module, dispatch}; +//! use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; //! use frame_system::{self as system, ensure_root}; //! //! pub trait Trait: frame_system::Trait {} //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] +//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] //! pub fn privileged_function(origin) -> dispatch::DispatchResult { //! ensure_root(origin)?; //! @@ -92,7 +93,7 @@ use sp_runtime::traits::{StaticLookup, Dispatchable}; use frame_support::{ Parameter, decl_module, decl_event, decl_storage, decl_error, ensure, }; -use frame_support::weights::{GetDispatchInfo, FunctionOf}; +use frame_support::weights::{MINIMUM_WEIGHT, GetDispatchInfo, FunctionOf}; use frame_system::{self as system, ensure_signed}; pub trait Trait: frame_system::Trait { @@ -150,7 +151,7 @@ decl_module! { /// - Limited storage reads. /// - One DB change. /// # - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn set_key(origin, new: ::Source) { // This is a public call, so we ensure that the origin is some signed account. let sender = ensure_signed(origin)?; diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index 4eba1c5e2f5e4..8512ccb0a8e22 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -74,14 +74,14 @@ impl 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::SimpleDispatchInfo; +/// # use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; /// # use frame_system::{self as system, Trait, ensure_signed}; /// decl_module! { /// pub struct Module for enum Call where origin: T::Origin { /// /// // Private functions are dispatchable, but not available to other /// // FRAME pallets. -/// #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] +/// #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] /// fn my_function(origin, var: u64) -> dispatch::DispatchResult { /// // Your implementation /// Ok(()) @@ -89,7 +89,7 @@ impl Parameter for T where T: Codec + EncodeLike + Clone + Eq + fmt::Debug {} /// /// // Public functions are both dispatchable and available to other /// // FRAME pallets. -/// #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] +/// #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] /// pub fn my_public_function(origin) -> dispatch::DispatchResult { /// // Your implementation /// Ok(()) @@ -117,17 +117,17 @@ impl 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::SimpleDispatchInfo; +/// # use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; /// # use frame_system::{self as system, Trait, ensure_signed}; /// decl_module! { /// pub struct Module for enum Call where origin: T::Origin { -/// #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] +/// #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] /// fn my_long_function(origin) -> dispatch::DispatchResult { /// // Your implementation /// Ok(()) /// } /// -/// #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] +/// #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] /// fn my_short_function(origin) { /// // Your implementation /// } @@ -182,11 +182,11 @@ impl 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::SimpleDispatchInfo; +/// # use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; /// # use frame_system::{self as system, Trait, ensure_signed, ensure_root}; /// decl_module! { /// pub struct Module for enum Call where origin: T::Origin { -/// #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] +/// #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] /// fn my_privileged_function(origin) -> dispatch::DispatchResult { /// ensure_root(origin)?; /// // Your implementation @@ -2086,7 +2086,7 @@ macro_rules! __check_reserved_fn_name { #[allow(dead_code)] mod tests { use super::*; - use crate::weights::{DispatchInfo, DispatchClass}; + use crate::weights::{MINIMUM_WEIGHT, DispatchInfo, DispatchClass}; use crate::traits::{ CallMetadata, GetCallMetadata, GetCallName, OnInitialize, OnFinalize, OnRuntimeUpgrade }; @@ -2112,22 +2112,22 @@ mod tests { decl_module! { pub struct Module for enum Call where origin: T::Origin, T::AccountId: From { /// Hi, this is a comment. - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn aux_0(_origin) -> DispatchResult { unreachable!() } - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn aux_1(_origin, #[compact] _data: u32,) -> DispatchResult { unreachable!() } - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn aux_2(_origin, _data: i32, _data2: String) -> DispatchResult { unreachable!() } #[weight = SimpleDispatchInfo::FixedNormal(3)] fn aux_3(_origin) -> DispatchResult { unreachable!() } - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn aux_4(_origin, _data: i32) -> DispatchResult { unreachable!() } - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn aux_5(_origin, _data: i32, #[compact] _data2: u32,) -> DispatchResult { unreachable!() } #[weight = SimpleDispatchInfo::FixedOperational(5)] diff --git a/frame/support/src/error.rs b/frame/support/src/error.rs index 05a1f446a2c8f..a06f46889224d 100644 --- a/frame/support/src/error.rs +++ b/frame/support/src/error.rs @@ -35,7 +35,7 @@ pub use frame_metadata::{ModuleErrorMetadata, ErrorMetadata, DecodeDifferent}; /// /// ``` /// # use frame_support::{decl_error, decl_module}; -/// # use frame_support::weights::SimpleDispatchInfo; +/// # use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; /// decl_error! { /// /// Errors that can occur in my module. /// pub enum MyError for Module { @@ -55,7 +55,7 @@ pub use frame_metadata::{ModuleErrorMetadata, ErrorMetadata, DecodeDifferent}; /// pub struct Module for enum Call where origin: T::Origin { /// type Error = MyError; /// -/// #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] +/// #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] /// fn do_something(origin) -> frame_support::dispatch::DispatchResult { /// Err(MyError::::YouAreNotCoolEnough.into()) /// } diff --git a/frame/support/src/metadata.rs b/frame/support/src/metadata.rs index 5d2f851520681..6a3e41b8096c1 100644 --- a/frame/support/src/metadata.rs +++ b/frame/support/src/metadata.rs @@ -334,7 +334,7 @@ mod tests { mod event_module { use crate::dispatch::DispatchResult; - use crate::weights::SimpleDispatchInfo; + use crate::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; pub trait Trait: super::system::Trait { type Balance; @@ -352,7 +352,7 @@ mod tests { pub struct Module for enum Call where origin: T::Origin { type Error = Error; - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn aux_0(_origin) -> DispatchResult { unreachable!() } } } diff --git a/frame/support/src/weights.rs b/frame/support/src/weights.rs index a85e215c01392..79cfa1b3974b3 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -55,6 +55,9 @@ pub use sp_runtime::transaction_validity::TransactionPriority; /// machine: (TODO: DEFINE STANDARD MACHINE SPECIFICATIONS) 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 { /// Weigh the data `T` given by `target`. When implementing this for a dispatchable, `T` will be diff --git a/frame/support/test/tests/decl_error.rs b/frame/support/test/tests/decl_error.rs index adb67a5ca586f..ae0303647f92f 100644 --- a/frame/support/test/tests/decl_error.rs +++ b/frame/support/test/tests/decl_error.rs @@ -32,7 +32,7 @@ mod module1 { pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: ::Origin { - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { Err(Error::::Something.into()) } @@ -59,7 +59,7 @@ mod module2 { pub struct Module for enum Call where origin: ::Origin { - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { Err(Error::::Something.into()) } diff --git a/frame/support/test/tests/instance.rs b/frame/support/test/tests/instance.rs index e53a5ec03c584..00b110ffb90e1 100644 --- a/frame/support/test/tests/instance.rs +++ b/frame/support/test/tests/instance.rs @@ -23,6 +23,7 @@ use frame_support::{ DecodeDifferent, StorageMetadata, StorageEntryModifier, StorageEntryType, DefaultByteGetter, StorageEntryMetadata, StorageHasher, }, + weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}, StorageValue, StorageMap, StorageDoubleMap, }; use sp_inherents::{ProvideInherent, InherentData, InherentIdentifier, MakeFatalError}; @@ -55,7 +56,7 @@ mod module1 { fn deposit_event() = default; - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn one(origin) { system::ensure_root(origin)?; Self::deposit_event(RawEvent::AnotherVariant(3)); diff --git a/frame/support/test/tests/reserved_keyword/on_initialize.rs b/frame/support/test/tests/reserved_keyword/on_initialize.rs index 54e28f228bd9d..9c15d1ef6ec55 100644 --- a/frame/support/test/tests/reserved_keyword/on_initialize.rs +++ b/frame/support/test/tests/reserved_keyword/on_initialize.rs @@ -19,7 +19,7 @@ macro_rules! reserved { frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin { - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn $reserved(_origin) -> dispatch::DispatchResult { unreachable!() } } } diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index 59d3b100b3328..02be52ecf3d3f 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -75,7 +75,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] +//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] //! pub fn system_module_example(origin) -> dispatch::DispatchResult { //! let _sender = ensure_signed(origin)?; //! let _extrinsic_count = >::extrinsic_count(); @@ -120,7 +120,7 @@ use frame_support::{ Contains, Get, ModuleToIndex, OnNewAccount, OnKilledAccount, IsDeadAccount, Happened, StoredMap, EnsureOrigin, }, - weights::{Weight, RuntimeDbWeight, DispatchInfo, PostDispatchInfo, DispatchClass, SimpleDispatchInfo, FunctionOf} + weights::{Weight, MINIMUM_WEIGHT, RuntimeDbWeight, DispatchInfo, PostDispatchInfo, DispatchClass, SimpleDispatchInfo, FunctionOf} }; use codec::{Encode, Decode, FullCodec, EncodeLike}; @@ -485,13 +485,13 @@ decl_module! { } /// Make some on-chain remark. - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn remark(origin, _remark: Vec) { ensure_signed(origin)?; } /// Set the number of pages in the WebAssembly environment's heap. - #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] + #[weight = SimpleDispatchInfo::FixedOperational(MINIMUM_WEIGHT)] fn set_heap_pages(origin, pages: u64) { ensure_root(origin)?; storage::unhashed::put_raw(well_known_keys::HEAP_PAGES, &pages.encode()); @@ -533,7 +533,7 @@ decl_module! { } /// Set some items of storage. - #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] + #[weight = SimpleDispatchInfo::FixedOperational(MINIMUM_WEIGHT)] fn set_storage(origin, items: Vec) { ensure_root(origin)?; for i in &items { @@ -542,7 +542,7 @@ decl_module! { } /// Kill some items from storage. - #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] + #[weight = SimpleDispatchInfo::FixedOperational(MINIMUM_WEIGHT)] fn kill_storage(origin, keys: Vec) { ensure_root(origin)?; for key in &keys { @@ -551,7 +551,7 @@ decl_module! { } /// Kill all storage items with a key that starts with the given prefix. - #[weight = SimpleDispatchInfo::FixedOperational(10_000_000)] + #[weight = SimpleDispatchInfo::FixedOperational(MINIMUM_WEIGHT)] fn kill_prefix(origin, prefix: Key) { ensure_root(origin)?; storage::unhashed::kill_prefix(&prefix); diff --git a/frame/timestamp/src/lib.rs b/frame/timestamp/src/lib.rs index 0d7fd59fe8999..0bd488009ddb3 100644 --- a/frame/timestamp/src/lib.rs +++ b/frame/timestamp/src/lib.rs @@ -69,7 +69,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(10_000_000)] +//! #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] //! pub fn get_time(origin) -> dispatch::DispatchResult { //! let _sender = ensure_signed(origin)?; //! let _now = >::get(); @@ -100,7 +100,7 @@ use frame_support::debug; use frame_support::{ Parameter, decl_storage, decl_module, traits::{Time, UnixTime, Get}, - weights::SimpleDispatchInfo, + weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}, }; use sp_runtime::{ RuntimeString, @@ -147,7 +147,7 @@ decl_module! { /// `MinimumPeriod`. /// /// The dispatch origin for this call must be `Inherent`. - #[weight = SimpleDispatchInfo::FixedMandatory(10_000_000)] + #[weight = SimpleDispatchInfo::FixedMandatory(MINIMUM_WEIGHT)] fn set(origin, #[compact] now: T::Moment) { ensure_none(origin)?; assert!(!::DidUpdate::exists(), "Timestamp must be updated only once in the block"); diff --git a/frame/treasury/src/lib.rs b/frame/treasury/src/lib.rs index 8707182073eb1..365524a9cbd54 100644 --- a/frame/treasury/src/lib.rs +++ b/frame/treasury/src/lib.rs @@ -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, WeighData, SimpleDispatchInfo}; +use frame_support::weights::{Weight, MINIMUM_WEIGHT, WeighData, SimpleDispatchInfo}; use frame_support::traits::{Contains, EnsureOrigin}; use codec::{Encode, Decode}; use frame_system::{self as system, ensure_signed, ensure_root}; @@ -558,7 +558,7 @@ decl_module! { Self::spend_funds(); } - SimpleDispatchInfo::FixedNormal(10_000_000).weigh_data(()) + SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) } } } diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index 39c1cd7797576..85545d92b0f65 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -57,7 +57,7 @@ use frame_support::traits::{ Currency, LockableCurrency, VestingSchedule, WithdrawReason, LockIdentifier, ExistenceRequirement, Get }; -use frame_support::weights::SimpleDispatchInfo; +use frame_support::weights::{SimpleDispatchInfo, 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 = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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 = SimpleDispatchInfo::FixedNormal(10_000_000)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn vest_other(origin, target: ::Source) -> DispatchResult { ensure_signed(origin)?; Self::update_lock(T::Lookup::lookup(target)?) From 8edc50acdcbe6a40838a168f00c7a1d573c4a077 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Tue, 14 Apr 2020 20:04:33 +0200 Subject: [PATCH 39/52] Update bin/node/runtime/src/impls.rs Co-Authored-By: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- bin/node/runtime/src/impls.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index 92b258b962142..5ae66dece726b 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -262,7 +262,7 @@ mod tests { let second_term = Fixed128::from_parts(12_500_000); assert_eq!( TargetedFeeAdjustment::::convert(Fixed128::default()), - first_term + second_term + first_term + second_term, ); }); From afc5f99caa62c0d5182fdc5120ec77119050b163 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Tue, 14 Apr 2020 20:17:15 +0200 Subject: [PATCH 40/52] Update test to show trend more clearly --- bin/node/runtime/src/impls.rs | 37 +++++++++++++---------------------- 1 file changed, 14 insertions(+), 23 deletions(-) diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index 92b258b962142..123bdc29944c2 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -241,8 +241,9 @@ mod tests { #[test] fn stateless_weight_mul() { + // This test will show that heavy blocks have a weight multiplier greater than 0 + // and light blocks will have a weight multiplier less than 0. run_with_system_weight(target() / 4, || { - // Light block. Fee is reduced a little. // Target = 25%, Weight is Target / 4 = 6.25%, Diff = -18.75%, V = 4/10^5 // So first term is -75/10^7 let first_term = Fixed128::from_rational(-75, NonZeroI128::new(10_000_000).unwrap()); @@ -252,38 +253,28 @@ mod tests { TargetedFeeAdjustment::::convert(Fixed128::default()), first_term + second_term, ); + + // Light block. Fee is reduced a little. + let target_fee_adjustment = TargetedFeeAdjustment::::convert(Fixed128::default()); + assert!(target_fee_adjustment < Fixed128::zero()) }); run_with_system_weight(target() / 2, || { // a bit more. Fee is decreased less, meaning that the fee increases as the block grows. - // Target = 25%, Weight is Target / 2 = 12.5%, Diff = -12.5%, V = 4/10^5 - // So first term is -5/10^6 - let first_term = Fixed128::from_rational(-5, NonZeroI128::new(1_000_000).unwrap()); - // Diff^2 = .015625, V^2 = 8/10^10... So second_term = 125/10^13 - let second_term = Fixed128::from_parts(12_500_000); - assert_eq!( - TargetedFeeAdjustment::::convert(Fixed128::default()), - first_term + second_term - ); + let target_fee_adjustment = TargetedFeeAdjustment::::convert(Fixed128::default()); + assert!(target_fee_adjustment < Fixed128::zero()); + // -74/10^7 is greater than the target/4 fee adjustment, and this should be even bigger. + assert!(target_fee_adjustment > Fixed128::from_rational(-74, NonZeroI128::new(10_000_000).unwrap())) }); run_with_system_weight(target(), || { // ideal. Original fee. No changes. - assert_eq!( - TargetedFeeAdjustment::::convert(Fixed128::default()), - Fixed128::from_natural(0), - ); + let target_fee_adjustment = TargetedFeeAdjustment::::convert(Fixed128::default()); + assert_eq!(target_fee_adjustment, Fixed128::zero()) }); run_with_system_weight(target() * 2, || { // More than ideal. Fee is increased. - // Target = 25%, Weight is Target * 2 = 50%, Diff = 25%, V = 4/10^5 - // So first term is 1/10^5 - let first_term = Fixed128::from_rational(1, NonZeroI128::new(100_000).unwrap()); - // Diff^2 = .0625, V^2 = 8/10^10... So second_term = 5/10^11 - let second_term = Fixed128::from_parts(50_000_000); - assert_eq!( - TargetedFeeAdjustment::::convert(Fixed128::default()), - first_term + second_term, - ); + let target_fee_adjustment = TargetedFeeAdjustment::::convert(Fixed128::default()); + assert!(target_fee_adjustment > Fixed128::zero()) }); } From 8af57975c6dffcc0e09619595a6725eb3b29c85e Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Tue, 14 Apr 2020 20:22:53 +0200 Subject: [PATCH 41/52] test nit --- bin/node/executor/tests/fees.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/node/executor/tests/fees.rs b/bin/node/executor/tests/fees.rs index e1270832e374e..32fef3b326615 100644 --- a/bin/node/executor/tests/fees.rs +++ b/bin/node/executor/tests/fees.rs @@ -190,7 +190,7 @@ fn transaction_fee_is_correct_ultimate() { // we know that weight to fee multiplier is effect-less in block 1. // current weight of transfer = 200_000_000 // Linear weight to fee is 1:1 right now (1 weight = 1 unit of balance) - assert_eq!(weight_fee as Balance, 200_000_000); + assert_eq!(weight_fee, weight as Balance); balance_alice -= weight_fee; balance_alice -= tip; From 8b4e34960fdcf2be90d3dd4b54a672ccbddadf73 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Tue, 14 Apr 2020 20:27:10 +0200 Subject: [PATCH 42/52] Update fixed64.rs --- primitives/arithmetic/src/fixed64.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/primitives/arithmetic/src/fixed64.rs b/primitives/arithmetic/src/fixed64.rs index 1f551c1604de7..6f7e5fe84249f 100644 --- a/primitives/arithmetic/src/fixed64.rs +++ b/primitives/arithmetic/src/fixed64.rs @@ -128,8 +128,7 @@ impl Saturating for Fixed64 { } } -/// Note that this is a standard, _potentially-panicking_, implementation. Use `Saturating` trait -/// for safe addition. +/// Use `Saturating` trait for safe addition. impl ops::Add for Fixed64 { type Output = Self; @@ -138,8 +137,7 @@ impl ops::Add for Fixed64 { } } -/// Note that this is a standard, _potentially-panicking_, implementation. Use `Saturating` trait -/// for safe subtraction. +/// Use `Saturating` trait for safe subtraction. impl ops::Sub for Fixed64 { type Output = Self; @@ -148,8 +146,7 @@ impl ops::Sub for Fixed64 { } } -/// Note that this is a standard, _potentially-panicking_, implementation. Use `CheckedDiv` trait -/// for safe division. +/// Use `CheckedDiv` trait for safe division. impl ops::Div for Fixed64 { type Output = Self; From e0a2be82733dc4f5247114d20826b1c514fb9ef5 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Tue, 14 Apr 2020 20:42:40 +0200 Subject: [PATCH 43/52] More fixes --- frame/indices/src/lib.rs | 8 ++++---- frame/recovery/src/lib.rs | 2 +- frame/scored-pool/src/lib.rs | 10 +++++----- frame/staking/src/lib.rs | 2 +- frame/sudo/src/lib.rs | 2 +- frame/support/test/tests/decl_error.rs | 4 ++-- .../test/tests/reserved_keyword/on_initialize.rs | 2 +- frame/timestamp/src/lib.rs | 3 ++- 8 files changed, 17 insertions(+), 16 deletions(-) diff --git a/frame/indices/src/lib.rs b/frame/indices/src/lib.rs index d75bfb04b59fb..26496e53086ce 100644 --- a/frame/indices/src/lib.rs +++ b/frame/indices/src/lib.rs @@ -121,7 +121,7 @@ decl_module! { /// - One reserve operation. /// - One event. /// # - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn claim(origin, index: T::AccountIndex) { let who = ensure_signed(origin)?; @@ -149,7 +149,7 @@ decl_module! { /// - One transfer operation. /// - One event. /// # - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn transfer(origin, new: T::AccountId, index: T::AccountIndex) { let who = ensure_signed(origin)?; ensure!(who != new, Error::::NotTransfer); @@ -180,7 +180,7 @@ decl_module! { /// - One reserve operation. /// - One event. /// # - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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 = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn force_transfer(origin, new: T::AccountId, index: T::AccountIndex) { ensure_root(origin)?; diff --git a/frame/recovery/src/lib.rs b/frame/recovery/src/lib.rs index e50a811290037..9933da5481866 100644 --- a/frame/recovery/src/lib.rs +++ b/frame/recovery/src/lib.rs @@ -647,7 +647,7 @@ decl_module! { /// # /// - One storage mutation to check account is recovered by `who`. O(1) /// # - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn cancel_recovered(origin, account: T::AccountId) { let who = ensure_signed(origin)?; // Check `who` is allowed to make a call on behalf of `account` diff --git a/frame/scored-pool/src/lib.rs b/frame/scored-pool/src/lib.rs index 6e4fd2b06176e..a869d37add545 100644 --- a/frame/scored-pool/src/lib.rs +++ b/frame/scored-pool/src/lib.rs @@ -267,7 +267,7 @@ decl_module! { /// /// The `index` parameter of this function must be set to /// the index of the transactor in the `Pool`. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn submit_candidacy(origin) { let who = ensure_signed(origin)?; ensure!(!>::contains_key(&who), Error::::AlreadyInPool); @@ -297,7 +297,7 @@ decl_module! { /// /// The `index` parameter of this function must be set to /// the index of the transactor in the `Pool`. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn withdraw_candidacy( origin, index: u32 @@ -317,7 +317,7 @@ decl_module! { /// /// The `index` parameter of this function must be set to /// the index of `dest` in the `Pool`. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn kick( origin, dest: ::Source, @@ -342,7 +342,7 @@ decl_module! { /// /// The `index` parameter of this function must be set to /// the index of the `dest` in the `Pool`. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn score( origin, dest: ::Source, @@ -383,7 +383,7 @@ decl_module! { /// (this happens each `Period`). /// /// May only be called from root. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn change_member_count(origin, count: u32) { ensure_root(origin)?; >::put(&count); diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index 597bace187b8c..2d1875ebf0196 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -1782,7 +1782,7 @@ decl_module! { /// This can be called from any origin. /// /// - `stash`: The stash account to reap. Its balance must be zero. - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn reap_stash(_origin, stash: T::AccountId) { ensure!(T::Currency::total_balance(&stash).is_zero(), Error::::FundedTarget); Self::kill_stash(&stash)?; diff --git a/frame/sudo/src/lib.rs b/frame/sudo/src/lib.rs index 441a22d6efa8e..8fd8870bdb91a 100644 --- a/frame/sudo/src/lib.rs +++ b/frame/sudo/src/lib.rs @@ -151,7 +151,7 @@ decl_module! { /// - Limited storage reads. /// - One DB change. /// # - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn set_key(origin, new: ::Source) { // This is a public call, so we ensure that the origin is some signed account. let sender = ensure_signed(origin)?; diff --git a/frame/support/test/tests/decl_error.rs b/frame/support/test/tests/decl_error.rs index ae0303647f92f..c2aa2de46337e 100644 --- a/frame/support/test/tests/decl_error.rs +++ b/frame/support/test/tests/decl_error.rs @@ -32,7 +32,7 @@ mod module1 { pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: ::Origin { - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { Err(Error::::Something.into()) } @@ -59,7 +59,7 @@ mod module2 { pub struct Module for enum Call where origin: ::Origin { - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { Err(Error::::Something.into()) } diff --git a/frame/support/test/tests/reserved_keyword/on_initialize.rs b/frame/support/test/tests/reserved_keyword/on_initialize.rs index 9c15d1ef6ec55..5149d84345aac 100644 --- a/frame/support/test/tests/reserved_keyword/on_initialize.rs +++ b/frame/support/test/tests/reserved_keyword/on_initialize.rs @@ -19,7 +19,7 @@ macro_rules! reserved { frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin { - #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn $reserved(_origin) -> dispatch::DispatchResult { unreachable!() } } } diff --git a/frame/timestamp/src/lib.rs b/frame/timestamp/src/lib.rs index 0bd488009ddb3..822848bf7dcc7 100644 --- a/frame/timestamp/src/lib.rs +++ b/frame/timestamp/src/lib.rs @@ -62,6 +62,7 @@ //! //! ``` //! use frame_support::{decl_module, dispatch}; +//! use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; //! # use pallet_timestamp as timestamp; //! use frame_system::{self as system, ensure_signed}; //! @@ -69,7 +70,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = frame_support::weights::SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] +//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] //! pub fn get_time(origin) -> dispatch::DispatchResult { //! let _sender = ensure_signed(origin)?; //! let _now = >::get(); From f9907bb3b465fd475ffc04e5f6ca39d860d1d275 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Tue, 14 Apr 2020 20:45:44 +0200 Subject: [PATCH 44/52] missed one --- frame/sudo/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/sudo/src/lib.rs b/frame/sudo/src/lib.rs index 8fd8870bdb91a..b8cf9a353f341 100644 --- a/frame/sudo/src/lib.rs +++ b/frame/sudo/src/lib.rs @@ -93,7 +93,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}; +use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT, GetDispatchInfo, FunctionOf}; use frame_system::{self as system, ensure_signed}; pub trait Trait: frame_system::Trait { From d164555eebbf5c0c6025dd2e7d907e5efddfd33c Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Tue, 14 Apr 2020 21:39:13 +0200 Subject: [PATCH 45/52] More test fixes --- frame/support/test/tests/decl_error.rs | 1 + frame/support/test/tests/reserved_keyword/on_initialize.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/frame/support/test/tests/decl_error.rs b/frame/support/test/tests/decl_error.rs index c2aa2de46337e..cf50b009ddf18 100644 --- a/frame/support/test/tests/decl_error.rs +++ b/frame/support/test/tests/decl_error.rs @@ -18,6 +18,7 @@ use sp_runtime::{generic, traits::{BlakeTwo256, Block as _, Verify}, DispatchError}; use sp_core::{H256, sr25519}; +use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; mod system; diff --git a/frame/support/test/tests/reserved_keyword/on_initialize.rs b/frame/support/test/tests/reserved_keyword/on_initialize.rs index 5149d84345aac..00aac51cab388 100644 --- a/frame/support/test/tests/reserved_keyword/on_initialize.rs +++ b/frame/support/test/tests/reserved_keyword/on_initialize.rs @@ -2,7 +2,7 @@ macro_rules! reserved { ($($reserved:ident)*) => { $( mod $reserved { - pub use frame_support::dispatch; + pub use frame_support::{dispatch, weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}}; pub trait Trait { type Origin; From 2baf8f6bbfee564f17d3d805f7581c56ca771503 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Tue, 14 Apr 2020 22:57:52 +0200 Subject: [PATCH 46/52] Update lib.rs --- frame/system/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index 02be52ecf3d3f..31b862f3b23c3 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -68,7 +68,7 @@ //! ### Example - Get extrinsic count and parent hash for the current block //! //! ``` -//! use frame_support::{decl_module, dispatch, weights::SimpleDispatchInfo}; +//! use frame_support::{decl_module, dispatch, weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}}; //! use frame_system::{self as system, ensure_signed}; //! //! pub trait Trait: system::Trait {} From e830b1189470dfab36ad1dd877195cf0c415cfcb Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Wed, 15 Apr 2020 01:10:09 +0200 Subject: [PATCH 47/52] Update Cargo.lock --- Cargo.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c8e7de77611e8..1f6848ba37a67 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4930,18 +4930,18 @@ dependencies = [ [[package]] name = "pin-project" -version = "0.4.8" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7804a463a8d9572f13453c516a5faea534a2403d7ced2f0c7e100eeff072772c" +checksum = "6f6a7f5eee6292c559c793430c55c00aea9d3b3d1905e855806ca4d7253426a2" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "0.4.8" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "385322a45f2ecf3410c68d2a549a4a2685e8051d0f278e39743ff4e451cb9b3f" +checksum = "8988430ce790d8682672117bc06dda364c0be32d3abd738234f19f3240bad99a" dependencies = [ "proc-macro2", "quote 1.0.3", From cf75a56f848ec12192154ec945f40af14d896f9a Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Wed, 15 Apr 2020 02:12:14 +0200 Subject: [PATCH 48/52] Bump spec version --- bin/node/runtime/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 51c9f125e48f0..b1d768eecd3e7 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -127,8 +127,8 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { // and set impl_version to 0. If only runtime // implementation changes and behavior does not, then leave spec_version as // is and increment impl_version. - spec_version: 240, - impl_version: 1, + spec_version: 241, + impl_version: 0, apis: RUNTIME_API_VERSIONS, }; From 98dbf611e7a4541f9996f6112fd2a383fac4c8e2 Mon Sep 17 00:00:00 2001 From: kianenigma Date: Wed, 15 Apr 2020 10:58:40 +0200 Subject: [PATCH 49/52] Clean and fic block weight tests. --- bin/node/runtime/src/impls.rs | 129 ++++++++++++-------------- primitives/arithmetic/src/fixed128.rs | 3 +- 2 files changed, 62 insertions(+), 70 deletions(-) diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index 123bdc29944c2..f613dc5af5048 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -78,9 +78,12 @@ impl> Convert for TargetedFeeAdjustment< // determines if the first_term is positive let positive = block_weight >= target_weight; let diff_abs = block_weight.max(target_weight) - block_weight.min(target_weight); - // TODO: This is not always safe! Diff can be larger than what fits into i64 - // It is safe as long as `block_weight` is less than `max_weight` - let diff = Fixed128::from_rational(diff_abs as i64, NonZeroI128::new(max_weight.max(1) as i128).unwrap()); + // safe, diff_abs cannot exceed u64 and it can always be computed safely even with the lossy + // `Fixed128::from_rational`. + let diff = Fixed128::from_rational( + diff_abs as i128, + NonZeroI128::new(max_weight.max(1) as i128).unwrap(), + ); let diff_squared = diff.saturating_mul(diff); // 0.00004 = 4/100_000 = 40_000/10^9 @@ -244,98 +247,87 @@ mod tests { // This test will show that heavy blocks have a weight multiplier greater than 0 // and light blocks will have a weight multiplier less than 0. run_with_system_weight(target() / 4, || { - // Target = 25%, Weight is Target / 4 = 6.25%, Diff = -18.75%, V = 4/10^5 - // So first term is -75/10^7 - let first_term = Fixed128::from_rational(-75, NonZeroI128::new(10_000_000).unwrap()); - // Diff^2 = .03515625, V^2 = 8/10^10... So second_term = 28125/10^15 - let second_term = Fixed128::from_parts(28_125_000); + // `fee_multiplier_update` is enough as it is the absolute truth value. + let next = TargetedFeeAdjustment::::convert(Fixed128::default()); assert_eq!( - TargetedFeeAdjustment::::convert(Fixed128::default()), - first_term + second_term, + next, + fee_multiplier_update(target() / 4 ,Fixed128::default()) ); // Light block. Fee is reduced a little. - let target_fee_adjustment = TargetedFeeAdjustment::::convert(Fixed128::default()); - assert!(target_fee_adjustment < Fixed128::zero()) + assert!(next < Fixed128::zero()) }); run_with_system_weight(target() / 2, || { - // a bit more. Fee is decreased less, meaning that the fee increases as the block grows. - let target_fee_adjustment = TargetedFeeAdjustment::::convert(Fixed128::default()); - assert!(target_fee_adjustment < Fixed128::zero()); - // -74/10^7 is greater than the target/4 fee adjustment, and this should be even bigger. - assert!(target_fee_adjustment > Fixed128::from_rational(-74, NonZeroI128::new(10_000_000).unwrap())) + let next = TargetedFeeAdjustment::::convert(Fixed128::default()); + assert_eq!( + next, + fee_multiplier_update(target() / 2 ,Fixed128::default()) + ); + + // Light block. Fee is reduced a little. + assert!(next < Fixed128::zero()) }); run_with_system_weight(target(), || { // ideal. Original fee. No changes. - let target_fee_adjustment = TargetedFeeAdjustment::::convert(Fixed128::default()); - assert_eq!(target_fee_adjustment, Fixed128::zero()) + let next = TargetedFeeAdjustment::::convert(Fixed128::default()); + assert_eq!(next, Fixed128::zero()) }); run_with_system_weight(target() * 2, || { // More than ideal. Fee is increased. - let target_fee_adjustment = TargetedFeeAdjustment::::convert(Fixed128::default()); - assert!(target_fee_adjustment > Fixed128::zero()) + let next = TargetedFeeAdjustment::::convert(Fixed128::default()); + assert_eq!( + next, + fee_multiplier_update(target() * 2 ,Fixed128::default()) + ); + + // Heavy block. Fee is increased a little. + assert!(next > Fixed128::zero()) }); } #[test] fn stateful_weight_mul_grow_to_infinity() { run_with_system_weight(target() * 2, || { - // Target = 25%, Weight is Target * 2 = 50%, Diff = 25%, V = 4/10^5 - // So first term is 1/10^5 - let first_term = Fixed128::from_rational(1, NonZeroI128::new(100_000).unwrap()); - // Diff^2 = .0625, V^2 = 8/10^10... So second_term = 5/10^11 - let second_term = Fixed128::from_rational(5, NonZeroI128::new(100_000_000_000).unwrap()); - - // We should see the fee in each of these tests increase by first_term + second_term in all cases. - let mut original = Fixed128::default(); // 0 - assert_eq!( - TargetedFeeAdjustment::::convert(original), - original + first_term + second_term, - ); - original = Fixed128::from_rational(1, NonZeroI128::new(100).unwrap()); - assert_eq!( - TargetedFeeAdjustment::::convert(original), - original + first_term + second_term, - ); - original = Fixed128::from_rational(3, NonZeroI128::new(100).unwrap()); - assert_eq!( - TargetedFeeAdjustment::::convert(original), - original + first_term + second_term, - ); - // ... keeps going up till infinity - assert_eq!( - TargetedFeeAdjustment::::convert(Fixed128::from_natural(1)), - Fixed128::from_natural(1) + first_term + second_term - ); + let mut original = Fixed128::default(); + let mut next = Fixed128::default(); + + (0..1_000).for_each(|_| { + next = TargetedFeeAdjustment::::convert(original); + assert_eq!( + next, + fee_multiplier_update(target() * 2, original), + ); + // must always increase + assert!(next > original); + original = next; + }); }); } #[test] fn stateful_weight_mil_collapse_to_minus_one() { run_with_system_weight(0, || { - // Target = 25%, Weight = 0%, Diff = -25%, V = 4/10^5 - // So first term is -1/10^5 - let first_term = Fixed128::from_rational(-1, NonZeroI128::new(100_000).unwrap()); - // Diff^2 = .0625, V^2 = 8/10^10... So second_term = 5/10^11 - let second_term = Fixed128::from_rational(5, NonZeroI128::new(100_000_000_000).unwrap()); - - // We should see the fee in each of these tests decrease by first_term - second_term until it hits -1. - let original = Fixed128::default(); // 0 - assert_eq!( - TargetedFeeAdjustment::::convert(original), - original + first_term + second_term, - ); - let original = Fixed128::from_rational(-1, NonZeroI128::new(100).unwrap()); + let mut original = Fixed128::default(); // 0 + let mut next; + + // decreases + next = TargetedFeeAdjustment::::convert(original); assert_eq!( - TargetedFeeAdjustment::::convert(original), - original + first_term + second_term, + next, + fee_multiplier_update(0, original), ); - let original = Fixed128::from_rational(-3, NonZeroI128::new(100).unwrap()); + assert!(next < original); + original = next; + + // keeps decreasing + next = TargetedFeeAdjustment::::convert(original); assert_eq!( - TargetedFeeAdjustment::::convert(original), - original + first_term + second_term, + next, + fee_multiplier_update(0, original), ); + assert!(next < original); + // ... stops going down at -1 assert_eq!( TargetedFeeAdjustment::::convert(Fixed128::from_natural(-1)), @@ -365,9 +357,8 @@ mod tests { 4294967295, MaximumBlockWeight::get() / 2, MaximumBlockWeight::get(), - // TODO these are not safe - // Weight::max_value() / 2, - // Weight::max_value(), + Weight::max_value() / 2, + Weight::max_value(), ].into_iter().for_each(|i| { run_with_system_weight(i, || { let next = TargetedFeeAdjustment::::convert(Fixed128::default()); diff --git a/primitives/arithmetic/src/fixed128.rs b/primitives/arithmetic/src/fixed128.rs index 1becc93359787..a0fafe5ee3ece 100644 --- a/primitives/arithmetic/src/fixed128.rs +++ b/primitives/arithmetic/src/fixed128.rs @@ -57,7 +57,8 @@ impl Fixed128 { /// Creates self from a rational number. Equal to `n/d`. /// - /// Note that this might be lossy. + /// Note that this might be lossy. Only use this if you are sure that `n * DIV` can fit into an + /// i128. pub fn from_rational>(n: N, d: NonZeroI128) -> Self { let n = n.unique_saturated_into(); Self(n.saturating_mul(DIV.into()) / d.get()) From 8fd3293759ce774249c068e58dc609f695198625 Mon Sep 17 00:00:00 2001 From: kianenigma Date: Wed, 15 Apr 2020 11:05:34 +0200 Subject: [PATCH 50/52] fix on-initialize weights --- frame/authorship/src/lib.rs | 2 +- frame/babe/src/lib.rs | 2 +- frame/democracy/src/lib.rs | 4 ++-- frame/elections-phragmen/src/lib.rs | 4 ++-- frame/elections/src/lib.rs | 2 +- frame/example/src/lib.rs | 2 +- frame/indices/src/lib.rs | 2 +- frame/offences/src/lib.rs | 4 ++-- frame/randomness-collective-flip/src/lib.rs | 2 +- frame/scored-pool/src/lib.rs | 2 +- frame/session/src/lib.rs | 2 +- frame/society/src/lib.rs | 2 +- frame/treasury/src/lib.rs | 2 +- 13 files changed, 16 insertions(+), 16 deletions(-) diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index 7d2d33da1cdf6..cbe52c35b6f9f 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -197,7 +197,7 @@ decl_module! { T::EventHandler::note_author(Self::author()); - SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) + MINIMUM_WEIGHT } fn on_finalize() { diff --git a/frame/babe/src/lib.rs b/frame/babe/src/lib.rs index 7b16e3006dd18..a9eb3c3929f0a 100644 --- a/frame/babe/src/lib.rs +++ b/frame/babe/src/lib.rs @@ -184,7 +184,7 @@ decl_module! { fn on_initialize(now: T::BlockNumber) -> Weight { Self::do_initialize(now); - SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) + MINIMUM_WEIGHT } /// Block finalization diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index fd7cb72dbd627..bb940e5f4840a 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -528,7 +528,7 @@ decl_module! { fn on_runtime_upgrade() -> Weight { Self::migrate(); - SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) + MINIMUM_WEIGHT } /// Propose a sensitive action to be taken. @@ -848,7 +848,7 @@ decl_module! { sp_runtime::print(e); } - SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) + MINIMUM_WEIGHT } /// Specify a proxy that is already open to us. Called by the stash. diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 040c3e716c4ab..8a8d3d392e912 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -267,7 +267,7 @@ decl_module! { fn on_runtime_upgrade() -> Weight { migration::migrate::(); - SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) + MINIMUM_WEIGHT } const CandidacyBond: BalanceOf = T::CandidacyBond::get(); @@ -510,7 +510,7 @@ decl_module! { print(e); } - SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) + MINIMUM_WEIGHT } } } diff --git a/frame/elections/src/lib.rs b/frame/elections/src/lib.rs index 2ab76bd769bae..41985bb1d99af 100644 --- a/frame/elections/src/lib.rs +++ b/frame/elections/src/lib.rs @@ -703,7 +703,7 @@ decl_module! { print("Guru meditation"); print(e); } - SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) + MINIMUM_WEIGHT } } } diff --git a/frame/example/src/lib.rs b/frame/example/src/lib.rs index 991120cbe5254..97cad2856a00d 100644 --- a/frame/example/src/lib.rs +++ b/frame/example/src/lib.rs @@ -524,7 +524,7 @@ decl_module! { // Anything that needs to be done at the start of the block. // We don't do anything here. - SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) + MINIMUM_WEIGHT } // The signature could also look like: `fn on_finalize()` diff --git a/frame/indices/src/lib.rs b/frame/indices/src/lib.rs index 26496e53086ce..888b1c47d72e9 100644 --- a/frame/indices/src/lib.rs +++ b/frame/indices/src/lib.rs @@ -102,7 +102,7 @@ decl_module! { fn on_initialize() -> Weight { Self::migrations(); - SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) + MINIMUM_WEIGHT } /// Assign an previously unassigned index. diff --git a/frame/offences/src/lib.rs b/frame/offences/src/lib.rs index 0d08565c17f25..ebf3f3aa4c96a 100644 --- a/frame/offences/src/lib.rs +++ b/frame/offences/src/lib.rs @@ -104,7 +104,7 @@ decl_module! { ConcurrentReportsIndex::::remove_all(); ReportsByKindIndex::remove_all(); - SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) + MINIMUM_WEIGHT } fn on_initialize(now: T::BlockNumber) -> Weight { @@ -125,7 +125,7 @@ decl_module! { }) } - SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) + MINIMUM_WEIGHT } } } diff --git a/frame/randomness-collective-flip/src/lib.rs b/frame/randomness-collective-flip/src/lib.rs index f1e51eb1da3b7..06fbc70fbcdca 100644 --- a/frame/randomness-collective-flip/src/lib.rs +++ b/frame/randomness-collective-flip/src/lib.rs @@ -83,7 +83,7 @@ decl_module! { values[index] = parent_hash; }); - SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) + MINIMUM_WEIGHT } } } diff --git a/frame/scored-pool/src/lib.rs b/frame/scored-pool/src/lib.rs index a869d37add545..e0c9309737e31 100644 --- a/frame/scored-pool/src/lib.rs +++ b/frame/scored-pool/src/lib.rs @@ -253,7 +253,7 @@ decl_module! { let pool = >::get(); >::refresh_members(pool, ChangeReceiver::MembershipChanged); } - SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) + MINIMUM_WEIGHT } /// Add `origin` to the pool of candidates. diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index 10af4430c8cd8..27e6332af0602 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -532,7 +532,7 @@ decl_module! { Self::rotate_session(); } - SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) + MINIMUM_WEIGHT } } } diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index 41ecc8d36aabf..48a2244c9344a 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -1046,7 +1046,7 @@ decl_module! { Self::rotate_challenge(&mut members); } - SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) + MINIMUM_WEIGHT } } } diff --git a/frame/treasury/src/lib.rs b/frame/treasury/src/lib.rs index 365524a9cbd54..b0a9577799bfd 100644 --- a/frame/treasury/src/lib.rs +++ b/frame/treasury/src/lib.rs @@ -558,7 +558,7 @@ decl_module! { Self::spend_funds(); } - SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT).weigh_data(()) + MINIMUM_WEIGHT } } } From 8da68dc2c837d4c355b4b4997ebc8a0ebe8ddae5 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Wed, 15 Apr 2020 12:00:13 +0200 Subject: [PATCH 51/52] Fix warnings --- frame/authorship/src/lib.rs | 2 +- frame/babe/src/lib.rs | 2 +- frame/democracy/src/lib.rs | 2 +- frame/elections-phragmen/src/lib.rs | 2 +- frame/indices/src/lib.rs | 2 +- frame/offences/src/lib.rs | 2 +- frame/randomness-collective-flip/src/lib.rs | 2 +- frame/session/src/lib.rs | 2 +- frame/society/src/lib.rs | 2 +- frame/treasury/src/lib.rs | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index cbe52c35b6f9f..fac4b7d48201c 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -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, SimpleDispatchInfo, WeighData}; +use frame_support::weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo}; use sp_inherents::{InherentIdentifier, ProvideInherent, InherentData}; use sp_authorship::{INHERENT_IDENTIFIER, UnclesInherentData, InherentError}; diff --git a/frame/babe/src/lib.rs b/frame/babe/src/lib.rs index a9eb3c3929f0a..ea2f97e7a9551 100644 --- a/frame/babe/src/lib.rs +++ b/frame/babe/src/lib.rs @@ -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, SimpleDispatchInfo, WeighData}, + weights::{Weight, MINIMUM_WEIGHT}, }; use sp_timestamp::OnTimestampSet; use sp_runtime::{generic::DigestItem, ConsensusEngineId, Perbill}; diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index bb940e5f4840a..a76567ba2743c 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -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::{SimpleDispatchInfo, Weight, MINIMUM_WEIGHT, WeighData}, + weights::{SimpleDispatchInfo, Weight, MINIMUM_WEIGHT}, traits::{ Currency, ReservableCurrency, LockableCurrency, WithdrawReason, LockIdentifier, Get, OnUnbalanced, BalanceStatus, schedule::Named as ScheduleNamed, EnsureOrigin diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 8a8d3d392e912..fe4218374366c 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -88,7 +88,7 @@ use sp_runtime::{ }; use frame_support::{ decl_storage, decl_event, ensure, decl_module, decl_error, - weights::{SimpleDispatchInfo, Weight, MINIMUM_WEIGHT, WeighData}, storage::{StorageMap, IterableStorageMap}, + weights::{SimpleDispatchInfo, Weight, MINIMUM_WEIGHT}, storage::{StorageMap, IterableStorageMap}, traits::{ Currency, Get, LockableCurrency, LockIdentifier, ReservableCurrency, WithdrawReasons, ChangeMembers, OnUnbalanced, WithdrawReason, Contains, BalanceStatus, InitializeMembers, diff --git a/frame/indices/src/lib.rs b/frame/indices/src/lib.rs index 888b1c47d72e9..2a66af7e7f8bb 100644 --- a/frame/indices/src/lib.rs +++ b/frame/indices/src/lib.rs @@ -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, SimpleDispatchInfo, WeighData}; +use frame_support::weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo}; use frame_support::dispatch::DispatchResult; use frame_support::traits::{Currency, ReservableCurrency, Get, BalanceStatus::Reserved}; use frame_support::storage::migration::take_storage_value; diff --git a/frame/offences/src/lib.rs b/frame/offences/src/lib.rs index ebf3f3aa4c96a..2b59c5e796fd2 100644 --- a/frame/offences/src/lib.rs +++ b/frame/offences/src/lib.rs @@ -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, SimpleDispatchInfo, WeighData}, + weights::{Weight, MINIMUM_WEIGHT}, }; use sp_runtime::{traits::Hash, Perbill}; use sp_staking::{ diff --git a/frame/randomness-collective-flip/src/lib.rs b/frame/randomness-collective-flip/src/lib.rs index 06fbc70fbcdca..194879eb65b80 100644 --- a/frame/randomness-collective-flip/src/lib.rs +++ b/frame/randomness-collective-flip/src/lib.rs @@ -57,7 +57,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, SimpleDispatchInfo, WeighData} + weights::{Weight, MINIMUM_WEIGHT} }; use safe_mix::TripletMix; use codec::Encode; diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index 27e6332af0602..f539004189a95 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -110,7 +110,7 @@ use frame_support::{ Get, FindAuthor, ValidatorRegistration, EstimateNextSessionRotation, EstimateNextNewSession, }, dispatch::{self, DispatchResult, DispatchError}, - weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo, WeighData}, + weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo}, }; use frame_system::{self as system, ensure_signed}; diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index 48a2244c9344a..f9908f5d9c6c0 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -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::{SimpleDispatchInfo, Weight, MINIMUM_WEIGHT, WeighData}; +use frame_support::weights::{SimpleDispatchInfo, Weight, MINIMUM_WEIGHT}; use frame_support::traits::{ Currency, ReservableCurrency, Randomness, Get, ChangeMembers, BalanceStatus, ExistenceRequirement::AllowDeath, EnsureOrigin diff --git a/frame/treasury/src/lib.rs b/frame/treasury/src/lib.rs index b0a9577799bfd..2a255ab2d6210 100644 --- a/frame/treasury/src/lib.rs +++ b/frame/treasury/src/lib.rs @@ -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, WeighData, SimpleDispatchInfo}; +use frame_support::weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo}; use frame_support::traits::{Contains, EnsureOrigin}; use codec::{Encode, Decode}; use frame_system::{self as system, ensure_signed, ensure_root}; From 1d6a9f284788f8a3b741d07ec2569638855264d3 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Wed, 15 Apr 2020 15:13:36 +0200 Subject: [PATCH 52/52] fix warnings --- frame/elections/src/lib.rs | 2 +- frame/scored-pool/src/lib.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/frame/elections/src/lib.rs b/frame/elections/src/lib.rs index 41985bb1d99af..a2398ad485960 100644 --- a/frame/elections/src/lib.rs +++ b/frame/elections/src/lib.rs @@ -30,7 +30,7 @@ use sp_runtime::{ }; use frame_support::{ decl_storage, decl_event, ensure, decl_module, decl_error, - weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo, WeighData}, + weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo}, traits::{ Currency, ExistenceRequirement, Get, LockableCurrency, LockIdentifier, BalanceStatus, OnUnbalanced, ReservableCurrency, WithdrawReason, WithdrawReasons, ChangeMembers diff --git a/frame/scored-pool/src/lib.rs b/frame/scored-pool/src/lib.rs index e0c9309737e31..eca877f096283 100644 --- a/frame/scored-pool/src/lib.rs +++ b/frame/scored-pool/src/lib.rs @@ -98,7 +98,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, SimpleDispatchInfo, WeighData}, + weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo}, }; use frame_system::{self as system, ensure_root, ensure_signed}; use sp_runtime::{