Weight annotation. (#3157)

* Make extrinsics extensible.

Also Remove old extrinsic types.

* Rest of mockup. Add tips.

* Fix some build issues

* Runtiem builds :)

* Substrate builds.

* Fix a doc test

* Compact encoding

* Extract out the era logic into an extension

* Weight Check signed extension. (#3115)

* Weight signed extension.

* Revert a bit + test for check era.

* Update Cargo.toml

* Update node/cli/src/factory_impl.rs

* Update node/executor/src/lib.rs

* Update node/executor/src/lib.rs

* Don't use len for weight - use data.

* Operational Transaction; second attempt (#3138)

* working poc added.

* some fixes.

* Update doc.

* Fix all tests + final logic.

* more refactoring.

* nits.

* System block limit in bytes.

* Silent the storage macro warnings.

* More logic more tests.

* Fix import.

* Refactor names.

* Fix build.

* Update srml/balances/src/lib.rs

* Final refactor.

* Bump transaction version

* Fix weight mult test.

* Fix more tests and improve doc.

* Bump.

* Make some tests work again.

* Fix subkey.

* Remove todos + bump.

* First draft of annotating weights.

* Refactor weight to u64.

* More refactoring and tests.

* New convert for weight to fee

* more tests.

* remove merge redundancy.

* Fix system test.

* Bring back subkey stuff.

* a few stress tests.

* fix some of the grumbles.

* Final nits.

* Update srml/system/src/lib.rs

Co-Authored-By: DemiMarie-parity <48690212+DemiMarie-parity@users.noreply.github.com>

* Scale weights by 1000.

* Bump.

* Fix decl_storage test.
This commit is contained in:
Kian Peymani
2019-07-25 11:58:47 +02:00
committed by Bastian Köcher
parent 80472956f8
commit 002acb9373
44 changed files with 844 additions and 259 deletions
+3 -1
View File
@@ -244,7 +244,7 @@ mod tests {
use substrate_primitives::{H256, Blake2Hasher};
// The testing primitives are very useful for avoiding having to work with signatures
// or public keys. `u64` is used as the `AccountId` and no `Signature`s are required.
use primitives::{traits::{BlakeTwo256, IdentityLookup}, testing::Header};
use primitives::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header};
impl_outer_origin! {
pub enum Origin for Test {}
@@ -259,6 +259,7 @@ mod tests {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Test {
type Origin = Origin;
@@ -273,6 +274,7 @@ mod tests {
type Event = ();
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
}
impl Trait for Test {
+3 -1
View File
@@ -19,7 +19,7 @@
#![cfg(test)]
use primitives::{
traits::IdentityLookup,
traits::IdentityLookup, Perbill,
testing::{Header, UintAuthorityId},
};
use srml_support::{impl_outer_origin, parameter_types};
@@ -39,6 +39,7 @@ parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
pub const MinimumPeriod: u64 = 1;
}
@@ -55,6 +56,7 @@ impl system::Trait for Test {
type Event = ();
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
}
+5
View File
@@ -28,6 +28,7 @@ use srml_support::dispatch::Result as DispatchResult;
use parity_codec::{Encode, Decode};
use system::ensure_none;
use primitives::traits::{SimpleArithmetic, Header as HeaderT, One, Zero};
use primitives::weights::SimpleDispatchInfo;
pub trait Trait: system::Trait {
/// Find the author of a block.
@@ -217,6 +218,7 @@ decl_module! {
}
/// Provide a set of uncles.
#[weight = SimpleDispatchInfo::FixedOperational(10_000)]
fn set_uncles(origin, new_uncles: Vec<T::Header>) -> DispatchResult {
ensure_none(origin)?;
@@ -326,6 +328,7 @@ mod tests {
use primitives::traits::{BlakeTwo256, IdentityLookup};
use primitives::testing::Header;
use primitives::generic::DigestItem;
use primitives::Perbill;
use srml_support::{parameter_types, impl_outer_origin, ConsensusEngineId};
impl_outer_origin!{
@@ -339,6 +342,7 @@ mod tests {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Test {
@@ -354,6 +358,7 @@ mod tests {
type Event = ();
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
}
+23 -8
View File
@@ -161,10 +161,10 @@ use srml_support::traits::{
use srml_support::dispatch::Result;
use primitives::traits::{
Zero, SimpleArithmetic, StaticLookup, Member, CheckedAdd, CheckedSub, MaybeSerializeDebug,
Saturating, Bounded, SignedExtension, SaturatedConversion, DispatchError
Saturating, Bounded, SignedExtension, SaturatedConversion, DispatchError, Convert,
};
use primitives::transaction_validity::{TransactionPriority, ValidTransaction};
use primitives::weights::DispatchInfo;
use primitives::weights::{DispatchInfo, SimpleDispatchInfo, Weight};
use system::{IsDeadAccount, OnNewAccount, ensure_signed, ensure_root};
mod mock;
@@ -206,6 +206,9 @@ pub trait Subtrait<I: Instance = DefaultInstance>: system::Trait {
/// The fee to be paid for making a transaction; the per-byte portion.
type TransactionByteFee: Get<Self::Balance>;
/// Convert a weight value into a deductible fee based on the currency type.
type WeightToFee: Convert<Weight, Self::Balance>;
}
pub trait Trait<I: Instance = DefaultInstance>: system::Trait {
@@ -249,6 +252,9 @@ pub trait Trait<I: Instance = DefaultInstance>: system::Trait {
/// The fee to be paid for making a transaction; the per-byte portion.
type TransactionByteFee: Get<Self::Balance>;
/// Convert a weight value into a deductible fee based on the currency type.
type WeightToFee: Convert<Weight, Self::Balance>;
}
impl<T: Trait<I>, I: Instance> Subtrait<I> for T {
@@ -260,6 +266,7 @@ impl<T: Trait<I>, I: Instance> Subtrait<I> for T {
type CreationFee = T::CreationFee;
type TransactionBaseFee = T::TransactionBaseFee;
type TransactionByteFee = T::TransactionByteFee;
type WeightToFee = T::WeightToFee;
}
decl_event!(
@@ -428,6 +435,7 @@ decl_module! {
/// `T::DustRemoval::on_unbalanced` and `T::OnFreeBalanceZero::on_free_balance_zero`.
///
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(1_000_000)]
pub fn transfer(
origin,
dest: <T::Lookup as StaticLookup>::Source,
@@ -451,6 +459,7 @@ decl_module! {
/// - Independent of the arguments.
/// - Contains a limited number of reads and writes.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedOperational(500_000)]
fn set_balance(
origin,
who: <T::Lookup as StaticLookup>::Source,
@@ -766,6 +775,7 @@ impl<T: Subtrait<I>, I: Instance> system::Trait for ElevatedTrait<T, I> {
type BlockHashCount = T::BlockHashCount;
type MaximumBlockWeight = T::MaximumBlockWeight;
type MaximumBlockLength = T::MaximumBlockLength;
type AvailableBlockRatio = T::AvailableBlockRatio;
}
impl<T: Subtrait<I>, I: Instance> Trait<I> for ElevatedTrait<T, I> {
type Balance = T::Balance;
@@ -780,6 +790,7 @@ impl<T: Subtrait<I>, I: Instance> Trait<I> for ElevatedTrait<T, I> {
type CreationFee = T::CreationFee;
type TransactionBaseFee = T::TransactionBaseFee;
type TransactionByteFee = T::TransactionByteFee;
type WeightToFee = T::WeightToFee;
}
impl<T: Trait<I>, I: Instance> Currency<T::AccountId> for Module<T, I>
@@ -1171,19 +1182,23 @@ impl<T: Trait<I>, I: Instance> TakeFees<T, I> {
/// - (optional) _tip_: if included in the transaction, it will be added on top. Only signed
/// transactions can have a tip.
fn compute_fee(len: usize, info: DispatchInfo, tip: T::Balance) -> T::Balance {
// length fee
let len_fee = if info.pay_length_fee() {
let len = T::Balance::from(len as u32);
let base = T::TransactionBaseFee::get();
let byte = T::TransactionByteFee::get();
base.saturating_add(byte.saturating_mul(len))
let per_byte = T::TransactionByteFee::get();
base.saturating_add(per_byte.saturating_mul(len))
} else {
Zero::zero()
};
// weight fee
let weight = info.weight;
let weight_fee: T::Balance = <system::Module<T>>::next_weight_multiplier().apply_to(weight).into();
let weight_fee = {
// cap the weight to the maximum defined in runtime, otherwise it will be the `Bounded`
// maximum of its data type, which is not desired.
let capped_weight = info.weight.min(<T as system::Trait>::MaximumBlockWeight::get());
let weight_update = <system::Module<T>>::next_weight_multiplier();
let adjusted_weight = weight_update.apply_to(capped_weight);
T::WeightToFee::convert(adjusted_weight)
};
len_fee.saturating_add(weight_fee).saturating_add(tip)
}
+18 -2
View File
@@ -18,7 +18,7 @@
#![cfg(test)]
use primitives::{traits::IdentityLookup, testing::Header, weights::{DispatchInfo, Weight}};
use primitives::{Perbill, traits::{Convert, IdentityLookup}, testing::Header, weights::{DispatchInfo, Weight}};
use substrate_primitives::{H256, Blake2Hasher};
use runtime_io;
use srml_support::{impl_outer_origin, parameter_types};
@@ -36,6 +36,8 @@ thread_local! {
static CREATION_FEE: RefCell<u64> = RefCell::new(0);
static TRANSACTION_BASE_FEE: RefCell<u64> = RefCell::new(0);
static TRANSACTION_BYTE_FEE: RefCell<u64> = RefCell::new(1);
static TRANSACTION_WEIGHT_FEE: RefCell<u64> = RefCell::new(1);
static WEIGHT_TO_FEE: RefCell<u64> = RefCell::new(1);
}
pub struct ExistentialDeposit;
@@ -63,6 +65,13 @@ impl Get<u64> for TransactionByteFee {
fn get() -> u64 { TRANSACTION_BYTE_FEE.with(|v| *v.borrow()) }
}
pub struct WeightToFee(u64);
impl Convert<Weight, u64> for WeightToFee {
fn convert(t: Weight) -> u64 {
WEIGHT_TO_FEE.with(|v| *v.borrow() * (t as u64))
}
}
// Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Runtime;
@@ -70,6 +79,7 @@ parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Runtime {
type Origin = Origin;
@@ -85,6 +95,7 @@ impl system::Trait for Runtime {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
}
impl Trait for Runtime {
type Balance = u64;
@@ -99,11 +110,13 @@ impl Trait for Runtime {
type CreationFee = CreationFee;
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = WeightToFee;
}
pub struct ExtBuilder {
transaction_base_fee: u64,
transaction_byte_fee: u64,
weight_to_fee: u64,
existential_deposit: u64,
transfer_fee: u64,
creation_fee: u64,
@@ -115,6 +128,7 @@ impl Default for ExtBuilder {
Self {
transaction_base_fee: 0,
transaction_byte_fee: 0,
weight_to_fee: 0,
existential_deposit: 0,
transfer_fee: 0,
creation_fee: 0,
@@ -124,9 +138,10 @@ impl Default for ExtBuilder {
}
}
impl ExtBuilder {
pub fn transaction_fees(mut self, base_fee: u64, byte_fee: u64) -> Self {
pub fn transaction_fees(mut self, base_fee: u64, byte_fee: u64, weight_fee: u64) -> Self {
self.transaction_base_fee = base_fee;
self.transaction_byte_fee = byte_fee;
self.weight_to_fee = weight_fee;
self
}
pub fn existential_deposit(mut self, existential_deposit: u64) -> Self {
@@ -159,6 +174,7 @@ impl ExtBuilder {
CREATION_FEE.with(|v| *v.borrow_mut() = self.creation_fee);
TRANSACTION_BASE_FEE.with(|v| *v.borrow_mut() = self.transaction_base_fee);
TRANSACTION_BYTE_FEE.with(|v| *v.borrow_mut() = self.transaction_byte_fee);
WEIGHT_TO_FEE.with(|v| *v.borrow_mut() = self.weight_to_fee);
}
pub fn build(self) -> runtime_io::TestExternalities<Blake2Hasher> {
self.set_associated_consts();
+27 -5
View File
@@ -114,7 +114,7 @@ fn lock_reasons_should_work() {
with_externalities(
&mut ExtBuilder::default()
.existential_deposit(1)
.monied(true).transaction_fees(0, 1)
.monied(true).transaction_fees(0, 1, 0)
.build(),
|| {
Balances::set_lock(ID_1, &1, 10, u64::max_value(), WithdrawReason::Transfer.into());
@@ -752,15 +752,37 @@ fn signed_extension_take_fees_work() {
with_externalities(
&mut ExtBuilder::default()
.existential_deposit(10)
.transaction_fees(10, 1)
.transaction_fees(10, 1, 5)
.monied(true)
.build(),
|| {
let len = 10;
assert!(TakeFees::<Runtime>::from(0).pre_dispatch(&1, info_from_weight(0), len).is_ok());
assert_eq!(Balances::free_balance(&1), 100 - 20);
assert!(TakeFees::<Runtime>::from(5 /* tipped */).pre_dispatch(&1, info_from_weight(0), len).is_ok());
assert!(TakeFees::<Runtime>::from(0).pre_dispatch(&1, info_from_weight(5), len).is_ok());
assert_eq!(Balances::free_balance(&1), 100 - 20 - 25);
assert!(TakeFees::<Runtime>::from(5 /* tipped */).pre_dispatch(&1, info_from_weight(3), len).is_ok());
assert_eq!(Balances::free_balance(&1), 100 - 20 - 25 - 20 - 5 - 15);
}
);
}
#[test]
fn signed_extension_take_fees_is_bounded() {
with_externalities(
&mut ExtBuilder::default()
.existential_deposit(1000)
.transaction_fees(0, 0, 1)
.monied(true)
.build(),
|| {
use primitives::weights::Weight;
// maximum weight possible
assert!(TakeFees::<Runtime>::from(0).pre_dispatch(&1, info_from_weight(Weight::max_value()), 10).is_ok());
// fee will be proportional to what is the actual maximum weight in the runtime.
assert_eq!(
Balances::free_balance(&1),
(10000 - <Runtime as system::Trait>::MaximumBlockWeight::get()) as u64
);
}
);
}
+21 -13
View File
@@ -23,6 +23,7 @@
use rstd::{prelude::*, result};
use substrate_primitives::u32_trait::Value as U32;
use primitives::traits::{Hash, EnsureOrigin};
use primitives::weights::SimpleDispatchInfo;
use srml_support::{
dispatch::{Dispatchable, Parameter}, codec::{Encode, Decode}, traits::ChangeMembers,
StorageValue, StorageMap, decl_module, decl_event, decl_storage, ensure
@@ -118,6 +119,9 @@ decl_event!(
}
);
// Note: this module is not benchmarked. The weights are obtained based on the similarity fo the
// executed logic with other democracy function. Note that councillor operations are assigned to the
// operational class.
decl_module! {
pub struct Module<T: Trait<I>, I: Instance=DefaultInstance> for enum Call where origin: <T as system::Trait>::Origin {
fn deposit_event<T, I>() = default;
@@ -126,6 +130,7 @@ decl_module! {
/// provide it pre-sorted.
///
/// Requires root origin.
#[weight = SimpleDispatchInfo::FixedOperational(100_000)]
fn set_members(origin, new_members: Vec<T::AccountId>) {
ensure_root(origin)?;
@@ -168,6 +173,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)]
fn execute(origin, proposal: Box<<T as Trait<I>>::Proposal>) {
let who = ensure_signed(origin)?;
ensure!(Self::is_member(&who), "proposer not a member");
@@ -181,9 +187,9 @@ decl_module! {
/// - Bounded storage reads and writes.
/// - Argument `threshold` has bearing on weight.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedOperational(5_000_000)]
fn propose(origin, #[compact] threshold: MemberCount, proposal: Box<<T as Trait<I>>::Proposal>) {
let who = ensure_signed(origin)?;
ensure!(Self::is_member(&who), "proposer not a member");
let proposal_hash = T::Hashing::hash_of(&proposal);
@@ -210,9 +216,9 @@ decl_module! {
/// - Bounded storage read and writes.
/// - Will be slightly heavier if the proposal is approved / disapproved after the vote.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedOperational(200_000)]
fn vote(origin, proposal: T::Hash, #[compact] index: ProposalIndex, approve: bool) {
let who = ensure_signed(origin)?;
ensure!(Self::is_member(&who), "voter not a member");
let mut voting = Self::voting(&proposal).ok_or("proposal must exist")?;
@@ -393,7 +399,7 @@ mod tests {
use runtime_io::with_externalities;
use substrate_primitives::{H256, Blake2Hasher};
use primitives::{
traits::{BlakeTwo256, IdentityLookup, Block as BlockT}, testing::Header, BuildStorage
Perbill, traits::{BlakeTwo256, IdentityLookup, Block as BlockT}, testing::Header, BuildStorage
};
use crate as collective;
@@ -401,6 +407,7 @@ mod tests {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Test {
type Origin = Origin;
@@ -416,6 +423,7 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
}
impl Trait<Instance1> for Test {
type Origin = Origin;
@@ -554,7 +562,7 @@ mod tests {
event: Event::collective_Instance1(RawEvent::Proposed(
1,
0,
hex!["10b209e55d0f37cd45574674bba42519a29bf0ccf3c85c3c773fcbacab820bb4"].into(),
hex!["68eea8f20b542ec656c6ac2d10435ae3bd1729efc34d1354ab85af840aad2d35"].into(),
3,
)),
topics: vec![],
@@ -622,7 +630,7 @@ mod tests {
event: Event::collective_Instance1(RawEvent::Proposed(
1,
0,
hex!["10b209e55d0f37cd45574674bba42519a29bf0ccf3c85c3c773fcbacab820bb4"].into(),
hex!["68eea8f20b542ec656c6ac2d10435ae3bd1729efc34d1354ab85af840aad2d35"].into(),
2,
)),
topics: vec![],
@@ -631,7 +639,7 @@ mod tests {
phase: Phase::Finalization,
event: Event::collective_Instance1(RawEvent::Voted(
1,
hex!["10b209e55d0f37cd45574674bba42519a29bf0ccf3c85c3c773fcbacab820bb4"].into(),
hex!["68eea8f20b542ec656c6ac2d10435ae3bd1729efc34d1354ab85af840aad2d35"].into(),
false,
0,
1,
@@ -658,7 +666,7 @@ mod tests {
RawEvent::Proposed(
1,
0,
hex!["10b209e55d0f37cd45574674bba42519a29bf0ccf3c85c3c773fcbacab820bb4"].into(),
hex!["68eea8f20b542ec656c6ac2d10435ae3bd1729efc34d1354ab85af840aad2d35"].into(),
3,
)),
topics: vec![],
@@ -667,7 +675,7 @@ mod tests {
phase: Phase::Finalization,
event: Event::collective_Instance1(RawEvent::Voted(
2,
hex!["10b209e55d0f37cd45574674bba42519a29bf0ccf3c85c3c773fcbacab820bb4"].into(),
hex!["68eea8f20b542ec656c6ac2d10435ae3bd1729efc34d1354ab85af840aad2d35"].into(),
false,
1,
1,
@@ -677,7 +685,7 @@ mod tests {
EventRecord {
phase: Phase::Finalization,
event: Event::collective_Instance1(RawEvent::Disapproved(
hex!["10b209e55d0f37cd45574674bba42519a29bf0ccf3c85c3c773fcbacab820bb4"].into(),
hex!["68eea8f20b542ec656c6ac2d10435ae3bd1729efc34d1354ab85af840aad2d35"].into(),
)),
topics: vec![],
}
@@ -700,7 +708,7 @@ mod tests {
event: Event::collective_Instance1(RawEvent::Proposed(
1,
0,
hex!["10b209e55d0f37cd45574674bba42519a29bf0ccf3c85c3c773fcbacab820bb4"].into(),
hex!["68eea8f20b542ec656c6ac2d10435ae3bd1729efc34d1354ab85af840aad2d35"].into(),
2,
)),
topics: vec![],
@@ -709,7 +717,7 @@ mod tests {
phase: Phase::Finalization,
event: Event::collective_Instance1(RawEvent::Voted(
2,
hex!["10b209e55d0f37cd45574674bba42519a29bf0ccf3c85c3c773fcbacab820bb4"].into(),
hex!["68eea8f20b542ec656c6ac2d10435ae3bd1729efc34d1354ab85af840aad2d35"].into(),
true,
2,
0,
@@ -719,14 +727,14 @@ mod tests {
EventRecord {
phase: Phase::Finalization,
event: Event::collective_Instance1(RawEvent::Approved(
hex!["10b209e55d0f37cd45574674bba42519a29bf0ccf3c85c3c773fcbacab820bb4"].into(),
hex!["68eea8f20b542ec656c6ac2d10435ae3bd1729efc34d1354ab85af840aad2d35"].into(),
)),
topics: vec![],
},
EventRecord {
phase: Phase::Finalization,
event: Event::collective_Instance1(RawEvent::Executed(
hex!["10b209e55d0f37cd45574674bba42519a29bf0ccf3c85c3c773fcbacab820bb4"].into(),
hex!["68eea8f20b542ec656c6ac2d10435ae3bd1729efc34d1354ab85af840aad2d35"].into(),
false,
)),
topics: vec![],
+4 -1
View File
@@ -31,7 +31,7 @@ use runtime_io;
use runtime_io::with_externalities;
use runtime_primitives::testing::{Digest, DigestItem, Header, UintAuthorityId, H256};
use runtime_primitives::traits::{BlakeTwo256, Hash, IdentityLookup};
use runtime_primitives::BuildStorage;
use runtime_primitives::{Perbill, BuildStorage};
use srml_support::{
assert_ok, assert_err, impl_outer_dispatch, impl_outer_event, impl_outer_origin, parameter_types,
storage::child, StorageMap, StorageValue, traits::{Currency, Get},
@@ -100,6 +100,7 @@ parameter_types! {
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const BalancesTransactionBaseFee: u64 = 0;
pub const BalancesTransactionByteFee: u64 = 0;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Test {
type Origin = Origin;
@@ -114,6 +115,7 @@ impl system::Trait for Test {
type Event = MetaEvent;
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
}
impl balances::Trait for Test {
@@ -129,6 +131,7 @@ impl balances::Trait for Test {
type CreationFee = CreationFee;
type TransactionBaseFee = BalancesTransactionBaseFee;
type TransactionByteFee = BalancesTransactionByteFee;
type WeightToFee = ();
}
parameter_types! {
pub const MinimumPeriod: u64 = 1;
+4
View File
@@ -44,6 +44,7 @@ mod tests {
pub use substrate_primitives::{H256, Blake2Hasher, u32_trait::{_1, _2, _3, _4}};
pub use primitives::traits::{BlakeTwo256, IdentityLookup};
pub use primitives::testing::{Digest, DigestItem, Header};
pub use primitives::Perbill;
pub use {seats, motions};
use std::cell::RefCell;
@@ -100,6 +101,7 @@ mod tests {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Test {
type Origin = Origin;
@@ -115,6 +117,7 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
}
parameter_types! {
pub const ExistentialDeposit: u64 = 0;
@@ -136,6 +139,7 @@ mod tests {
type CreationFee = CreationFee;
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = ();
}
parameter_types! {
pub const LaunchPeriod: u64 = 1;
+22
View File
@@ -21,6 +21,7 @@
use rstd::prelude::*;
use rstd::{result, convert::TryFrom};
use primitives::traits::{Zero, Bounded, CheckedMul, CheckedDiv, EnsureOrigin, Hash};
use primitives::weights::SimpleDispatchInfo;
use parity_codec::{Encode, Decode, Input, Output};
use srml_support::{
decl_module, decl_storage, decl_event, ensure,
@@ -359,6 +360,7 @@ decl_module! {
/// - O(1).
/// - Two DB changes, one DB entry.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(5_000_000)]
fn propose(origin,
proposal: Box<T::Proposal>,
#[compact] value: BalanceOf<T>
@@ -386,6 +388,7 @@ decl_module! {
/// - O(1).
/// - One DB entry.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(5_000_000)]
fn second(origin, #[compact] proposal: PropIndex) {
let who = ensure_signed(origin)?;
let mut deposit = Self::deposit_of(proposal)
@@ -403,6 +406,7 @@ decl_module! {
/// - O(1).
/// - One DB change, one DB entry.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(200_000)]
fn vote(origin,
#[compact] ref_index: ReferendumIndex,
vote: Vote
@@ -418,6 +422,7 @@ decl_module! {
/// - O(1).
/// - One DB change, one DB entry.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(200_000)]
fn proxy_vote(origin,
#[compact] ref_index: ReferendumIndex,
vote: Vote
@@ -432,6 +437,7 @@ decl_module! {
/// exceed `threshold` and, if approved, enacted after the given `delay`.
///
/// It may be called from either the Root or the Emergency origin.
#[weight = SimpleDispatchInfo::FixedOperational(500_000)]
fn emergency_propose(origin,
proposal: Box<T::Proposal>,
threshold: VoteThreshold,
@@ -453,6 +459,7 @@ decl_module! {
/// Schedule an emergency cancellation of a referendum. Cannot happen twice to the same
/// referendum.
#[weight = SimpleDispatchInfo::FixedOperational(500_000)]
fn emergency_cancel(origin, ref_index: ReferendumIndex) {
T::CancellationOrigin::ensure_origin(origin)?;
@@ -466,6 +473,7 @@ decl_module! {
/// Schedule a referendum to be tabled once it is legal to schedule an external
/// referendum.
#[weight = SimpleDispatchInfo::FixedNormal(5_000_000)]
fn external_propose(origin, proposal: Box<T::Proposal>) {
T::ExternalOrigin::ensure_origin(origin)?;
ensure!(!<NextExternal<T>>::exists(), "proposal already made");
@@ -478,6 +486,7 @@ decl_module! {
/// Schedule a majority-carries referendum to be tabled next once it is legal to schedule
/// an external referendum.
#[weight = SimpleDispatchInfo::FixedNormal(5_000_000)]
fn external_propose_majority(origin, proposal: Box<T::Proposal>) {
T::ExternalMajorityOrigin::ensure_origin(origin)?;
ensure!(!<NextExternal<T>>::exists(), "proposal already made");
@@ -496,6 +505,7 @@ decl_module! {
/// - `voting_period`: The period that is allowed for voting on this proposal.
/// - `delay`: The number of block after voting has ended in approval and this should be
/// enacted. Increased to `EmergencyVotingPeriod` if too low.
#[weight = SimpleDispatchInfo::FixedNormal(200_000)]
fn external_push(origin,
proposal_hash: T::Hash,
voting_period: T::BlockNumber,
@@ -514,6 +524,7 @@ decl_module! {
}
/// Veto and blacklist the external proposal hash.
#[weight = SimpleDispatchInfo::FixedNormal(200_000)]
fn veto_external(origin, proposal_hash: T::Hash) {
let who = T::VetoOrigin::ensure_origin(origin)?;
@@ -538,12 +549,14 @@ decl_module! {
}
/// Remove a referendum.
#[weight = SimpleDispatchInfo::FixedOperational(10_000)]
fn cancel_referendum(origin, #[compact] ref_index: ReferendumIndex) {
ensure_root(origin)?;
Self::clear_referendum(ref_index);
}
/// Cancel a proposal queued for enactment.
#[weight = SimpleDispatchInfo::FixedOperational(10_000)]
fn cancel_queued(
origin,
#[compact] when: T::BlockNumber,
@@ -572,6 +585,7 @@ decl_module! {
/// # <weight>
/// - One extra DB entry.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(100_000)]
fn set_proxy(origin, proxy: T::AccountId) {
let who = ensure_signed(origin)?;
ensure!(!<Proxy<T>>::exists(&proxy), "already a proxy");
@@ -583,6 +597,7 @@ decl_module! {
/// # <weight>
/// - One DB clear.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(100_000)]
fn resign_proxy(origin) {
let who = ensure_signed(origin)?;
<Proxy<T>>::remove(who);
@@ -593,6 +608,7 @@ decl_module! {
/// # <weight>
/// - One DB clear.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(100_000)]
fn remove_proxy(origin, proxy: T::AccountId) {
let who = ensure_signed(origin)?;
ensure!(&Self::proxy(&proxy).ok_or("not a proxy")? == &who, "wrong proxy");
@@ -604,6 +620,7 @@ decl_module! {
/// # <weight>
/// - One extra DB entry.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
pub fn delegate(origin, to: T::AccountId, conviction: Conviction) {
let who = ensure_signed(origin)?;
<Delegations<T>>::insert(who.clone(), (to.clone(), conviction));
@@ -623,6 +640,7 @@ decl_module! {
/// # <weight>
/// - O(1).
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
fn undelegate(origin) {
let who = ensure_signed(origin)?;
ensure!(<Delegations<T>>::exists(&who), "not delegated");
@@ -974,6 +992,7 @@ mod tests {
};
use substrate_primitives::{H256, Blake2Hasher};
use primitives::{traits::{BlakeTwo256, IdentityLookup, Bounded}, testing::Header};
use primitives::Perbill;
use balances::BalanceLock;
use system::EnsureSignedBy;
@@ -1000,6 +1019,7 @@ mod tests {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Test {
type Origin = Origin;
@@ -1015,6 +1035,7 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
}
parameter_types! {
pub const ExistentialDeposit: u64 = 0;
@@ -1036,6 +1057,7 @@ mod tests {
type CreationFee = CreationFee;
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = ();
}
parameter_types! {
pub const LaunchPeriod: u64 = 2;
+15 -1
View File
@@ -25,6 +25,7 @@
use rstd::prelude::*;
use primitives::traits::{Zero, One, StaticLookup, Bounded, Saturating};
use primitives::weights::SimpleDispatchInfo;
use runtime_io::print;
use srml_support::{
StorageValue, StorageMap,
@@ -331,6 +332,7 @@ decl_module! {
/// - Two extra DB entries, one DB change.
/// - Argument `votes` is limited in length to number of candidates.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(2_500_000)]
fn set_approvals(origin, votes: Vec<bool>, #[compact] index: VoteIndex, hint: SetIndex) -> Result {
let who = ensure_signed(origin)?;
Self::do_set_approvals(who, votes, index, hint)
@@ -342,6 +344,7 @@ decl_module! {
/// # <weight>
/// - Same as `set_approvals` with one additional storage read.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(2_500_000)]
fn proxy_set_approvals(origin,
votes: Vec<bool>,
#[compact] index: VoteIndex,
@@ -363,6 +366,7 @@ decl_module! {
/// - O(1).
/// - Two fewer DB entries, one DB change.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(2_500_000)]
fn reap_inactive_voter(
origin,
#[compact] reporter_index: u32,
@@ -436,6 +440,7 @@ decl_module! {
/// - O(1).
/// - Two fewer DB entries, one DB change.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(1_250_000)]
fn retract_voter(origin, #[compact] index: u32) {
let who = ensure_signed(origin)?;
@@ -463,6 +468,7 @@ decl_module! {
/// - Independent of input.
/// - Three DB changes.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(2_500_000)]
fn submit_candidacy(origin, #[compact] slot: u32) {
let who = ensure_signed(origin)?;
@@ -498,6 +504,7 @@ decl_module! {
/// - O(voters) compute.
/// - One DB change.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(10_000_000)]
fn present_winner(
origin,
candidate: <T::Lookup as StaticLookup>::Source,
@@ -566,6 +573,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)]
fn set_desired_seats(origin, #[compact] count: u32) {
ensure_root(origin)?;
DesiredSeats::put(count);
@@ -575,6 +583,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)]
fn remove_member(origin, who: <T::Lookup as StaticLookup>::Source) {
ensure_root(origin)?;
let who = T::Lookup::lookup(who)?;
@@ -589,6 +598,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)]
fn set_presentation_duration(origin, #[compact] count: T::BlockNumber) {
ensure_root(origin)?;
<PresentationDuration<T>>::put(count);
@@ -596,6 +606,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)]
fn set_term_duration(origin, #[compact] count: T::BlockNumber) {
ensure_root(origin)?;
<TermDuration<T>>::put(count);
@@ -1107,7 +1118,7 @@ mod tests {
use runtime_io::with_externalities;
use substrate_primitives::{H256, Blake2Hasher};
use primitives::{
traits::{BlakeTwo256, IdentityLookup, Block as BlockT}, testing::Header, BuildStorage
Perbill, traits::{BlakeTwo256, IdentityLookup, Block as BlockT}, testing::Header, BuildStorage
};
use crate as elections;
@@ -1115,6 +1126,7 @@ mod tests {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Test {
type Origin = Origin;
@@ -1130,6 +1142,7 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
}
parameter_types! {
pub const ExistentialDeposit: u64 = 0;
@@ -1151,6 +1164,7 @@ mod tests {
type CreationFee = CreationFee;
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = ();
}
parameter_types! {
pub const CandidacyBond: u64 = 3;
+4 -1
View File
@@ -510,7 +510,7 @@ mod tests {
// The testing primitives are very useful for avoiding having to work with signatures
// or public keys. `u64` is used as the `AccountId` and no `Signature`s are requried.
use sr_primitives::{
traits::{BlakeTwo256, OnInitialize, OnFinalize, IdentityLookup}, testing::Header
Perbill, traits::{BlakeTwo256, OnInitialize, OnFinalize, IdentityLookup}, testing::Header
};
impl_outer_origin! {
@@ -526,6 +526,7 @@ mod tests {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Test {
type Origin = Origin;
@@ -541,6 +542,7 @@ mod tests {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
}
parameter_types! {
pub const ExistentialDeposit: u64 = 0;
@@ -562,6 +564,7 @@ mod tests {
type CreationFee = CreationFee;
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = ();
}
impl Trait for Test {
type Event = ();
+15 -9
View File
@@ -108,6 +108,7 @@ mod internal {
fn from(d: DispatchError) -> Self {
match d {
DispatchError::Payment => ApplyError::CantPay,
DispatchError::Resource => ApplyError::FullBlock,
DispatchError::NoPermission => ApplyError::CantPay,
DispatchError::BadState => ApplyError::CantPay,
DispatchError::Stale => ApplyError::Stale,
@@ -357,10 +358,12 @@ mod tests {
use runtime_io::with_externalities;
use substrate_primitives::{H256, Blake2Hasher};
use primitives::generic::Era;
use primitives::traits::{Header as HeaderT, BlakeTwo256, IdentityLookup};
use primitives::Perbill;
use primitives::weights::Weight;
use primitives::traits::{Header as HeaderT, BlakeTwo256, IdentityLookup, ConvertInto};
use primitives::testing::{Digest, Header, Block};
use srml_support::{impl_outer_event, impl_outer_origin, parameter_types};
use srml_support::traits::{Currency, LockIdentifier, LockableCurrency, WithdrawReasons, WithdrawReason, Get};
use srml_support::traits::{Currency, LockIdentifier, LockableCurrency, WithdrawReasons, WithdrawReason};
use system;
use hex_literal::hex;
@@ -382,6 +385,7 @@ mod tests {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Runtime {
type Origin = Origin;
@@ -396,6 +400,7 @@ mod tests {
type BlockHashCount = BlockHashCount;
type WeightMultiplierUpdate = ();
type MaximumBlockWeight = MaximumBlockWeight;
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
}
parameter_types! {
@@ -418,6 +423,7 @@ mod tests {
type CreationFee = CreationFee;
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = ConvertInto;
}
impl ValidateUnsigned for Runtime {
@@ -457,7 +463,7 @@ mod tests {
fn balance_transfer_dispatch_works() {
let mut t = system::GenesisConfig::default().build_storage::<Runtime>().unwrap();
balances::GenesisConfig::<Runtime> {
balances: vec![(1, 111)],
balances: vec![(1, 211)],
vesting: vec![],
}.assimilate_storage(&mut t.0, &mut t.1).unwrap();
let xt = primitives::testing::TestXt(sign_extra(1, 0, 0), Call::transfer(2, 69));
@@ -473,7 +479,7 @@ mod tests {
));
let r = Executive::apply_extrinsic(xt);
assert_eq!(r, Ok(ApplyOutcome::Success));
assert_eq!(<balances::Module<Runtime>>::total_balance(&1), 42 - 10 - weight);
assert_eq!(<balances::Module<Runtime>>::total_balance(&1), 142 - 10 - weight);
assert_eq!(<balances::Module<Runtime>>::total_balance(&2), 69);
});
}
@@ -561,8 +567,8 @@ mod tests {
// given: TestXt uses the encoded len as fixed Len:
let xt = primitives::testing::TestXt(sign_extra(1, 0, 0), Call::transfer::<Runtime>(33, 0));
let encoded = xt.encode();
let encoded_len = encoded.len() as u32;
let limit = <MaximumBlockWeight as Get<u32>>::get() / 4;
let encoded_len = encoded.len() as Weight;
let limit = AvailableBlockRatio::get() * MaximumBlockWeight::get();
let num_to_exhaust_block = limit / encoded_len;
with_externalities(&mut t, || {
Executive::initialize_block(&Header::new(
@@ -580,9 +586,9 @@ mod tests {
if nonce != num_to_exhaust_block {
assert_eq!(res.unwrap(), ApplyOutcome::Success);
assert_eq!(<system::Module<Runtime>>::all_extrinsics_weight(), encoded_len * (nonce + 1));
assert_eq!(<system::Module<Runtime>>::extrinsic_index(), Some(nonce + 1));
assert_eq!(<system::Module<Runtime>>::extrinsic_index(), Some(nonce as u32 + 1));
} else {
assert_eq!(res, Err(ApplyError::CantPay));
assert_eq!(res, Err(ApplyError::FullBlock));
}
}
});
@@ -604,7 +610,7 @@ mod tests {
assert_eq!(Executive::apply_extrinsic(x2.clone()).unwrap(), ApplyOutcome::Success);
// default weight for `TestXt` == encoded length.
assert_eq!( <system::Module<Runtime>>::all_extrinsics_weight(), 3 * len);
assert_eq!(<system::Module<Runtime>>::all_extrinsics_weight(), (3 * len).into());
assert_eq!(<system::Module<Runtime>>::all_extrinsics_len(), 3 * len);
let _ = <system::Module<Runtime>>::finalize();
@@ -268,6 +268,7 @@ mod tests {
use substrate_primitives::H256;
use primitives::traits::{BlakeTwo256, IdentityLookup, OnFinalize, Header as HeaderT};
use primitives::testing::Header;
use primitives::Perbill;
use srml_support::{assert_ok, impl_outer_origin, parameter_types};
use srml_system as system;
use std::cell::RefCell;
@@ -301,6 +302,7 @@ mod tests {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Test {
type Origin = Origin;
@@ -315,6 +317,7 @@ mod tests {
type Event = ();
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
}
parameter_types! {
+1
View File
@@ -1058,6 +1058,7 @@ impl<T: Subtrait> system::Trait for ElevatedTrait<T> {
type Event = ();
type MaximumBlockWeight = T::MaximumBlockWeight;
type MaximumBlockLength = T::MaximumBlockLength;
type AvailableBlockRatio = T::AvailableBlockRatio;
type WeightMultiplierUpdate = ();
type BlockHashCount = T::BlockHashCount;
}
+4 -5
View File
@@ -20,10 +20,7 @@
#![cfg(test)]
use primitives::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
};
use primitives::{Perbill, testing::Header, traits::{BlakeTwo256, IdentityLookup}};
use substrate_primitives::{Blake2Hasher, H256};
use support::{parameter_types, impl_outer_event, impl_outer_origin};
@@ -42,6 +39,7 @@ parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Test {
type Origin = Origin;
@@ -53,9 +51,10 @@ impl system::Trait for Test {
type Lookup = IdentityLookup<u64>;
type Header = Header;
type Event = TestEvent;
type WeightMultiplierUpdate = ();
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type WeightMultiplierUpdate = ();
type AvailableBlockRatio = AvailableBlockRatio;
type BlockHashCount = BlockHashCount;
}
+3 -1
View File
@@ -18,7 +18,7 @@
#![cfg(test)]
use primitives::{DigestItem, traits::IdentityLookup, testing::{Header, UintAuthorityId}};
use primitives::{Perbill, DigestItem, traits::IdentityLookup, testing::{Header, UintAuthorityId}};
use runtime_io;
use srml_support::{impl_outer_origin, impl_outer_event, parameter_types};
use substrate_primitives::{H256, Blake2Hasher};
@@ -45,6 +45,7 @@ parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Test {
type Origin = Origin;
@@ -60,6 +61,7 @@ impl system::Trait for Test {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
}
mod grandpa {
+3
View File
@@ -21,6 +21,7 @@
use std::collections::HashSet;
use ref_thread_local::{ref_thread_local, RefThreadLocal};
use primitives::testing::Header;
use primitives::Perbill;
use substrate_primitives::{H256, Blake2Hasher};
use srml_support::{impl_outer_origin, parameter_types};
use {runtime_io, system};
@@ -68,6 +69,7 @@ parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Runtime {
type Origin = Origin;
@@ -83,6 +85,7 @@ impl system::Trait for Runtime {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
}
impl Trait for Runtime {
type AccountIndex = u64;
+2
View File
@@ -122,6 +122,7 @@
use rstd::{prelude::*, marker::PhantomData, ops::{Sub, Rem}};
use parity_codec::Decode;
use primitives::KeyTypeId;
use primitives::weights::SimpleDispatchInfo;
use primitives::traits::{Convert, Zero, Member, OpaqueKeys, TypedKey};
use srml_support::{
dispatch::Result, ConsensusEngineId, StorageValue, StorageDoubleMap, for_each_tuple,
@@ -378,6 +379,7 @@ decl_module! {
/// - O(log n) in number of accounts.
/// - One extra DB entry.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(150_000)]
fn set_keys(origin, keys: T::Keys, proof: Vec<u8>) -> Result {
let who = ensure_signed(origin)?;
+3
View File
@@ -21,6 +21,7 @@ use std::cell::RefCell;
use srml_support::{impl_outer_origin, parameter_types};
use substrate_primitives::H256;
use primitives::{
Perbill,
traits::{BlakeTwo256, IdentityLookup, ConvertInto},
testing::{Header, UintAuthorityId}
};
@@ -116,6 +117,7 @@ parameter_types! {
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const MinimumPeriod: u64 = 5;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Test {
type Origin = Origin;
@@ -130,6 +132,7 @@ impl system::Trait for Test {
type Event = ();
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
}
impl timestamp::Trait for Test {
+14
View File
@@ -294,6 +294,7 @@ use srml_support::{
};
use session::{historical::OnSessionEnding, SelectInitialValidators, SessionIndex};
use primitives::Perbill;
use primitives::weights::SimpleDispatchInfo;
use primitives::traits::{
Convert, Zero, One, StaticLookup, CheckedSub, CheckedShl, Saturating, Bounded,
SaturatedConversion, SimpleArithmetic
@@ -696,6 +697,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>
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
fn bond(origin,
controller: <T::Lookup as StaticLookup>::Source,
#[compact] value: BalanceOf<T>,
@@ -743,6 +745,7 @@ decl_module! {
/// - O(1).
/// - One DB entry.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
fn bond_extra(origin, #[compact] max_additional: BalanceOf<T>) {
let stash = ensure_signed(origin)?;
@@ -782,6 +785,7 @@ decl_module! {
/// The only way to clean the aforementioned storage item is also user-controlled via `withdraw_unbonded`.
/// - One DB entry.
/// </weight>
#[weight = SimpleDispatchInfo::FixedNormal(400_000)]
fn unbond(origin, #[compact] value: BalanceOf<T>) {
let controller = ensure_signed(origin)?;
let mut ledger = Self::ledger(&controller).ok_or("not a controller")?;
@@ -823,6 +827,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>
#[weight = SimpleDispatchInfo::FixedNormal(400_000)]
fn withdraw_unbonded(origin) {
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or("not a controller")?;
@@ -854,6 +859,7 @@ decl_module! {
/// - Contains a limited number of reads.
/// - Writes are limited to the `origin` account key.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(750_000)]
fn validate(origin, prefs: ValidatorPrefs<BalanceOf<T>>) {
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or("not a controller")?;
@@ -877,6 +883,7 @@ decl_module! {
/// which is capped at `MAX_NOMINATIONS`.
/// - Both the reads and writes follow a similar pattern.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(750_000)]
fn nominate(origin, targets: Vec<<T::Lookup as StaticLookup>::Source>) {
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or("not a controller")?;
@@ -902,6 +909,7 @@ decl_module! {
/// - Contains one read.
/// - Writes are limited to the `origin` account key.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
fn chill(origin) {
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or("not a controller")?;
@@ -921,6 +929,7 @@ decl_module! {
/// - Contains a limited number of reads.
/// - Writes are limited to the `origin` account key.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
fn set_payee(origin, payee: RewardDestination) {
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or("not a controller")?;
@@ -939,6 +948,7 @@ decl_module! {
/// - Contains a limited number of reads.
/// - Writes are limited to the `origin` account key.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(750_000)]
fn set_controller(origin, controller: <T::Lookup as StaticLookup>::Source) {
let stash = ensure_signed(origin)?;
let old_controller = Self::bonded(&stash).ok_or("not a stash")?;
@@ -955,6 +965,7 @@ decl_module! {
}
/// The ideal number of validators.
#[weight = SimpleDispatchInfo::FixedOperational(150_000)]
fn set_validator_count(origin, #[compact] new: u32) {
ensure_root(origin)?;
ValidatorCount::put(new);
@@ -970,18 +981,21 @@ decl_module! {
/// - Triggers the Phragmen election. Expensive but not user-controlled.
/// - Depends on state: `O(|edges| * |validators|)`.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedOperational(10_000)]
fn force_new_era(origin) {
ensure_root(origin)?;
Self::apply_force_new_era()
}
/// Set the offline slash grace period.
#[weight = SimpleDispatchInfo::FixedOperational(10_000)]
fn set_offline_slash_grace(origin, #[compact] new: u32) {
ensure_root(origin)?;
OfflineSlashGrace::put(new);
}
/// Set the validators who cannot be slashed (if any).
#[weight = SimpleDispatchInfo::FixedOperational(10_000)]
fn set_invulnerables(origin, validators: Vec<T::AccountId>) {
ensure_root(origin)?;
<Invulnerables<T>>::put(validators);
+3
View File
@@ -104,6 +104,7 @@ parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Test {
type Origin = Origin;
@@ -118,6 +119,7 @@ impl system::Trait for Test {
type Event = ();
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
}
parameter_types! {
@@ -139,6 +141,7 @@ impl balances::Trait for Test {
type CreationFee = CreationFee;
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = ();
}
parameter_types! {
pub const Period: BlockNumber = 1;
+2
View File
@@ -88,6 +88,7 @@
use sr_std::prelude::*;
use sr_primitives::traits::StaticLookup;
use sr_primitives::weights::SimpleDispatchInfo;
use srml_support::{
StorageValue, Parameter, Dispatchable, decl_module, decl_event,
decl_storage, ensure
@@ -116,6 +117,7 @@ decl_module! {
/// - Limited storage reads.
/// - No DB writes.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedOperational(1_000_000)]
fn sudo(origin, proposal: Box<T::Proposal>) {
// This is a public call, so we ensure that the origin is some signed account.
let sender = ensure_signed(origin)?;
+4 -4
View File
@@ -1622,7 +1622,7 @@ mod tests {
fn aux_0(_origin) -> Result { unreachable!() }
fn aux_1(_origin, #[compact] _data: u32) -> Result { unreachable!() }
fn aux_2(_origin, _data: i32, _data2: String) -> Result { unreachable!() }
#[weight = SimpleDispatchInfo::FixedNormal(10)]
#[weight = SimpleDispatchInfo::FixedNormal(3)]
fn aux_3(_origin) -> Result { unreachable!() }
fn aux_4(_origin, _data: i32) -> Result { unreachable!() }
fn aux_5(_origin, _data: i32, #[compact] _data2: u32) -> Result { unreachable!() }
@@ -1772,7 +1772,7 @@ mod tests {
#[test]
fn weight_should_attach_to_call_enum() {
// max weight. not dependent on input.
// operational.
assert_eq!(
Call::<TraitImpl>::operational().get_dispatch_info(),
DispatchInfo { weight: 5, class: DispatchClass::Operational },
@@ -1780,12 +1780,12 @@ mod tests {
// default weight.
assert_eq!(
Call::<TraitImpl>::aux_0().get_dispatch_info(),
DispatchInfo { weight: 100, class: DispatchClass::Normal },
DispatchInfo { weight: 10_000, class: DispatchClass::Normal },
);
// custom basic
assert_eq!(
Call::<TraitImpl>::aux_3().get_dispatch_info(),
DispatchInfo { weight: 10, class: DispatchClass::Normal },
DispatchInfo { weight: 3, class: DispatchClass::Normal },
);
}
}
+31
View File
@@ -223,6 +223,37 @@ macro_rules! __assert_eq_uvec {
}
}
/// Checks that `$x` is equal to `$y` with an error rate of `$error`.
///
/// # Example
///
/// ```rust
/// # fn main() {
/// srml_support::assert_eq_error_rate!(10, 10, 0);
/// srml_support::assert_eq_error_rate!(10, 11, 1);
/// srml_support::assert_eq_error_rate!(12, 10, 2);
/// # }
/// ```
///
/// ```rust,should_panic
/// # fn main() {
/// srml_support::assert_eq_error_rate!(12, 10, 1);
/// # }
/// ```
#[macro_export]
#[cfg(feature = "std")]
macro_rules! assert_eq_error_rate {
($x:expr, $y:expr, $error:expr) => {
assert!(
($x) >= (($y) - ($error)) && ($x) <= (($y) + ($error)),
"{:?} != {:?} (with error rate {:?})",
$x,
$y,
$error,
);
};
}
/// The void type - it cannot exist.
// Oh rust, you crack me up...
#[derive(Clone, Eq, PartialEq)]
+3 -4
View File
@@ -19,10 +19,7 @@ use srml_system as system;
use srml_support::{decl_module, decl_event, impl_outer_origin, impl_outer_event};
use runtime_io::{with_externalities, Blake2Hasher};
use substrate_primitives::H256;
use primitives::{
traits::{BlakeTwo256, IdentityLookup},
testing::Header,
};
use primitives::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header};
mod module {
use super::*;
@@ -58,6 +55,7 @@ srml_support::parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 4 * 1024 * 1024;
pub const MaximumBlockLength: u32 = 4 * 1024 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);
}
#[derive(Clone, Eq, PartialEq)]
pub struct Runtime;
@@ -75,6 +73,7 @@ impl system::Trait for Runtime {
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
}
impl module::Trait for Runtime {
+66 -25
View File
@@ -78,7 +78,8 @@ use rstd::prelude::*;
use rstd::map;
use rstd::marker::PhantomData;
use primitives::generic::{self, Era};
use primitives::weights::{Weight, DispatchInfo, DispatchClass, WeightMultiplier};
use primitives::Perbill;
use primitives::weights::{Weight, DispatchInfo, DispatchClass, WeightMultiplier, SimpleDispatchInfo};
use primitives::transaction_validity::{ValidTransaction, TransactionPriority, TransactionLongevity};
use primitives::traits::{self, CheckEqual, SimpleArithmetic, Zero, SignedExtension, Convert,
SimpleBitOps, Hash, Member, MaybeDisplay, EnsureOrigin, CurrentHeight, BlockNumberToHash,
@@ -203,6 +204,12 @@ pub trait Trait: 'static + Eq + Clone {
/// The maximum length of a block (in bytes).
type MaximumBlockLength: Get<u32>;
/// The portion of the block that is available to normal transaction. The rest can only be used
/// by operational transactions. This can be applied to any resource limit managed by the system
/// module, including weight and length.
type AvailableBlockRatio: Get<Perbill>;
}
pub type DigestOf<T> = generic::Digest<<T as Trait>::Hash>;
@@ -218,24 +225,35 @@ decl_module! {
Self::deposit_event_indexed(&[], event);
}
/// A big dispatch that will disallow any other transaction to be included.
// TODO: this must be preferable available for testing really (not possible at the moment).
#[weight = SimpleDispatchInfo::MaxOperational]
fn fill_block(origin) {
ensure_root(origin)?;
}
/// Make some on-chain remark.
#[weight = SimpleDispatchInfo::FixedNormal(1_000_000)]
fn remark(origin, _remark: Vec<u8>) {
ensure_signed(origin)?;
}
/// Set the number of pages in the WebAssembly environment's heap.
#[weight = SimpleDispatchInfo::FixedOperational(10_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 code.
#[weight = SimpleDispatchInfo::FixedOperational(200_000)]
pub fn set_code(origin, new: Vec<u8>) {
ensure_root(origin)?;
storage::unhashed::put_raw(well_known_keys::CODE, &new);
}
/// Set some items of storage.
#[weight = SimpleDispatchInfo::FixedOperational(10_000)]
fn set_storage(origin, items: Vec<KeyValue>) {
ensure_root(origin)?;
for i in &items {
@@ -244,6 +262,7 @@ decl_module! {
}
/// Kill some items from storage.
#[weight = SimpleDispatchInfo::FixedOperational(10_000)]
fn kill_storage(origin, keys: Vec<Key>) {
ensure_root(origin)?;
for key in &keys {
@@ -792,26 +811,28 @@ pub struct CheckWeight<T: Trait + Send + Sync>(PhantomData<T>);
impl<T: Trait + Send + Sync> CheckWeight<T> {
/// Get the quota divisor of each dispatch class type. This indicates that all operational
/// Get the quota ratio of each dispatch class type. This indicates that all operational
/// dispatches can use the full capacity of any resource, while user-triggered ones can consume
/// a quarter.
fn get_dispatch_limit_divisor(class: DispatchClass) -> Weight {
/// a portion.
fn get_dispatch_limit_ratio(class: DispatchClass) -> Perbill {
match class {
DispatchClass::Operational => 1,
DispatchClass::Normal => 4,
DispatchClass::Operational => Perbill::one(),
// TODO: this must be some sort of a constant.
DispatchClass::Normal => T::AvailableBlockRatio::get(),
}
}
/// Checks if the current extrinsic can fit into the block with respect to block weight limits.
///
/// Upon successes, it returns the new block weight as a `Result`.
fn check_weight(info: DispatchInfo) -> Result<Weight, DispatchError> {
let current_weight = Module::<T>::all_extrinsics_weight();
let maximum_weight = T::MaximumBlockWeight::get();
let limit = maximum_weight / Self::get_dispatch_limit_divisor(info.class);
let limit = Self::get_dispatch_limit_ratio(info.class) * maximum_weight;
let added_weight = info.weight.min(limit);
let next_weight = current_weight.saturating_add(added_weight);
if next_weight > limit {
return Err(DispatchError::BadState)
return Err(DispatchError::Resource)
}
Ok(next_weight)
}
@@ -822,11 +843,11 @@ impl<T: Trait + Send + Sync> CheckWeight<T> {
fn check_block_length(info: DispatchInfo, len: usize) -> Result<u32, DispatchError> {
let current_len = Module::<T>::all_extrinsics_len();
let maximum_len = T::MaximumBlockLength::get();
let limit = maximum_len / Self::get_dispatch_limit_divisor(info.class);
let limit = Self::get_dispatch_limit_ratio(info.class) * maximum_len;
let added_len = len as u32;
let next_len = current_len.saturating_add(added_len);
if next_len > limit {
return Err(DispatchError::BadState)
return Err(DispatchError::Resource)
}
Ok(next_len)
}
@@ -872,8 +893,8 @@ impl<T: Trait + Send + Sync> SignedExtension for CheckWeight<T> {
len: usize,
) -> Result<ValidTransaction, DispatchError> {
// There is no point in writing to storage here since changes are discarded. This basically
// discards any transaction which is bigger than the length or weight limit alone, which is
// a guarantee that it will fail in the pre-dispatch phase.
// discards any transaction which is bigger than the length or weight limit **alone**,which
// is a guarantee that it will fail in the pre-dispatch phase.
let _ = Self::check_block_length(info, len)?;
let _ = Self::check_weight(info)?;
Ok(ValidTransaction { priority: Self::get_priority(info), ..Default::default() })
@@ -1035,7 +1056,8 @@ mod tests {
parameter_types! {
pub const BlockHashCount: u64 = 10;
pub const MaximumBlockWeight: Weight = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);
pub const MaximumBlockLength: u32 = 1024;
}
impl Trait for Test {
@@ -1051,6 +1073,7 @@ mod tests {
type Event = u16;
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
}
@@ -1069,6 +1092,14 @@ mod tests {
GenesisConfig::default().build_storage::<Test>().unwrap().0.into()
}
fn normal_weight_limit() -> Weight {
<Test as Trait>::AvailableBlockRatio::get() * <Test as Trait>::MaximumBlockWeight::get()
}
fn normal_length_limit() -> u32 {
<Test as Trait>::AvailableBlockRatio::get() * <Test as Trait>::MaximumBlockLength::get()
}
#[test]
fn origin_works() {
let o = Origin::from(RawOrigin::<u64>::Signed(1u64));
@@ -1222,15 +1253,16 @@ mod tests {
}
#[test]
fn signed_ext_check_weight_works_user_tx() {
fn signed_ext_check_weight_works_normal_tx() {
with_externalities(&mut new_test_ext(), || {
let normal_limit = normal_weight_limit();
let small = DispatchInfo { weight: 100, ..Default::default() };
let medium = DispatchInfo {
weight: <MaximumBlockWeight as Get<Weight>>::get() / 4 - 1,
weight: normal_limit - 1,
..Default::default()
};
let big = DispatchInfo {
weight: <MaximumBlockWeight as Get<Weight>>::get() / 4 + 1,
weight: normal_limit + 1,
..Default::default()
};
let len = 0_usize;
@@ -1265,11 +1297,12 @@ mod tests {
with_externalities(&mut new_test_ext(), || {
let max = DispatchInfo { weight: Weight::max_value(), ..Default::default() };
let len = 0_usize;
let normal_limit = normal_weight_limit();
assert_eq!(System::all_extrinsics_weight(), 0);
let r = CheckWeight::<Test>(PhantomData).pre_dispatch(&1, max, len);
assert!(r.is_ok());
assert_eq!(System::all_extrinsics_weight(), <MaximumBlockWeight as Get<Weight>>::get() / 4);
assert_eq!(System::all_extrinsics_weight(), normal_limit);
})
}
@@ -1279,9 +1312,10 @@ mod tests {
let normal = DispatchInfo { weight: 100, ..Default::default() };
let op = DispatchInfo { weight: 100, class: DispatchClass::Operational };
let len = 0_usize;
let normal_limit = normal_weight_limit();
// given almost full block
AllExtrinsicsWeight::put(<MaximumBlockWeight as Get<Weight>>::get() / 4);
AllExtrinsicsWeight::put(normal_limit);
// will not fit.
assert!(CheckWeight::<Test>(PhantomData).pre_dispatch(&1, normal, len).is_err());
// will fit.
@@ -1289,7 +1323,7 @@ mod tests {
// likewise for length limit.
let len = 100_usize;
AllExtrinsicsLen::put(<MaximumBlockLength as Get<Weight>>::get() / 4);
AllExtrinsicsLen::put(normal_length_limit());
assert!(CheckWeight::<Test>(PhantomData).pre_dispatch(&1, normal, len).is_err());
assert!(CheckWeight::<Test>(PhantomData).pre_dispatch(&1, op, len).is_ok());
})
@@ -1316,17 +1350,24 @@ mod tests {
#[test]
fn signed_ext_check_weight_block_size_works() {
with_externalities(&mut new_test_ext(), || {
let tx = DispatchInfo::default();
let reset_check_weight = |s, f| {
let normal = DispatchInfo::default();
let normal_limit = normal_weight_limit() as usize;
let reset_check_weight = |tx, s, f| {
AllExtrinsicsLen::put(0);
let r = CheckWeight::<Test>(PhantomData).pre_dispatch(&1, tx, s);
if f { assert!(r.is_err()) } else { assert!(r.is_ok()) }
};
reset_check_weight(128, false);
reset_check_weight(512, false);
reset_check_weight(513, true);
reset_check_weight(normal, normal_limit - 1, false);
reset_check_weight(normal, normal_limit, false);
reset_check_weight(normal, normal_limit + 1, true);
// Operational ones don't have this limit.
let op = DispatchInfo { weight: 0, class: DispatchClass::Operational };
reset_check_weight(op, normal_limit, false);
reset_check_weight(op, normal_limit + 100, false);
reset_check_weight(op, 1024, false);
reset_check_weight(op, 1025, true);
})
}
+5 -1
View File
@@ -99,6 +99,7 @@ use inherents::ProvideInherentData;
use srml_support::{StorageValue, Parameter, decl_storage, decl_module, for_each_tuple};
use srml_support::traits::{Time, Get};
use runtime_primitives::traits::{SimpleArithmetic, Zero, SaturatedConversion};
use runtime_primitives::weights::SimpleDispatchInfo;
use system::ensure_none;
use inherents::{RuntimeString, InherentIdentifier, ProvideInherent, IsFatalError, InherentData};
@@ -236,6 +237,7 @@ decl_module! {
/// `MinimumPeriod`.
///
/// The dispatch origin for this call must be `Inherent`.
#[weight = SimpleDispatchInfo::FixedOperational(10_000)]
fn set(origin, #[compact] now: T::Moment) {
ensure_none(origin)?;
assert!(!<Self as Store>::DidUpdate::exists(), "Timestamp must be updated only once in the block");
@@ -338,7 +340,7 @@ mod tests {
use srml_support::{impl_outer_origin, assert_ok, parameter_types};
use runtime_io::{with_externalities, TestExternalities};
use substrate_primitives::H256;
use runtime_primitives::{traits::{BlakeTwo256, IdentityLookup}, testing::Header};
use runtime_primitives::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header};
impl_outer_origin! {
pub enum Origin for Test {}
@@ -350,6 +352,7 @@ mod tests {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Test {
type Origin = Origin;
@@ -364,6 +367,7 @@ mod tests {
type Event = ();
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
}
parameter_types! {
+8 -1
View File
@@ -79,6 +79,7 @@ use runtime_primitives::{Permill, ModuleId};
use runtime_primitives::traits::{
Zero, EnsureOrigin, StaticLookup, CheckedSub, CheckedMul, AccountIdConversion
};
use runtime_primitives::weights::SimpleDispatchInfo;
use parity_codec::{Encode, Decode};
use system::ensure_signed;
@@ -153,6 +154,7 @@ decl_module! {
/// - Limited storage reads.
/// - One DB change, one extra DB entry.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
fn propose_spend(
origin,
#[compact] value: BalanceOf<T>,
@@ -179,6 +181,7 @@ decl_module! {
/// - Limited storage reads.
/// - One DB clear.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedOperational(100_000)]
fn reject_proposal(origin, #[compact] proposal_id: ProposalIndex) {
T::RejectOrigin::ensure_origin(origin)?;
let proposal = <Proposals<T>>::take(proposal_id).ok_or("No proposal at that index")?;
@@ -196,6 +199,7 @@ decl_module! {
/// - Limited storage reads.
/// - One DB change.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedOperational(100_000)]
fn approve_proposal(origin, #[compact] proposal_id: ProposalIndex) {
T::ApproveOrigin::ensure_origin(origin)?;
@@ -360,7 +364,7 @@ mod tests {
use runtime_io::with_externalities;
use srml_support::{assert_noop, assert_ok, impl_outer_origin, parameter_types};
use substrate_primitives::{H256, Blake2Hasher};
use runtime_primitives::{traits::{BlakeTwo256, OnFinalize, IdentityLookup}, testing::Header};
use runtime_primitives::{Perbill, traits::{BlakeTwo256, OnFinalize, IdentityLookup}, testing::Header};
impl_outer_origin! {
pub enum Origin for Test {}
@@ -372,6 +376,7 @@ mod tests {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl system::Trait for Test {
type Origin = Origin;
@@ -386,6 +391,7 @@ mod tests {
type Event = ();
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
}
parameter_types! {
@@ -408,6 +414,7 @@ mod tests {
type CreationFee = CreationFee;
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = ();
}
parameter_types! {
pub const ProposalBond: Permill = Permill::from_percent(5);