From f579912b42f19f0c76547b69ba31f2364d1fab58 Mon Sep 17 00:00:00 2001 From: kianenigma Date: Thu, 2 Apr 2020 13:53:23 +0200 Subject: [PATCH 1/9] Master.into() --- Cargo.lock | 21 + Cargo.toml | 1 + bin/node/runtime/src/lib.rs | 5 +- frame/session/benchmarking/src/mock.rs | 2 + frame/staking/fuzz/.gitignore | 4 - frame/staking/fuzz/Cargo.toml | 38 -- .../fuzz/fuzz_targets/submit_solution.rs | 130 ------ frame/staking/fuzzer/.gitignore | 2 + frame/staking/{fuzz => fuzzer}/Cargo.lock | 435 +++++++++++------- frame/staking/fuzzer/Cargo.toml | 30 ++ .../{fuzz/fuzz_targets => fuzzer/src}/mock.rs | 29 +- frame/staking/fuzzer/src/submit_solution.rs | 152 ++++++ frame/staking/src/lib.rs | 36 +- frame/staking/src/mock.rs | 21 + frame/staking/src/offchain_election.rs | 34 +- frame/staking/src/testing_utils.rs | 23 +- frame/staking/src/tests.rs | 43 ++ 17 files changed, 646 insertions(+), 360 deletions(-) delete mode 100644 frame/staking/fuzz/.gitignore delete mode 100644 frame/staking/fuzz/Cargo.toml delete mode 100644 frame/staking/fuzz/fuzz_targets/submit_solution.rs create mode 100644 frame/staking/fuzzer/.gitignore rename frame/staking/{fuzz => fuzzer}/Cargo.lock (85%) create mode 100644 frame/staking/fuzzer/Cargo.toml rename frame/staking/{fuzz/fuzz_targets => fuzzer/src}/mock.rs (87%) create mode 100644 frame/staking/fuzzer/src/submit_solution.rs diff --git a/Cargo.lock b/Cargo.lock index c0cb38679a10c..2069939ec38c0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4521,6 +4521,27 @@ dependencies = [ "substrate-test-utils", ] +[[package]] +name = "pallet-staking-fuzz" +version = "0.0.0" +dependencies = [ + "frame-support", + "frame-system", + "honggfuzz", + "pallet-balances", + "pallet-indices", + "pallet-session", + "pallet-staking", + "pallet-staking-reward-curve", + "pallet-timestamp", + "parity-scale-codec", + "sp-core", + "sp-io", + "sp-phragmen", + "sp-runtime", + "sp-std", +] + [[package]] name = "pallet-staking-reward-curve" version = "2.0.0-dev" diff --git a/Cargo.toml b/Cargo.toml index 5c4e93d84cb0a..860b5ed89a78f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -94,6 +94,7 @@ members = [ "frame/society", "frame/staking", "frame/staking/reward-curve", + "frame/staking/fuzzer", "frame/sudo", "frame/support", "frame/support/procedural", diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 337242f884ddc..3c077d5b35e5e 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -340,8 +340,9 @@ parameter_types! { pub const BondingDuration: pallet_staking::EraIndex = 24 * 28; pub const SlashDeferDuration: pallet_staking::EraIndex = 24 * 7; // 1/4 the bonding duration. pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE; - pub const ElectionLookahead: BlockNumber = 25; // 10 minutes per session => 100 block. + pub const ElectionLookahead: BlockNumber = EPOCH_DURATION_IN_BLOCKS / 4; pub const MaxNominatorRewardedPerValidator: u32 = 64; + pub const MaxIterations: u32 = 5; } impl pallet_staking::Trait for Runtime { @@ -363,6 +364,8 @@ impl pallet_staking::Trait for Runtime { type ElectionLookahead = ElectionLookahead; type Call = Call; type SubmitTransaction = TransactionSubmitterOf<()>; + type Randomness = RandomnessCollectiveFlip; + type MaxIterations = MaxIterations; type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator; type UnsignedPriority = StakingUnsignedPriority; } diff --git a/frame/session/benchmarking/src/mock.rs b/frame/session/benchmarking/src/mock.rs index 4c022eb8b89b6..300721767d5fd 100644 --- a/frame/session/benchmarking/src/mock.rs +++ b/frame/session/benchmarking/src/mock.rs @@ -177,6 +177,8 @@ impl pallet_staking::Trait for Test { type SubmitTransaction = SubmitTransaction; type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator; type UnsignedPriority = UnsignedPriority; + type Randomness = (); + type MaxIterations = (); } impl crate::Trait for Test {} diff --git a/frame/staking/fuzz/.gitignore b/frame/staking/fuzz/.gitignore deleted file mode 100644 index 572e03bdf321b..0000000000000 --- a/frame/staking/fuzz/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ - -target -corpus -artifacts diff --git a/frame/staking/fuzz/Cargo.toml b/frame/staking/fuzz/Cargo.toml deleted file mode 100644 index a78fbf17dc8a3..0000000000000 --- a/frame/staking/fuzz/Cargo.toml +++ /dev/null @@ -1,38 +0,0 @@ -[package] -name = "pallet-staking-fuzz" -version = "0.0.0" -authors = ["Automatically generated"] -publish = false -edition = "2018" - -[package.metadata] -cargo-fuzz = true - -[dependencies] -libfuzzer-sys = "0.3" -codec = { package = "parity-scale-codec", version = "1.3.0", default-features = false, features = ["derive"] } -pallet-staking = { version = "2.0.0-alpha.2", path = "..", features = ["testing-utils"] } -pallet-staking-reward-curve = { version = "2.0.0-alpha.2", path = "../reward-curve" } -pallet-session = { version = "2.0.0-alpha.2", path = "../../session" } -pallet-indices = { version = "2.0.0-alpha.2", path = "../../indices" } -pallet-balances = { version = "2.0.0-alpha.2", path = "../../balances" } -pallet-timestamp = { version = "2.0.0-alpha.2", path = "../../timestamp" } -frame-system = { version = "2.0.0-alpha.2", path = "../../system" } -frame-support = { version = "2.0.0-alpha.2", path = "../../support" } -sp-std = { version = "2.0.0-alpha.2", path = "../../../primitives/std" } -sp-io ={ version = "2.0.0-alpha.2", path = "../../../primitives/io" } -sp-core = { version = "2.0.0-alpha.2", path = "../../../primitives/core" } -sp-phragmen = { version = "2.0.0-alpha.2", path = "../../../primitives/phragmen" } -sp-runtime = { version = "2.0.0-alpha.2", path = "../../../primitives/runtime" } -rand = "0.7.3" - -# Prevent this from interfering with workspaces -[workspace] -members = ["."] - -[[bin]] -name = "submit_solution" -path = "fuzz_targets/submit_solution.rs" - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] diff --git a/frame/staking/fuzz/fuzz_targets/submit_solution.rs b/frame/staking/fuzz/fuzz_targets/submit_solution.rs deleted file mode 100644 index 5d1fcf1d7ea85..0000000000000 --- a/frame/staking/fuzz/fuzz_targets/submit_solution.rs +++ /dev/null @@ -1,130 +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 . - -//! Fuzzing for staking pallet. - -#![no_main] -use libfuzzer_sys::fuzz_target; -use mock::Test; -use pallet_staking::testing_utils::{ - self, USER, get_seq_phragmen_solution, get_weak_solution, setup_chain_stakers, - set_validator_count, signed_account, -}; -use frame_support::assert_ok; -use sp_runtime::{traits::Dispatchable, DispatchError}; - -mod mock; - -#[repr(u32)] -#[allow(dead_code)] -#[derive(Debug, Clone, Copy)] -enum Mode { - /// Initial submission. This will be rather cheap. - InitialSubmission, - /// A better submission that will replace the previous ones. This is the most expensive. - StrongerSubmission, - /// A weak submission that will be rejected. This will be rather cheap. - WeakerSubmission, -} - -pub fn new_test_ext() -> Result { - frame_system::GenesisConfig::default().build_storage::().map(Into::into) -} - -fuzz_target!(|do_reduce: bool| { - let ext = new_test_ext(); - let mode: Mode = unsafe { std::mem::transmute(testing_utils::random(0, 2)) }; - let num_validators = testing_utils::random(50, 500); - let num_nominators = testing_utils::random(200, 2000); - let edge_per_voter = testing_utils::random(1, 16); - let to_elect = testing_utils::random(10, num_validators); - - println!("+++ instance with params {} / {} / {} / {:?} / {}", - num_nominators, - num_validators, - edge_per_voter, - mode, - to_elect, - ); - - ext.unwrap_or_default().execute_with(|| { - // initial setup - set_validator_count::(to_elect); - setup_chain_stakers::( - num_validators, - num_nominators, - edge_per_voter, - ); - - println!("++ Chain setup done."); - - // stuff to submit - let (winners, compact, score) = match mode { - Mode::InitialSubmission => { - /* No need to setup anything */ - get_seq_phragmen_solution::(do_reduce) - }, - Mode::StrongerSubmission => { - let (winners, compact, score) = get_weak_solution::(false); - assert_ok!( - >::submit_election_solution( - signed_account::(USER), - winners, - compact, - score, - ) - ); - get_seq_phragmen_solution::(do_reduce) - }, - Mode::WeakerSubmission => { - let (winners, compact, score) = get_seq_phragmen_solution::(do_reduce); - assert_ok!( - >::submit_election_solution( - signed_account::(USER), - winners, - compact, - score, - ) - ); - get_weak_solution::(false) - } - }; - - println!("++ Submission ready."); - - // must have chosen correct number of winners. - assert_eq!(winners.len() as u32, >::validator_count()); - - // final call and origin - let call = pallet_staking::Call::::submit_election_solution( - winners, - compact, - score, - ); - let caller = signed_account::(USER); - - // actually submit - match mode { - Mode::WeakerSubmission => { - assert_eq!( - call.dispatch(caller.into()).unwrap_err(), - DispatchError::Module { index: 0, error: 11, message: Some("PhragmenWeakSubmission") }, - ); - }, - _ => assert_ok!(call.dispatch(caller.into())), - }; - }) -}); diff --git a/frame/staking/fuzzer/.gitignore b/frame/staking/fuzzer/.gitignore new file mode 100644 index 0000000000000..3ebcb104d4a50 --- /dev/null +++ b/frame/staking/fuzzer/.gitignore @@ -0,0 +1,2 @@ +hfuzz_target +hfuzz_workspace diff --git a/frame/staking/fuzz/Cargo.lock b/frame/staking/fuzzer/Cargo.lock similarity index 85% rename from frame/staking/fuzz/Cargo.lock rename to frame/staking/fuzzer/Cargo.lock index f6e8cfa08d667..a45f33fdce249 100644 --- a/frame/staking/fuzz/Cargo.lock +++ b/frame/staking/fuzzer/Cargo.lock @@ -28,11 +28,31 @@ dependencies = [ "memchr", ] +[[package]] +name = "alga" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f823d037a7ec6ea2197046bafd4ae150e6bc36f9ca347404f46a46823fa84f2" +dependencies = [ + "approx", + "num-complex", + "num-traits", +] + +[[package]] +name = "approx" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0e60b75072ecd4168020818c0107f2857bb6c4e64252d8d3983f6263b40a5c3" +dependencies = [ + "num-traits", +] + [[package]] name = "arbitrary" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16971f2f0ce65c5cf2a1546cc6a0af102ecb11e265ddaa9433fb3e5bfdf676a4" +checksum = "75153c95fdedd7db9732dfbfc3702324a1627eec91ba56e37cd0ac78314ab2ed" [[package]] name = "arrayref" @@ -69,9 +89,9 @@ checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" [[package]] name = "backtrace" -version = "0.3.45" +version = "0.3.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad235dabf00f36301792cfe82499880ba54c6486be094d1047b02bacb67c14e8" +checksum = "b1e692897359247cc6bb902933361652380af0f1b7651ae5c5013407f30e109e" dependencies = [ "backtrace-sys", "cfg-if", @@ -81,9 +101,9 @@ dependencies = [ [[package]] name = "backtrace-sys" -version = "0.1.33" +version = "0.1.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17b52e737c40a7d75abca20b29a19a0eb7ba9fc72c5a72dd282a0a3c2c0dc35" +checksum = "7de8aba10a69c8e8d7622c5710229485ec32e9d55fdad160ea559c086fdcd118" dependencies = [ "cc", "libc", @@ -109,9 +129,13 @@ checksum = "5da9b3d9f6f585199287a473f4f8dfab6566cf827d15c00c219f53c645687ead" [[package]] name = "bitvec" -version = "0.15.2" +version = "0.17.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a993f74b4c99c1908d156b8d2e0fb6277736b0ecbd833982fd1241d39b2766a6" +checksum = "41262f11d771fd4a61aa3ce019fca363b4b6c282fca9da2a31186d3965a47a5c" +dependencies = [ + "either", + "radium", +] [[package]] name = "blake2-rfc" @@ -146,9 +170,9 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.2.0" +version = "3.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f359dc14ff8911330a51ef78022d376f25ed00248912803b58f00cb1c27f742" +checksum = "12ae9db68ad7fac5fe51304d20f016c911539251075a214f8e663babefa35187" [[package]] name = "byte-slice-cast" @@ -168,15 +192,6 @@ version = "1.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de" -[[package]] -name = "c2-chacha" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "214238caa1bf3a496ec3392968969cab8549f96ff30652c9e56885329315f6bb" -dependencies = [ - "ppv-lite86", -] - [[package]] name = "cc" version = "1.0.50" @@ -249,19 +264,6 @@ dependencies = [ "subtle 1.0.0", ] -[[package]] -name = "curve25519-dalek" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b7dcd30ba50cdf88b55b033456138b7c0ac4afdc436d82e1b79f370f24cc66d" -dependencies = [ - "byteorder", - "clear_on_drop", - "digest", - "rand_core 0.3.1", - "subtle 2.2.2", -] - [[package]] name = "curve25519-dalek" version = "2.0.0" @@ -272,14 +274,14 @@ dependencies = [ "digest", "rand_core 0.5.1", "subtle 2.2.2", - "zeroize 1.1.0", + "zeroize", ] [[package]] name = "derive_more" -version = "0.99.3" +version = "0.99.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a806e96c59a76a5ba6e18735b6cf833344671e61e7863f2edb5c518ea2cac95c" +checksum = "e2323f3f47db9a0e77ce7a300605d8d2098597fc451ed1a97bb1f6411bb550a7" dependencies = [ "proc-macro2", "quote", @@ -302,11 +304,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "978710b352437433c97b2bff193f2fb1dfd58a093f863dd95e225a19baa599a2" dependencies = [ "clear_on_drop", - "curve25519-dalek 2.0.0", + "curve25519-dalek", "rand 0.7.3", "sha2", ] +[[package]] +name = "either" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" + [[package]] name = "environmental" version = "1.1.1" @@ -343,12 +351,11 @@ checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" [[package]] name = "fixed-hash" -version = "0.5.2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3367952ceb191f4ab95dd5685dc163ac539e36202f9fcfd0cb22f9f9c542fefc" +checksum = "32529fc42e86ec06e5047092082aab9ad459b070c5d2a76b14f4f5ce70bf2e84" dependencies = [ "byteorder", - "libc", "rand 0.7.3", "rustc-hex", "static_assertions", @@ -356,10 +363,11 @@ dependencies = [ [[package]] name = "frame-benchmarking" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "frame-support", "frame-system", + "linregress", "parity-scale-codec", "sp-api", "sp-io", @@ -370,7 +378,7 @@ dependencies = [ [[package]] name = "frame-metadata" -version = "11.0.0-alpha.3" +version = "11.0.0-alpha.5" dependencies = [ "parity-scale-codec", "serde", @@ -380,7 +388,7 @@ dependencies = [ [[package]] name = "frame-support" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "bitmask", "frame-metadata", @@ -403,7 +411,7 @@ dependencies = [ [[package]] name = "frame-support-procedural" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "frame-support-procedural-tools", "proc-macro2", @@ -413,7 +421,7 @@ dependencies = [ [[package]] name = "frame-support-procedural-tools" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "frame-support-procedural-tools-derive", "proc-macro-crate", @@ -424,7 +432,7 @@ dependencies = [ [[package]] name = "frame-support-procedural-tools-derive" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "proc-macro2", "quote", @@ -433,7 +441,7 @@ dependencies = [ [[package]] name = "frame-system" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "frame-support", "impl-trait-for-tuples", @@ -492,6 +500,7 @@ dependencies = [ "futures-core", "futures-task", "futures-util", + "num_cpus", ] [[package]] @@ -597,6 +606,15 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "hermit-abi" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "725cf19794cf90aa94e65050cb4191ff5d8fa87a498383774c47b332e3af952e" +dependencies = [ + "libc", +] + [[package]] name = "hex" version = "0.4.2" @@ -670,9 +688,9 @@ checksum = "f65877bf7d44897a473350b1046277941cee20b263397e90869c50b6e766088b" [[package]] name = "js-sys" -version = "0.3.36" +version = "0.3.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1cb931d43e71f560c81badb0191596562bafad2be06a3f9025b845c847c60df5" +checksum = "6a27d435371a2fa5b6d2b028a74bbdb1234f308da363226a2854ca3ff8ba7055" dependencies = [ "wasm-bindgen", ] @@ -691,20 +709,26 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" -version = "0.2.67" +version = "0.2.68" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb147597cdf94ed43ab7a9038716637d2d1bf2bc571da995d0028dec06bd3018" +checksum = "dea0c0405123bba743ee3f91f49b1c7cfb684eef0da0a50110f758ccf24cdff0" [[package]] name = "libfuzzer-sys" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb789afcc589a08928d1e466087445ab740a0f70a2ee23d9349a0e3723d65e1b" +checksum = "8d718794b8e23533b9069bd2c4597d69e41cc7ab1c02700a502971aca0cdcf24" dependencies = [ "arbitrary", "cc", ] +[[package]] +name = "libm" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7d73b3f436185384286bd8098d17ec07c9a7d2388a6599f824d8502b529702a" + [[package]] name = "libsecp256k1" version = "0.3.5" @@ -721,6 +745,17 @@ dependencies = [ "typenum", ] +[[package]] +name = "linregress" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9290cf6f928576eeb9c096c6fad9d8d452a0a1a70a2bbffa6e36064eedc0aac9" +dependencies = [ + "failure", + "nalgebra", + "statrs", +] + [[package]] name = "lock_api" version = "0.3.3" @@ -739,6 +774,15 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "matrixmultiply" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4f7ec66360130972f34830bfad9ef05c6610a43938a467bcc9ab9369ab3478f" +dependencies = [ + "rawpointer", +] + [[package]] name = "maybe-uninit" version = "2.0.0" @@ -753,9 +797,9 @@ checksum = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400" [[package]] name = "memory-db" -version = "0.19.0" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "198831fe8722331a395bc199a5d08efbc197497ef354cb4c77b969c02ffc0fc4" +checksum = "f58381b20ebe2c578e75dececd9da411414903415349548ccc46aac3209cdfbc" dependencies = [ "ahash", "hash-db", @@ -771,14 +815,31 @@ checksum = "71d96e3f3c0b6325d8ccd83c33b28acb183edcb6c67938ba104ec546854b0882" [[package]] name = "merlin" -version = "1.3.0" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b0942b357c1b4d0dc43ba724674ec89c3218e6ca2b3e8269e7cb53bcecd2f6e" +checksum = "c6feca46f4fa3443a01769d768727f10c10a20fdb65e52dc16a81f0c8269bb78" dependencies = [ "byteorder", "keccak", - "rand_core 0.4.2", - "zeroize 1.1.0", + "rand_core 0.5.1", + "zeroize", +] + +[[package]] +name = "nalgebra" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaa9fddbc34c8c35dd2108515587b8ce0cab396f17977b8c738568e4edb521a2" +dependencies = [ + "alga", + "approx", + "generic-array", + "matrixmultiply", + "num-complex", + "num-rational", + "num-traits", + "rand 0.6.5", + "typenum", ] [[package]] @@ -798,6 +859,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-complex" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b19411a9719e753aff12e5187b74d60d3dc449ec3f4dc21e3989c3f554bc95" +dependencies = [ + "autocfg 1.0.0", + "num-traits", +] + [[package]] name = "num-integer" version = "0.1.42" @@ -810,9 +881,9 @@ dependencies = [ [[package]] name = "num-rational" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da4dc79f9e6c81bef96148c8f6b8e72ad4541caa4a24373e900a36da07de03a3" +checksum = "5c000134b5dbf44adc5cb772486d335293351644b801551abe8f75c84cfa4aef" dependencies = [ "autocfg 1.0.0", "num-bigint", @@ -827,6 +898,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c62be47e61d1842b9170f0fdeec8eba98e60e90e5446449a0545e5152acd7096" dependencies = [ "autocfg 1.0.0", + "libm", +] + +[[package]] +name = "num_cpus" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46203554f085ff89c235cd12f7075f3233af9b11ed7c9e16dfe2560d03313ce6" +dependencies = [ + "hermit-abi", + "libc", ] [[package]] @@ -846,7 +928,7 @@ checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" [[package]] name = "pallet-authorship" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "frame-support", "frame-system", @@ -862,7 +944,7 @@ dependencies = [ [[package]] name = "pallet-balances" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "frame-benchmarking", "frame-support", @@ -876,7 +958,7 @@ dependencies = [ [[package]] name = "pallet-indices" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "frame-support", "frame-system", @@ -891,7 +973,7 @@ dependencies = [ [[package]] name = "pallet-session" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "frame-support", "frame-system", @@ -908,7 +990,7 @@ dependencies = [ [[package]] name = "pallet-staking" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "frame-support", "frame-system", @@ -952,7 +1034,7 @@ dependencies = [ [[package]] name = "pallet-staking-reward-curve" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -962,7 +1044,7 @@ dependencies = [ [[package]] name = "pallet-timestamp" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "frame-benchmarking", "frame-support", @@ -980,7 +1062,7 @@ dependencies = [ name = "parity-scale-codec" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f509c5e67ca0605ee17dcd3f91ef41cadd685c75a298fb6261b781a5acb3f910" +checksum = "329c8f7f4244ddb5c37c103641027a76c530e65e8e4b8240b29f81ea40508b17" dependencies = [ "arrayvec 0.5.1", "bitvec", @@ -991,7 +1073,7 @@ dependencies = [ [[package]] name = "parity-scale-codec-derive" -version = "1.3.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a0ec292e92e8ec7c58e576adacc1e3f399c597c8f263c42f18420abe58e7245" dependencies = [ @@ -1003,9 +1085,9 @@ dependencies = [ [[package]] name = "parity-util-mem" -version = "0.5.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef1476e40bf8f5c6776e9600983435821ca86eb9819d74a6207cca69d091406a" +checksum = "6e42755f26e5ea21a6a819d9e63cbd70713e9867a2b767ec2cc65ca7659532c5" dependencies = [ "cfg-if", "impl-trait-for-tuples", @@ -1078,15 +1160,15 @@ dependencies = [ "cloudabi", "libc", "redox_syscall", - "smallvec 1.3.0", + "smallvec 1.2.0", "winapi", ] [[package]] name = "paste" -version = "0.1.7" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63e1afe738d71b1ebab5f1207c055054015427dbfc7bbe9ee1266894156ec046" +checksum = "092d791bf7847f70bbd49085489fba25fc2c193571752bff9e36e74e72403932" dependencies = [ "paste-impl", "proc-macro-hack", @@ -1094,9 +1176,9 @@ dependencies = [ [[package]] name = "paste-impl" -version = "0.1.7" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d4dc4a7f6f743211c5aab239640a65091535d97d43d92a52bca435a640892bb" +checksum = "406c23fb4c45cc6f68a9bbabb8ec7bd6f8cfcbd17e9e8f72c2460282f8325729" dependencies = [ "proc-macro-hack", "proc-macro2", @@ -1128,9 +1210,9 @@ checksum = "74490b50b9fbe561ac330df47c08f3f33073d2d00c150f719147d7c54522fa1b" [[package]] name = "primitive-types" -version = "0.6.2" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4336f4f5d5524fa60bcbd6fe626f9223d8142a50e7053e979acdf0da41ab975" +checksum = "e5e4b9943a2da369aec5e96f7c10ebc74fcf434d39590d974b0a3460e6f67fbb" dependencies = [ "fixed-hash", "impl-codec", @@ -1149,26 +1231,21 @@ dependencies = [ [[package]] name = "proc-macro-hack" -version = "0.5.11" +version = "0.5.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecd45702f76d6d3c75a80564378ae228a85f0b59d2f3ed43c91b4a69eb2ebfc5" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] +checksum = "fcfdefadc3d57ca21cf17990a28ef4c0f7c61383a28cb7604cf4a18e6ede1420" [[package]] name = "proc-macro-nested" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "369a6ed065f249a159e06c45752c780bda2fb53c995718f9e484d08daa9eb42e" +checksum = "8e946095f9d3ed29ec38de908c22f95d9ac008e424c7bcae54c75a79c527c694" [[package]] name = "proc-macro2" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c09721c6781493a2a492a96b5a5bf19b65917fe6728884e7c44dd0c60ca3435" +checksum = "df246d292ff63439fea9bc8c0a270bed0e390d5ebd4db4ba15aba81111b5abe3" dependencies = [ "unicode-xid", ] @@ -1182,6 +1259,25 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "radium" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "def50a86306165861203e7f84ecffbbdfdea79f0e51039b33de1e952358c47ac" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +dependencies = [ + "cloudabi", + "fuchsia-cprng", + "libc", + "rand_core 0.3.1", + "winapi", +] + [[package]] name = "rand" version = "0.6.5" @@ -1209,7 +1305,7 @@ checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" dependencies = [ "getrandom", "libc", - "rand_chacha 0.2.1", + "rand_chacha 0.2.2", "rand_core 0.5.1", "rand_hc 0.2.0", ] @@ -1226,11 +1322,11 @@ dependencies = [ [[package]] name = "rand_chacha" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03a2a90da8c7523f554344f921aa97283eadf6ac484a6d2a7d0212fa7f8d6853" +checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" dependencies = [ - "c2-chacha", + "ppv-lite86", "rand_core 0.5.1", ] @@ -1329,6 +1425,12 @@ dependencies = [ "rand_core 0.3.1", ] +[[package]] +name = "rawpointer" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" + [[package]] name = "rdrand" version = "0.4.0" @@ -1346,9 +1448,9 @@ checksum = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" [[package]] name = "regex" -version = "1.3.4" +version = "1.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "322cf97724bea3ee221b78fe25ac9c46114ebb51747ad5babd51a2fc6a8235a8" +checksum = "7f6946991529684867e47d86474e3a6d0c0ab9b82d5821e314b1ede31fa3a4b3" dependencies = [ "aho-corasick", "memchr", @@ -1358,9 +1460,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.6.16" +version = "0.6.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1132f845907680735a84409c3bebc64d1364a5683ffbce899550cd09d5eaefc1" +checksum = "7fe5bd57d1d7414c6b5ed48563a2c855d995ff777729dcd91c369ec7fea395ae" [[package]] name = "rustc-demangle" @@ -1391,19 +1493,20 @@ dependencies = [ [[package]] name = "schnorrkel" -version = "0.8.5" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eacd8381b3c37840c9c9f40472af529e49975bdcbc24f83c31059fd6539023d3" +checksum = "021b403afe70d81eea68f6ea12f6b3c9588e5d536a94c3bf80f15e7faa267862" dependencies = [ - "curve25519-dalek 1.2.3", - "failure", + "arrayref", + "arrayvec 0.5.1", + "curve25519-dalek", + "getrandom", "merlin", - "rand 0.6.5", - "rand_core 0.4.2", - "rand_os", + "rand 0.7.3", + "rand_core 0.5.1", "sha2", "subtle 2.2.2", - "zeroize 0.9.3", + "zeroize", ] [[package]] @@ -1435,18 +1538,18 @@ checksum = "a0eddf2e8f50ced781f288c19f18621fa72a3779e3cb58dbf23b07469b0abeb4" [[package]] name = "serde" -version = "1.0.104" +version = "1.0.105" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "414115f25f818d7dfccec8ee535d76949ae78584fc4f79a6f45a904bf8ab4449" +checksum = "e707fbbf255b8fc8c3b99abb91e7257a622caeb20a9818cbadbeeede4e0932ff" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.104" +version = "1.0.105" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "128f9e303a5a29922045a830221b8f78ec74a5f544944f3d5984f8ec3895ef64" +checksum = "ac5d00fc561ba2724df6758a17de23df5914f20e41cb00f94d5b7ae42fffaff8" dependencies = [ "proc-macro2", "quote", @@ -1482,13 +1585,13 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.3.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c2fb2ec9bcd216a5b0d0ccf31ab17b5ed1d627960edff65bbe95d3ce221cefc" [[package]] name = "sp-api" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "hash-db", "parity-scale-codec", @@ -1502,7 +1605,7 @@ dependencies = [ [[package]] name = "sp-api-proc-macro" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "blake2-rfc", "proc-macro-crate", @@ -1513,7 +1616,7 @@ dependencies = [ [[package]] name = "sp-application-crypto" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "parity-scale-codec", "serde", @@ -1524,7 +1627,7 @@ dependencies = [ [[package]] name = "sp-arithmetic" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "integer-sqrt", "num-traits", @@ -1536,7 +1639,7 @@ dependencies = [ [[package]] name = "sp-authorship" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "parity-scale-codec", "sp-inherents", @@ -1546,12 +1649,13 @@ dependencies = [ [[package]] name = "sp-core" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "base58", "blake2-rfc", "byteorder", "ed25519-dalek", + "futures", "hash-db", "hash256-std-hasher", "hex", @@ -1566,7 +1670,6 @@ dependencies = [ "primitive-types", "rand 0.7.3", "regex", - "rustc-hex", "schnorrkel", "serde", "sha2", @@ -1580,12 +1683,12 @@ dependencies = [ "tiny-keccak", "twox-hash", "wasmi", - "zeroize 1.1.0", + "zeroize", ] [[package]] name = "sp-debug-derive" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "proc-macro2", "quote", @@ -1594,7 +1697,7 @@ dependencies = [ [[package]] name = "sp-externalities" -version = "0.8.0-alpha.3" +version = "0.8.0-alpha.5" dependencies = [ "environmental", "sp-std", @@ -1603,7 +1706,7 @@ dependencies = [ [[package]] name = "sp-inherents" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "derive_more", "parity-scale-codec", @@ -1614,7 +1717,7 @@ dependencies = [ [[package]] name = "sp-io" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "hash-db", "libsecp256k1", @@ -1631,7 +1734,7 @@ dependencies = [ [[package]] name = "sp-keyring" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "lazy_static", "sp-core", @@ -1641,7 +1744,7 @@ dependencies = [ [[package]] name = "sp-panic-handler" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "backtrace", "log", @@ -1649,11 +1752,10 @@ dependencies = [ [[package]] name = "sp-phragmen" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "parity-scale-codec", "serde", - "sp-core", "sp-phragmen-compact", "sp-runtime", "sp-std", @@ -1671,7 +1773,7 @@ dependencies = [ [[package]] name = "sp-runtime" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "hash256-std-hasher", "impl-trait-for-tuples", @@ -1691,7 +1793,7 @@ dependencies = [ [[package]] name = "sp-runtime-interface" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "parity-scale-codec", "primitive-types", @@ -1704,7 +1806,7 @@ dependencies = [ [[package]] name = "sp-runtime-interface-proc-macro" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "Inflector", "proc-macro-crate", @@ -1715,7 +1817,7 @@ dependencies = [ [[package]] name = "sp-staking" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "parity-scale-codec", "sp-runtime", @@ -1724,7 +1826,7 @@ dependencies = [ [[package]] name = "sp-state-machine" -version = "0.8.0-alpha.3" +version = "0.8.0-alpha.5" dependencies = [ "hash-db", "log", @@ -1742,11 +1844,11 @@ dependencies = [ [[package]] name = "sp-std" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" [[package]] name = "sp-storage" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "impl-serde 0.2.3", "serde", @@ -1756,7 +1858,7 @@ dependencies = [ [[package]] name = "sp-timestamp" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "impl-trait-for-tuples", "parity-scale-codec", @@ -1769,7 +1871,7 @@ dependencies = [ [[package]] name = "sp-trie" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "hash-db", "memory-db", @@ -1782,7 +1884,7 @@ dependencies = [ [[package]] name = "sp-version" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "impl-serde 0.2.3", "parity-scale-codec", @@ -1793,7 +1895,7 @@ dependencies = [ [[package]] name = "sp-wasm-interface" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.5" dependencies = [ "impl-trait-for-tuples", "parity-scale-codec", @@ -1807,6 +1909,15 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "statrs" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10102ac8d55e35db2b3fafc26f81ba8647da2e15879ab686a67e6d19af2685e8" +dependencies = [ + "rand 0.5.6", +] + [[package]] name = "strum" version = "0.16.0" @@ -1830,9 +1941,9 @@ dependencies = [ [[package]] name = "substrate-bip39" -version = "0.3.1" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3be511be555a3633e71739a79e4ddff6a6aaa6579fa6114182a51d72c3eb93c5" +checksum = "c004e8166d6e0aa3a9d5fa673e5b7098ff25f930de1013a21341988151e681bb" dependencies = [ "hmac", "pbkdf2", @@ -1854,9 +1965,9 @@ checksum = "7c65d530b10ccaeac294f349038a597e435b18fb456aadd0840a623f83b9e941" [[package]] name = "syn" -version = "1.0.16" +version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "123bd9499cfb380418d509322d7a6d52e5315f064fe4b3ad18a53d6b92c07859" +checksum = "0df0eb663f387145cab623dea85b09c2c5b4b0aef44e945d928e682fce71bb03" dependencies = [ "proc-macro2", "quote", @@ -1886,9 +1997,9 @@ dependencies = [ [[package]] name = "tiny-bip39" -version = "0.7.1" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6848cd8f566953ce1e8faeba12ee23cbdbb0437754792cd857d44628b5685e3" +checksum = "b0165e045cc2ae1660270ca65e1676dbaab60feb0f91b10f7d0665e9b47e31f2" dependencies = [ "failure", "hmac", @@ -1958,7 +2069,7 @@ dependencies = [ "hashbrown", "log", "rustc-hex", - "smallvec 1.3.0", + "smallvec 1.2.0", ] [[package]] @@ -2003,7 +2114,7 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5479532badd04e128284890390c1e876ef7a993d0570b3597ae43dfa1d59afa4" dependencies = [ - "smallvec 1.3.0", + "smallvec 1.2.0", ] [[package]] @@ -2026,9 +2137,9 @@ checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" [[package]] name = "wasm-bindgen" -version = "0.2.59" +version = "0.2.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3557c397ab5a8e347d434782bcd31fc1483d927a6826804cec05cc792ee2519d" +checksum = "2cc57ce05287f8376e998cbddfb4c8cb43b84a7ec55cf4551d7c00eef317a47f" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -2036,9 +2147,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.59" +version = "0.2.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0da9c9a19850d3af6df1cb9574970b566d617ecfaf36eb0b706b6f3ef9bd2f8" +checksum = "d967d37bf6c16cca2973ca3af071d0a2523392e4a594548155d89a678f4237cd" dependencies = [ "bumpalo", "lazy_static", @@ -2051,9 +2162,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.9" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "457414a91863c0ec00090dba537f88ab955d93ca6555862c29b6d860990b8a8a" +checksum = "7add542ea1ac7fdaa9dc25e031a6af33b7d63376292bd24140c637d00d1c312a" dependencies = [ "cfg-if", "js-sys", @@ -2063,9 +2174,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.59" +version = "0.2.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f6fde1d36e75a714b5fe0cffbb78978f222ea6baebb726af13c78869fdb4205" +checksum = "8bd151b63e1ea881bb742cd20e1d6127cef28399558f3b5d415289bc41eee3a4" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2073,9 +2184,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.59" +version = "0.2.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25bda4168030a6412ea8a047e27238cadf56f0e53516e1e83fec0a8b7c786f6d" +checksum = "d68a5b36eef1be7868f668632863292e37739656a80fc4b9acec7b0bd35a4931" dependencies = [ "proc-macro2", "quote", @@ -2086,9 +2197,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.59" +version = "0.2.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc9f36ad51f25b0219a3d4d13b90eb44cd075dff8b6280cca015775d7acaddd8" +checksum = "daf76fe7d25ac79748a37538b7daeed1c7a6867c92d3245c12c6222e4a20d639" [[package]] name = "wasm-timer" @@ -2131,9 +2242,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.36" +version = "0.3.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "721c6263e2c66fd44501cc5efbfa2b7dfa775d13e4ea38c46299646ed1f9c70a" +checksum = "2d6f51648d8c56c366144378a33290049eafdd784071077f6fe37dae64c1c4cb" dependencies = [ "js-sys", "wasm-bindgen", @@ -2161,12 +2272,6 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -[[package]] -name = "zeroize" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45af6a010d13e4cf5b54c94ba5a2b2eba5596b9e46bf5875612d332a1f2b3f86" - [[package]] name = "zeroize" version = "1.1.0" diff --git a/frame/staking/fuzzer/Cargo.toml b/frame/staking/fuzzer/Cargo.toml new file mode 100644 index 0000000000000..12ecfd120356b --- /dev/null +++ b/frame/staking/fuzzer/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "pallet-staking-fuzz" +version = "0.0.0" +authors = ["Automatically generated"] +publish = false +edition = "2018" + +[dependencies] +honggfuzz = "0.5" +codec = { package = "parity-scale-codec", version = "1.3.0", default-features = false, features = ["derive"] } +pallet-staking = { version = "2.0.0-alpha.5", path = "..", features = ["testing-utils"] } +pallet-staking-reward-curve = { version = "2.0.0-alpha.5", path = "../reward-curve" } +pallet-session = { version = "2.0.0-alpha.5", path = "../../session" } +pallet-indices = { version = "2.0.0-alpha.5", path = "../../indices" } +pallet-balances = { version = "2.0.0-alpha.5", path = "../../balances" } +pallet-timestamp = { version = "2.0.0-alpha.5", path = "../../timestamp" } +frame-system = { version = "2.0.0-alpha.5", path = "../../system" } +frame-support = { version = "2.0.0-alpha.5", path = "../../support" } +sp-std = { version = "2.0.0-alpha.5", path = "../../../primitives/std" } +sp-io ={ version = "2.0.0-alpha.5", path = "../../../primitives/io" } +sp-core = { version = "2.0.0-alpha.5", path = "../../../primitives/core" } +sp-phragmen = { version = "2.0.0-alpha.5", path = "../../../primitives/phragmen" } +sp-runtime = { version = "2.0.0-alpha.5", path = "../../../primitives/runtime" } + +[[bin]] +name = "submit_solution" +path = "src/submit_solution.rs" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] diff --git a/frame/staking/fuzz/fuzz_targets/mock.rs b/frame/staking/fuzzer/src/mock.rs similarity index 87% rename from frame/staking/fuzz/fuzz_targets/mock.rs rename to frame/staking/fuzzer/src/mock.rs index 4bb3437f92368..2a4d7a913b4ee 100644 --- a/frame/staking/fuzz/fuzz_targets/mock.rs +++ b/frame/staking/fuzzer/src/mock.rs @@ -16,6 +16,8 @@ //! Mock file for staking fuzzing. +use codec::Encode; +use sp_core::H256; use sp_runtime::traits::{Convert, SaturatedConversion}; use frame_support::{impl_outer_origin, impl_outer_dispatch, parameter_types}; @@ -24,11 +26,11 @@ type AccountIndex = u32; type BlockNumber = u64; type Balance = u64; -type System = frame_system::Module; -type Balances = pallet_balances::Module; -type Staking = pallet_staking::Module; -type Indices = pallet_indices::Module; -type Session = pallet_session::Module; +pub type System = frame_system::Module; +pub type Balances = pallet_balances::Module; +pub type Staking = pallet_staking::Module; +pub type Indices = pallet_indices::Module; +pub type Session = pallet_session::Module; impl_outer_origin! { pub enum Origin for Test where system = frame_system {} @@ -52,11 +54,21 @@ impl Convert for CurrencyToVoteHandler { } } +pub struct StaticRandomness; +impl frame_support::traits::Randomness for StaticRandomness { + fn random(_subject: &[u8]) -> H256 { + let mut static_value = 10u32.encode(); + static_value.resize_with(32, || 0u8); + H256::from_slice(&static_value) + } +} + #[derive(Clone, Eq, PartialEq, Debug)] pub struct Test; impl frame_system::Trait for Test { type Origin = Origin; + type DbWeight = (); type Index = AccountIndex; type BlockNumber = BlockNumber; type Call = Call; @@ -150,6 +162,7 @@ pallet_staking_reward_curve::build! { parameter_types! { pub const RewardCurve: &'static sp_runtime::curve::PiecewiseLinear<'static> = &I_NPOS; pub const MaxNominatorRewardedPerValidator: u32 = 64; + pub const MaxIterations: u32 = 20; } pub type Extrinsic = sp_runtime::testing::TestXt; @@ -161,7 +174,7 @@ type SubmitTransaction = frame_system::offchain::TransactionSubmitter< impl pallet_staking::Trait for Test { type Currency = Balances; - type Time = pallet_timestamp::Module; + type UnixTime = pallet_timestamp::Module; type CurrencyToVote = CurrencyToVoteHandler; type RewardRemainder = (); type Event = (); @@ -177,6 +190,8 @@ impl pallet_staking::Trait for Test { type ElectionLookahead = (); type Call = Call; type SubmitTransaction = SubmitTransaction; - type KeyType = sp_runtime::testing::UintAuthorityId; + type MaxIterations = MaxIterations; + type Randomness = StaticRandomness; type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator; + type UnsignedPriority = (); } diff --git a/frame/staking/fuzzer/src/submit_solution.rs b/frame/staking/fuzzer/src/submit_solution.rs new file mode 100644 index 0000000000000..90d8fc56efc50 --- /dev/null +++ b/frame/staking/fuzzer/src/submit_solution.rs @@ -0,0 +1,152 @@ +// 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 . + +//! Fuzzing for staking pallet. + +use honggfuzz::fuzz; + +use mock::Test; +use pallet_staking::testing_utils::{ + USER, get_seq_phragmen_solution, get_weak_solution, setup_chain_stakers, + set_validator_count, signed_account, +}; +use frame_support::assert_ok; +use sp_runtime::{traits::Dispatchable, DispatchError}; + +mod mock; + +#[repr(u32)] +#[allow(dead_code)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Mode { + /// Initial submission. This will be rather cheap. + InitialSubmission, + /// A better submission that will replace the previous ones. This is the most expensive. + StrongerSubmission, + /// A weak submission that will be rejected. This will be rather cheap. + WeakerSubmission, +} + +pub fn new_test_ext() -> Result { + frame_system::GenesisConfig::default().build_storage::().map(Into::into) +} + +fn main() { + let to_range = |x: u32, a: u32, b: u32| { + let collapsed = x % b; + if collapsed >= a { + collapsed + } else { + collapsed + a + } + }; + loop { + fuzz!(|data: (u32, u32, u32, u32, u32)| { + let (mut num_validators, mut num_nominators, mut edge_per_voter, mut to_elect, mode_u32) = data; + let ext = new_test_ext(); + let mode: Mode = unsafe { std::mem::transmute(mode_u32) }; + num_validators = to_range(num_validators, 50, 1000); + num_nominators = to_range(num_nominators, 50, 2000); + edge_per_voter = to_range(edge_per_voter, 1, 16); + to_elect = to_range(to_elect, 20, num_validators); + let do_reduce = true; + + println!("+++ instance with params {} / {} / {} / {:?}({}) / {}", + num_nominators, + num_validators, + edge_per_voter, + mode, + mode_u32, + to_elect, + ); + + ext.unwrap_or_default().execute_with(|| { + // initial setup + set_validator_count::(to_elect); + pallet_staking::testing_utils::init_active_era(); + setup_chain_stakers::( + num_validators, + num_nominators, + edge_per_voter, + ); + + println!("++ Chain setup done."); + + // stuff to submit + let (winners, compact, score) = match mode { + Mode::InitialSubmission => { + /* No need to setup anything */ + get_seq_phragmen_solution::(do_reduce) + }, + Mode::StrongerSubmission => { + let (winners, compact, score) = get_weak_solution::(false); + println!("Weak on chain score = {:?}", score); + assert_ok!( + >::submit_election_solution( + signed_account::(USER), + winners, + compact, + score, + pallet_staking::testing_utils::active_era::(), + ) + ); + get_seq_phragmen_solution::(do_reduce) + }, + Mode::WeakerSubmission => { + let (winners, compact, score) = get_seq_phragmen_solution::(do_reduce); + println!("Strong on chain score = {:?}", score); + assert_ok!( + >::submit_election_solution( + signed_account::(USER), + winners, + compact, + score, + pallet_staking::testing_utils::active_era::(), + ) + ); + get_weak_solution::(false) + } + }; + + println!("++ Submission ready. Score = {:?}", score); + + // must have chosen correct number of winners. + assert_eq!(winners.len() as u32, >::validator_count()); + + // final call and origin + let call = pallet_staking::Call::::submit_election_solution( + winners, + compact, + score, + pallet_staking::testing_utils::active_era::(), + ); + let caller = signed_account::(USER); + + // actually submit + match mode { + Mode::WeakerSubmission => { + assert_eq!( + call.dispatch(caller.into()).unwrap_err().error, + DispatchError::Module { index: 0, error: 15, message: Some("PhragmenWeakSubmission") }, + ); + }, + // NOTE: so exhaustive pattern doesn't work here.. maybe some rust issue? or due to `#[repr(u32)]`? + Mode::InitialSubmission | Mode::StrongerSubmission => assert!(call.dispatch(caller.into()).is_ok()), + }; + }) + }); + } +} diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index b6ffa9081bbce..3931c611b19fb 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -280,7 +280,7 @@ use frame_support::{ dispatch::{IsSubType, DispatchResult}, traits::{ Currency, LockIdentifier, LockableCurrency, WithdrawReasons, OnUnbalanced, Imbalance, Get, - UnixTime, EstimateNextNewSession, EnsureOrigin, + UnixTime, EstimateNextNewSession, Randomness, EnsureOrigin, } }; use pallet_session::historical; @@ -355,7 +355,7 @@ generate_compact_solution_type!(pub GenericCompactAssignments, 16); #[derive(Encode, Decode, RuntimeDebug)] pub struct ActiveEraInfo { /// Index of era. - index: EraIndex, + pub index: EraIndex, /// Moment of start expresed as millisecond from `$UNIX_EPOCH`. /// /// Start can be none if start hasn't been set for the era yet, @@ -789,7 +789,13 @@ pub trait Trait: frame_system::Trait { /// A transaction submitter. type SubmitTransaction: SubmitUnsignedTransaction::Call>; - /// The maximum number of nominators rewarded for each validator. + /// Something that can provide randomness + type Randomness: Randomness; + + /// Maximum number of equalise iterations to run in the offchain submission + type MaxIterations: Get; + + /// The maximum number of nominator rewarded for each validator. /// /// For each validator only the `$MaxNominatorRewardedPerValidator` biggest stakers can claim /// their reward. This used to limit the i/o cost for the nominator payout. @@ -1172,6 +1178,7 @@ decl_module! { { if let Some(next_session_change) = T::NextNewSession::estimate_next_new_session(now){ if let Some(remaining) = next_session_change.checked_sub(&now) { + debug::native::debug!(target: "staking", "remaining: {:?}", remaining); if remaining <= T::ElectionLookahead::get() && !remaining.is_zero() { // create snapshot. if Self::create_stakers_snapshot() { @@ -1202,6 +1209,13 @@ decl_module! { if Self::era_election_status().is_open_at(now) { let offchain_status = set_check_offchain_execution_status::(now); + debug::native::debug!( + target: "staking", + "RUNNING OFFCHAIN WORKER! {:?}/{}/{:?}", + Self::era_election_status(), + now, + offchain_status, + ); if let Err(why) = offchain_status { log!(debug, "skipping offchain worker in open election window due to [{}]", why); } else { @@ -2285,6 +2299,7 @@ impl Module { fn new_session(session_index: SessionIndex) -> Option> { if let Some(current_era) = Self::current_era() { // Initial era has been set. + sp_runtime::print("💰 new_session normal era"); let current_era_start_session_index = Self::eras_start_session_index(current_era) .unwrap_or_else(|| { @@ -2312,6 +2327,7 @@ impl Module { IsCurrentSessionFinal::put(false); Self::new_era(session_index) } else { + sp_runtime::print("💰 new_session initial era"); // Set initial era Self::new_era(session_index) } @@ -2494,6 +2510,16 @@ impl Module { /// Start a session potentially starting an era. fn start_session(start_session: SessionIndex) { + sp_runtime::print("💸 start_session doing something"); + sp_std::if_std! { + let next_active_era = Self::active_era().map(|e| e.index + 1).unwrap_or(0); + println!( + "next_active = {} / eras_start_session_index(next_active) = {:?} / start_session = {}", + next_active_era, + Self::eras_start_session_index(next_active_era), + start_session, + ); + } let next_active_era = Self::active_era().map(|e| e.index + 1).unwrap_or(0); if let Some(next_active_era_start_session_index) = Self::eras_start_session_index(next_active_era) @@ -2921,9 +2947,13 @@ impl Module { /// some session can lag in between the newest session planned and the latest session started. impl pallet_session::SessionManager for Module { fn new_session(new_index: SessionIndex) -> Option> { + sp_runtime::print("⏰ Staking new session"); + sp_runtime::print(new_index as u64); Self::new_session(new_index) } fn start_session(start_index: SessionIndex) { + sp_runtime::print("⏰ Staking start session"); + sp_runtime::print(start_index); Self::start_session(start_index) } fn end_session(end_index: SessionIndex) { diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index d522a19615951..e4f60b97a0302 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -17,6 +17,7 @@ //! Test utilities use std::{collections::{HashSet, HashMap}, cell::RefCell}; +use codec::Encode; use sp_runtime::Perbill; use sp_runtime::curve::PiecewiseLinear; use sp_runtime::traits::{IdentityLookup, Convert, SaturatedConversion, Zero}; @@ -65,6 +66,7 @@ thread_local! { static SLASH_DEFER_DURATION: RefCell = RefCell::new(0); static ELECTION_LOOKAHEAD: RefCell = RefCell::new(0); static PERIOD: RefCell = RefCell::new(1); + static ITERATIONS: RefCell = RefCell::new(0); } /// Another session handler struct to test on_disabled. @@ -95,6 +97,15 @@ impl pallet_session::OneSessionHandler for OtherSessionHandler { } } +pub struct StaticRandomness; +impl frame_support::traits::Randomness for StaticRandomness { + fn random(_subject: &[u8]) -> H256 { + let mut static_value = ITERATIONS.with(|v| *v.borrow()).encode(); + static_value.resize_with(32, || 0u8); + H256::from_slice(&static_value) + } +} + impl sp_runtime::BoundToRuntimeAppPublic for OtherSessionHandler { type Public = UintAuthorityId; } @@ -275,6 +286,7 @@ parameter_types! { pub const RewardCurve: &'static PiecewiseLinear<'static> = &I_NPOS; pub const MaxNominatorRewardedPerValidator: u32 = 64; pub const UnsignedPriority: u64 = 1 << 20; + pub const MaxIterations: u32 = 5; } impl Trait for Test { @@ -295,6 +307,8 @@ impl Trait for Test { type ElectionLookahead = ElectionLookahead; type Call = Call; type SubmitTransaction = SubmitTransaction; + type Randomness = StaticRandomness; + type MaxIterations = MaxIterations; type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator; type UnsignedPriority = UnsignedPriority; } @@ -316,6 +330,7 @@ pub struct ExtBuilder { num_validators: Option, invulnerables: Vec, has_stakers: bool, + offchain_iterations: u32, } impl Default for ExtBuilder { @@ -334,6 +349,7 @@ impl Default for ExtBuilder { num_validators: None, invulnerables: vec![], has_stakers: true, + offchain_iterations: 0, } } } @@ -391,6 +407,10 @@ impl ExtBuilder { self.has_stakers = has; self } + pub fn offchain_iterations(mut self, iterations: u32) -> Self { + self.offchain_iterations = iterations; + self + } pub fn offchain_phragmen_ext(self) -> Self { self.session_per_era(4) .session_length(5) @@ -402,6 +422,7 @@ impl ExtBuilder { SESSION_PER_ERA.with(|v| *v.borrow_mut() = self.session_per_era); ELECTION_LOOKAHEAD.with(|v| *v.borrow_mut() = self.election_lookahead); PERIOD.with(|v| *v.borrow_mut() = self.session_length); + ITERATIONS.with(|v| *v.borrow_mut() = self.offchain_iterations); } pub fn build(self) -> sp_io::TestExternalities { let _ = env_logger::try_init(); diff --git a/frame/staking/src/offchain_election.rs b/frame/staking/src/offchain_election.rs index 4d8ccc6f25cca..c71c3e83dea8e 100644 --- a/frame/staking/src/offchain_election.rs +++ b/frame/staking/src/offchain_election.rs @@ -16,17 +16,18 @@ //! Helpers for offchain worker election. +use codec::Decode; use crate::{ Call, CompactAssignments, Module, NominatorIndex, OffchainAccuracy, Trait, ValidatorIndex, }; use frame_system::offchain::SubmitUnsignedTransaction; use sp_phragmen::{ build_support_map, evaluate_support, reduce, Assignment, ExtendedBalance, PhragmenResult, - PhragmenScore, + PhragmenScore, equalize, }; use sp_runtime::offchain::storage::StorageValueRef; -use sp_runtime::PerThing; -use sp_runtime::RuntimeDebug; +use sp_runtime::{PerThing, RuntimeDebug, traits::{TrailingZeroInput, Zero}}; +use frame_support::{debug, traits::{Randomness, Get}}; use sp_std::{convert::TryInto, prelude::*}; /// Error types related to the offchain election machinery. @@ -159,10 +160,7 @@ pub fn prepare_submission( }; // Clean winners. - let winners = winners - .into_iter() - .map(|(w, _)| w) - .collect::>(); + let winners = sp_phragmen::to_without_backing(winners); // convert into absolute value and to obtain the reduced version. let mut staked = sp_phragmen::assignment_ratio_to_staked( @@ -170,10 +168,25 @@ pub fn prepare_submission( >::slashable_balance_of_vote_weight, ); + // reduce if do_reduce { reduce(&mut staked); } + let (mut support_map, _) = build_support_map::(&winners, &staked); + + // equalize a random number of times. + let phrase = b"staking_offchain_phragmen"; + let seed = T::Randomness::random(phrase); + let iterations = ::decode(&mut TrailingZeroInput::new(seed.as_ref())) + .expect("input is padded with zeroes; qed") % T::MaxIterations::get(); + let iterations_executed = equalize( + &mut staked, + &mut support_map, + Zero::zero(), + iterations as usize, + ); + // Convert back to ratio assignment. This takes less space. let low_accuracy_assignment = sp_phragmen::assignment_staked_to_ratio(staked); @@ -215,5 +228,12 @@ pub fn prepare_submission( } } + debug::native::debug!( + target: "staking", + "prepared solution after {} equalization iterations with score {:?}", + iterations_executed, + score, + ); + Ok((winners_indexed, compact, score)) } diff --git a/frame/staking/src/testing_utils.rs b/frame/staking/src/testing_utils.rs index 4c1ee66a75692..229b1e2c96995 100644 --- a/frame/staking/src/testing_utils.rs +++ b/frame/staking/src/testing_utils.rs @@ -153,13 +153,13 @@ pub fn get_weak_solution( let mut backing_stake_of: BTreeMap> = BTreeMap::new(); // self stake - >::enumerate().for_each(|(who, _p)| { + >::iter().for_each(|(who, _p)| { *backing_stake_of.entry(who.clone()).or_insert(Zero::zero()) += >::slashable_balance_of(&who) }); // add nominator stuff - >::enumerate().for_each(|(who, nomination)| { + >::iter().for_each(|(who, nomination)| { nomination.targets.into_iter().for_each(|v| { *backing_stake_of.entry(v).or_insert(Zero::zero()) += >::slashable_balance_of(&who) @@ -176,7 +176,7 @@ pub fn get_weak_solution( .collect(); let mut staked_assignments: Vec> = Vec::new(); - >::enumerate().for_each(|(who, nomination)| { + >::iter().for_each(|(who, nomination)| { let mut dist: Vec<(T::AccountId, ExtendedBalance)> = Vec::new(); nomination.targets.into_iter().for_each(|v| { if winners.iter().find(|&w| *w == v).is_some() { @@ -325,16 +325,29 @@ pub fn clean(era: EraIndex) ::AccountId: codec::EncodeLike, u32: codec::EncodeLike, { - >::enumerate().for_each(|(k, _)| { + >::iter().for_each(|(k, _)| { let ctrl = >::bonded(&k).unwrap(); >::remove(&k); >::remove(&k); >::remove(&ctrl); >::remove(k, era); }); - >::enumerate().for_each(|(k, _)| >::remove(k)); + >::iter().for_each(|(k, _)| >::remove(k)); >::remove_all(); >::remove_all(); >::kill(); QueuedScore::kill(); } + +/// get the active era. +pub fn active_era() -> EraIndex { + >::active_era().unwrap().index +} + +/// initialize the first era. +pub fn init_active_era() { + ActiveEra::put(ActiveEraInfo { + index: 1, + start: None, + }) +} diff --git a/frame/staking/src/tests.rs b/frame/staking/src/tests.rs index 15afda1e3af9d..40af50e6ddbbc 100644 --- a/frame/staking/src/tests.rs +++ b/frame/staking/src/tests.rs @@ -3124,6 +3124,49 @@ mod offchain_phragmen { }) } + #[test] + fn offchain_worker_runs_with_equalise() { + // Offchain worker equalises based on the number provided by randomness. See the difference + // in the priority, which comes from the computed score. + let mut ext = ExtBuilder::default() + .offchain_phragmen_ext() + .validator_count(2) + .offchain_iterations(2) + .build(); + let state = offchainify(&mut ext); + ext.execute_with(|| { + run_to_block(12); + + // local key 11 is in the elected set. + assert_eq_uvec!(Session::validators(), vec![11, 21]); + assert_eq!(state.read().transactions.len(), 0); + Staking::offchain_worker(12); + assert_eq!(state.read().transactions.len(), 1); + + let encoded = state.read().transactions[0].clone(); + let extrinsic: Extrinsic = Decode::decode(&mut &*encoded).unwrap(); + + let call = extrinsic.call; + let inner = match call { + mock::Call::Staking(inner) => inner, + }; + + assert_eq!( + ::validate_unsigned( + TransactionSource::Local, + &inner, + ), + TransactionValidity::Ok(ValidTransaction { + priority: 1250, // the proposed slot stake. + requires: vec![], + provides: vec![("StakingOffchain", active_era()).encode()], + longevity: 3, + propagate: false, + }) + ) + }) + } + #[test] fn mediocre_submission_from_authority_is_early_rejected() { let mut ext = ExtBuilder::default() From cb40663f057c890661d7feb563edf3af34895319 Mon Sep 17 00:00:00 2001 From: kianenigma Date: Fri, 17 Apr 2020 14:47:08 +0200 Subject: [PATCH 2/9] Remove debug stuff --- frame/staking/src/lib.rs | 24 ------------------------ 1 file changed, 24 deletions(-) diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index 3931c611b19fb..c653169a909db 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -1178,7 +1178,6 @@ decl_module! { { if let Some(next_session_change) = T::NextNewSession::estimate_next_new_session(now){ if let Some(remaining) = next_session_change.checked_sub(&now) { - debug::native::debug!(target: "staking", "remaining: {:?}", remaining); if remaining <= T::ElectionLookahead::get() && !remaining.is_zero() { // create snapshot. if Self::create_stakers_snapshot() { @@ -1209,13 +1208,6 @@ decl_module! { if Self::era_election_status().is_open_at(now) { let offchain_status = set_check_offchain_execution_status::(now); - debug::native::debug!( - target: "staking", - "RUNNING OFFCHAIN WORKER! {:?}/{}/{:?}", - Self::era_election_status(), - now, - offchain_status, - ); if let Err(why) = offchain_status { log!(debug, "skipping offchain worker in open election window due to [{}]", why); } else { @@ -2299,7 +2291,6 @@ impl Module { fn new_session(session_index: SessionIndex) -> Option> { if let Some(current_era) = Self::current_era() { // Initial era has been set. - sp_runtime::print("💰 new_session normal era"); let current_era_start_session_index = Self::eras_start_session_index(current_era) .unwrap_or_else(|| { @@ -2327,7 +2318,6 @@ impl Module { IsCurrentSessionFinal::put(false); Self::new_era(session_index) } else { - sp_runtime::print("💰 new_session initial era"); // Set initial era Self::new_era(session_index) } @@ -2510,16 +2500,6 @@ impl Module { /// Start a session potentially starting an era. fn start_session(start_session: SessionIndex) { - sp_runtime::print("💸 start_session doing something"); - sp_std::if_std! { - let next_active_era = Self::active_era().map(|e| e.index + 1).unwrap_or(0); - println!( - "next_active = {} / eras_start_session_index(next_active) = {:?} / start_session = {}", - next_active_era, - Self::eras_start_session_index(next_active_era), - start_session, - ); - } let next_active_era = Self::active_era().map(|e| e.index + 1).unwrap_or(0); if let Some(next_active_era_start_session_index) = Self::eras_start_session_index(next_active_era) @@ -2947,13 +2927,9 @@ impl Module { /// some session can lag in between the newest session planned and the latest session started. impl pallet_session::SessionManager for Module { fn new_session(new_index: SessionIndex) -> Option> { - sp_runtime::print("⏰ Staking new session"); - sp_runtime::print(new_index as u64); Self::new_session(new_index) } fn start_session(start_index: SessionIndex) { - sp_runtime::print("⏰ Staking start session"); - sp_runtime::print(start_index); Self::start_session(start_index) } fn end_session(end_index: SessionIndex) { From f95d7aa15cbc32d803d802c2ca067535e6908a1c Mon Sep 17 00:00:00 2001 From: kianenigma Date: Fri, 17 Apr 2020 14:49:22 +0200 Subject: [PATCH 3/9] Better license --- frame/staking/fuzzer/Cargo.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/frame/staking/fuzzer/Cargo.toml b/frame/staking/fuzzer/Cargo.toml index 12ecfd120356b..34e956a36724e 100644 --- a/frame/staking/fuzzer/Cargo.toml +++ b/frame/staking/fuzzer/Cargo.toml @@ -4,6 +4,10 @@ version = "0.0.0" authors = ["Automatically generated"] publish = false edition = "2018" +license = "GPL-3.0" +homepage = "https://substrate.dev" +repository = "https://github.com/paritytech/substrate/" +description = "FRAME pallet staking fuzzing" [dependencies] honggfuzz = "0.5" From dbdd27fa19948f16bd17defdc01d3dd32986df11 Mon Sep 17 00:00:00 2001 From: kianenigma Date: Fri, 17 Apr 2020 17:30:12 +0200 Subject: [PATCH 4/9] Migrate away from SimpleDispatchInfo --- bin/node-template/pallets/template/src/lib.rs | 6 +- frame/assets/src/lib.rs | 8 +- frame/authorship/src/lib.rs | 4 +- frame/benchmark/src/lib.rs | 28 +- frame/benchmarking/src/tests.rs | 6 +- frame/collective/src/lib.rs | 11 +- frame/contracts/src/lib.rs | 12 +- frame/democracy/src/lib.rs | 60 ++-- frame/elections-phragmen/src/lib.rs | 14 +- frame/elections/src/lib.rs | 30 +- frame/evm/src/lib.rs | 5 +- frame/example-offchain-worker/src/lib.rs | 6 +- frame/example/src/lib.rs | 10 +- frame/executive/src/lib.rs | 8 +- frame/finality-tracker/src/lib.rs | 4 +- frame/generic-asset/src/lib.rs | 14 +- frame/grandpa/src/lib.rs | 4 +- frame/identity/src/lib.rs | 24 +- frame/im-online/src/lib.rs | 8 +- frame/indices/src/lib.rs | 10 +- frame/membership/src/lib.rs | 15 +- frame/nicks/src/lib.rs | 9 +- frame/randomness-collective-flip/src/lib.rs | 4 +- frame/recovery/src/lib.rs | 18 +- frame/scored-pool/src/lib.rs | 16 +- frame/session/src/lib.rs | 6 +- frame/society/src/lib.rs | 26 +- frame/staking/src/lib.rs | 54 ++-- frame/sudo/src/lib.rs | 8 +- frame/support/src/dispatch.rs | 37 ++- frame/support/src/error.rs | 4 +- frame/support/src/metadata.rs | 4 +- frame/support/src/weights.rs | 288 +++++++++++------- frame/support/test/tests/decl_error.rs | 6 +- frame/support/test/tests/instance.rs | 4 +- .../tests/reserved_keyword/on_initialize.rs | 4 +- frame/system/src/lib.rs | 24 +- frame/timestamp/src/lib.rs | 8 +- frame/treasury/src/lib.rs | 18 +- frame/vesting/src/lib.rs | 8 +- 40 files changed, 439 insertions(+), 394 deletions(-) diff --git a/bin/node-template/pallets/template/src/lib.rs b/bin/node-template/pallets/template/src/lib.rs index adddbac21b554..ad721985b2674 100644 --- a/bin/node-template/pallets/template/src/lib.rs +++ b/bin/node-template/pallets/template/src/lib.rs @@ -10,7 +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_support::weights::MINIMUM_WEIGHT; use frame_system::{self as system, ensure_signed}; #[cfg(test)] @@ -76,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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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)?; @@ -92,7 +92,7 @@ decl_module! { /// Another dummy entry point. /// takes no parameters, attempts to increment storage value, and possibly throws an error - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 15726c9bcb1e9..60a9ab87a75a6 100644 --- a/frame/assets/src/lib.rs +++ b/frame/assets/src/lib.rs @@ -133,7 +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 frame_support::weights::MINIMUM_WEIGHT; use sp_runtime::traits::{Member, AtLeast32Bit, Zero, StaticLookup}; use frame_system::{self as system, ensure_signed}; use sp_runtime::traits::One; @@ -158,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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn issue(origin, #[compact] total: T::Balance) { let origin = ensure_signed(origin)?; @@ -172,7 +172,7 @@ decl_module! { } /// Move some assets from one holder to another. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn transfer(origin, #[compact] id: T::AssetId, target: ::Source, @@ -191,7 +191,7 @@ decl_module! { } /// Destroy any assets of `id` owned by `origin`. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 fac4b7d48201c..e77a0e27e29e4 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}; +use frame_support::weights::{Weight, MINIMUM_WEIGHT}; use sp_inherents::{InherentIdentifier, ProvideInherent, InherentData}; use sp_authorship::{INHERENT_IDENTIFIER, UnclesInherentData, InherentError}; @@ -207,7 +207,7 @@ decl_module! { } /// Provide a set of uncles. - #[weight = SimpleDispatchInfo::FixedMandatory(MINIMUM_WEIGHT)] + #[weight = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Mandatory)] fn set_uncles(origin, new_uncles: Vec) -> dispatch::DispatchResult { ensure_none(origin)?; ensure!(new_uncles.len() <= MAX_UNCLES, Error::::TooManyUncles); diff --git a/frame/benchmark/src/lib.rs b/frame/benchmark/src/lib.rs index 24b0e433101be..61b6ac9415565 100644 --- a/frame/benchmark/src/lib.rs +++ b/frame/benchmark/src/lib.rs @@ -21,7 +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::weights::MINIMUM_WEIGHT; use frame_support::traits::Currency; use frame_system::{self as system, ensure_signed}; use codec::{Encode, Decode}; @@ -71,7 +71,7 @@ decl_module! { fn deposit_event() = default; /// Do nothing. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] pub fn do_nothing(_origin, input: u32) { if input > 0 { return Ok(()); @@ -83,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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] pub fn read_value(_origin, repeat: u32) { for _ in 0..repeat { MyValue::get(); @@ -91,7 +91,7 @@ decl_module! { } /// Put a value into a storage value. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] pub fn put_value(_origin, repeat: u32) { for r in 0..repeat { MyValue::put(r); @@ -103,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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] pub fn exists_value(_origin, repeat: u32) { for _ in 0..repeat { MyValue::exists(); @@ -111,7 +111,7 @@ decl_module! { } /// Remove a value from storage `repeat` number of times. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] pub fn remove_value(_origin, repeat: u32) { for r in 0..repeat { MyMap::remove(r); @@ -119,7 +119,7 @@ decl_module! { } /// Read a value from storage map `repeat` number of times. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] pub fn read_map(_origin, repeat: u32) { for r in 0..repeat { MyMap::get(r); @@ -127,7 +127,7 @@ decl_module! { } /// Insert a value into a map. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] pub fn insert_map(_origin, repeat: u32) { for r in 0..repeat { MyMap::insert(r, r); @@ -135,7 +135,7 @@ decl_module! { } /// Check is a map contains a value `repeat` number of times. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] pub fn contains_key_map(_origin, repeat: u32) { for r in 0..repeat { MyMap::contains_key(r); @@ -143,7 +143,7 @@ decl_module! { } /// Read a value from storage `repeat` number of times. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] pub fn remove_prefix(_origin, repeat: u32) { for r in 0..repeat { MyDoubleMap::remove_prefix(r); @@ -151,21 +151,21 @@ decl_module! { } /// Add user to the list. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] pub fn append_member_list(origin) { let who = ensure_signed(origin)?; MyMemberList::::append(&[who])?; } /// Encode a vector of accounts to bytes. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] pub fn encode_accounts(_origin, accounts: Vec) { let bytes = accounts.encode(); @@ -177,7 +177,7 @@ decl_module! { } /// Decode bytes into a vector of accounts. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 4b26ec732d296..cb8bb8603f6b0 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -24,7 +24,7 @@ use sp_std::prelude::*; use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::{H256, Header}}; use frame_support::{ dispatch::DispatchResult, - weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}, + weights::MINIMUM_WEIGHT, decl_module, decl_storage, impl_outer_origin, assert_ok, assert_err, ensure }; use frame_system::{RawOrigin, ensure_signed, ensure_none}; @@ -37,14 +37,14 @@ decl_storage! { decl_module! { pub struct Module for enum Call where origin: T::Origin { - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn set_value(origin, n: u32) -> DispatchResult { let _sender = ensure_signed(origin)?; Value::put(n); Ok(()) } - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn dummy(origin, _n: u32) -> DispatchResult { let _sender = ensure_none(origin)?; Ok(()) diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index b5626ae4a6814..bfcdc86f1db50 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -40,7 +40,6 @@ use sp_std::{prelude::*, result}; use sp_core::u32_trait::Value as U32; use sp_runtime::RuntimeDebug; use sp_runtime::traits::Hash; -use frame_support::weights::SimpleDispatchInfo; use frame_support::{ dispatch::{Dispatchable, Parameter}, codec::{Encode, Decode}, traits::{Get, ChangeMembers, InitializeMembers, EnsureOrigin}, decl_module, decl_event, @@ -187,7 +186,7 @@ decl_module! { /// - `prime`: The prime member whose vote sets the default. /// /// Requires root origin. - #[weight = SimpleDispatchInfo::FixedOperational(100_000_000)] + #[weight = (100_000_000, frame_support::weights::DispatchClass::Operational)] fn set_members(origin, new_members: Vec, prime: Option) { ensure_root(origin)?; let mut new_members = new_members; @@ -200,7 +199,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_000)] + #[weight = (100_000_000, frame_support::weights::DispatchClass::Operational)] fn execute(origin, proposal: Box<>::Proposal>) { let who = ensure_signed(origin)?; ensure!(Self::is_member(&who), Error::::NotMember); @@ -214,7 +213,7 @@ decl_module! { /// - Bounded storage reads and writes. /// - Argument `threshold` has bearing on weight. /// # - #[weight = SimpleDispatchInfo::FixedOperational(5_000_000_000)] + #[weight = (5_000_000_000, frame_support::weights::DispatchClass::Operational)] fn propose(origin, #[compact] threshold: MemberCount, proposal: Box<>::Proposal>) { let who = ensure_signed(origin)?; ensure!(Self::is_member(&who), Error::::NotMember); @@ -244,7 +243,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_000)] + #[weight = (200_000_000, frame_support::weights::DispatchClass::Operational)] 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 +302,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_000)] + #[weight = (200_000_000, frame_support::weights::DispatchClass::Operational)] fn close(origin, proposal: T::Hash, #[compact] index: ProposalIndex) { let _ = ensure_signed(origin)?; diff --git a/frame/contracts/src/lib.rs b/frame/contracts/src/lib.rs index 91f06d5607c8b..e7c8fe5b12916 100644 --- a/frame/contracts/src/lib.rs +++ b/frame/contracts/src/lib.rs @@ -123,7 +123,7 @@ use sp_runtime::{ RuntimeDebug, }; use frame_support::dispatch::{DispatchResult, Dispatchable}; -use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; +use frame_support::weights::MINIMUM_WEIGHT; use frame_support::{ Parameter, decl_module, decl_event, decl_storage, decl_error, storage::child, parameter_types, IsSubType, @@ -551,7 +551,7 @@ decl_module! { /// Updates the schedule for metering contracts. /// /// The schedule must have a greater version than the stored schedule. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] pub fn update_schedule(origin, schedule: Schedule) -> DispatchResult { ensure_root(origin)?; if >::current_schedule().version >= schedule.version { @@ -566,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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] pub fn put_code( origin, #[compact] gas_limit: Gas, @@ -594,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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] pub fn call( origin, dest: ::Source, @@ -620,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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] pub fn instantiate( origin, #[compact] endowment: BalanceOf, @@ -643,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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 a76567ba2743c..cc81571a2d4f3 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}, + weights::{Weight, MINIMUM_WEIGHT}, traits::{ Currency, ReservableCurrency, LockableCurrency, WithdrawReason, LockIdentifier, Get, OnUnbalanced, BalanceStatus, schedule::Named as ScheduleNamed, EnsureOrigin @@ -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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = (500_000_000, frame_support::weights::DispatchClass::Operational)] 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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(MINIMUM_WEIGHT)] + #[weight = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Operational)] fn cancel_referendum(origin, #[compact] ref_index: ReferendumIndex) { ensure_root(origin)?; Self::internal_cancel_referendum(ref_index); @@ -836,7 +836,7 @@ decl_module! { /// - One DB change. /// - O(d) where d is the items in the dispatch queue. /// # - #[weight = SimpleDispatchInfo::FixedOperational(MINIMUM_WEIGHT)] + #[weight = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Operational)] 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] 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_000)] + #[weight = 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_000)] + #[weight = 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(MINIMUM_WEIGHT)] + #[weight = 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(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] 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_000)] + #[weight = 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(MINIMUM_WEIGHT)] + #[weight = 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(MINIMUM_WEIGHT)] + #[weight = 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 }; @@ -1207,7 +1207,7 @@ decl_module! { /// /// # /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] + #[weight = 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_000)] + #[weight = 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(MINIMUM_WEIGHT)] + #[weight = 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)?; @@ -1259,7 +1259,7 @@ decl_module! { } /// Enact a proposal from a referendum. For now we just make the weight be the maximum. - #[weight = SimpleDispatchInfo::MaxNormal] + #[weight = Weight::max_value()] fn enact_proposal(origin, proposal_hash: T::Hash, index: ReferendumIndex) -> DispatchResult { ensure_root(origin)?; Self::do_enact_proposal(proposal_hash, index) diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 610f008457277..1e419e2c24fd9 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}, storage::{StorageMap, IterableStorageMap}, + weights::{Weight, MINIMUM_WEIGHT}, storage::{StorageMap, IterableStorageMap}, traits::{ Currency, Get, LockableCurrency, LockIdentifier, ReservableCurrency, WithdrawReasons, ChangeMembers, OnUnbalanced, WithdrawReason, Contains, BalanceStatus, InitializeMembers, @@ -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_000)] + #[weight = 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(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = (2_000_000_000, frame_support::weights::DispatchClass::Operational)] 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_000)] + #[weight = (2_000_000_000, frame_support::weights::DispatchClass::Operational)] 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 a2398ad485960..5c090c4711a74 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}, + weights::{Weight, MINIMUM_WEIGHT}, traits::{ Currency, ExistenceRequirement, Get, LockableCurrency, LockIdentifier, BalanceStatus, OnUnbalanced, ReservableCurrency, WithdrawReason, WithdrawReasons, ChangeMembers @@ -405,13 +405,13 @@ 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_000)] + #[weight = 2_500_000_000] fn set_approvals( origin, votes: Vec, #[compact] index: VoteIndex, hint: SetIndex, - #[compact] value: BalanceOf + #[compact] value: BalanceOf, ) -> DispatchResult { let who = ensure_signed(origin)?; Self::do_set_approvals(who, votes, index, hint, value) @@ -423,12 +423,12 @@ decl_module! { /// # /// - Same as `set_approvals` with one additional storage read. /// # - #[weight = SimpleDispatchInfo::FixedNormal(2_500_000_000)] + #[weight = 2_500_000_000] fn proxy_set_approvals(origin, votes: Vec, #[compact] index: VoteIndex, hint: SetIndex, - #[compact] value: BalanceOf + #[compact] value: BalanceOf, ) -> DispatchResult { let who = Self::proxy(ensure_signed(origin)?).ok_or(Error::::NotProxy)?; Self::do_set_approvals(who, votes, index, hint, value) @@ -446,13 +446,13 @@ decl_module! { /// - O(1). /// - Two fewer DB entries, one DB change. /// # - #[weight = SimpleDispatchInfo::FixedNormal(2_500_000_000)] + #[weight = 2_500_000_000] fn reap_inactive_voter( origin, #[compact] reporter_index: u32, who: ::Source, #[compact] who_index: u32, - #[compact] assumed_vote_index: VoteIndex + #[compact] assumed_vote_index: VoteIndex, ) { let reporter = ensure_signed(origin)?; let who = T::Lookup::lookup(who)?; @@ -520,7 +520,7 @@ decl_module! { /// - O(1). /// - Two fewer DB entries, one DB change. /// # - #[weight = SimpleDispatchInfo::FixedNormal(1_250_000_000)] + #[weight = 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_000)] + #[weight = 2_500_000_000] fn submit_candidacy(origin, #[compact] slot: u32) { let who = ensure_signed(origin)?; @@ -585,12 +585,12 @@ decl_module! { /// - O(voters) compute. /// - One DB change. /// # - #[weight = SimpleDispatchInfo::FixedNormal(10_000_000_000)] + #[weight = 10_000_000_000] fn present_winner( origin, candidate: ::Source, #[compact] total: BalanceOf, - #[compact] index: VoteIndex + #[compact] index: VoteIndex, ) -> DispatchResult { let who = ensure_signed(origin)?; ensure!( @@ -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(MINIMUM_WEIGHT)] + #[weight = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Operational)] 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(MINIMUM_WEIGHT)] + #[weight = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Operational)] 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(MINIMUM_WEIGHT)] + #[weight = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Operational)] 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(MINIMUM_WEIGHT)] + #[weight = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Operational)] 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 f67ab767ed320..48946858dffb6 100644 --- a/frame/evm/src/lib.rs +++ b/frame/evm/src/lib.rs @@ -29,7 +29,6 @@ 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; -use frame_support::weights::SimpleDispatchInfo; use sp_core::{U256, H256, H160, Hasher}; use sp_runtime::{ DispatchResult, traits::{UniqueSaturatedInto, AccountIdConversion, SaturatedConversion}, @@ -191,7 +190,7 @@ decl_module! { fn deposit_event() = default; /// Deposit balance from currency/balances module into EVM. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn deposit_balance(origin, value: BalanceOf) { let sender = ensure_signed(origin)?; @@ -212,7 +211,7 @@ decl_module! { } /// Withdraw balance from EVM into currency/balances module. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 29a4859c78e21..1762d95bc94a1 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, MINIMUM_WEIGHT}, + weights::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(MINIMUM_WEIGHT)] + #[weight = 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(MINIMUM_WEIGHT)] + #[weight = 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 97cad2856a00d..e7a5a0c02e5ae 100644 --- a/frame/example/src/lib.rs +++ b/frame/example/src/lib.rs @@ -256,10 +256,7 @@ use sp_std::marker::PhantomData; use frame_support::{ dispatch::DispatchResult, decl_module, decl_storage, decl_event, - weights::{ - SimpleDispatchInfo, DispatchClass, ClassifyDispatch, WeighData, Weight, PaysFee, - MINIMUM_WEIGHT, - }, + weights::{DispatchClass, ClassifyDispatch, WeighData, Weight, PaysFee, MINIMUM_WEIGHT}, }; use sp_std::prelude::*; use frame_system::{self as system, ensure_signed, ensure_root}; @@ -469,7 +466,7 @@ decl_module! { // weight (a numeric representation of pure execution time and difficulty) of the // transaction and the latter demonstrates the [`DispatchClass`] of the call. A higher // weight means a larger transaction (less of which can be placed in a single block). - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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)?; @@ -518,8 +515,7 @@ decl_module! { // The signature could also look like: `fn on_initialize()`. // This function could also very well have a weight annotation, similar to any other. The - // only difference being that if it is not annotated, the default is - // `SimpleDispatchInfo::zero()`, which resolves into no weight. + // only difference is that it mut be returned, not annotated. fn on_initialize(_n: T::BlockNumber) -> Weight { // Anything that needs to be done at the start of the block. // We don't do anything here. diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index 747fc85866862..f99ad03416e75 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -416,22 +416,22 @@ mod tests { use hex_literal::hex; mod custom { - use frame_support::weights::{SimpleDispatchInfo, Weight}; + use frame_support::weights::Weight; pub trait Trait: frame_system::Trait {} frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin { - #[weight = SimpleDispatchInfo::FixedNormal(100)] + #[weight = 100] fn some_function(origin) { // NOTE: does not make any different. let _ = frame_system::ensure_signed(origin); } - #[weight = SimpleDispatchInfo::FixedOperational(200)] + #[weight = (200, frame_support::weights::DispatchClass::Operational)] fn some_root_operation(origin) { let _ = frame_system::ensure_root(origin); } - #[weight = SimpleDispatchInfo::InsecureFreeNormal] + #[weight = 0] fn some_unsigned_message(origin) { let _ = frame_system::ensure_none(origin); } diff --git a/frame/finality-tracker/src/lib.rs b/frame/finality-tracker/src/lib.rs index 54506784a9f1b..a7d41848250ef 100644 --- a/frame/finality-tracker/src/lib.rs +++ b/frame/finality-tracker/src/lib.rs @@ -23,7 +23,7 @@ use sp_runtime::traits::{One, Zero, SaturatedConversion}; use sp_std::{prelude::*, result, cmp, vec}; use frame_support::{decl_module, decl_storage, decl_error, ensure}; use frame_support::traits::Get; -use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; +use frame_support::weights::MINIMUM_WEIGHT; use frame_system::{ensure_none, Trait as SystemTrait}; use sp_finality_tracker::{INHERENT_IDENTIFIER, FinalizedInherentData}; @@ -77,7 +77,7 @@ decl_module! { /// Hint that the author of this block thinks the best finalized /// block is the given number. - #[weight = SimpleDispatchInfo::FixedMandatory(MINIMUM_WEIGHT)] + #[weight = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Mandatory)] 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 720ccd85cccc6..b56c724336111 100644 --- a/frame/generic-asset/src/lib.rs +++ b/frame/generic-asset/src/lib.rs @@ -164,7 +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}, + weights::MINIMUM_WEIGHT, traits::{ Currency, ExistenceRequirement, Imbalance, LockIdentifier, LockableCurrency, ReservableCurrency, SignedImbalance, WithdrawReason, WithdrawReasons, TryDrop, BalanceStatus, @@ -361,14 +361,14 @@ decl_module! { fn deposit_event() = default; /// Create a new kind of asset. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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); @@ -378,7 +378,7 @@ decl_module! { /// Updates permission for a given `asset_id` and an account. /// /// The `origin` must have `update` permission. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn update_permission( origin, #[compact] asset_id: T::AssetId, @@ -401,7 +401,7 @@ decl_module! { /// Mints an asset, increases its total issuance. /// The origin must have `mint` permissions. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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)?; @@ -411,7 +411,7 @@ decl_module! { /// Burns an asset, decreases its total issuance. /// The `origin` must have `burn` permissions. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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)?; @@ -421,7 +421,7 @@ decl_module! { /// Can be used to create reserved tokens. /// Requires Root call. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 10cc8162db3a7..49326c71cb23c 100644 --- a/frame/grandpa/src/lib.rs +++ b/frame/grandpa/src/lib.rs @@ -33,7 +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 frame_support::weights::MINIMUM_WEIGHT; use sp_runtime::{ DispatchResult, generic::{DigestItem, OpaqueDigestItemId}, traits::Zero, Perbill, }; @@ -185,7 +185,7 @@ decl_module! { fn deposit_event() = default; /// Report some misbehavior. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 ddb9bdcce2163..31eb93f04b21a 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, MINIMUM_WEIGHT}, + weights::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(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 100_000_000] fn kill_identity(origin, target: ::Source) { T::ForceOrigin::try_origin(origin) .map(|_| ()) diff --git a/frame/im-online/src/lib.rs b/frame/im-online/src/lib.rs index 1137fc2699fe3..20726a8388b65 100644 --- a/frame/im-online/src/lib.rs +++ b/frame/im-online/src/lib.rs @@ -43,7 +43,7 @@ //! //! ``` //! use frame_support::{decl_module, dispatch}; -//! use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; +//! use frame_support::weights::MINIMUM_WEIGHT; //! use frame_system::{self as system, ensure_signed}; //! use pallet_im_online::{self as im_online}; //! @@ -51,7 +51,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] +//! #[weight = MINIMUM_WEIGHT] //! pub fn is_online(origin, authority_index: u32) -> dispatch::DispatchResult { //! let _sender = ensure_signed(origin)?; //! let _is_online = >::is_online(authority_index); @@ -95,7 +95,7 @@ use sp_staking::{ use frame_support::{ decl_module, decl_event, decl_storage, Parameter, debug, decl_error, traits::Get, - weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}, + weights::MINIMUM_WEIGHT, }; use frame_system::{self as system, ensure_none}; use frame_system::offchain::SubmitUnsignedTransaction; @@ -318,7 +318,7 @@ decl_module! { fn deposit_event() = default; - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn heartbeat( origin, heartbeat: Heartbeat, diff --git a/frame/indices/src/lib.rs b/frame/indices/src/lib.rs index 2a66af7e7f8bb..f4f5b69e8cdf1 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}; +use frame_support::weights::{Weight, MINIMUM_WEIGHT}; use frame_support::dispatch::DispatchResult; use frame_support::traits::{Currency, ReservableCurrency, Get, BalanceStatus::Reserved}; use frame_support::storage::migration::take_storage_value; @@ -121,7 +121,7 @@ decl_module! { /// - One reserve operation. /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn force_transfer(origin, new: T::AccountId, index: T::AccountIndex) { ensure_root(origin)?; diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index e968be19a6be1..188a0b268c104 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -26,7 +26,6 @@ use sp_std::prelude::*; use frame_support::{ decl_module, decl_storage, decl_event, decl_error, traits::{ChangeMembers, InitializeMembers, EnsureOrigin}, - weights::SimpleDispatchInfo, }; use frame_system::{self as system, ensure_root, ensure_signed}; @@ -118,7 +117,7 @@ decl_module! { /// Add a member `who` to the set. /// /// May only be called from `AddOrigin` or root. - #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] + #[weight = 50_000_000] fn add_member(origin, who: T::AccountId) { T::AddOrigin::try_origin(origin) .map(|_| ()) @@ -137,7 +136,7 @@ decl_module! { /// Remove a member `who` from the set. /// /// May only be called from `RemoveOrigin` or root. - #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] + #[weight = 50_000_000] fn remove_member(origin, who: T::AccountId) { T::RemoveOrigin::try_origin(origin) .map(|_| ()) @@ -159,7 +158,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_000)] + #[weight = 50_000_000] fn swap_member(origin, remove: T::AccountId, add: T::AccountId) { T::SwapOrigin::try_origin(origin) .map(|_| ()) @@ -188,7 +187,7 @@ decl_module! { /// pass `members` pre-sorted. /// /// May only be called from `ResetOrigin` or root. - #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] + #[weight = 50_000_000] fn reset_members(origin, members: Vec) { T::ResetOrigin::try_origin(origin) .map(|_| ()) @@ -211,7 +210,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_000)] + #[weight = 50_000_000] fn change_key(origin, new: T::AccountId) { let remove = ensure_signed(origin)?; @@ -239,7 +238,7 @@ decl_module! { } /// Set the prime member. Must be a current member. - #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] + #[weight = 50_000_000] fn set_prime(origin, who: T::AccountId) { T::PrimeOrigin::try_origin(origin) .map(|_| ()) @@ -250,7 +249,7 @@ decl_module! { } /// Remove the prime member if it exists. - #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] + #[weight = 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 b8a2359450458..97a5074046168 100644 --- a/frame/nicks/src/lib.rs +++ b/frame/nicks/src/lib.rs @@ -45,7 +45,6 @@ use sp_runtime::{ use frame_support::{ decl_module, decl_event, decl_storage, ensure, decl_error, traits::{Currency, EnsureOrigin, ReservableCurrency, OnUnbalanced, Get}, - weights::SimpleDispatchInfo, }; use frame_system::{self as system, ensure_signed, ensure_root}; @@ -141,7 +140,7 @@ decl_module! { /// - One storage read/write. /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] + #[weight = 50_000_000] fn set_name(origin, name: Vec) { let sender = ensure_signed(origin)?; @@ -171,7 +170,7 @@ decl_module! { /// - One storage read/write. /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(70_000_000)] + #[weight = 70_000_000] fn clear_name(origin) { let sender = ensure_signed(origin)?; @@ -195,7 +194,7 @@ decl_module! { /// - One storage read/write. /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(70_000_000)] + #[weight = 70_000_000] fn kill_name(origin, target: ::Source) { T::ForceOrigin::try_origin(origin) .map(|_| ()) @@ -223,7 +222,7 @@ decl_module! { /// - One storage read/write. /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(70_000_000)] + #[weight = 70_000_000] fn force_name(origin, target: ::Source, name: Vec) { T::ForceOrigin::try_origin(origin) .map(|_| ()) diff --git a/frame/randomness-collective-flip/src/lib.rs b/frame/randomness-collective-flip/src/lib.rs index 194879eb65b80..0e8373f884ce9 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, MINIMUM_WEIGHT}}; +//! use frame_support::{decl_module, dispatch, traits::Randomness, weights::MINIMUM_WEIGHT}; //! //! pub trait Trait: frame_system::Trait {} //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] +//! #[weight = MINIMUM_WEIGHT] //! pub fn random_module_example(origin) -> dispatch::DispatchResult { //! let _random_seed = >::random_seed(); //! Ok(()) diff --git a/frame/recovery/src/lib.rs b/frame/recovery/src/lib.rs index 9f30061f935fa..e0397cc1a5d46 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::{MINIMUM_WEIGHT, GetDispatchInfo, SimpleDispatchInfo, FunctionOf}, + Parameter, RuntimeDebug, weights::{MINIMUM_WEIGHT, GetDispatchInfo, FunctionOf}, traits::{Currency, ReservableCurrency, Get, BalanceStatus}, dispatch::PostDispatchInfo, }; @@ -365,7 +365,7 @@ decl_module! { /// - One storage write O(1) /// - One event /// # - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 30_000_000] fn remove_recovery(origin) { let who = ensure_signed(origin)?; // Check there are no active recoveries @@ -647,7 +647,7 @@ decl_module! { /// # /// - One storage mutation to check account is recovered by `who`. O(1) /// # - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 eca877f096283..8cbf20af805d3 100644 --- a/frame/scored-pool/src/lib.rs +++ b/frame/scored-pool/src/lib.rs @@ -54,7 +54,7 @@ //! //! ``` //! use frame_support::{decl_module, dispatch}; -//! use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; +//! use frame_support::weights::MINIMUM_WEIGHT; //! use frame_system::{self as system, ensure_signed}; //! use pallet_scored_pool::{self as scored_pool}; //! @@ -62,7 +62,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] +//! #[weight = MINIMUM_WEIGHT] //! pub fn candidate(origin) -> dispatch::DispatchResult { //! let who = ensure_signed(origin)?; //! @@ -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}, + weights::{Weight, MINIMUM_WEIGHT}, }; use frame_system::{self as system, ensure_root, ensure_signed}; use sp_runtime::{ @@ -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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 f539004189a95..afab71734ea04 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}, + weights::{Weight, MINIMUM_WEIGHT}, }; use frame_system::{self as system, ensure_signed}; @@ -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_000)] + #[weight = 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_000)] + #[weight = 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 f9908f5d9c6c0..9799368e9d81c 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}; +use frame_support::weights::{Weight, MINIMUM_WEIGHT}; use frame_support::traits::{ Currency, ReservableCurrency, Randomness, Get, ChangeMembers, BalanceStatus, ExistenceRequirement::AllowDeath, EnsureOrigin @@ -527,7 +527,7 @@ decl_module! { /// /// Total Complexity: O(M + B + C + logM + logB + X) /// # - #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] 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 b6ffa9081bbce..e5b2a25dde54a 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -150,7 +150,7 @@ //! //! ``` //! use frame_support::{decl_module, dispatch}; -//! use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; +//! use frame_support::weights::MINIMUM_WEIGHT; //! use frame_system::{self as system, ensure_signed}; //! use pallet_staking::{self as staking}; //! @@ -159,7 +159,7 @@ //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { //! /// Reward a validator. -//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] +//! #[weight = MINIMUM_WEIGHT] //! pub fn reward_myself(origin) -> dispatch::DispatchResult { //! let reported = ensure_signed(origin)?; //! >::reward_by_ids(vec![(reported, 10)]); @@ -275,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, MINIMUM_WEIGHT, Weight}, + weights::{MINIMUM_WEIGHT, Weight}, storage::IterableStorageMap, dispatch::{IsSubType, DispatchResult}, traits::{ @@ -1250,7 +1250,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_000)] + #[weight = 500_000_000] pub fn bond(origin, controller: ::Source, #[compact] value: BalanceOf, @@ -1314,7 +1314,7 @@ decl_module! { /// - O(1). /// - One DB entry. /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] + #[weight = 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)?; @@ -1360,7 +1360,7 @@ decl_module! { /// `withdraw_unbonded`. /// - One DB entry. /// - #[weight = SimpleDispatchInfo::FixedNormal(400_000_000)] + #[weight = 400_000_000] fn unbond(origin, #[compact] value: BalanceOf) { ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed); let controller = ensure_signed(origin)?; @@ -1408,7 +1408,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_000)] + #[weight = 400_000_000] fn withdraw_unbonded(origin) { ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed); let controller = ensure_signed(origin)?; @@ -1451,7 +1451,7 @@ decl_module! { /// - Contains a limited number of reads. /// - Writes are limited to the `origin` account key. /// # - #[weight = SimpleDispatchInfo::FixedNormal(750_000_000)] + #[weight = 750_000_000] pub fn validate(origin, prefs: ValidatorPrefs) { ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed); let controller = ensure_signed(origin)?; @@ -1474,7 +1474,7 @@ decl_module! { /// which is capped at CompactAssignments::LIMIT. /// - Both the reads and writes follow a similar pattern. /// # - #[weight = SimpleDispatchInfo::FixedNormal(750_000_000)] + #[weight = 750_000_000] pub fn nominate(origin, targets: Vec<::Source>) { ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed); let controller = ensure_signed(origin)?; @@ -1509,7 +1509,7 @@ decl_module! { /// - Contains one read. /// - Writes are limited to the `origin` account key. /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] + #[weight = 500_000_000] fn chill(origin) { ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed); let controller = ensure_signed(origin)?; @@ -1528,7 +1528,7 @@ decl_module! { /// - Contains a limited number of reads. /// - Writes are limited to the `origin` account key. /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] + #[weight = 500_000_000] fn set_payee(origin, payee: RewardDestination) { let controller = ensure_signed(origin)?; let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; @@ -1547,7 +1547,7 @@ decl_module! { /// - Contains a limited number of reads. /// - Writes are limited to the `origin` account key. /// # - #[weight = SimpleDispatchInfo::FixedNormal(750_000_000)] + #[weight = 750_000_000] fn set_controller(origin, controller: ::Source) { let stash = ensure_signed(origin)?; let old_controller = Self::bonded(&stash).ok_or(Error::::NotStash)?; @@ -1564,7 +1564,7 @@ decl_module! { } /// The ideal number of validators. - #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] + #[weight = 5_000_000] fn set_validator_count(origin, #[compact] new: u32) { ensure_root(origin)?; ValidatorCount::put(new); @@ -1575,7 +1575,7 @@ decl_module! { /// # /// - No arguments. /// # - #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] + #[weight = 5_000_000] fn force_no_eras(origin) { ensure_root(origin)?; ForceEra::put(Forcing::ForceNone); @@ -1587,21 +1587,21 @@ decl_module! { /// # /// - No arguments. /// # - #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] + #[weight = 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_000)] + #[weight = 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(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn force_unstake(origin, stash: T::AccountId) { ensure_root(origin)?; @@ -1617,7 +1617,7 @@ decl_module! { /// # /// - One storage write /// # - #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] + #[weight = 5_000_000] fn force_new_era_always(origin) { ensure_root(origin)?; ForceEra::put(Forcing::ForceAlways); @@ -1630,7 +1630,7 @@ decl_module! { /// # /// - One storage write. /// # - #[weight = SimpleDispatchInfo::FixedNormal(1_000_000_000)] + #[weight = 1_000_000_000] fn cancel_deferred_slash(origin, era: EraIndex, slash_indices: Vec) { T::SlashCancelOrigin::try_origin(origin) .map(|_| ()) @@ -1681,7 +1681,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_000)] + #[weight = 500_000_000] fn payout_nominator(origin, era: EraIndex, validators: Vec<(T::AccountId, u32)>) -> DispatchResult { @@ -1708,7 +1708,7 @@ decl_module! { /// - Time complexity: O(1). /// - Contains a limited number of reads and writes. /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] + #[weight = 500_000_000] fn payout_validator(origin, era: EraIndex) -> DispatchResult { let ctrl = ensure_signed(origin)?; Self::do_payout_validator(ctrl, era) @@ -1729,7 +1729,7 @@ decl_module! { /// - Time complexity: at most O(MaxNominatorRewardedPerValidator). /// - Contains a limited number of reads and writes. /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] + #[weight = 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)?; @@ -1745,7 +1745,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_000)] + #[weight = 500_000_000] fn rebond(origin, #[compact] value: BalanceOf) { ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed); let controller = ensure_signed(origin)?; @@ -1759,7 +1759,7 @@ decl_module! { /// Set history_depth value. /// /// Origin must be root. - #[weight = SimpleDispatchInfo::FixedOperational(500_000_000)] + #[weight = (500_000_000, frame_support::weights::DispatchClass::Operational)] fn set_history_depth(origin, #[compact] new_history_depth: EraIndex) { ensure_root(origin)?; if let Some(current_era) = Self::current_era() { @@ -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 = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn reap_stash(_origin, stash: T::AccountId) { ensure!(T::Currency::total_balance(&stash).is_zero(), Error::::FundedTarget); Self::kill_stash(&stash)?; @@ -1862,7 +1862,7 @@ decl_module! { /// /// The weight of this call is 1/10th of the blocks total weight. /// # - #[weight = SimpleDispatchInfo::FixedNormal(100_000_000_000)] + #[weight = 100_000_000_000] pub fn submit_election_solution( origin, winners: Vec, @@ -1885,7 +1885,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_000)] + #[weight = 100_000_000_000] pub fn submit_election_solution_unsigned( origin, winners: Vec, diff --git a/frame/sudo/src/lib.rs b/frame/sudo/src/lib.rs index b8cf9a353f341..ce0de2027c713 100644 --- a/frame/sudo/src/lib.rs +++ b/frame/sudo/src/lib.rs @@ -52,14 +52,14 @@ //! //! ``` //! use frame_support::{decl_module, dispatch}; -//! use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; +//! use frame_support::weights::MINIMUM_WEIGHT; //! use frame_system::{self as system, ensure_root}; //! //! pub trait Trait: frame_system::Trait {} //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] +//! #[weight = MINIMUM_WEIGHT] //! pub fn privileged_function(origin) -> dispatch::DispatchResult { //! ensure_root(origin)?; //! @@ -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::{SimpleDispatchInfo, MINIMUM_WEIGHT, GetDispatchInfo, FunctionOf}; +use frame_support::weights::{MINIMUM_WEIGHT, GetDispatchInfo, FunctionOf}; use frame_system::{self as system, ensure_signed}; pub trait Trait: frame_system::Trait { @@ -151,7 +151,7 @@ decl_module! { /// - Limited storage reads. /// - One DB change. /// # - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 8512ccb0a8e22..434c8591a283b 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -24,8 +24,8 @@ pub use frame_metadata::{ ModuleConstantMetadata, DefaultByte, DefaultByteGetter, ModuleErrorMetadata, ErrorMetadata }; pub use crate::weights::{ - SimpleDispatchInfo, GetDispatchInfo, DispatchInfo, WeighData, ClassifyDispatch, - TransactionPriority, Weight, PaysFee, PostDispatchInfo, WithPostDispatchInfo, + GetDispatchInfo, DispatchInfo, WeighData, ClassifyDispatch, TransactionPriority, Weight, + PaysFee, PostDispatchInfo, WithPostDispatchInfo, }; pub use sp_runtime::{traits::Dispatchable, DispatchError}; pub use crate::traits::{CallMetadata, GetCallMetadata, GetCallName}; @@ -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, MINIMUM_WEIGHT}; +/// # use frame_support::weights::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(MINIMUM_WEIGHT)] +/// #[weight = 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(MINIMUM_WEIGHT)] +/// #[weight = 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, MINIMUM_WEIGHT}; +/// # use frame_support::weights::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(MINIMUM_WEIGHT)] +/// #[weight = MINIMUM_WEIGHT] /// fn my_long_function(origin) -> dispatch::DispatchResult { /// // Your implementation /// Ok(()) /// } /// -/// #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] +/// #[weight = MINIMUM_WEIGHT] /// fn my_short_function(origin) { /// // Your implementation /// } @@ -153,11 +153,10 @@ impl Parameter for T where T: Codec + EncodeLike + Clone + Eq + fmt::Debug {} /// # #[macro_use] /// # extern crate frame_support; /// # use frame_support::dispatch::{DispatchResultWithPostInfo, WithPostDispatchInfo}; -/// # use frame_support::weights::SimpleDispatchInfo; /// # use frame_system::{self as system, Trait, ensure_signed}; /// decl_module! { /// pub struct Module for enum Call where origin: T::Origin { -/// #[weight = SimpleDispatchInfo::FixedNormal(1_000_000)] +/// #[weight = 1_000_000] /// fn my_long_function(origin, do_expensive_calc: bool) -> DispatchResultWithPostInfo { /// ensure_signed(origin).map_err(|e| e.with_weight(100_000))?; /// if do_expensive_calc { @@ -182,11 +181,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, MINIMUM_WEIGHT}; +/// # use frame_support::weights::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(MINIMUM_WEIGHT)] +/// #[weight = MINIMUM_WEIGHT] /// fn my_privileged_function(origin) -> dispatch::DispatchResult { /// ensure_root(origin)?; /// // Your implementation @@ -2112,25 +2111,25 @@ 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(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn aux_0(_origin) -> DispatchResult { unreachable!() } - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn aux_1(_origin, #[compact] _data: u32,) -> DispatchResult { unreachable!() } - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn aux_2(_origin, _data: i32, _data2: String) -> DispatchResult { unreachable!() } - #[weight = SimpleDispatchInfo::FixedNormal(3)] + #[weight = 3] fn aux_3(_origin) -> DispatchResult { unreachable!() } - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn aux_4(_origin, _data: i32) -> DispatchResult { unreachable!() } - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn aux_5(_origin, _data: i32, #[compact] _data2: u32,) -> DispatchResult { unreachable!() } - #[weight = SimpleDispatchInfo::FixedOperational(5)] + #[weight = (5, DispatchClass::Operational)] fn operational(_origin) { unreachable!() } fn on_initialize(n: T::BlockNumber,) -> Weight { if n.into() == 42 { panic!("on_initialize") } 7 } diff --git a/frame/support/src/error.rs b/frame/support/src/error.rs index a06f46889224d..1e3028961aea5 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, MINIMUM_WEIGHT}; +/// # use frame_support::weights::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(MINIMUM_WEIGHT)] +/// #[weight = 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 6a3e41b8096c1..88fb1f7420a18 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, MINIMUM_WEIGHT}; + use crate::weights::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(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn aux_0(_origin) -> DispatchResult { unreachable!() } } } diff --git a/frame/support/src/weights.rs b/frame/support/src/weights.rs index 79cfa1b3974b3..7f8791f9dc8c7 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -16,29 +16,97 @@ //! # Primitives for transaction weighting. //! -//! All dispatchable functions defined in `decl_module!` must provide two trait implementations: -//! - [`WeightData`]: To determine the weight of the dispatch. -//! - [`ClassifyDispatch`]: To determine the class of the dispatch. See the enum definition for -//! more information on dispatch classes. +//! Every dispatchable function is responsible for providing `#[weight = $x]` attribute. In this +//! snipped, `$x` can be any user provided struct that implements the following traits: //! -//! Every dispatchable function is responsible for providing this data via an optional `#[weight = -//! $x]` attribute. In this snipped, `$x` can be any user provided struct that implements the -//! two aforementioned traits. +//! - [`WeighData`]: the weight amount. +//! - [`ClassifyDispatch`]: class of the dispatch. +//! - [`PaysFee`]: weather this weight should be translated to fee and deducted upon dispatch. //! //! Substrate then bundles then output information of the two traits into [`DispatchInfo`] struct -//! and provides it by implementing the [`GetDispatchInfo`] for all `Call` variants, and opaque -//! extrinsic types. +//! and provides it by implementing the [`GetDispatchInfo`] for all `Call` both inner and outer call +//! types. //! -//! If no `#[weight]` is defined, the macro automatically injects the `Default` implementation of -//! the [`SimpleDispatchInfo`]. +//! Substrate provides two pre-defined ways to annotate weight: +//! +//! ### 1. Fixed values +//! +//! This can only be used when all 3 traits can be resolved statically. You have 3 degrees of +//! configuration: +//! +//! 1. Define only weight, **in which case `ClassifyDispatch` will be `Normal` and `PaysFee` will be +//! `true`**. +//! +//! ``` +//! # use frame_system::{self as system, Trait}; +//! frame_support::decl_module! { +//! pub struct Module for enum Call where origin: T::Origin { +//! #[weight = 1000] +//! fn dispatching(origin) { unimplemented!() } +//! } +//! } +//! # fn main() {} +//! ``` +//! +//! 2. Define weight and class, **in which case `PaysFee` would be `true`**. +//! +//! ``` +//! # use frame_system::{self as system, Trait}; +//! # use frame_support::weights::DispatchClass; +//! frame_support::decl_module! { +//! pub struct Module for enum Call where origin: T::Origin { +//! #[weight = (1000, DispatchClass::Operational)] +//! fn dispatching(origin) { unimplemented!() } +//! } +//! } +//! # fn main() {} +//! ``` +//! +//! 3. Define all 3 parameters. +//! +//! ``` +//! # use frame_system::{self as system, Trait}; +//! # use frame_support::weights::DispatchClass; +//! frame_support::decl_module! { +//! pub struct Module for enum Call where origin: T::Origin { +//! #[weight = (1000, DispatchClass::Operational, false)] +//! fn dispatching(origin) { unimplemented!() } +//! } +//! } +//! # fn main() {} +//! ``` +//! +//! ### 2. Define weights as a function of input arguments using `FunctionOf` tuple struct. This struct works +//! in a similar manner as above. 3 items must be provided and each can be either a fixed value or a +//! function/closure with the same parameters list as the dispatchable function itself, wrapper in a +//! tuple. +//! +//! Using this only makes sense if you want to use a function for at least one of the elements. If +//! all 3 are static values, providing a raw tuple is easier. +//! +//! ``` +//! # use frame_system::{self as system, Trait}; +//! # use frame_support::weights::{DispatchClass, FunctionOf}; +//! frame_support::decl_module! { +//! pub struct Module for enum Call where origin: T::Origin { +//! #[weight = FunctionOf( +//! // weight, function. +//! |args: (&u32, &u64)| *args.0 as u64 + args.1, +//! // class, fixed. +//! DispatchClass::Operational, +//! // pays fee, function. +//! |args: (&u32, &u64)| *args.0 > 1000, +//! )] +//! fn dispatching(origin, a: u32, b: u64) { unimplemented!() } +//! } +//! } +//! # fn main() {} +//! ``` //! -//! Note that the decl_module macro _cannot_ enforce this and will simply fail if an invalid struct -//! (something that does not implement `Weighable`) is passed in. #[cfg(feature = "std")] use serde::{Serialize, Deserialize}; use codec::{Encode, Decode}; -use sp_arithmetic::traits::Bounded; use sp_runtime::{ RuntimeDebug, traits::SignedExtension, @@ -81,8 +149,7 @@ pub trait PaysFee { } } -/// A generalized group of dispatch types. This is only distinguishing normal, user-triggered transactions -/// (`Normal`) and anything beyond which serves a higher purpose to the system (`Operational`). +/// A generalized group of dispatch types. #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] #[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, RuntimeDebug)] @@ -112,40 +179,6 @@ 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 { - SimpleDispatchInfo::FixedOperational(_) => DispatchClass::Operational, - SimpleDispatchInfo::MaxOperational => DispatchClass::Operational, - - SimpleDispatchInfo::FixedNormal(_) => DispatchClass::Normal, - SimpleDispatchInfo::MaxNormal => DispatchClass::Normal, - SimpleDispatchInfo::InsecureFreeNormal => DispatchClass::Normal, - - SimpleDispatchInfo::FixedMandatory(_) => DispatchClass::Mandatory, - } - } -} - /// A bundle of static information collected from the `#[weight = $x]` attributes. #[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)] pub struct DispatchInfo { @@ -157,6 +190,15 @@ pub struct DispatchInfo { pub pays_fee: bool, } +/// A `Dispatchable` function (aka transaction) that can carry some static information along with +/// it, using the `#[weight]` attribute. +pub trait GetDispatchInfo { + /// Return a `DispatchInfo`, containing relevant information of this dispatch. + /// + /// This is done independently of its encoded size. + fn get_dispatch_info(&self) -> DispatchInfo; +} + /// Weight information that is only available post dispatch. #[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)] pub struct PostDispatchInfo { @@ -230,86 +272,75 @@ impl WithPostDispatchInfo for T where } } -/// A `Dispatchable` function (aka transaction) that can carry some static information along with -/// it, using the `#[weight]` attribute. -pub trait GetDispatchInfo { - /// Return a `DispatchInfo`, containing relevant information of this dispatch. - /// - /// This is done independently of its encoded size. - fn get_dispatch_info(&self) -> DispatchInfo; +impl WeighData for Weight { + fn weigh_data(&self, _: T) -> Weight { + return *self + } } -/// Default type used with the `#[weight = x]` attribute in a substrate chain. -/// -/// A user may pass in any other type that implements the correct traits. If not, the `Default` -/// implementation of [`SimpleDispatchInfo`] is used. -/// -/// For each generalized group (`Normal` and `Operation`): -/// - A `Fixed` variant means weight fee is charged normally and the weight is the number -/// specified in the inner value of the variant. -/// - A `Free` variant is equal to `::Fixed(0)`. Note that this does not guarantee inclusion. -/// - A `Max` variant is equal to `::Fixed(Weight::max_value())`. -/// -/// As for the generalized groups themselves: -/// - `Normal` variants will be assigned a priority proportional to their weight. They can only -/// consume a portion (defined in the system module) of the maximum block resource limits. -/// - `Operational` variants will be assigned the maximum priority. They can potentially consume -/// the entire block resource limit. -#[derive(Clone, Copy)] -pub enum SimpleDispatchInfo { - /// A normal dispatch with fixed weight. - FixedNormal(Weight), - /// A normal dispatch with the maximum weight. - MaxNormal, - /// A normal dispatch with no weight. Base and bytes fees still need to be paid. - InsecureFreeNormal, - /// An operational dispatch with fixed weight. - FixedOperational(Weight), - /// An operational dispatch with the maximum weight. - MaxOperational, - /// A mandatory dispatch with fixed weight. - /// - /// NOTE: Signed transactions may not (directly) dispatch this kind of a call, so the other - /// attributes concerning transactability (e.g. priority, fee paying) are moot. - FixedMandatory(Weight), +impl ClassifyDispatch for Weight { + fn classify_dispatch(&self, _: T) -> DispatchClass { + DispatchClass::default() + } } -impl WeighData for SimpleDispatchInfo { +impl PaysFee for Weight { + fn pays_fee(&self, _: T) -> bool { + true + } +} + +impl WeighData for (Weight, DispatchClass, bool) { fn weigh_data(&self, _: T) -> Weight { - match self { - SimpleDispatchInfo::FixedNormal(w) => *w, - SimpleDispatchInfo::MaxNormal => Bounded::max_value(), - SimpleDispatchInfo::InsecureFreeNormal => Bounded::min_value(), - SimpleDispatchInfo::FixedOperational(w) => *w, - SimpleDispatchInfo::MaxOperational => Bounded::max_value(), - SimpleDispatchInfo::FixedMandatory(w) => *w, - } + return self.0 } } -impl ClassifyDispatch for SimpleDispatchInfo { +impl ClassifyDispatch for (Weight, DispatchClass, bool) { fn classify_dispatch(&self, _: T) -> DispatchClass { - DispatchClass::from(*self) + self.1 } } -impl PaysFee for SimpleDispatchInfo { +impl PaysFee for (Weight, DispatchClass, bool) { fn pays_fee(&self, _: T) -> bool { - match self { - SimpleDispatchInfo::FixedNormal(_) => true, - SimpleDispatchInfo::MaxNormal => true, - SimpleDispatchInfo::InsecureFreeNormal => true, - SimpleDispatchInfo::FixedOperational(_) => true, - SimpleDispatchInfo::MaxOperational => true, - SimpleDispatchInfo::FixedMandatory(_) => true, - } + self.2 + } +} + +impl WeighData for (Weight, DispatchClass) { + fn weigh_data(&self, _: T) -> Weight { + return self.0 } } -impl SimpleDispatchInfo { - /// An _additive zero_ variant of SimpleDispatchInfo. - pub fn zero() -> Self { - Self::FixedNormal(0) +impl ClassifyDispatch for (Weight, DispatchClass) { + fn classify_dispatch(&self, _: T) -> DispatchClass { + self.1 + } +} + +impl PaysFee for (Weight, DispatchClass) { + fn pays_fee(&self, _: T) -> bool { + true + } +} + +impl WeighData for (Weight, bool) { + fn weigh_data(&self, _: T) -> Weight { + return self.0 + } +} + +impl ClassifyDispatch for (Weight, bool) { + fn classify_dispatch(&self, _: T) -> DispatchClass { + DispatchClass::Normal + } +} + +impl PaysFee for (Weight, bool) { + fn pays_fee(&self, _: T) -> bool { + self.1 } } @@ -463,8 +494,14 @@ mod tests { decl_module! { pub struct Module for enum Call where origin: T::Origin { // no arguments, fixed weight - #[weight = SimpleDispatchInfo::FixedNormal(1000)] - fn f0(_origin) { unimplemented!(); } + #[weight = 1000] + fn f00(_origin) { unimplemented!(); } + + #[weight = (1000, DispatchClass::Mandatory)] + fn f01(_origin) { unimplemented!(); } + + #[weight = (1000, DispatchClass::Operational, false)] + fn f02(_origin) { unimplemented!(); } // weight = a x 10 + b #[weight = FunctionOf(|args: (&u32, &u32)| (args.0 * 10 + args.1) as Weight, DispatchClass::Normal, true)] @@ -484,7 +521,24 @@ mod tests { #[test] fn weights_are_correct() { - assert_eq!(Call::::f0().get_dispatch_info().weight, 1000); + // #[weight = 1000] + let info = Call::::f00().get_dispatch_info(); + assert_eq!(info.weight, 1000); + assert_eq!(info.class, DispatchClass::Normal); + assert_eq!(info.pays_fee, true); + + // #[weight = (1000, DispatchClass::Mandatory)] + let info = Call::::f01().get_dispatch_info(); + assert_eq!(info.weight, 1000); + assert_eq!(info.class, DispatchClass::Mandatory); + assert_eq!(info.pays_fee, true); + + // #[weight = (1000, DispatchClass::Operational, false)] + let info = Call::::f02().get_dispatch_info(); + assert_eq!(info.weight, 1000); + assert_eq!(info.class, DispatchClass::Operational); + assert_eq!(info.pays_fee, false); + 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::::f12(10, 20).get_dispatch_info().weight, 0); diff --git a/frame/support/test/tests/decl_error.rs b/frame/support/test/tests/decl_error.rs index cf50b009ddf18..283e747a9ec4a 100644 --- a/frame/support/test/tests/decl_error.rs +++ b/frame/support/test/tests/decl_error.rs @@ -18,7 +18,7 @@ use sp_runtime::{generic, traits::{BlakeTwo256, Block as _, Verify}, DispatchError}; use sp_core::{H256, sr25519}; -use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; +use frame_support::weights::MINIMUM_WEIGHT; mod system; @@ -33,7 +33,7 @@ mod module1 { pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: ::Origin { - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { Err(Error::::Something.into()) } @@ -60,7 +60,7 @@ mod module2 { pub struct Module for enum Call where origin: ::Origin { - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 00b110ffb90e1..aa6f635cccd4f 100644 --- a/frame/support/test/tests/instance.rs +++ b/frame/support/test/tests/instance.rs @@ -23,7 +23,7 @@ use frame_support::{ DecodeDifferent, StorageMetadata, StorageEntryModifier, StorageEntryType, DefaultByteGetter, StorageEntryMetadata, StorageHasher, }, - weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}, + weights::MINIMUM_WEIGHT, StorageValue, StorageMap, StorageDoubleMap, }; use sp_inherents::{ProvideInherent, InherentData, InherentIdentifier, MakeFatalError}; @@ -56,7 +56,7 @@ mod module1 { fn deposit_event() = default; - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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 00aac51cab388..ef19fee0e6966 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, weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}}; + pub use frame_support::{dispatch, weights::MINIMUM_WEIGHT}; pub trait Trait { type Origin; @@ -19,7 +19,7 @@ macro_rules! reserved { frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin { - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn $reserved(_origin) -> dispatch::DispatchResult { unreachable!() } } } diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index 50f2b089f2074..3b9daf861031f 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -68,14 +68,14 @@ //! ### Example - Get extrinsic count and parent hash for the current block //! //! ``` -//! use frame_support::{decl_module, dispatch, weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}}; +//! use frame_support::{decl_module, dispatch, weights::MINIMUM_WEIGHT}; //! use frame_system::{self as system, ensure_signed}; //! //! pub trait Trait: system::Trait {} //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] +//! #[weight = 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, MINIMUM_WEIGHT, RuntimeDbWeight, DispatchInfo, PostDispatchInfo, DispatchClass, SimpleDispatchInfo, FunctionOf} + weights::{Weight, MINIMUM_WEIGHT, RuntimeDbWeight, DispatchInfo, PostDispatchInfo, DispatchClass, FunctionOf} }; use codec::{Encode, Decode, FullCodec, EncodeLike}; @@ -485,20 +485,20 @@ decl_module! { } /// Make some on-chain remark. - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn remark(origin, _remark: Vec) { ensure_signed(origin)?; } /// Set the number of pages in the WebAssembly environment's heap. - #[weight = SimpleDispatchInfo::FixedOperational(MINIMUM_WEIGHT)] + #[weight = (MINIMUM_WEIGHT, DispatchClass::Operational)] fn set_heap_pages(origin, pages: u64) { ensure_root(origin)?; storage::unhashed::put_raw(well_known_keys::HEAP_PAGES, &pages.encode()); } /// Set the new runtime code. - #[weight = SimpleDispatchInfo::FixedOperational(200_000_000)] + #[weight = (200_000_000, DispatchClass::Operational)] 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_000)] + #[weight = (200_000_000, DispatchClass::Operational)] 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_000)] + #[weight = (20_000_000, DispatchClass::Operational)] 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(MINIMUM_WEIGHT)] + #[weight = (MINIMUM_WEIGHT, DispatchClass::Operational)] 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(MINIMUM_WEIGHT)] + #[weight = (MINIMUM_WEIGHT, DispatchClass::Operational)] 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(MINIMUM_WEIGHT)] + #[weight = (MINIMUM_WEIGHT, DispatchClass::Operational)] 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_000)] + #[weight = (25_000_000, DispatchClass::Operational)] 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 822848bf7dcc7..6109c3dddeae3 100644 --- a/frame/timestamp/src/lib.rs +++ b/frame/timestamp/src/lib.rs @@ -62,7 +62,7 @@ //! //! ``` //! use frame_support::{decl_module, dispatch}; -//! use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; +//! use frame_support::weights::MINIMUM_WEIGHT; //! # use pallet_timestamp as timestamp; //! use frame_system::{self as system, ensure_signed}; //! @@ -70,7 +70,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] +//! #[weight = MINIMUM_WEIGHT] //! pub fn get_time(origin) -> dispatch::DispatchResult { //! let _sender = ensure_signed(origin)?; //! let _now = >::get(); @@ -101,7 +101,7 @@ use frame_support::debug; use frame_support::{ Parameter, decl_storage, decl_module, traits::{Time, UnixTime, Get}, - weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}, + weights::MINIMUM_WEIGHT, }; use sp_runtime::{ RuntimeString, @@ -148,7 +148,7 @@ decl_module! { /// `MinimumPeriod`. /// /// The dispatch origin for this call must be `Inherent`. - #[weight = SimpleDispatchInfo::FixedMandatory(MINIMUM_WEIGHT)] + #[weight = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Mandatory)] 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 af39985133c81..394355a989fe3 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, SimpleDispatchInfo}; +use frame_support::weights::{Weight, MINIMUM_WEIGHT}; use frame_support::traits::{Contains, EnsureOrigin}; use codec::{Encode, Decode}; use frame_system::{self as system, ensure_signed, ensure_root}; @@ -327,7 +327,7 @@ decl_module! { /// - Limited storage reads. /// - One DB change, one extra DB entry. /// # - #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] + #[weight = 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_000)] + #[weight = (100_000_000, frame_support::weights::DispatchClass::Operational)] 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_000)] + #[weight = (100_000_000, frame_support::weights::DispatchClass::Operational)] 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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_000)] + #[weight = 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 85545d92b0f65..6da92ea15a479 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, MINIMUM_WEIGHT}; +use frame_support::weights::MINIMUM_WEIGHT; use frame_system::{self as system, ensure_signed}; mod benchmarking; @@ -194,7 +194,7 @@ decl_module! { /// - One storage read (codec `O(1)`) and up to one removal. /// - One event. /// # - #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] + #[weight = 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(MINIMUM_WEIGHT)] + #[weight = MINIMUM_WEIGHT] fn vest_other(origin, target: ::Source) -> DispatchResult { ensure_signed(origin)?; Self::update_lock(T::Lookup::lookup(target)?) @@ -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_000)] + #[weight = 1_000_000_000] pub fn vested_transfer( origin, target: ::Source, From 394df29286c7d526e2ed847213bd81b512d5981a Mon Sep 17 00:00:00 2001 From: kianenigma Date: Fri, 17 Apr 2020 17:47:05 +0200 Subject: [PATCH 5/9] Fix test --- frame/staking/src/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frame/staking/src/tests.rs b/frame/staking/src/tests.rs index 40af50e6ddbbc..d8d04300fd3f7 100644 --- a/frame/staking/src/tests.rs +++ b/frame/staking/src/tests.rs @@ -3114,7 +3114,7 @@ mod offchain_phragmen { &inner, ), TransactionValidity::Ok(ValidTransaction { - priority: (1 << 20) + 1125, // the proposed slot stake. + priority: UnsignedPriority::get() + 1125, // the proposed slot stake. requires: vec![], provides: vec![("StakingOffchain", current_era()).encode()], longevity: 3, @@ -3157,7 +3157,7 @@ mod offchain_phragmen { &inner, ), TransactionValidity::Ok(ValidTransaction { - priority: 1250, // the proposed slot stake. + priority: UnsignedPriority::get() + 1250, // the proposed slot stake. requires: vec![], provides: vec![("StakingOffchain", active_era()).encode()], longevity: 3, From f478d8addaecf3b2498a3bd3c50d416e1f5e62bf Mon Sep 17 00:00:00 2001 From: kianenigma Date: Mon, 20 Apr 2020 16:16:05 +0200 Subject: [PATCH 6/9] Revert "Migrate away from SimpleDispatchInfo" This reverts commit dbdd27fa19948f16bd17defdc01d3dd32986df11. --- bin/node-template/pallets/template/src/lib.rs | 6 +- frame/assets/src/lib.rs | 8 +- frame/authorship/src/lib.rs | 4 +- frame/benchmark/src/lib.rs | 28 +- frame/benchmarking/src/tests.rs | 6 +- frame/collective/src/lib.rs | 11 +- frame/contracts/src/lib.rs | 12 +- frame/democracy/src/lib.rs | 60 ++-- frame/elections-phragmen/src/lib.rs | 14 +- frame/elections/src/lib.rs | 30 +- frame/evm/src/lib.rs | 5 +- frame/example-offchain-worker/src/lib.rs | 6 +- frame/example/src/lib.rs | 10 +- frame/executive/src/lib.rs | 8 +- frame/finality-tracker/src/lib.rs | 4 +- frame/generic-asset/src/lib.rs | 14 +- frame/grandpa/src/lib.rs | 4 +- frame/identity/src/lib.rs | 24 +- frame/im-online/src/lib.rs | 8 +- frame/indices/src/lib.rs | 10 +- frame/membership/src/lib.rs | 15 +- frame/nicks/src/lib.rs | 9 +- frame/randomness-collective-flip/src/lib.rs | 4 +- frame/recovery/src/lib.rs | 18 +- frame/scored-pool/src/lib.rs | 16 +- frame/session/src/lib.rs | 6 +- frame/society/src/lib.rs | 26 +- frame/staking/src/lib.rs | 54 ++-- frame/sudo/src/lib.rs | 8 +- frame/support/src/dispatch.rs | 37 +-- frame/support/src/error.rs | 4 +- frame/support/src/metadata.rs | 4 +- frame/support/src/weights.rs | 288 +++++++----------- frame/support/test/tests/decl_error.rs | 6 +- frame/support/test/tests/instance.rs | 4 +- .../tests/reserved_keyword/on_initialize.rs | 4 +- frame/system/src/lib.rs | 24 +- frame/timestamp/src/lib.rs | 8 +- frame/treasury/src/lib.rs | 18 +- frame/vesting/src/lib.rs | 8 +- 40 files changed, 394 insertions(+), 439 deletions(-) diff --git a/bin/node-template/pallets/template/src/lib.rs b/bin/node-template/pallets/template/src/lib.rs index ad721985b2674..adddbac21b554 100644 --- a/bin/node-template/pallets/template/src/lib.rs +++ b/bin/node-template/pallets/template/src/lib.rs @@ -10,7 +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::MINIMUM_WEIGHT; +use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; use frame_system::{self as system, ensure_signed}; #[cfg(test)] @@ -76,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 = MINIMUM_WEIGHT] + #[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)?; @@ -92,7 +92,7 @@ decl_module! { /// Another dummy entry point. /// takes no parameters, attempts to increment storage value, and possibly throws an error - #[weight = MINIMUM_WEIGHT] + #[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 60a9ab87a75a6..15726c9bcb1e9 100644 --- a/frame/assets/src/lib.rs +++ b/frame/assets/src/lib.rs @@ -133,7 +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::MINIMUM_WEIGHT; +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; @@ -158,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 = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn issue(origin, #[compact] total: T::Balance) { let origin = ensure_signed(origin)?; @@ -172,7 +172,7 @@ decl_module! { } /// Move some assets from one holder to another. - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn transfer(origin, #[compact] id: T::AssetId, target: ::Source, @@ -191,7 +191,7 @@ decl_module! { } /// Destroy any assets of `id` owned by `origin`. - #[weight = MINIMUM_WEIGHT] + #[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 e77a0e27e29e4..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}; +use frame_support::weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo}; use sp_inherents::{InherentIdentifier, ProvideInherent, InherentData}; use sp_authorship::{INHERENT_IDENTIFIER, UnclesInherentData, InherentError}; @@ -207,7 +207,7 @@ decl_module! { } /// Provide a set of uncles. - #[weight = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Mandatory)] + #[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/benchmark/src/lib.rs b/frame/benchmark/src/lib.rs index 61b6ac9415565..24b0e433101be 100644 --- a/frame/benchmark/src/lib.rs +++ b/frame/benchmark/src/lib.rs @@ -21,7 +21,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use frame_support::{decl_module, decl_storage, decl_event, decl_error}; -use frame_support::weights::MINIMUM_WEIGHT; +use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; use frame_support::traits::Currency; use frame_system::{self as system, ensure_signed}; use codec::{Encode, Decode}; @@ -71,7 +71,7 @@ decl_module! { fn deposit_event() = default; /// Do nothing. - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn do_nothing(_origin, input: u32) { if input > 0 { return Ok(()); @@ -83,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 = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn read_value(_origin, repeat: u32) { for _ in 0..repeat { MyValue::get(); @@ -91,7 +91,7 @@ decl_module! { } /// Put a value into a storage value. - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn put_value(_origin, repeat: u32) { for r in 0..repeat { MyValue::put(r); @@ -103,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 = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn exists_value(_origin, repeat: u32) { for _ in 0..repeat { MyValue::exists(); @@ -111,7 +111,7 @@ decl_module! { } /// Remove a value from storage `repeat` number of times. - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn remove_value(_origin, repeat: u32) { for r in 0..repeat { MyMap::remove(r); @@ -119,7 +119,7 @@ decl_module! { } /// Read a value from storage map `repeat` number of times. - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn read_map(_origin, repeat: u32) { for r in 0..repeat { MyMap::get(r); @@ -127,7 +127,7 @@ decl_module! { } /// Insert a value into a map. - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn insert_map(_origin, repeat: u32) { for r in 0..repeat { MyMap::insert(r, r); @@ -135,7 +135,7 @@ decl_module! { } /// Check is a map contains a value `repeat` number of times. - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn contains_key_map(_origin, repeat: u32) { for r in 0..repeat { MyMap::contains_key(r); @@ -143,7 +143,7 @@ decl_module! { } /// Read a value from storage `repeat` number of times. - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn remove_prefix(_origin, repeat: u32) { for r in 0..repeat { MyDoubleMap::remove_prefix(r); @@ -151,21 +151,21 @@ decl_module! { } /// Add user to the list. - #[weight = MINIMUM_WEIGHT] + #[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 = MINIMUM_WEIGHT] + #[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 = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn encode_accounts(_origin, accounts: Vec) { let bytes = accounts.encode(); @@ -177,7 +177,7 @@ decl_module! { } /// Decode bytes into a vector of accounts. - #[weight = MINIMUM_WEIGHT] + #[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 cb8bb8603f6b0..4b26ec732d296 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -24,7 +24,7 @@ use sp_std::prelude::*; use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::{H256, Header}}; use frame_support::{ dispatch::DispatchResult, - weights::MINIMUM_WEIGHT, + weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}, decl_module, decl_storage, impl_outer_origin, assert_ok, assert_err, ensure }; use frame_system::{RawOrigin, ensure_signed, ensure_none}; @@ -37,14 +37,14 @@ decl_storage! { decl_module! { pub struct Module for enum Call where origin: T::Origin { - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn set_value(origin, n: u32) -> DispatchResult { let _sender = ensure_signed(origin)?; Value::put(n); Ok(()) } - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn dummy(origin, _n: u32) -> DispatchResult { let _sender = ensure_none(origin)?; Ok(()) diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index bfcdc86f1db50..b5626ae4a6814 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -40,6 +40,7 @@ use sp_std::{prelude::*, result}; use sp_core::u32_trait::Value as U32; use sp_runtime::RuntimeDebug; use sp_runtime::traits::Hash; +use frame_support::weights::SimpleDispatchInfo; use frame_support::{ dispatch::{Dispatchable, Parameter}, codec::{Encode, Decode}, traits::{Get, ChangeMembers, InitializeMembers, EnsureOrigin}, decl_module, decl_event, @@ -186,7 +187,7 @@ decl_module! { /// - `prime`: The prime member whose vote sets the default. /// /// Requires root origin. - #[weight = (100_000_000, frame_support::weights::DispatchClass::Operational)] + #[weight = SimpleDispatchInfo::FixedOperational(100_000_000)] fn set_members(origin, new_members: Vec, prime: Option) { ensure_root(origin)?; let mut new_members = new_members; @@ -199,7 +200,7 @@ decl_module! { /// Dispatch a proposal from a member using the `Member` origin. /// /// Origin must be a member of the collective. - #[weight = (100_000_000, frame_support::weights::DispatchClass::Operational)] + #[weight = SimpleDispatchInfo::FixedOperational(100_000_000)] fn execute(origin, proposal: Box<>::Proposal>) { let who = ensure_signed(origin)?; ensure!(Self::is_member(&who), Error::::NotMember); @@ -213,7 +214,7 @@ decl_module! { /// - Bounded storage reads and writes. /// - Argument `threshold` has bearing on weight. /// # - #[weight = (5_000_000_000, frame_support::weights::DispatchClass::Operational)] + #[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); @@ -243,7 +244,7 @@ decl_module! { /// - Bounded storage read and writes. /// - Will be slightly heavier if the proposal is approved / disapproved after the vote. /// # - #[weight = (200_000_000, frame_support::weights::DispatchClass::Operational)] + #[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); @@ -302,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 = (200_000_000, frame_support::weights::DispatchClass::Operational)] + #[weight = SimpleDispatchInfo::FixedOperational(200_000_000)] fn close(origin, proposal: T::Hash, #[compact] index: ProposalIndex) { let _ = ensure_signed(origin)?; diff --git a/frame/contracts/src/lib.rs b/frame/contracts/src/lib.rs index e7c8fe5b12916..91f06d5607c8b 100644 --- a/frame/contracts/src/lib.rs +++ b/frame/contracts/src/lib.rs @@ -123,7 +123,7 @@ use sp_runtime::{ RuntimeDebug, }; use frame_support::dispatch::{DispatchResult, Dispatchable}; -use frame_support::weights::MINIMUM_WEIGHT; +use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; use frame_support::{ Parameter, decl_module, decl_event, decl_storage, decl_error, storage::child, parameter_types, IsSubType, @@ -551,7 +551,7 @@ decl_module! { /// Updates the schedule for metering contracts. /// /// The schedule must have a greater version than the stored schedule. - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn update_schedule(origin, schedule: Schedule) -> DispatchResult { ensure_root(origin)?; if >::current_schedule().version >= schedule.version { @@ -566,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 = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn put_code( origin, #[compact] gas_limit: Gas, @@ -594,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 = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn call( origin, dest: ::Source, @@ -620,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 = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn instantiate( origin, #[compact] endowment: BalanceOf, @@ -643,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 = MINIMUM_WEIGHT] + #[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 cc81571a2d4f3..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::{Weight, MINIMUM_WEIGHT}, + weights::{SimpleDispatchInfo, Weight, MINIMUM_WEIGHT}, traits::{ Currency, ReservableCurrency, LockableCurrency, WithdrawReason, LockIdentifier, Get, OnUnbalanced, BalanceStatus, schedule::Named as ScheduleNamed, EnsureOrigin @@ -546,7 +546,7 @@ decl_module! { /// - P is the number proposals in the `PublicProps` vec. /// - Two DB changes, one DB entry. /// # - #[weight = 5_000_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 = 5_000_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 = 200_000_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 = 200_000_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 = (500_000_000, frame_support::weights::DispatchClass::Operational)] + #[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 = 5_000_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 = 5_000_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 = 5_000_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 = 200_000_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 = 200_000_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 = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Operational)] + #[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 = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Operational)] + #[weight = SimpleDispatchInfo::FixedOperational(MINIMUM_WEIGHT)] 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 = 100_000_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 = 100_000_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 = 100_000_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 = 500_000_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 = 500_000_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 = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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 = 100_000_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 = 100_000_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 = MINIMUM_WEIGHT] + #[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 = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn unlock(origin, target: T::AccountId) { ensure_signed(origin)?; Self::update_lock(&target); @@ -1115,7 +1115,7 @@ decl_module! { /// # /// - One extra DB entry. /// # - #[weight = 100_000_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 = MINIMUM_WEIGHT] + #[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 = MINIMUM_WEIGHT] + #[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 }; @@ -1207,7 +1207,7 @@ decl_module! { /// /// # /// # - #[weight = 500_000_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 = 500_000_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 = MINIMUM_WEIGHT] + #[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)?; @@ -1259,7 +1259,7 @@ decl_module! { } /// Enact a proposal from a referendum. For now we just make the weight be the maximum. - #[weight = Weight::max_value()] + #[weight = SimpleDispatchInfo::MaxNormal] fn enact_proposal(origin, proposal_hash: T::Hash, index: ReferendumIndex) -> DispatchResult { ensure_root(origin)?; Self::do_enact_proposal(proposal_hash, index) diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 1e419e2c24fd9..610f008457277 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::{Weight, MINIMUM_WEIGHT}, storage::{StorageMap, IterableStorageMap}, + weights::{SimpleDispatchInfo, Weight, MINIMUM_WEIGHT}, storage::{StorageMap, IterableStorageMap}, traits::{ Currency, Get, LockableCurrency, LockIdentifier, ReservableCurrency, WithdrawReasons, ChangeMembers, OnUnbalanced, WithdrawReason, Contains, BalanceStatus, InitializeMembers, @@ -291,7 +291,7 @@ decl_module! { /// Reads: O(1) /// Writes: O(V) given `V` votes. V is bounded by 16. /// # - #[weight = 100_000_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 = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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 = 1_000_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 = 500_000_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 = (2_000_000_000, frame_support::weights::DispatchClass::Operational)] + #[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 = (2_000_000_000, frame_support::weights::DispatchClass::Operational)] + #[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 5c090c4711a74..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}, + weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo}, traits::{ Currency, ExistenceRequirement, Get, LockableCurrency, LockIdentifier, BalanceStatus, OnUnbalanced, ReservableCurrency, WithdrawReason, WithdrawReasons, ChangeMembers @@ -405,13 +405,13 @@ decl_module! { /// - Two extra DB entries, one DB change. /// - Argument `votes` is limited in length to number of candidates. /// # - #[weight = 2_500_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(2_500_000_000)] fn set_approvals( origin, votes: Vec, #[compact] index: VoteIndex, hint: SetIndex, - #[compact] value: BalanceOf, + #[compact] value: BalanceOf ) -> DispatchResult { let who = ensure_signed(origin)?; Self::do_set_approvals(who, votes, index, hint, value) @@ -423,12 +423,12 @@ decl_module! { /// # /// - Same as `set_approvals` with one additional storage read. /// # - #[weight = 2_500_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(2_500_000_000)] fn proxy_set_approvals(origin, votes: Vec, #[compact] index: VoteIndex, hint: SetIndex, - #[compact] value: BalanceOf, + #[compact] value: BalanceOf ) -> DispatchResult { let who = Self::proxy(ensure_signed(origin)?).ok_or(Error::::NotProxy)?; Self::do_set_approvals(who, votes, index, hint, value) @@ -446,13 +446,13 @@ decl_module! { /// - O(1). /// - Two fewer DB entries, one DB change. /// # - #[weight = 2_500_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(2_500_000_000)] fn reap_inactive_voter( origin, #[compact] reporter_index: u32, who: ::Source, #[compact] who_index: u32, - #[compact] assumed_vote_index: VoteIndex, + #[compact] assumed_vote_index: VoteIndex ) { let reporter = ensure_signed(origin)?; let who = T::Lookup::lookup(who)?; @@ -520,7 +520,7 @@ decl_module! { /// - O(1). /// - Two fewer DB entries, one DB change. /// # - #[weight = 1_250_000_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 = 2_500_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(2_500_000_000)] fn submit_candidacy(origin, #[compact] slot: u32) { let who = ensure_signed(origin)?; @@ -585,12 +585,12 @@ decl_module! { /// - O(voters) compute. /// - One DB change. /// # - #[weight = 10_000_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(10_000_000_000)] fn present_winner( origin, candidate: ::Source, #[compact] total: BalanceOf, - #[compact] index: VoteIndex, + #[compact] index: VoteIndex ) -> DispatchResult { let who = ensure_signed(origin)?; ensure!( @@ -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 = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Operational)] + #[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 = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Operational)] + #[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 = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Operational)] + #[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 = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Operational)] + #[weight = SimpleDispatchInfo::FixedOperational(MINIMUM_WEIGHT)] 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 48946858dffb6..f67ab767ed320 100644 --- a/frame/evm/src/lib.rs +++ b/frame/evm/src/lib.rs @@ -29,6 +29,7 @@ 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; +use frame_support::weights::SimpleDispatchInfo; use sp_core::{U256, H256, H160, Hasher}; use sp_runtime::{ DispatchResult, traits::{UniqueSaturatedInto, AccountIdConversion, SaturatedConversion}, @@ -190,7 +191,7 @@ decl_module! { fn deposit_event() = default; /// Deposit balance from currency/balances module into EVM. - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn deposit_balance(origin, value: BalanceOf) { let sender = ensure_signed(origin)?; @@ -211,7 +212,7 @@ decl_module! { } /// Withdraw balance from EVM into currency/balances module. - #[weight = MINIMUM_WEIGHT] + #[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 1762d95bc94a1..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::MINIMUM_WEIGHT, + 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 = MINIMUM_WEIGHT] + #[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 = MINIMUM_WEIGHT] + #[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 e7a5a0c02e5ae..97cad2856a00d 100644 --- a/frame/example/src/lib.rs +++ b/frame/example/src/lib.rs @@ -256,7 +256,10 @@ use sp_std::marker::PhantomData; use frame_support::{ dispatch::DispatchResult, decl_module, decl_storage, decl_event, - weights::{DispatchClass, ClassifyDispatch, WeighData, Weight, PaysFee, MINIMUM_WEIGHT}, + weights::{ + SimpleDispatchInfo, DispatchClass, ClassifyDispatch, WeighData, Weight, PaysFee, + MINIMUM_WEIGHT, + }, }; use sp_std::prelude::*; use frame_system::{self as system, ensure_signed, ensure_root}; @@ -466,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 = MINIMUM_WEIGHT] + #[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)?; @@ -515,7 +518,8 @@ decl_module! { // The signature could also look like: `fn on_initialize()`. // This function could also very well have a weight annotation, similar to any other. The - // only difference is that it mut be returned, not annotated. + // only difference being that if it is not annotated, the default is + // `SimpleDispatchInfo::zero()`, which resolves into no weight. fn on_initialize(_n: T::BlockNumber) -> Weight { // Anything that needs to be done at the start of the block. // We don't do anything here. diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index f99ad03416e75..747fc85866862 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -416,22 +416,22 @@ mod tests { use hex_literal::hex; mod custom { - use frame_support::weights::Weight; + use frame_support::weights::{SimpleDispatchInfo, Weight}; pub trait Trait: frame_system::Trait {} frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin { - #[weight = 100] + #[weight = SimpleDispatchInfo::FixedNormal(100)] fn some_function(origin) { // NOTE: does not make any different. let _ = frame_system::ensure_signed(origin); } - #[weight = (200, frame_support::weights::DispatchClass::Operational)] + #[weight = SimpleDispatchInfo::FixedOperational(200)] fn some_root_operation(origin) { let _ = frame_system::ensure_root(origin); } - #[weight = 0] + #[weight = SimpleDispatchInfo::InsecureFreeNormal] fn some_unsigned_message(origin) { let _ = frame_system::ensure_none(origin); } diff --git a/frame/finality-tracker/src/lib.rs b/frame/finality-tracker/src/lib.rs index a7d41848250ef..54506784a9f1b 100644 --- a/frame/finality-tracker/src/lib.rs +++ b/frame/finality-tracker/src/lib.rs @@ -23,7 +23,7 @@ use sp_runtime::traits::{One, Zero, SaturatedConversion}; use sp_std::{prelude::*, result, cmp, vec}; use frame_support::{decl_module, decl_storage, decl_error, ensure}; use frame_support::traits::Get; -use frame_support::weights::MINIMUM_WEIGHT; +use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; use frame_system::{ensure_none, Trait as SystemTrait}; use sp_finality_tracker::{INHERENT_IDENTIFIER, FinalizedInherentData}; @@ -77,7 +77,7 @@ decl_module! { /// Hint that the author of this block thinks the best finalized /// block is the given number. - #[weight = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Mandatory)] + #[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 b56c724336111..720ccd85cccc6 100644 --- a/frame/generic-asset/src/lib.rs +++ b/frame/generic-asset/src/lib.rs @@ -164,7 +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::MINIMUM_WEIGHT, + weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}, traits::{ Currency, ExistenceRequirement, Imbalance, LockIdentifier, LockableCurrency, ReservableCurrency, SignedImbalance, WithdrawReason, WithdrawReasons, TryDrop, BalanceStatus, @@ -361,14 +361,14 @@ decl_module! { fn deposit_event() = default; /// Create a new kind of asset. - #[weight = MINIMUM_WEIGHT] + #[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 = MINIMUM_WEIGHT] + #[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); @@ -378,7 +378,7 @@ decl_module! { /// Updates permission for a given `asset_id` and an account. /// /// The `origin` must have `update` permission. - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn update_permission( origin, #[compact] asset_id: T::AssetId, @@ -401,7 +401,7 @@ decl_module! { /// Mints an asset, increases its total issuance. /// The origin must have `mint` permissions. - #[weight = MINIMUM_WEIGHT] + #[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)?; @@ -411,7 +411,7 @@ decl_module! { /// Burns an asset, decreases its total issuance. /// The `origin` must have `burn` permissions. - #[weight = MINIMUM_WEIGHT] + #[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)?; @@ -421,7 +421,7 @@ decl_module! { /// Can be used to create reserved tokens. /// Requires Root call. - #[weight = MINIMUM_WEIGHT] + #[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 49326c71cb23c..10cc8162db3a7 100644 --- a/frame/grandpa/src/lib.rs +++ b/frame/grandpa/src/lib.rs @@ -33,7 +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::MINIMUM_WEIGHT; +use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; use sp_runtime::{ DispatchResult, generic::{DigestItem, OpaqueDigestItemId}, traits::Zero, Perbill, }; @@ -185,7 +185,7 @@ decl_module! { fn deposit_event() = default; /// Report some misbehavior. - #[weight = MINIMUM_WEIGHT] + #[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 31eb93f04b21a..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::MINIMUM_WEIGHT, + 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 = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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 = 50_000_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 = 50_000_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 = 50_000_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 = 50_000_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 = 50_000_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 = 50_000_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 = 50_000_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 = 50_000_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 = 50_000_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 = 100_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000)] fn kill_identity(origin, target: ::Source) { T::ForceOrigin::try_origin(origin) .map(|_| ()) diff --git a/frame/im-online/src/lib.rs b/frame/im-online/src/lib.rs index 20726a8388b65..1137fc2699fe3 100644 --- a/frame/im-online/src/lib.rs +++ b/frame/im-online/src/lib.rs @@ -43,7 +43,7 @@ //! //! ``` //! use frame_support::{decl_module, dispatch}; -//! use frame_support::weights::MINIMUM_WEIGHT; +//! use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; //! use frame_system::{self as system, ensure_signed}; //! use pallet_im_online::{self as im_online}; //! @@ -51,7 +51,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = MINIMUM_WEIGHT] +//! #[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); @@ -95,7 +95,7 @@ use sp_staking::{ use frame_support::{ decl_module, decl_event, decl_storage, Parameter, debug, decl_error, traits::Get, - weights::MINIMUM_WEIGHT, + weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}, }; use frame_system::{self as system, ensure_none}; use frame_system::offchain::SubmitUnsignedTransaction; @@ -318,7 +318,7 @@ decl_module! { fn deposit_event() = default; - #[weight = MINIMUM_WEIGHT] + #[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 f4f5b69e8cdf1..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}; +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; @@ -121,7 +121,7 @@ decl_module! { /// - One reserve operation. /// - One event. /// # - #[weight = 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 = 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 = 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 = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn force_transfer(origin, new: T::AccountId, index: T::AccountIndex) { ensure_root(origin)?; diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index 188a0b268c104..e968be19a6be1 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -26,6 +26,7 @@ use sp_std::prelude::*; use frame_support::{ decl_module, decl_storage, decl_event, decl_error, traits::{ChangeMembers, InitializeMembers, EnsureOrigin}, + weights::SimpleDispatchInfo, }; use frame_system::{self as system, ensure_root, ensure_signed}; @@ -117,7 +118,7 @@ decl_module! { /// Add a member `who` to the set. /// /// May only be called from `AddOrigin` or root. - #[weight = 50_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn add_member(origin, who: T::AccountId) { T::AddOrigin::try_origin(origin) .map(|_| ()) @@ -136,7 +137,7 @@ decl_module! { /// Remove a member `who` from the set. /// /// May only be called from `RemoveOrigin` or root. - #[weight = 50_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn remove_member(origin, who: T::AccountId) { T::RemoveOrigin::try_origin(origin) .map(|_| ()) @@ -158,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 = 50_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn swap_member(origin, remove: T::AccountId, add: T::AccountId) { T::SwapOrigin::try_origin(origin) .map(|_| ()) @@ -187,7 +188,7 @@ decl_module! { /// pass `members` pre-sorted. /// /// May only be called from `ResetOrigin` or root. - #[weight = 50_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn reset_members(origin, members: Vec) { T::ResetOrigin::try_origin(origin) .map(|_| ()) @@ -210,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 = 50_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn change_key(origin, new: T::AccountId) { let remove = ensure_signed(origin)?; @@ -238,7 +239,7 @@ decl_module! { } /// Set the prime member. Must be a current member. - #[weight = 50_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn set_prime(origin, who: T::AccountId) { T::PrimeOrigin::try_origin(origin) .map(|_| ()) @@ -249,7 +250,7 @@ decl_module! { } /// Remove the prime member if it exists. - #[weight = 50_000_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 97a5074046168..b8a2359450458 100644 --- a/frame/nicks/src/lib.rs +++ b/frame/nicks/src/lib.rs @@ -45,6 +45,7 @@ use sp_runtime::{ use frame_support::{ decl_module, decl_event, decl_storage, ensure, decl_error, traits::{Currency, EnsureOrigin, ReservableCurrency, OnUnbalanced, Get}, + weights::SimpleDispatchInfo, }; use frame_system::{self as system, ensure_signed, ensure_root}; @@ -140,7 +141,7 @@ decl_module! { /// - One storage read/write. /// - One event. /// # - #[weight = 50_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(50_000_000)] fn set_name(origin, name: Vec) { let sender = ensure_signed(origin)?; @@ -170,7 +171,7 @@ decl_module! { /// - One storage read/write. /// - One event. /// # - #[weight = 70_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(70_000_000)] fn clear_name(origin) { let sender = ensure_signed(origin)?; @@ -194,7 +195,7 @@ decl_module! { /// - One storage read/write. /// - One event. /// # - #[weight = 70_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(70_000_000)] fn kill_name(origin, target: ::Source) { T::ForceOrigin::try_origin(origin) .map(|_| ()) @@ -222,7 +223,7 @@ decl_module! { /// - One storage read/write. /// - One event. /// # - #[weight = 70_000_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/randomness-collective-flip/src/lib.rs b/frame/randomness-collective-flip/src/lib.rs index 0e8373f884ce9..194879eb65b80 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::MINIMUM_WEIGHT}; +//! 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 = MINIMUM_WEIGHT] +//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] //! pub fn random_module_example(origin) -> dispatch::DispatchResult { //! let _random_seed = >::random_seed(); //! Ok(()) diff --git a/frame/recovery/src/lib.rs b/frame/recovery/src/lib.rs index e0397cc1a5d46..9f30061f935fa 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::{MINIMUM_WEIGHT, GetDispatchInfo, 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 = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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 = 100_000_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 = 100_000_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 = 100_000_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 = 100_000_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 = 30_000_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 = 30_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(30_000_000)] fn remove_recovery(origin) { let who = ensure_signed(origin)?; // Check there are no active recoveries @@ -647,7 +647,7 @@ decl_module! { /// # /// - One storage mutation to check account is recovered by `who`. O(1) /// # - #[weight = 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 8cbf20af805d3..eca877f096283 100644 --- a/frame/scored-pool/src/lib.rs +++ b/frame/scored-pool/src/lib.rs @@ -54,7 +54,7 @@ //! //! ``` //! use frame_support::{decl_module, dispatch}; -//! use frame_support::weights::MINIMUM_WEIGHT; +//! use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; //! use frame_system::{self as system, ensure_signed}; //! use pallet_scored_pool::{self as scored_pool}; //! @@ -62,7 +62,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = MINIMUM_WEIGHT] +//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] //! pub fn candidate(origin) -> dispatch::DispatchResult { //! let who = ensure_signed(origin)?; //! @@ -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}, + weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo}, }; use frame_system::{self as system, ensure_root, ensure_signed}; use sp_runtime::{ @@ -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 = 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 = 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 = 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 = 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 = MINIMUM_WEIGHT] + #[weight = 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 afab71734ea04..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}, + weights::{Weight, MINIMUM_WEIGHT, SimpleDispatchInfo}, }; use frame_system::{self as system, ensure_signed}; @@ -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 = 150_000_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 = 150_000_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 9799368e9d81c..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::{Weight, MINIMUM_WEIGHT}; +use frame_support::weights::{SimpleDispatchInfo, Weight, MINIMUM_WEIGHT}; use frame_support::traits::{ Currency, ReservableCurrency, Randomness, Get, ChangeMembers, BalanceStatus, ExistenceRequirement::AllowDeath, EnsureOrigin @@ -527,7 +527,7 @@ decl_module! { /// /// Total Complexity: O(M + B + C + logM + logB + X) /// # - #[weight = 50_000_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 = 20_000_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 = 50_000_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 = 20_000_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 = 30_000_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 = 20_000_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 = 30_000_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 = MINIMUM_WEIGHT] + #[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); @@ -847,7 +847,7 @@ decl_module! { /// /// Total Complexity: O(1) /// # - #[weight = 20_000_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 = 30_000_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 = 50_000_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 = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] 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 79ecbbd02e488..c653169a909db 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -150,7 +150,7 @@ //! //! ``` //! use frame_support::{decl_module, dispatch}; -//! use frame_support::weights::MINIMUM_WEIGHT; +//! use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; //! use frame_system::{self as system, ensure_signed}; //! use pallet_staking::{self as staking}; //! @@ -159,7 +159,7 @@ //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { //! /// Reward a validator. -//! #[weight = MINIMUM_WEIGHT] +//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] //! pub fn reward_myself(origin) -> dispatch::DispatchResult { //! let reported = ensure_signed(origin)?; //! >::reward_by_ids(vec![(reported, 10)]); @@ -275,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::{MINIMUM_WEIGHT, Weight}, + weights::{SimpleDispatchInfo, MINIMUM_WEIGHT, Weight}, storage::IterableStorageMap, dispatch::{IsSubType, DispatchResult}, traits::{ @@ -1256,7 +1256,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 = 500_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] pub fn bond(origin, controller: ::Source, #[compact] value: BalanceOf, @@ -1320,7 +1320,7 @@ decl_module! { /// - O(1). /// - One DB entry. /// # - #[weight = 500_000_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)?; @@ -1366,7 +1366,7 @@ decl_module! { /// `withdraw_unbonded`. /// - One DB entry. /// - #[weight = 400_000_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)?; @@ -1414,7 +1414,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 = 400_000_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)?; @@ -1457,7 +1457,7 @@ decl_module! { /// - Contains a limited number of reads. /// - Writes are limited to the `origin` account key. /// # - #[weight = 750_000_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)?; @@ -1480,7 +1480,7 @@ decl_module! { /// which is capped at CompactAssignments::LIMIT. /// - Both the reads and writes follow a similar pattern. /// # - #[weight = 750_000_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)?; @@ -1515,7 +1515,7 @@ decl_module! { /// - Contains one read. /// - Writes are limited to the `origin` account key. /// # - #[weight = 500_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] fn chill(origin) { ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed); let controller = ensure_signed(origin)?; @@ -1534,7 +1534,7 @@ decl_module! { /// - Contains a limited number of reads. /// - Writes are limited to the `origin` account key. /// # - #[weight = 500_000_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)?; @@ -1553,7 +1553,7 @@ decl_module! { /// - Contains a limited number of reads. /// - Writes are limited to the `origin` account key. /// # - #[weight = 750_000_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)?; @@ -1570,7 +1570,7 @@ decl_module! { } /// The ideal number of validators. - #[weight = 5_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] fn set_validator_count(origin, #[compact] new: u32) { ensure_root(origin)?; ValidatorCount::put(new); @@ -1581,7 +1581,7 @@ decl_module! { /// # /// - No arguments. /// # - #[weight = 5_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] fn force_no_eras(origin) { ensure_root(origin)?; ForceEra::put(Forcing::ForceNone); @@ -1593,21 +1593,21 @@ decl_module! { /// # /// - No arguments. /// # - #[weight = 5_000_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 = 5_000_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 = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn force_unstake(origin, stash: T::AccountId) { ensure_root(origin)?; @@ -1623,7 +1623,7 @@ decl_module! { /// # /// - One storage write /// # - #[weight = 5_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] fn force_new_era_always(origin) { ensure_root(origin)?; ForceEra::put(Forcing::ForceAlways); @@ -1636,7 +1636,7 @@ decl_module! { /// # /// - One storage write. /// # - #[weight = 1_000_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(|_| ()) @@ -1687,7 +1687,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 = 500_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(500_000_000)] fn payout_nominator(origin, era: EraIndex, validators: Vec<(T::AccountId, u32)>) -> DispatchResult { @@ -1714,7 +1714,7 @@ decl_module! { /// - Time complexity: O(1). /// - Contains a limited number of reads and writes. /// # - #[weight = 500_000_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) @@ -1735,7 +1735,7 @@ decl_module! { /// - Time complexity: at most O(MaxNominatorRewardedPerValidator). /// - Contains a limited number of reads and writes. /// # - #[weight = 500_000_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)?; @@ -1751,7 +1751,7 @@ decl_module! { /// - Time complexity: O(1). Bounded by `MAX_UNLOCKING_CHUNKS`. /// - Storage changes: Can't increase storage, only decrease it. /// # - #[weight = 500_000_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)?; @@ -1765,7 +1765,7 @@ decl_module! { /// Set history_depth value. /// /// Origin must be root. - #[weight = (500_000_000, frame_support::weights::DispatchClass::Operational)] + #[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() { @@ -1787,7 +1787,7 @@ decl_module! { /// This can be called from any origin. /// /// - `stash`: The stash account to reap. Its balance must be zero. - #[weight = MINIMUM_WEIGHT] + #[weight = 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)?; @@ -1868,7 +1868,7 @@ decl_module! { /// /// The weight of this call is 1/10th of the blocks total weight. /// # - #[weight = 100_000_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000_000)] pub fn submit_election_solution( origin, winners: Vec, @@ -1891,7 +1891,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 = 100_000_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(100_000_000_000)] pub fn submit_election_solution_unsigned( origin, winners: Vec, diff --git a/frame/sudo/src/lib.rs b/frame/sudo/src/lib.rs index ce0de2027c713..b8cf9a353f341 100644 --- a/frame/sudo/src/lib.rs +++ b/frame/sudo/src/lib.rs @@ -52,14 +52,14 @@ //! //! ``` //! use frame_support::{decl_module, dispatch}; -//! use frame_support::weights::MINIMUM_WEIGHT; +//! 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 = MINIMUM_WEIGHT] +//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] //! pub fn privileged_function(origin) -> dispatch::DispatchResult { //! ensure_root(origin)?; //! @@ -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 { @@ -151,7 +151,7 @@ decl_module! { /// - Limited storage reads. /// - One DB change. /// # - #[weight = 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/src/dispatch.rs b/frame/support/src/dispatch.rs index 434c8591a283b..8512ccb0a8e22 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -24,8 +24,8 @@ pub use frame_metadata::{ ModuleConstantMetadata, DefaultByte, DefaultByteGetter, ModuleErrorMetadata, ErrorMetadata }; pub use crate::weights::{ - GetDispatchInfo, DispatchInfo, WeighData, ClassifyDispatch, TransactionPriority, Weight, - PaysFee, PostDispatchInfo, WithPostDispatchInfo, + SimpleDispatchInfo, GetDispatchInfo, DispatchInfo, WeighData, ClassifyDispatch, + TransactionPriority, Weight, PaysFee, PostDispatchInfo, WithPostDispatchInfo, }; pub use sp_runtime::{traits::Dispatchable, DispatchError}; pub use crate::traits::{CallMetadata, GetCallMetadata, GetCallName}; @@ -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::MINIMUM_WEIGHT; +/// # 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 = MINIMUM_WEIGHT] +/// #[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 = MINIMUM_WEIGHT] +/// #[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::MINIMUM_WEIGHT; +/// # 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 = MINIMUM_WEIGHT] +/// #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] /// fn my_long_function(origin) -> dispatch::DispatchResult { /// // Your implementation /// Ok(()) /// } /// -/// #[weight = MINIMUM_WEIGHT] +/// #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] /// fn my_short_function(origin) { /// // Your implementation /// } @@ -153,10 +153,11 @@ impl Parameter for T where T: Codec + EncodeLike + Clone + Eq + fmt::Debug {} /// # #[macro_use] /// # extern crate frame_support; /// # use frame_support::dispatch::{DispatchResultWithPostInfo, WithPostDispatchInfo}; +/// # use frame_support::weights::SimpleDispatchInfo; /// # use frame_system::{self as system, Trait, ensure_signed}; /// decl_module! { /// pub struct Module for enum Call where origin: T::Origin { -/// #[weight = 1_000_000] +/// #[weight = SimpleDispatchInfo::FixedNormal(1_000_000)] /// fn my_long_function(origin, do_expensive_calc: bool) -> DispatchResultWithPostInfo { /// ensure_signed(origin).map_err(|e| e.with_weight(100_000))?; /// if do_expensive_calc { @@ -181,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::MINIMUM_WEIGHT; +/// # 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 = MINIMUM_WEIGHT] +/// #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] /// fn my_privileged_function(origin) -> dispatch::DispatchResult { /// ensure_root(origin)?; /// // Your implementation @@ -2111,25 +2112,25 @@ mod tests { decl_module! { pub struct Module for enum Call where origin: T::Origin, T::AccountId: From { /// Hi, this is a comment. - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn aux_0(_origin) -> DispatchResult { unreachable!() } - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn aux_1(_origin, #[compact] _data: u32,) -> DispatchResult { unreachable!() } - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn aux_2(_origin, _data: i32, _data2: String) -> DispatchResult { unreachable!() } - #[weight = 3] + #[weight = SimpleDispatchInfo::FixedNormal(3)] fn aux_3(_origin) -> DispatchResult { unreachable!() } - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn aux_4(_origin, _data: i32) -> DispatchResult { unreachable!() } - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn aux_5(_origin, _data: i32, #[compact] _data2: u32,) -> DispatchResult { unreachable!() } - #[weight = (5, DispatchClass::Operational)] + #[weight = SimpleDispatchInfo::FixedOperational(5)] fn operational(_origin) { unreachable!() } fn on_initialize(n: T::BlockNumber,) -> Weight { if n.into() == 42 { panic!("on_initialize") } 7 } diff --git a/frame/support/src/error.rs b/frame/support/src/error.rs index 1e3028961aea5..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::MINIMUM_WEIGHT; +/// # 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 = MINIMUM_WEIGHT] +/// #[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 88fb1f7420a18..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::MINIMUM_WEIGHT; + 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 = MINIMUM_WEIGHT] + #[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 7f8791f9dc8c7..79cfa1b3974b3 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -16,97 +16,29 @@ //! # Primitives for transaction weighting. //! -//! Every dispatchable function is responsible for providing `#[weight = $x]` attribute. In this -//! snipped, `$x` can be any user provided struct that implements the following traits: +//! All dispatchable functions defined in `decl_module!` must provide two trait implementations: +//! - [`WeightData`]: To determine the weight of the dispatch. +//! - [`ClassifyDispatch`]: To determine the class of the dispatch. See the enum definition for +//! more information on dispatch classes. //! -//! - [`WeighData`]: the weight amount. -//! - [`ClassifyDispatch`]: class of the dispatch. -//! - [`PaysFee`]: weather this weight should be translated to fee and deducted upon dispatch. +//! Every dispatchable function is responsible for providing this data via an optional `#[weight = +//! $x]` attribute. In this snipped, `$x` can be any user provided struct that implements the +//! two aforementioned traits. //! //! Substrate then bundles then output information of the two traits into [`DispatchInfo`] struct -//! and provides it by implementing the [`GetDispatchInfo`] for all `Call` both inner and outer call -//! types. +//! and provides it by implementing the [`GetDispatchInfo`] for all `Call` variants, and opaque +//! extrinsic types. //! -//! Substrate provides two pre-defined ways to annotate weight: -//! -//! ### 1. Fixed values -//! -//! This can only be used when all 3 traits can be resolved statically. You have 3 degrees of -//! configuration: -//! -//! 1. Define only weight, **in which case `ClassifyDispatch` will be `Normal` and `PaysFee` will be -//! `true`**. -//! -//! ``` -//! # use frame_system::{self as system, Trait}; -//! frame_support::decl_module! { -//! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = 1000] -//! fn dispatching(origin) { unimplemented!() } -//! } -//! } -//! # fn main() {} -//! ``` -//! -//! 2. Define weight and class, **in which case `PaysFee` would be `true`**. -//! -//! ``` -//! # use frame_system::{self as system, Trait}; -//! # use frame_support::weights::DispatchClass; -//! frame_support::decl_module! { -//! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = (1000, DispatchClass::Operational)] -//! fn dispatching(origin) { unimplemented!() } -//! } -//! } -//! # fn main() {} -//! ``` -//! -//! 3. Define all 3 parameters. -//! -//! ``` -//! # use frame_system::{self as system, Trait}; -//! # use frame_support::weights::DispatchClass; -//! frame_support::decl_module! { -//! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = (1000, DispatchClass::Operational, false)] -//! fn dispatching(origin) { unimplemented!() } -//! } -//! } -//! # fn main() {} -//! ``` -//! -//! ### 2. Define weights as a function of input arguments using `FunctionOf` tuple struct. This struct works -//! in a similar manner as above. 3 items must be provided and each can be either a fixed value or a -//! function/closure with the same parameters list as the dispatchable function itself, wrapper in a -//! tuple. -//! -//! Using this only makes sense if you want to use a function for at least one of the elements. If -//! all 3 are static values, providing a raw tuple is easier. -//! -//! ``` -//! # use frame_system::{self as system, Trait}; -//! # use frame_support::weights::{DispatchClass, FunctionOf}; -//! frame_support::decl_module! { -//! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = FunctionOf( -//! // weight, function. -//! |args: (&u32, &u64)| *args.0 as u64 + args.1, -//! // class, fixed. -//! DispatchClass::Operational, -//! // pays fee, function. -//! |args: (&u32, &u64)| *args.0 > 1000, -//! )] -//! fn dispatching(origin, a: u32, b: u64) { unimplemented!() } -//! } -//! } -//! # fn main() {} -//! ``` +//! If no `#[weight]` is defined, the macro automatically injects the `Default` implementation of +//! the [`SimpleDispatchInfo`]. //! +//! Note that the decl_module macro _cannot_ enforce this and will simply fail if an invalid struct +//! (something that does not implement `Weighable`) is passed in. #[cfg(feature = "std")] use serde::{Serialize, Deserialize}; use codec::{Encode, Decode}; +use sp_arithmetic::traits::Bounded; use sp_runtime::{ RuntimeDebug, traits::SignedExtension, @@ -149,7 +81,8 @@ pub trait PaysFee { } } -/// A generalized group of dispatch types. +/// A generalized group of dispatch types. This is only distinguishing normal, user-triggered transactions +/// (`Normal`) and anything beyond which serves a higher purpose to the system (`Operational`). #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] #[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, RuntimeDebug)] @@ -179,6 +112,40 @@ 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 { + SimpleDispatchInfo::FixedOperational(_) => DispatchClass::Operational, + SimpleDispatchInfo::MaxOperational => DispatchClass::Operational, + + SimpleDispatchInfo::FixedNormal(_) => DispatchClass::Normal, + SimpleDispatchInfo::MaxNormal => DispatchClass::Normal, + SimpleDispatchInfo::InsecureFreeNormal => DispatchClass::Normal, + + SimpleDispatchInfo::FixedMandatory(_) => DispatchClass::Mandatory, + } + } +} + /// A bundle of static information collected from the `#[weight = $x]` attributes. #[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)] pub struct DispatchInfo { @@ -190,15 +157,6 @@ pub struct DispatchInfo { pub pays_fee: bool, } -/// A `Dispatchable` function (aka transaction) that can carry some static information along with -/// it, using the `#[weight]` attribute. -pub trait GetDispatchInfo { - /// Return a `DispatchInfo`, containing relevant information of this dispatch. - /// - /// This is done independently of its encoded size. - fn get_dispatch_info(&self) -> DispatchInfo; -} - /// Weight information that is only available post dispatch. #[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)] pub struct PostDispatchInfo { @@ -272,75 +230,86 @@ impl WithPostDispatchInfo for T where } } -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 WeighData for (Weight, DispatchClass, bool) { - fn weigh_data(&self, _: T) -> Weight { - return self.0 - } -} - -impl ClassifyDispatch for (Weight, DispatchClass, bool) { - fn classify_dispatch(&self, _: T) -> DispatchClass { - self.1 - } +/// A `Dispatchable` function (aka transaction) that can carry some static information along with +/// it, using the `#[weight]` attribute. +pub trait GetDispatchInfo { + /// Return a `DispatchInfo`, containing relevant information of this dispatch. + /// + /// This is done independently of its encoded size. + fn get_dispatch_info(&self) -> DispatchInfo; } -impl PaysFee for (Weight, DispatchClass, bool) { - fn pays_fee(&self, _: T) -> bool { - self.2 - } +/// Default type used with the `#[weight = x]` attribute in a substrate chain. +/// +/// A user may pass in any other type that implements the correct traits. If not, the `Default` +/// implementation of [`SimpleDispatchInfo`] is used. +/// +/// For each generalized group (`Normal` and `Operation`): +/// - A `Fixed` variant means weight fee is charged normally and the weight is the number +/// specified in the inner value of the variant. +/// - A `Free` variant is equal to `::Fixed(0)`. Note that this does not guarantee inclusion. +/// - A `Max` variant is equal to `::Fixed(Weight::max_value())`. +/// +/// As for the generalized groups themselves: +/// - `Normal` variants will be assigned a priority proportional to their weight. They can only +/// consume a portion (defined in the system module) of the maximum block resource limits. +/// - `Operational` variants will be assigned the maximum priority. They can potentially consume +/// the entire block resource limit. +#[derive(Clone, Copy)] +pub enum SimpleDispatchInfo { + /// A normal dispatch with fixed weight. + FixedNormal(Weight), + /// A normal dispatch with the maximum weight. + MaxNormal, + /// A normal dispatch with no weight. Base and bytes fees still need to be paid. + InsecureFreeNormal, + /// An operational dispatch with fixed weight. + FixedOperational(Weight), + /// An operational dispatch with the maximum weight. + MaxOperational, + /// A mandatory dispatch with fixed weight. + /// + /// NOTE: Signed transactions may not (directly) dispatch this kind of a call, so the other + /// attributes concerning transactability (e.g. priority, fee paying) are moot. + FixedMandatory(Weight), } -impl WeighData for (Weight, DispatchClass) { +impl WeighData for SimpleDispatchInfo { fn weigh_data(&self, _: T) -> Weight { - return self.0 + match self { + SimpleDispatchInfo::FixedNormal(w) => *w, + SimpleDispatchInfo::MaxNormal => Bounded::max_value(), + SimpleDispatchInfo::InsecureFreeNormal => Bounded::min_value(), + SimpleDispatchInfo::FixedOperational(w) => *w, + SimpleDispatchInfo::MaxOperational => Bounded::max_value(), + SimpleDispatchInfo::FixedMandatory(w) => *w, + } } } -impl ClassifyDispatch for (Weight, DispatchClass) { +impl ClassifyDispatch for SimpleDispatchInfo { fn classify_dispatch(&self, _: T) -> DispatchClass { - self.1 + DispatchClass::from(*self) } } -impl PaysFee for (Weight, DispatchClass) { +impl PaysFee for SimpleDispatchInfo { fn pays_fee(&self, _: T) -> bool { - true - } -} - -impl WeighData for (Weight, bool) { - fn weigh_data(&self, _: T) -> Weight { - return self.0 - } -} - -impl ClassifyDispatch for (Weight, bool) { - fn classify_dispatch(&self, _: T) -> DispatchClass { - DispatchClass::Normal + match self { + SimpleDispatchInfo::FixedNormal(_) => true, + SimpleDispatchInfo::MaxNormal => true, + SimpleDispatchInfo::InsecureFreeNormal => true, + SimpleDispatchInfo::FixedOperational(_) => true, + SimpleDispatchInfo::MaxOperational => true, + SimpleDispatchInfo::FixedMandatory(_) => true, + } } } -impl PaysFee for (Weight, bool) { - fn pays_fee(&self, _: T) -> bool { - self.1 +impl SimpleDispatchInfo { + /// An _additive zero_ variant of SimpleDispatchInfo. + pub fn zero() -> Self { + Self::FixedNormal(0) } } @@ -494,14 +463,8 @@ mod tests { decl_module! { pub struct Module for enum Call where origin: T::Origin { // no arguments, fixed weight - #[weight = 1000] - fn f00(_origin) { unimplemented!(); } - - #[weight = (1000, DispatchClass::Mandatory)] - fn f01(_origin) { unimplemented!(); } - - #[weight = (1000, DispatchClass::Operational, false)] - fn f02(_origin) { unimplemented!(); } + #[weight = SimpleDispatchInfo::FixedNormal(1000)] + fn f0(_origin) { unimplemented!(); } // weight = a x 10 + b #[weight = FunctionOf(|args: (&u32, &u32)| (args.0 * 10 + args.1) as Weight, DispatchClass::Normal, true)] @@ -521,24 +484,7 @@ mod tests { #[test] fn weights_are_correct() { - // #[weight = 1000] - let info = Call::::f00().get_dispatch_info(); - assert_eq!(info.weight, 1000); - assert_eq!(info.class, DispatchClass::Normal); - assert_eq!(info.pays_fee, true); - - // #[weight = (1000, DispatchClass::Mandatory)] - let info = Call::::f01().get_dispatch_info(); - assert_eq!(info.weight, 1000); - assert_eq!(info.class, DispatchClass::Mandatory); - assert_eq!(info.pays_fee, true); - - // #[weight = (1000, DispatchClass::Operational, false)] - let info = Call::::f02().get_dispatch_info(); - assert_eq!(info.weight, 1000); - assert_eq!(info.class, DispatchClass::Operational); - assert_eq!(info.pays_fee, false); - + 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::::f12(10, 20).get_dispatch_info().weight, 0); diff --git a/frame/support/test/tests/decl_error.rs b/frame/support/test/tests/decl_error.rs index 283e747a9ec4a..cf50b009ddf18 100644 --- a/frame/support/test/tests/decl_error.rs +++ b/frame/support/test/tests/decl_error.rs @@ -18,7 +18,7 @@ use sp_runtime::{generic, traits::{BlakeTwo256, Block as _, Verify}, DispatchError}; use sp_core::{H256, sr25519}; -use frame_support::weights::MINIMUM_WEIGHT; +use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; mod system; @@ -33,7 +33,7 @@ mod module1 { pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: ::Origin { - #[weight = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { Err(Error::::Something.into()) } @@ -60,7 +60,7 @@ mod module2 { pub struct Module for enum Call where origin: ::Origin { - #[weight = 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/instance.rs b/frame/support/test/tests/instance.rs index aa6f635cccd4f..00b110ffb90e1 100644 --- a/frame/support/test/tests/instance.rs +++ b/frame/support/test/tests/instance.rs @@ -23,7 +23,7 @@ use frame_support::{ DecodeDifferent, StorageMetadata, StorageEntryModifier, StorageEntryType, DefaultByteGetter, StorageEntryMetadata, StorageHasher, }, - weights::MINIMUM_WEIGHT, + weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}, StorageValue, StorageMap, StorageDoubleMap, }; use sp_inherents::{ProvideInherent, InherentData, InherentIdentifier, MakeFatalError}; @@ -56,7 +56,7 @@ mod module1 { fn deposit_event() = default; - #[weight = MINIMUM_WEIGHT] + #[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 ef19fee0e6966..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, weights::MINIMUM_WEIGHT}; + pub use frame_support::{dispatch, weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}}; pub trait Trait { type Origin; @@ -19,7 +19,7 @@ macro_rules! reserved { frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin { - #[weight = MINIMUM_WEIGHT] + #[weight = 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 3b9daf861031f..50f2b089f2074 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -68,14 +68,14 @@ //! ### Example - Get extrinsic count and parent hash for the current block //! //! ``` -//! use frame_support::{decl_module, dispatch, weights::MINIMUM_WEIGHT}; +//! use frame_support::{decl_module, dispatch, weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}}; //! use frame_system::{self as system, ensure_signed}; //! //! pub trait Trait: system::Trait {} //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = MINIMUM_WEIGHT] +//! #[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, MINIMUM_WEIGHT, RuntimeDbWeight, DispatchInfo, PostDispatchInfo, DispatchClass, FunctionOf} + weights::{Weight, MINIMUM_WEIGHT, RuntimeDbWeight, DispatchInfo, PostDispatchInfo, DispatchClass, SimpleDispatchInfo, FunctionOf} }; use codec::{Encode, Decode, FullCodec, EncodeLike}; @@ -485,20 +485,20 @@ decl_module! { } /// Make some on-chain remark. - #[weight = MINIMUM_WEIGHT] + #[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 = (MINIMUM_WEIGHT, DispatchClass::Operational)] + #[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()); } /// Set the new runtime code. - #[weight = (200_000_000, DispatchClass::Operational)] + #[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 = (200_000_000, DispatchClass::Operational)] + #[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 = (20_000_000, DispatchClass::Operational)] + #[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 = (MINIMUM_WEIGHT, DispatchClass::Operational)] + #[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 = (MINIMUM_WEIGHT, DispatchClass::Operational)] + #[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 = (MINIMUM_WEIGHT, DispatchClass::Operational)] + #[weight = SimpleDispatchInfo::FixedOperational(MINIMUM_WEIGHT)] 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 = (25_000_000, DispatchClass::Operational)] + #[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 6109c3dddeae3..822848bf7dcc7 100644 --- a/frame/timestamp/src/lib.rs +++ b/frame/timestamp/src/lib.rs @@ -62,7 +62,7 @@ //! //! ``` //! use frame_support::{decl_module, dispatch}; -//! use frame_support::weights::MINIMUM_WEIGHT; +//! use frame_support::weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}; //! # use pallet_timestamp as timestamp; //! use frame_system::{self as system, ensure_signed}; //! @@ -70,7 +70,7 @@ //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = MINIMUM_WEIGHT] +//! #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] //! pub fn get_time(origin) -> dispatch::DispatchResult { //! let _sender = ensure_signed(origin)?; //! let _now = >::get(); @@ -101,7 +101,7 @@ use frame_support::debug; use frame_support::{ Parameter, decl_storage, decl_module, traits::{Time, UnixTime, Get}, - weights::MINIMUM_WEIGHT, + weights::{SimpleDispatchInfo, MINIMUM_WEIGHT}, }; use sp_runtime::{ RuntimeString, @@ -148,7 +148,7 @@ decl_module! { /// `MinimumPeriod`. /// /// The dispatch origin for this call must be `Inherent`. - #[weight = (MINIMUM_WEIGHT, frame_support::weights::DispatchClass::Mandatory)] + #[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 394355a989fe3..af39985133c81 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}; +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}; @@ -327,7 +327,7 @@ decl_module! { /// - Limited storage reads. /// - One DB change, one extra DB entry. /// # - #[weight = 500_000_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 = (100_000_000, frame_support::weights::DispatchClass::Operational)] + #[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 = (100_000_000, frame_support::weights::DispatchClass::Operational)] + #[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 = 100_000_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 = 50_000_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 = 150_000_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 = 50_000_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 = 50_000_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 6da92ea15a479..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::MINIMUM_WEIGHT; +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 = MINIMUM_WEIGHT] + #[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 = MINIMUM_WEIGHT] + #[weight = SimpleDispatchInfo::FixedNormal(MINIMUM_WEIGHT)] fn vest_other(origin, target: ::Source) -> DispatchResult { ensure_signed(origin)?; Self::update_lock(T::Lookup::lookup(target)?) @@ -236,7 +236,7 @@ decl_module! { /// - Creates a new storage entry, but is protected by a minimum transfer /// amount needed to succeed. /// # - #[weight = 1_000_000_000] + #[weight = SimpleDispatchInfo::FixedNormal(1_000_000_000)] pub fn vested_transfer( origin, target: ::Source, From 48316538398ab8d1745e1747e70117232b063028 Mon Sep 17 00:00:00 2001 From: kianenigma Date: Mon, 27 Apr 2020 10:57:15 +0200 Subject: [PATCH 7/9] Move to offchain randomness --- bin/node/runtime/src/lib.rs | 1 - frame/session/benchmarking/src/mock.rs | 1 - frame/staking/fuzzer/src/mock.rs | 12 ------------ frame/staking/src/lib.rs | 5 +---- frame/staking/src/mock.rs | 11 ----------- frame/staking/src/offchain_election.rs | 5 ++--- frame/staking/src/tests.rs | 2 +- primitives/core/Cargo.toml | 2 +- primitives/core/src/offchain/testing.rs | 7 ++++++- primitives/phragmen/src/lib.rs | 2 +- 10 files changed, 12 insertions(+), 36 deletions(-) diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 622356b1d2c9b..e2822fbb24bc0 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -319,7 +319,6 @@ impl pallet_staking::Trait for Runtime { type NextNewSession = Session; type ElectionLookahead = ElectionLookahead; type Call = Call; - type Randomness = RandomnessCollectiveFlip; type MaxIterations = MaxIterations; type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator; type UnsignedPriority = StakingUnsignedPriority; diff --git a/frame/session/benchmarking/src/mock.rs b/frame/session/benchmarking/src/mock.rs index 06bbf8cebb85c..e07f23f64e970 100644 --- a/frame/session/benchmarking/src/mock.rs +++ b/frame/session/benchmarking/src/mock.rs @@ -178,7 +178,6 @@ impl pallet_staking::Trait for Test { type Call = Call; type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator; type UnsignedPriority = UnsignedPriority; - type Randomness = (); type MaxIterations = (); } diff --git a/frame/staking/fuzzer/src/mock.rs b/frame/staking/fuzzer/src/mock.rs index 267f6869b931c..40a2fd912e3a3 100644 --- a/frame/staking/fuzzer/src/mock.rs +++ b/frame/staking/fuzzer/src/mock.rs @@ -16,8 +16,6 @@ //! Mock file for staking fuzzing. -use codec::Encode; -use sp_core::H256; use sp_runtime::traits::{Convert, SaturatedConversion}; use frame_support::{impl_outer_origin, impl_outer_dispatch, parameter_types}; @@ -54,15 +52,6 @@ impl Convert for CurrencyToVoteHandler { } } -pub struct StaticRandomness; -impl frame_support::traits::Randomness for StaticRandomness { - fn random(_subject: &[u8]) -> H256 { - let mut static_value = 10u32.encode(); - static_value.resize_with(32, || 0u8); - H256::from_slice(&static_value) - } -} - #[derive(Clone, Eq, PartialEq, Debug)] pub struct Test; @@ -192,7 +181,6 @@ impl pallet_staking::Trait for Test { type ElectionLookahead = (); type Call = Call; type MaxIterations = MaxIterations; - type Randomness = StaticRandomness; type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator; type UnsignedPriority = (); } diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index 7f839f9a8a6f7..6a60630fb46ed 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -296,7 +296,7 @@ use frame_support::{ dispatch::{IsSubType, DispatchResult}, traits::{ Currency, LockIdentifier, LockableCurrency, WithdrawReasons, OnUnbalanced, Imbalance, Get, - UnixTime, EstimateNextNewSession, Randomness, EnsureOrigin, + UnixTime, EstimateNextNewSession, EnsureOrigin, } }; use pallet_session::historical; @@ -804,9 +804,6 @@ pub trait Trait: frame_system::Trait + SendTransactionTypes> { /// The overarching call type. type Call: Dispatchable + From> + IsSubType, Self> + Clone; - /// Something that can provide randomness - type Randomness: Randomness; - /// Maximum number of equalise iterations to run in the offchain submission type MaxIterations: Get; diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index dd9d8e593780e..634d921f5da6d 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -17,7 +17,6 @@ //! Test utilities use std::{collections::{HashSet, HashMap}, cell::RefCell}; -use codec::Encode; use sp_runtime::Perbill; use sp_runtime::curve::PiecewiseLinear; use sp_runtime::traits::{IdentityLookup, Convert, SaturatedConversion, Zero}; @@ -96,15 +95,6 @@ impl pallet_session::OneSessionHandler for OtherSessionHandler { } } -pub struct StaticRandomness; -impl frame_support::traits::Randomness for StaticRandomness { - fn random(_subject: &[u8]) -> H256 { - let mut static_value = ITERATIONS.with(|v| *v.borrow()).encode(); - static_value.resize_with(32, || 0u8); - H256::from_slice(&static_value) - } -} - impl sp_runtime::BoundToRuntimeAppPublic for OtherSessionHandler { type Public = UintAuthorityId; } @@ -320,7 +310,6 @@ impl Trait for Test { type NextNewSession = Session; type ElectionLookahead = ElectionLookahead; type Call = Call; - type Randomness = StaticRandomness; type MaxIterations = MaxIterations; type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator; type UnsignedPriority = UnsignedPriority; diff --git a/frame/staking/src/offchain_election.rs b/frame/staking/src/offchain_election.rs index 895c03f274c09..1f6a648182c89 100644 --- a/frame/staking/src/offchain_election.rs +++ b/frame/staking/src/offchain_election.rs @@ -27,7 +27,7 @@ use sp_phragmen::{ }; use sp_runtime::offchain::storage::StorageValueRef; use sp_runtime::{PerThing, RuntimeDebug, traits::{TrailingZeroInput, Zero}}; -use frame_support::{debug, traits::{Randomness, Get}}; +use frame_support::{debug, traits::Get}; use sp_std::{convert::TryInto, prelude::*}; /// Error types related to the offchain election machinery. @@ -176,8 +176,7 @@ pub fn prepare_submission( let (mut support_map, _) = build_support_map::(&winners, &staked); // equalize a random number of times. - let phrase = b"staking_offchain_phragmen"; - let seed = T::Randomness::random(phrase); + let seed = sp_io::offchain::random_seed(); let iterations = ::decode(&mut TrailingZeroInput::new(seed.as_ref())) .expect("input is padded with zeroes; qed") % T::MaxIterations::get(); let iterations_executed = equalize( diff --git a/frame/staking/src/tests.rs b/frame/staking/src/tests.rs index 8c250e93aa657..498240d4a45d0 100644 --- a/frame/staking/src/tests.rs +++ b/frame/staking/src/tests.rs @@ -3119,7 +3119,7 @@ mod offchain_phragmen { &inner, ), TransactionValidity::Ok(ValidTransaction { - priority: UnsignedPriority::get() + 1125, // the proposed slot stake. + priority: UnsignedPriority::get() + 1250, // the proposed slot stake. requires: vec![], provides: vec![("StakingOffchain", current_era()).encode()], longevity: 3, diff --git a/primitives/core/Cargo.toml b/primitives/core/Cargo.toml index 5eecd83853ba8..2ab23d23c4a0e 100644 --- a/primitives/core/Cargo.toml +++ b/primitives/core/Cargo.toml @@ -24,7 +24,7 @@ wasmi = { version = "0.6.2", optional = true } hash-db = { version = "0.15.2", default-features = false } hash256-std-hasher = { version = "0.15.2", default-features = false } base58 = { version = "0.1.0", optional = true } -rand = { version = "0.7.2", optional = true } +rand = { version = "0.7.3", optional = true, features = ["small_rng"] } substrate-bip39 = { version = "0.4.1", optional = true } tiny-bip39 = { version = "0.7", optional = true } regex = { version = "1.3.1", optional = true } diff --git a/primitives/core/src/offchain/testing.rs b/primitives/core/src/offchain/testing.rs index f4faee6b026eb..fecf442c57841 100644 --- a/primitives/core/src/offchain/testing.rs +++ b/primitives/core/src/offchain/testing.rs @@ -165,7 +165,12 @@ impl offchain::Externalities for TestOffchainExt { } fn random_seed(&mut self) -> [u8; 32] { - unimplemented!("not needed in tests so far") + use rand::{SeedableRng, RngCore}; + use rand::rngs::SmallRng; + let mut seed = [0u8; 32]; + let mut small_rng = SmallRng::from_entropy(); + small_rng.fill_bytes(&mut seed); + seed } fn local_storage_set(&mut self, kind: StorageKind, key: &[u8], value: &[u8]) { diff --git a/primitives/phragmen/src/lib.rs b/primitives/phragmen/src/lib.rs index 01d034a95ecef..f45732d5b8e1e 100644 --- a/primitives/phragmen/src/lib.rs +++ b/primitives/phragmen/src/lib.rs @@ -158,7 +158,7 @@ pub struct PhragmenResult { #[derive(RuntimeDebug, Clone, Default)] #[cfg_attr(feature = "std", derive(PartialEq, Eq, Encode, Decode))] pub struct Assignment { - /// Voter's identifier + /// Voter's identifier. pub who: AccountId, /// The distribution of the voter's stake. pub distribution: Vec<(AccountId, T)>, From 6780b60430457902bc7cadd1887ff8c3930db31b Mon Sep 17 00:00:00 2001 From: kianenigma Date: Mon, 27 Apr 2020 11:19:16 +0200 Subject: [PATCH 8/9] Fix tests --- frame/staking/fuzzer/src/mock.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/frame/staking/fuzzer/src/mock.rs b/frame/staking/fuzzer/src/mock.rs index 40a2fd912e3a3..1819970e6061e 100644 --- a/frame/staking/fuzzer/src/mock.rs +++ b/frame/staking/fuzzer/src/mock.rs @@ -58,6 +58,8 @@ pub struct Test; impl frame_system::Trait for Test { type Origin = Origin; type DbWeight = (); + type BlockExecutionWeight = (); + type ExtrinsicBaseWeight = (); type Index = AccountIndex; type BlockNumber = BlockNumber; type Call = Call; From df1a7b5709bbcf23bdc9ec171d6a2013bcb34ec0 Mon Sep 17 00:00:00 2001 From: kianenigma Date: Mon, 27 Apr 2020 11:49:19 +0200 Subject: [PATCH 9/9] Fix tests more --- frame/staking/src/lib.rs | 3 ++- frame/staking/src/mock.rs | 20 ++++++++++++------- frame/staking/src/offchain_election.rs | 27 +++++++++++++++++--------- frame/staking/src/tests.rs | 15 +++++++------- 4 files changed, 41 insertions(+), 24 deletions(-) diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index 67e70a2832675..67240d8d34b2a 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -803,7 +803,8 @@ pub trait Trait: frame_system::Trait + SendTransactionTypes> { /// The overarching call type. type Call: Dispatchable + From> + IsSubType, Self> + Clone; - /// Maximum number of equalise iterations to run in the offchain submission + /// Maximum number of equalise iterations to run in the offchain submission. If set to 0, + /// equalize will not be executed at all. type MaxIterations: Get; /// The maximum number of nominator rewarded for each validator. diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index be38682373591..a34f3425564cd 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -64,7 +64,7 @@ thread_local! { static SLASH_DEFER_DURATION: RefCell = RefCell::new(0); static ELECTION_LOOKAHEAD: RefCell = RefCell::new(0); static PERIOD: RefCell = RefCell::new(1); - static ITERATIONS: RefCell = RefCell::new(0); + static MAX_ITERATIONS: RefCell = RefCell::new(0); } /// Another session handler struct to test on_disabled. @@ -144,6 +144,13 @@ impl Get for SlashDeferDuration { } } +pub struct MaxIterations; +impl Get for MaxIterations { + fn get() -> u32 { + MAX_ITERATIONS.with(|v| *v.borrow()) + } +} + impl_outer_origin! { pub enum Origin for Test where system = frame_system {} } @@ -277,7 +284,6 @@ parameter_types! { pub const RewardCurve: &'static PiecewiseLinear<'static> = &I_NPOS; pub const MaxNominatorRewardedPerValidator: u32 = 64; pub const UnsignedPriority: u64 = 1 << 20; - pub const MaxIterations: u32 = 5; } thread_local! { @@ -340,7 +346,7 @@ pub struct ExtBuilder { num_validators: Option, invulnerables: Vec, has_stakers: bool, - offchain_iterations: u32, + max_offchain_iterations: u32, } impl Default for ExtBuilder { @@ -359,7 +365,7 @@ impl Default for ExtBuilder { num_validators: None, invulnerables: vec![], has_stakers: true, - offchain_iterations: 0, + max_offchain_iterations: 0, } } } @@ -417,8 +423,8 @@ impl ExtBuilder { self.has_stakers = has; self } - pub fn offchain_iterations(mut self, iterations: u32) -> Self { - self.offchain_iterations = iterations; + pub fn max_offchain_iterations(mut self, iterations: u32) -> Self { + self.max_offchain_iterations = iterations; self } pub fn offchain_phragmen_ext(self) -> Self { @@ -432,7 +438,7 @@ impl ExtBuilder { SESSION_PER_ERA.with(|v| *v.borrow_mut() = self.session_per_era); ELECTION_LOOKAHEAD.with(|v| *v.borrow_mut() = self.election_lookahead); PERIOD.with(|v| *v.borrow_mut() = self.session_length); - ITERATIONS.with(|v| *v.borrow_mut() = self.offchain_iterations); + MAX_ITERATIONS.with(|v| *v.borrow_mut() = self.max_offchain_iterations); } pub fn build(self) -> sp_io::TestExternalities { let _ = env_logger::try_init(); diff --git a/frame/staking/src/offchain_election.rs b/frame/staking/src/offchain_election.rs index 1f6a648182c89..572703f895ec7 100644 --- a/frame/staking/src/offchain_election.rs +++ b/frame/staking/src/offchain_election.rs @@ -176,15 +176,24 @@ pub fn prepare_submission( let (mut support_map, _) = build_support_map::(&winners, &staked); // equalize a random number of times. - let seed = sp_io::offchain::random_seed(); - let iterations = ::decode(&mut TrailingZeroInput::new(seed.as_ref())) - .expect("input is padded with zeroes; qed") % T::MaxIterations::get(); - let iterations_executed = equalize( - &mut staked, - &mut support_map, - Zero::zero(), - iterations as usize, - ); + let iterations_executed = match T::MaxIterations::get() { + 0 => { + // Don't run equalize at all + 0 + } + iterations @ _ => { + let seed = sp_io::offchain::random_seed(); + let iterations = ::decode(&mut TrailingZeroInput::new(seed.as_ref())) + .expect("input is padded with zeroes; qed") % iterations.saturating_add(1); + equalize( + &mut staked, + &mut support_map, + Zero::zero(), + iterations as usize, + ) + } + }; + // Convert back to ratio assignment. This takes less space. let low_accuracy_assignment = sp_phragmen::assignment_staked_to_ratio(staked); diff --git a/frame/staking/src/tests.rs b/frame/staking/src/tests.rs index 498240d4a45d0..487a3fc346188 100644 --- a/frame/staking/src/tests.rs +++ b/frame/staking/src/tests.rs @@ -2901,8 +2901,8 @@ mod offchain_phragmen { #[test] fn signed_result_can_be_submitted() { - // should check that we have a new validator set normally, - // event says that it comes from offchain. + // should check that we have a new validator set normally, event says that it comes from + // offchain. ExtBuilder::default() .offchain_phragmen_ext() .build() @@ -2989,8 +2989,8 @@ mod offchain_phragmen { #[test] fn early_solution_submission_is_rejected() { - // should check that we have a new validator set normally, - // event says that it comes from offchain. + // should check that we have a new validator set normally, event says that it comes from + // offchain. ExtBuilder::default() .offchain_phragmen_ext() .build() @@ -3119,7 +3119,7 @@ mod offchain_phragmen { &inner, ), TransactionValidity::Ok(ValidTransaction { - priority: UnsignedPriority::get() + 1250, // the proposed slot stake. + priority: UnsignedPriority::get() + 1125, // the proposed slot stake. requires: vec![], provides: vec![("StakingOffchain", current_era()).encode()], longevity: 3, @@ -3136,7 +3136,7 @@ mod offchain_phragmen { let mut ext = ExtBuilder::default() .offchain_phragmen_ext() .validator_count(2) - .offchain_iterations(2) + .max_offchain_iterations(2) .build(); let state = offchainify(&mut ext); ext.execute_with(|| { @@ -3162,7 +3162,8 @@ mod offchain_phragmen { &inner, ), TransactionValidity::Ok(ValidTransaction { - priority: UnsignedPriority::get() + 1250, // the proposed slot stake. + // the proposed slot stake, with equalize. + priority: UnsignedPriority::get() + 1250, requires: vec![], provides: vec![("StakingOffchain", active_era()).encode()], longevity: 3,