From c32f5ed2ae6746d6f791f08cecbfc22fa188f5f9 Mon Sep 17 00:00:00 2001 From: Liam Aharon Date: Thu, 6 Jul 2023 00:44:56 +1000 Subject: [PATCH 01/39] emit warn log on bad state (#14513) --- frame/nomination-pools/src/lib.rs | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/frame/nomination-pools/src/lib.rs b/frame/nomination-pools/src/lib.rs index fbee831a7217d..8518ca58bab5c 100644 --- a/frame/nomination-pools/src/lib.rs +++ b/frame/nomination-pools/src/lib.rs @@ -3135,16 +3135,18 @@ impl Pallet { RewardPools::::iter_keys().try_for_each(|id| -> Result<(), TryRuntimeError> { // the sum of the pending rewards must be less than the leftover balance. Since the // reward math rounds down, we might accumulate some dust here. - log!( - trace, - "pool {:?}, sum pending rewards = {:?}, remaining balance = {:?}", - id, - pools_members_pending_rewards.get(&id), - RewardPool::::current_balance(id) - ); + let pending_rewards_lt_leftover_bal = RewardPool::::current_balance(id) >= + pools_members_pending_rewards.get(&id).copied().unwrap_or_default(); + if !pending_rewards_lt_leftover_bal { + log::warn!( + "pool {:?}, sum pending rewards = {:?}, remaining balance = {:?}", + id, + pools_members_pending_rewards.get(&id), + RewardPool::::current_balance(id) + ); + } ensure!( - RewardPool::::current_balance(id) >= - pools_members_pending_rewards.get(&id).copied().unwrap_or_default(), + pending_rewards_lt_leftover_bal, "The sum of the pending rewards must be less than the leftover balance." ); Ok(()) From 69b6549da385a699fdfed83a7d8eb38ce4127767 Mon Sep 17 00:00:00 2001 From: Qinxuan Chen Date: Thu, 6 Jul 2023 22:46:44 +0800 Subject: [PATCH 02/39] chore: update some deps to prune duplicated deps (#14515) * chore: update some deps to prune duplicated deps - array-bytes: 4.1.0 => 6.1.0 - cid: 0.8.6 => 0.9.0 * fix --- Cargo.lock | 135 +++++++----------- bin/node/bench/Cargo.toml | 2 +- bin/node/cli/Cargo.toml | 2 +- client/cli/Cargo.toml | 2 +- client/cli/src/commands/generate_node_key.rs | 2 +- client/consensus/beefy/Cargo.toml | 2 +- .../consensus/beefy/src/communication/mod.rs | 2 +- client/consensus/grandpa/Cargo.toml | 2 +- .../grandpa/src/communication/tests.rs | 2 +- client/db/Cargo.toml | 2 +- client/executor/Cargo.toml | 2 +- client/keystore/Cargo.toml | 2 +- client/network/Cargo.toml | 2 +- client/network/bitswap/Cargo.toml | 2 +- client/network/light/Cargo.toml | 2 +- client/network/statement/Cargo.toml | 2 +- client/network/sync/Cargo.toml | 2 +- client/network/transactions/Cargo.toml | 2 +- client/offchain/Cargo.toml | 2 +- client/rpc-spec-v2/Cargo.toml | 2 +- client/service/test/Cargo.toml | 2 +- client/transaction-pool/Cargo.toml | 2 +- frame/alliance/Cargo.toml | 4 +- frame/beefy-mmr/Cargo.toml | 4 +- frame/beefy-mmr/src/tests.rs | 6 +- frame/benchmarking/Cargo.toml | 2 +- frame/contracts/Cargo.toml | 2 +- frame/contracts/src/exec.rs | 4 +- frame/contracts/src/wasm/mod.rs | 2 +- frame/executive/Cargo.toml | 2 +- frame/merkle-mountain-range/Cargo.toml | 2 +- frame/support/Cargo.toml | 2 +- frame/transaction-storage/Cargo.toml | 2 +- primitives/consensus/beefy/Cargo.toml | 2 +- primitives/core/Cargo.toml | 2 +- primitives/core/src/bls.rs | 2 +- primitives/core/src/ecdsa.rs | 4 +- primitives/core/src/ed25519.rs | 4 +- primitives/core/src/sr25519.rs | 2 +- primitives/merkle-mountain-range/Cargo.toml | 2 +- primitives/state-machine/Cargo.toml | 2 +- primitives/state-machine/src/testing.rs | 2 +- primitives/trie/Cargo.toml | 2 +- test-utils/client/Cargo.toml | 2 +- utils/binary-merkle-tree/Cargo.toml | 4 +- utils/binary-merkle-tree/src/lib.rs | 48 +++---- utils/frame/benchmarking-cli/Cargo.toml | 2 +- 47 files changed, 126 insertions(+), 163 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d7c5ac6f29e64..fe67e1bec2df0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -511,12 +511,6 @@ dependencies = [ "rand 0.8.5", ] -[[package]] -name = "array-bytes" -version = "4.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f52f63c5c1316a16a4b35eaac8b76a98248961a533f061684cb2a7cb0eafb6c6" - [[package]] name = "array-bytes" version = "6.1.0" @@ -822,7 +816,7 @@ dependencies = [ name = "binary-merkle-tree" version = "4.0.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "env_logger 0.9.3", "hash-db", "log", @@ -1234,13 +1228,13 @@ dependencies = [ [[package]] name = "cid" -version = "0.8.6" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6ed9c8b2d17acb8110c46f1da5bf4a696d745e1474a16db0cd2b49cd0249bf2" +checksum = "b9b68e3193982cd54187d71afdb2a271ad4cf8af157858e9cb911b91321de143" dependencies = [ "core2", "multibase", - "multihash 0.16.3", + "multihash", "serde", "unsigned-varint", ] @@ -2613,7 +2607,7 @@ checksum = "6c2141d6d6c8512188a7891b4b01590a45f6dac67afb4f255c4124dbb86d4eaa" name = "frame-benchmarking" version = "4.0.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "frame-support", "frame-support-procedural", "frame-system", @@ -2641,7 +2635,7 @@ name = "frame-benchmarking-cli" version = "4.0.0-dev" dependencies = [ "Inflector", - "array-bytes 4.2.0", + "array-bytes", "chrono", "clap 4.3.2", "comfy-table", @@ -2752,7 +2746,7 @@ dependencies = [ name = "frame-executive" version = "4.0.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "frame-support", "frame-system", "frame-try-runtime", @@ -2808,7 +2802,7 @@ dependencies = [ name = "frame-support" version = "4.0.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "assert_matches", "bitflags", "environmental", @@ -4298,7 +4292,7 @@ dependencies = [ "libp2p-identity", "log", "multiaddr", - "multihash 0.17.0", + "multihash", "multistream-select", "once_cell", "parking_lot 0.12.1", @@ -4358,7 +4352,7 @@ dependencies = [ "ed25519-dalek", "log", "multiaddr", - "multihash 0.17.0", + "multihash", "quick-protobuf", "rand 0.8.5", "sha2 0.10.6", @@ -4605,7 +4599,7 @@ dependencies = [ "libp2p-identity", "libp2p-noise", "log", - "multihash 0.17.0", + "multihash", "quick-protobuf", "quick-protobuf-codec", "rand 0.8.5", @@ -5137,7 +5131,7 @@ dependencies = [ "data-encoding", "log", "multibase", - "multihash 0.17.0", + "multihash", "percent-encoding", "serde", "static_assertions", @@ -5158,9 +5152,9 @@ dependencies = [ [[package]] name = "multihash" -version = "0.16.3" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c346cf9999c631f002d8f977c4eaeaa0e6386f16007202308d0b3757522c2cc" +checksum = "835d6ff01d610179fbce3de1694d007e500bf33a7f29689838941d6bf783ae40" dependencies = [ "blake2b_simd", "blake2s_simd", @@ -5173,19 +5167,6 @@ dependencies = [ "unsigned-varint", ] -[[package]] -name = "multihash" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "835d6ff01d610179fbce3de1694d007e500bf33a7f29689838941d6bf783ae40" -dependencies = [ - "core2", - "digest 0.10.7", - "multihash-derive", - "sha2 0.10.6", - "unsigned-varint", -] - [[package]] name = "multihash-derive" version = "0.8.1" @@ -5352,7 +5333,7 @@ dependencies = [ name = "node-bench" version = "0.9.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "clap 4.3.2", "derive_more", "fs_extra", @@ -5388,7 +5369,7 @@ dependencies = [ name = "node-cli" version = "3.0.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "assert_cmd", "clap 4.3.2", "clap_complete", @@ -5954,7 +5935,7 @@ dependencies = [ name = "pallet-alliance" version = "4.0.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "frame-benchmarking", "frame-support", "frame-system", @@ -6251,7 +6232,7 @@ dependencies = [ name = "pallet-beefy-mmr" version = "4.0.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "binary-merkle-tree", "frame-support", "frame-system", @@ -6328,7 +6309,7 @@ dependencies = [ name = "pallet-contracts" version = "4.0.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "assert_matches", "bitflags", "env_logger 0.9.3", @@ -6831,7 +6812,7 @@ dependencies = [ name = "pallet-mmr" version = "4.0.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "env_logger 0.9.3", "frame-benchmarking", "frame-support", @@ -7563,7 +7544,7 @@ dependencies = [ name = "pallet-transaction-storage" version = "4.0.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "frame-benchmarking", "frame-support", "frame-system", @@ -8956,7 +8937,7 @@ dependencies = [ "ip_network", "libp2p", "log", - "multihash 0.17.0", + "multihash", "parity-scale-codec", "prost", "prost-build", @@ -9049,7 +9030,7 @@ dependencies = [ name = "sc-cli" version = "0.10.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "chrono", "clap 4.3.2", "fdlimit", @@ -9119,7 +9100,7 @@ dependencies = [ name = "sc-client-db" version = "0.10.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "criterion", "hash-db", "kitchensink-runtime", @@ -9285,7 +9266,7 @@ dependencies = [ name = "sc-consensus-beefy" version = "4.0.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "async-channel", "async-trait", "fnv", @@ -9361,7 +9342,7 @@ name = "sc-consensus-grandpa" version = "0.10.0-dev" dependencies = [ "ahash 0.8.3", - "array-bytes 4.2.0", + "array-bytes", "assert_matches", "async-trait", "dyn-clone", @@ -9515,7 +9496,7 @@ dependencies = [ name = "sc-executor" version = "0.10.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "assert_matches", "criterion", "env_logger 0.9.3", @@ -9602,7 +9583,7 @@ dependencies = [ name = "sc-keystore" version = "4.0.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "parking_lot 0.12.1", "serde_json", "sp-application-crypto", @@ -9616,7 +9597,7 @@ dependencies = [ name = "sc-network" version = "0.10.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "assert_matches", "async-channel", "async-trait", @@ -9731,7 +9712,7 @@ dependencies = [ name = "sc-network-light" version = "0.10.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "async-channel", "futures", "libp2p-identity", @@ -9751,7 +9732,7 @@ dependencies = [ name = "sc-network-statement" version = "0.10.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "async-channel", "futures", "libp2p", @@ -9768,7 +9749,7 @@ dependencies = [ name = "sc-network-sync" version = "0.10.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "async-channel", "async-trait", "fork-tree", @@ -9837,7 +9818,7 @@ dependencies = [ name = "sc-network-transactions" version = "0.10.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "futures", "libp2p", "log", @@ -9854,7 +9835,7 @@ dependencies = [ name = "sc-offchain" version = "4.0.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "bytes", "fnv", "futures", @@ -9969,7 +9950,7 @@ dependencies = [ name = "sc-rpc-spec-v2" version = "0.10.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "assert_matches", "futures", "futures-util", @@ -10082,7 +10063,7 @@ dependencies = [ name = "sc-service-test" version = "2.0.0" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "async-channel", "fdlimit", "futures", @@ -10254,7 +10235,7 @@ dependencies = [ name = "sc-transaction-pool" version = "4.0.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "assert_matches", "async-trait", "criterion", @@ -10342,11 +10323,11 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.21" +version = "0.1.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "713cfb06c7059f3588fb8044c0fad1d09e3c01d225e25b9220dbfdcf16dbb1b3" +checksum = "0c3733bf4cf7ea0880754e19cb5a462007c4a8c1914bff372ccc95b464f1df88" dependencies = [ - "windows-sys 0.42.0", + "windows-sys 0.48.0", ] [[package]] @@ -11071,7 +11052,7 @@ dependencies = [ name = "sp-consensus-beefy" version = "4.0.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "lazy_static", "parity-scale-codec", "scale-info", @@ -11130,7 +11111,7 @@ dependencies = [ name = "sp-core" version = "21.0.0" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "bitflags", "blake2", "bounded-collections", @@ -11342,7 +11323,7 @@ dependencies = [ name = "sp-mmr-primitives" version = "4.0.0-dev" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "ckb-merkle-mountain-range", "log", "parity-scale-codec", @@ -11538,7 +11519,7 @@ dependencies = [ name = "sp-state-machine" version = "0.28.0" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "assert_matches", "hash-db", "log", @@ -11653,7 +11634,7 @@ name = "sp-trie" version = "22.0.0" dependencies = [ "ahash 0.8.3", - "array-bytes 4.2.0", + "array-bytes", "criterion", "hash-db", "hashbrown 0.13.2", @@ -12010,7 +11991,7 @@ dependencies = [ name = "substrate-test-client" version = "2.0.1" dependencies = [ - "array-bytes 4.2.0", + "array-bytes", "async-trait", "futures", "parity-scale-codec", @@ -12035,7 +12016,7 @@ dependencies = [ name = "substrate-test-runtime" version = "2.0.0" dependencies = [ - "array-bytes 6.1.0", + "array-bytes", "frame-executive", "frame-support", "frame-system", @@ -12250,15 +12231,16 @@ checksum = "fd1ba337640d60c3e96bc6f0638a939b9c9a7f2c316a1598c279828b3d1dc8c5" [[package]] name = "tempfile" -version = "3.5.0" +version = "3.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9fbec84f381d5795b08656e4912bec604d162bff9291d6189a78f4c8ab87998" +checksum = "31c0432476357e58790aaa47a8efb0c5138f137343f3b5f23bd36a27e3b0a6d6" dependencies = [ + "autocfg", "cfg-if", "fastrand", "redox_syscall 0.3.5", "rustix 0.37.19", - "windows-sys 0.45.0", + "windows-sys 0.48.0", ] [[package]] @@ -13888,21 +13870,6 @@ dependencies = [ "windows-targets 0.48.0", ] -[[package]] -name = "windows-sys" -version = "0.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - [[package]] name = "windows-sys" version = "0.45.0" diff --git a/bin/node/bench/Cargo.toml b/bin/node/bench/Cargo.toml index 22f5b88420ef8..7703f8ed2e4e0 100644 --- a/bin/node/bench/Cargo.toml +++ b/bin/node/bench/Cargo.toml @@ -12,7 +12,7 @@ publish = false # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -array-bytes = "4.1" +array-bytes = "6.1" clap = { version = "4.2.5", features = ["derive"] } log = "0.4.17" node-primitives = { version = "2.0.0", path = "../primitives" } diff --git a/bin/node/cli/Cargo.toml b/bin/node/cli/Cargo.toml index d6566dec8a783..d9b3ebee995d8 100644 --- a/bin/node/cli/Cargo.toml +++ b/bin/node/cli/Cargo.toml @@ -35,7 +35,7 @@ crate-type = ["cdylib", "rlib"] [dependencies] # third-party dependencies -array-bytes = "4.1" +array-bytes = "6.1" clap = { version = "4.2.5", features = ["derive"], optional = true } codec = { package = "parity-scale-codec", version = "3.6.1" } serde = { version = "1.0.163", features = ["derive"] } diff --git a/client/cli/Cargo.toml b/client/cli/Cargo.toml index 562720f31b68f..61750766fa3f8 100644 --- a/client/cli/Cargo.toml +++ b/client/cli/Cargo.toml @@ -13,7 +13,7 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = "4.1" +array-bytes = "6.1" chrono = "0.4.10" clap = { version = "4.2.5", features = ["derive", "string"] } fdlimit = "0.2.1" diff --git a/client/cli/src/commands/generate_node_key.rs b/client/cli/src/commands/generate_node_key.rs index c3579f7dc826e..43851dc1af5cc 100644 --- a/client/cli/src/commands/generate_node_key.rs +++ b/client/cli/src/commands/generate_node_key.rs @@ -55,7 +55,7 @@ impl GenerateNodeKeyCmd { let file_data = if self.bin { secret.as_ref().to_owned() } else { - array_bytes::bytes2hex("", secret.as_ref()).into_bytes() + array_bytes::bytes2hex("", secret).into_bytes() }; match &self.file { diff --git a/client/consensus/beefy/Cargo.toml b/client/consensus/beefy/Cargo.toml index b4963684d4e09..aec605c6bf11b 100644 --- a/client/consensus/beefy/Cargo.toml +++ b/client/consensus/beefy/Cargo.toml @@ -9,7 +9,7 @@ description = "BEEFY Client gadget for substrate" homepage = "https://substrate.io" [dependencies] -array-bytes = "4.1" +array-bytes = "6.1" async-channel = "1.8.0" async-trait = "0.1.57" codec = { package = "parity-scale-codec", version = "3.6.1", features = ["derive"] } diff --git a/client/consensus/beefy/src/communication/mod.rs b/client/consensus/beefy/src/communication/mod.rs index 0de67f6062339..7f9535bfc23f1 100644 --- a/client/consensus/beefy/src/communication/mod.rs +++ b/client/consensus/beefy/src/communication/mod.rs @@ -117,7 +117,7 @@ mod tests { use beefy_protocol_name::{gossip_protocol_name, justifications_protocol_name}; // Create protocol name using random genesis hash. let genesis_hash = H256::random(); - let genesis_hex = array_bytes::bytes2hex("", genesis_hash.as_ref()); + let genesis_hex = array_bytes::bytes2hex("", genesis_hash); let expected_gossip_name = format!("/{}/beefy/2", genesis_hex); let gossip_proto_name = gossip_protocol_name(&genesis_hash, None); diff --git a/client/consensus/grandpa/Cargo.toml b/client/consensus/grandpa/Cargo.toml index ad4ff9db3363c..13b472dc70322 100644 --- a/client/consensus/grandpa/Cargo.toml +++ b/client/consensus/grandpa/Cargo.toml @@ -15,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] ahash = "0.8.2" -array-bytes = "4.1" +array-bytes = "6.1" async-trait = "0.1.57" dyn-clone = "1.0" finality-grandpa = { version = "0.16.2", features = ["derive-codec"] } diff --git a/client/consensus/grandpa/src/communication/tests.rs b/client/consensus/grandpa/src/communication/tests.rs index eb88382989175..eee9fddcea2d3 100644 --- a/client/consensus/grandpa/src/communication/tests.rs +++ b/client/consensus/grandpa/src/communication/tests.rs @@ -669,7 +669,7 @@ fn grandpa_protocol_name() { // Create protocol name using random genesis hash. let genesis_hash = sp_core::H256::random(); - let expected = format!("/{}/grandpa/1", array_bytes::bytes2hex("", genesis_hash.as_ref())); + let expected = format!("/{}/grandpa/1", array_bytes::bytes2hex("", genesis_hash)); let proto_name = grandpa_protocol_name::standard_name(&genesis_hash, &chain_spec); assert_eq!(proto_name.to_string(), expected); diff --git a/client/db/Cargo.toml b/client/db/Cargo.toml index 0b421e6c67ae5..a038cf802a7ac 100644 --- a/client/db/Cargo.toml +++ b/client/db/Cargo.toml @@ -44,7 +44,7 @@ quickcheck = { version = "1.0.3", default-features = false } kitchensink-runtime = { path = "../../bin/node/runtime" } sp-tracing = { version = "10.0.0", path = "../../primitives/tracing" } substrate-test-runtime-client = { version = "2.0.0", path = "../../test-utils/runtime/client" } -array-bytes = "4.1" +array-bytes = "6.1" [features] default = [] diff --git a/client/executor/Cargo.toml b/client/executor/Cargo.toml index a3450fbb2a1c5..790dd5a9846a2 100644 --- a/client/executor/Cargo.toml +++ b/client/executor/Cargo.toml @@ -32,7 +32,7 @@ sp-version = { version = "22.0.0", path = "../../primitives/version" } sp-wasm-interface = { version = "14.0.0", path = "../../primitives/wasm-interface" } [dev-dependencies] -array-bytes = "4.1" +array-bytes = "6.1" assert_matches = "1.3.0" wat = "1.0" sc-runtime-test = { version = "2.0.0", path = "runtime-test" } diff --git a/client/keystore/Cargo.toml b/client/keystore/Cargo.toml index aa1527a4f67eb..0ecdb896199cb 100644 --- a/client/keystore/Cargo.toml +++ b/client/keystore/Cargo.toml @@ -14,7 +14,7 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = "4.1" +array-bytes = "6.1" parking_lot = "0.12.1" serde_json = "1.0.85" thiserror = "1.0" diff --git a/client/network/Cargo.toml b/client/network/Cargo.toml index 5d20570fdbbe9..786aa68d808a5 100644 --- a/client/network/Cargo.toml +++ b/client/network/Cargo.toml @@ -14,7 +14,7 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = "4.1" +array-bytes = "6.1" async-channel = "1.8.0" async-trait = "0.1" asynchronous-codec = "0.6" diff --git a/client/network/bitswap/Cargo.toml b/client/network/bitswap/Cargo.toml index 4a3a03f0ab4d5..bdc9e18f7457d 100644 --- a/client/network/bitswap/Cargo.toml +++ b/client/network/bitswap/Cargo.toml @@ -17,7 +17,7 @@ prost-build = "0.11" [dependencies] async-channel = "1.8.0" -cid = "0.8.6" +cid = "0.9.0" futures = "0.3.21" libp2p-identity = { version = "0.1.2", features = ["peerid"] } log = "0.4.17" diff --git a/client/network/light/Cargo.toml b/client/network/light/Cargo.toml index 1851819f9c3b3..8bdb640d5558b 100644 --- a/client/network/light/Cargo.toml +++ b/client/network/light/Cargo.toml @@ -17,7 +17,7 @@ prost-build = "0.11" [dependencies] async-channel = "1.8.0" -array-bytes = "4.1" +array-bytes = "6.1" codec = { package = "parity-scale-codec", version = "3.6.1", features = [ "derive", ] } diff --git a/client/network/statement/Cargo.toml b/client/network/statement/Cargo.toml index 42bfd57463ce7..63377710dc403 100644 --- a/client/network/statement/Cargo.toml +++ b/client/network/statement/Cargo.toml @@ -13,7 +13,7 @@ documentation = "https://docs.rs/sc-network-statement" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = "4.1" +array-bytes = "6.1" async-channel = "1.8.0" codec = { package = "parity-scale-codec", version = "3.6.1", features = ["derive"] } futures = "0.3.21" diff --git a/client/network/sync/Cargo.toml b/client/network/sync/Cargo.toml index a6ff1561bd7f8..5afc92265e26f 100644 --- a/client/network/sync/Cargo.toml +++ b/client/network/sync/Cargo.toml @@ -16,7 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"] prost-build = "0.11" [dependencies] -array-bytes = "4.1" +array-bytes = "6.1" async-channel = "1.8.0" async-trait = "0.1.58" codec = { package = "parity-scale-codec", version = "3.6.1", features = ["derive"] } diff --git a/client/network/transactions/Cargo.toml b/client/network/transactions/Cargo.toml index e568105fa0c4d..ce62c89e8a55a 100644 --- a/client/network/transactions/Cargo.toml +++ b/client/network/transactions/Cargo.toml @@ -13,7 +13,7 @@ documentation = "https://docs.rs/sc-network-transactions" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = "4.1" +array-bytes = "6.1" codec = { package = "parity-scale-codec", version = "3.6.1", features = ["derive"] } futures = "0.3.21" libp2p = "0.51.3" diff --git a/client/offchain/Cargo.toml b/client/offchain/Cargo.toml index 3b17fedfb7f14..42504ec590c70 100644 --- a/client/offchain/Cargo.toml +++ b/client/offchain/Cargo.toml @@ -13,7 +13,7 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = "4.1" +array-bytes = "6.1" bytes = "1.1" codec = { package = "parity-scale-codec", version = "3.6.1", features = ["derive"] } fnv = "1.0.6" diff --git a/client/rpc-spec-v2/Cargo.toml b/client/rpc-spec-v2/Cargo.toml index 59abeefcf26ec..c691b7b05fcb4 100644 --- a/client/rpc-spec-v2/Cargo.toml +++ b/client/rpc-spec-v2/Cargo.toml @@ -31,7 +31,7 @@ hex = "0.4" futures = "0.3.21" parking_lot = "0.12.1" tokio-stream = { version = "0.1", features = ["sync"] } -array-bytes = "4.1" +array-bytes = "6.1" log = "0.4.17" futures-util = { version = "0.3.19", default-features = false } diff --git a/client/service/test/Cargo.toml b/client/service/test/Cargo.toml index 151a6589c5949..dea7bfaa5b7d8 100644 --- a/client/service/test/Cargo.toml +++ b/client/service/test/Cargo.toml @@ -13,7 +13,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] async-channel = "1.8.0" -array-bytes = "4.1" +array-bytes = "6.1" fdlimit = "0.2.1" futures = "0.3.21" log = "0.4.17" diff --git a/client/transaction-pool/Cargo.toml b/client/transaction-pool/Cargo.toml index 6f02b1cbad243..1718751e6d83c 100644 --- a/client/transaction-pool/Cargo.toml +++ b/client/transaction-pool/Cargo.toml @@ -34,7 +34,7 @@ sp-tracing = { version = "10.0.0", path = "../../primitives/tracing" } sp-transaction-pool = { version = "4.0.0-dev", path = "../../primitives/transaction-pool" } [dev-dependencies] -array-bytes = "4.1" +array-bytes = "6.1" assert_matches = "1.3.0" criterion = "0.4.0" sc-block-builder = { version = "0.10.0-dev", path = "../block-builder" } diff --git a/frame/alliance/Cargo.toml b/frame/alliance/Cargo.toml index 6913aa711cb35..b411df760f616 100644 --- a/frame/alliance/Cargo.toml +++ b/frame/alliance/Cargo.toml @@ -13,7 +13,7 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = { version = "4.1", optional = true } +array-bytes = { version = "6.1", optional = true } log = { version = "0.4.14", default-features = false } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } @@ -33,7 +33,7 @@ pallet-identity = { version = "4.0.0-dev", path = "../identity", default-feature pallet-collective = { version = "4.0.0-dev", path = "../collective", default-features = false, optional = true } [dev-dependencies] -array-bytes = "4.1" +array-bytes = "6.1" sp-core-hashing = { version = "9.0.0", default-features = false, path = "../../primitives/core/hashing" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } pallet-collective = { version = "4.0.0-dev", path = "../collective" } diff --git a/frame/beefy-mmr/Cargo.toml b/frame/beefy-mmr/Cargo.toml index 0eb0cdd995dfe..fb6846efc21e3 100644 --- a/frame/beefy-mmr/Cargo.toml +++ b/frame/beefy-mmr/Cargo.toml @@ -9,7 +9,7 @@ repository = "https://github.com/paritytech/substrate" homepage = "https://substrate.io" [dependencies] -array-bytes = { version = "4.1", optional = true } +array-bytes = { version = "6.1", optional = true } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.5.0", default-features = false, features = ["derive"] } @@ -28,7 +28,7 @@ sp-std = { version = "8.0.0", default-features = false, path = "../../primitives sp-api = { version = "4.0.0-dev", default-features = false, path = "../../primitives/api" } [dev-dependencies] -array-bytes = "4.1" +array-bytes = "6.1" sp-staking = { version = "4.0.0-dev", path = "../../primitives/staking" } [features] diff --git a/frame/beefy-mmr/src/tests.rs b/frame/beefy-mmr/src/tests.rs index d7e0ddd98cde0..067c3851ba839 100644 --- a/frame/beefy-mmr/src/tests.rs +++ b/frame/beefy-mmr/src/tests.rs @@ -164,7 +164,7 @@ fn should_update_authorities() { // check current authority set assert_eq!(0, auth_set.id); assert_eq!(2, auth_set.len); - let want = array_bytes::hex_n_into_unchecked::( + let want = array_bytes::hex_n_into_unchecked::<_, H256, 32>( "176e73f1bf656478b728e28dd1a7733c98621b8acf830bff585949763dca7a96", ); assert_eq!(want, auth_set.root); @@ -184,7 +184,7 @@ fn should_update_authorities() { assert_eq!(1, auth_set.id); // check next auth set assert_eq!(2, next_auth_set.id); - let want = array_bytes::hex_n_into_unchecked::( + let want = array_bytes::hex_n_into_unchecked::<_, H256, 32>( "9c6b2c1b0d0b25a008e6c882cc7b415f309965c72ad2b944ac0931048ca31cd5", ); assert_eq!(2, next_auth_set.len); @@ -200,7 +200,7 @@ fn should_update_authorities() { assert_eq!(2, auth_set.id); // check next auth set assert_eq!(3, next_auth_set.id); - let want = array_bytes::hex_n_into_unchecked::( + let want = array_bytes::hex_n_into_unchecked::<_, H256, 32>( "9c6b2c1b0d0b25a008e6c882cc7b415f309965c72ad2b944ac0931048ca31cd5", ); assert_eq!(2, next_auth_set.len); diff --git a/frame/benchmarking/Cargo.toml b/frame/benchmarking/Cargo.toml index 33010f86cf60a..9bf7613e6d274 100644 --- a/frame/benchmarking/Cargo.toml +++ b/frame/benchmarking/Cargo.toml @@ -33,7 +33,7 @@ sp-storage = { version = "13.0.0", default-features = false, path = "../../primi static_assertions = "1.1.0" [dev-dependencies] -array-bytes = "4.1" +array-bytes = "6.1" rusty-fork = { version = "0.3.0", default-features = false } sp-keystore = { version = "0.27.0", path = "../../primitives/keystore" } diff --git a/frame/contracts/Cargo.toml b/frame/contracts/Cargo.toml index 3d88c3831375b..f23e44741a6cb 100644 --- a/frame/contracts/Cargo.toml +++ b/frame/contracts/Cargo.toml @@ -47,7 +47,7 @@ sp-runtime = { version = "24.0.0", default-features = false, path = "../../primi sp-std = { version = "8.0.0", default-features = false, path = "../../primitives/std" } [dev-dependencies] -array-bytes = "4.1" +array-bytes = "6.1" assert_matches = "1" env_logger = "0.9" pretty_assertions = "1" diff --git a/frame/contracts/src/exec.rs b/frame/contracts/src/exec.rs index 2bf3f44717c27..2c38f68b3ce08 100644 --- a/frame/contracts/src/exec.rs +++ b/frame/contracts/src/exec.rs @@ -3608,7 +3608,9 @@ mod tests { ); assert_eq!( ctx.ext.ecdsa_to_eth_address(&pubkey_compressed).unwrap(), - array_bytes::hex2array_unchecked::<20>("09231da7b19A016f9e576d23B16277062F4d46A8") + array_bytes::hex2array_unchecked::<_, 20>( + "09231da7b19A016f9e576d23B16277062F4d46A8" + ) ); exec_success() }); diff --git a/frame/contracts/src/wasm/mod.rs b/frame/contracts/src/wasm/mod.rs index 04f1ecfb5a6f3..01075b2a4c9d9 100644 --- a/frame/contracts/src/wasm/mod.rs +++ b/frame/contracts/src/wasm/mod.rs @@ -2180,7 +2180,7 @@ mod tests { ExecReturnValue { flags: ReturnFlags::empty(), data: ( - array_bytes::hex2array_unchecked::<32>( + array_bytes::hex2array_unchecked::<_, 32>( "000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F" ), 42u64, diff --git a/frame/executive/Cargo.toml b/frame/executive/Cargo.toml index bb8eb4f4a2c71..6c76513581290 100644 --- a/frame/executive/Cargo.toml +++ b/frame/executive/Cargo.toml @@ -27,7 +27,7 @@ sp-std = { version = "8.0.0", default-features = false, path = "../../primitives sp-tracing = { version = "10.0.0", default-features = false, path = "../../primitives/tracing" } [dev-dependencies] -array-bytes = "4.1" +array-bytes = "6.1" pallet-balances = { version = "4.0.0-dev", path = "../balances" } pallet-transaction-payment = { version = "4.0.0-dev", path = "../transaction-payment" } sp-core = { version = "21.0.0", path = "../../primitives/core" } diff --git a/frame/merkle-mountain-range/Cargo.toml b/frame/merkle-mountain-range/Cargo.toml index afc309b0868c1..83bb7405f3d93 100644 --- a/frame/merkle-mountain-range/Cargo.toml +++ b/frame/merkle-mountain-range/Cargo.toml @@ -24,7 +24,7 @@ sp-runtime = { version = "24.0.0", default-features = false, path = "../../primi sp-std = { version = "8.0.0", default-features = false, path = "../../primitives/std" } [dev-dependencies] -array-bytes = "4.1" +array-bytes = "6.1" env_logger = "0.9" itertools = "0.10.3" diff --git a/frame/support/Cargo.toml b/frame/support/Cargo.toml index 619ccfbb248e0..bfcb821b8c8e4 100644 --- a/frame/support/Cargo.toml +++ b/frame/support/Cargo.toml @@ -46,7 +46,7 @@ serde_json = "1.0.85" assert_matches = "1.3.0" pretty_assertions = "1.2.1" frame-system = { version = "4.0.0-dev", path = "../system" } -array-bytes = "4.1" +array-bytes = "6.1" [features] default = ["std"] diff --git a/frame/transaction-storage/Cargo.toml b/frame/transaction-storage/Cargo.toml index 07addfe7141b3..0d258a3d83bd8 100644 --- a/frame/transaction-storage/Cargo.toml +++ b/frame/transaction-storage/Cargo.toml @@ -13,7 +13,7 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = { version = "4.1", optional = true } +array-bytes = { version = "6.1", optional = true } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } scale-info = { version = "2.5.0", default-features = false, features = ["derive"] } serde = { version = "1.0.163", optional = true } diff --git a/primitives/consensus/beefy/Cargo.toml b/primitives/consensus/beefy/Cargo.toml index 4bffe1fcd4d96..3673397b877ec 100644 --- a/primitives/consensus/beefy/Cargo.toml +++ b/primitives/consensus/beefy/Cargo.toml @@ -26,7 +26,7 @@ strum = { version = "0.24.1", features = ["derive"], default-features = false } lazy_static = "1.4.0" [dev-dependencies] -array-bytes = "4.1" +array-bytes = "6.1" sp-keystore = { version = "0.27.0", path = "../../keystore" } [features] diff --git a/primitives/core/Cargo.toml b/primitives/core/Cargo.toml index 92933fdbd9aff..65c252a523114 100644 --- a/primitives/core/Cargo.toml +++ b/primitives/core/Cargo.toml @@ -43,7 +43,7 @@ bitflags = "1.3" paste = "1.0.7" # full crypto -array-bytes = { version = "4.1", optional = true } +array-bytes = { version = "6.1", optional = true } ed25519-zebra = { version = "3.1.0", default-features = false, optional = true } blake2 = { version = "0.10.4", default-features = false, optional = true } libsecp256k1 = { version = "0.7", default-features = false, features = ["static-context"], optional = true } diff --git a/primitives/core/src/bls.rs b/primitives/core/src/bls.rs index 86db4525fb8ae..770f7d65cea05 100644 --- a/primitives/core/src/bls.rs +++ b/primitives/core/src/bls.rs @@ -332,7 +332,7 @@ impl Serialize for Signature { where S: Serializer, { - serializer.serialize_str(&array_bytes::bytes2hex("", self.as_ref())) + serializer.serialize_str(&array_bytes::bytes2hex("", self)) } } diff --git a/primitives/core/src/ecdsa.rs b/primitives/core/src/ecdsa.rs index 872447122bbb8..143482e94cd12 100644 --- a/primitives/core/src/ecdsa.rs +++ b/primitives/core/src/ecdsa.rs @@ -220,7 +220,7 @@ impl Serialize for Signature { where S: Serializer, { - serializer.serialize_str(&array_bytes::bytes2hex("", self.as_ref())) + serializer.serialize_str(&array_bytes::bytes2hex("", self)) } } @@ -552,7 +552,7 @@ mod test { let derived = pair.derive(path.into_iter(), None).ok().unwrap(); assert_eq!( derived.0.seed(), - array_bytes::hex2array_unchecked::<32>( + array_bytes::hex2array_unchecked::<_, 32>( "b8eefc4937200a8382d00050e050ced2d4ab72cc2ef1b061477afb51564fdd61" ) ); diff --git a/primitives/core/src/ed25519.rs b/primitives/core/src/ed25519.rs index ba947990e1c0b..9d948a5bcea66 100644 --- a/primitives/core/src/ed25519.rs +++ b/primitives/core/src/ed25519.rs @@ -234,7 +234,7 @@ impl Serialize for Signature { where S: Serializer, { - serializer.serialize_str(&array_bytes::bytes2hex("", self.as_ref())) + serializer.serialize_str(&array_bytes::bytes2hex("", self)) } } @@ -499,7 +499,7 @@ mod test { let derived = pair.derive(path.into_iter(), None).ok().unwrap().0; assert_eq!( derived.seed(), - array_bytes::hex2array_unchecked::<32>( + array_bytes::hex2array_unchecked::<_, 32>( "ede3354e133f9c8e337ddd6ee5415ed4b4ffe5fc7d21e933f4930a3730e5b21c" ) ); diff --git a/primitives/core/src/sr25519.rs b/primitives/core/src/sr25519.rs index 963ca1c3fedc3..1c040f6ccf7be 100644 --- a/primitives/core/src/sr25519.rs +++ b/primitives/core/src/sr25519.rs @@ -240,7 +240,7 @@ impl Serialize for Signature { where S: Serializer, { - serializer.serialize_str(&array_bytes::bytes2hex("", self.as_ref())) + serializer.serialize_str(&array_bytes::bytes2hex("", self)) } } diff --git a/primitives/merkle-mountain-range/Cargo.toml b/primitives/merkle-mountain-range/Cargo.toml index 21a5f78f5c3de..9ede77ba40be2 100644 --- a/primitives/merkle-mountain-range/Cargo.toml +++ b/primitives/merkle-mountain-range/Cargo.toml @@ -25,7 +25,7 @@ sp-std = { version = "8.0.0", default-features = false, path = "../std" } thiserror = "1.0" [dev-dependencies] -array-bytes = "4.1" +array-bytes = "6.1" [features] default = ["std"] diff --git a/primitives/state-machine/Cargo.toml b/primitives/state-machine/Cargo.toml index 4bdd665b2984d..cffa4236c2a2f 100644 --- a/primitives/state-machine/Cargo.toml +++ b/primitives/state-machine/Cargo.toml @@ -30,7 +30,7 @@ sp-trie = { version = "22.0.0", default-features = false, path = "../trie" } trie-db = { version = "0.27.1", default-features = false } [dev-dependencies] -array-bytes = "4.1" +array-bytes = "6.1" pretty_assertions = "1.2.1" rand = "0.8.5" sp-runtime = { version = "24.0.0", path = "../runtime" } diff --git a/primitives/state-machine/src/testing.rs b/primitives/state-machine/src/testing.rs index eefd6b1fbde93..78e956952f723 100644 --- a/primitives/state-machine/src/testing.rs +++ b/primitives/state-machine/src/testing.rs @@ -391,7 +391,7 @@ mod tests { ext.set_storage(b"doe".to_vec(), b"reindeer".to_vec()); ext.set_storage(b"dog".to_vec(), b"puppy".to_vec()); ext.set_storage(b"dogglesworth".to_vec(), b"cat".to_vec()); - let root = array_bytes::hex_n_into_unchecked::( + let root = array_bytes::hex_n_into_unchecked::<_, H256, 32>( "ed4d8c799d996add422395a6abd7545491d40bd838d738afafa1b8a4de625489", ); assert_eq!(H256::from_slice(ext.storage_root(Default::default()).as_slice()), root); diff --git a/primitives/trie/Cargo.toml b/primitives/trie/Cargo.toml index a56a17bcdbe89..e0f170052c9e7 100644 --- a/primitives/trie/Cargo.toml +++ b/primitives/trie/Cargo.toml @@ -36,7 +36,7 @@ sp-std = { version = "8.0.0", default-features = false, path = "../std" } schnellru = { version = "0.2.1", optional = true } [dev-dependencies] -array-bytes = "4.1" +array-bytes = "6.1" criterion = "0.4.0" trie-bench = "0.37.0" trie-standardmap = "0.16.0" diff --git a/test-utils/client/Cargo.toml b/test-utils/client/Cargo.toml index d813f8e465469..d921a879fba2e 100644 --- a/test-utils/client/Cargo.toml +++ b/test-utils/client/Cargo.toml @@ -13,7 +13,7 @@ publish = false targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = "4.1" +array-bytes = "6.1" async-trait = "0.1.57" codec = { package = "parity-scale-codec", version = "3.6.1" } futures = "0.3.21" diff --git a/utils/binary-merkle-tree/Cargo.toml b/utils/binary-merkle-tree/Cargo.toml index 831c1d6a31f87..596c39401802e 100644 --- a/utils/binary-merkle-tree/Cargo.toml +++ b/utils/binary-merkle-tree/Cargo.toml @@ -9,12 +9,12 @@ description = "A no-std/Substrate compatible library to construct binary merkle homepage = "https://substrate.io" [dependencies] -array-bytes = { version = "4.1", optional = true } +array-bytes = { version = "6.1", optional = true } log = { version = "0.4", default-features = false, optional = true } hash-db = { version = "0.16.0", default-features = false } [dev-dependencies] -array-bytes = "4.1" +array-bytes = "6.1" env_logger = "0.9" sp-core = { version = "21.0.0", path = "../../primitives/core" } sp-runtime = { version = "24.0.0", path = "../../primitives/runtime" } diff --git a/utils/binary-merkle-tree/src/lib.rs b/utils/binary-merkle-tree/src/lib.rs index ab532fd0b192e..0efab9186c25f 100644 --- a/utils/binary-merkle-tree/src/lib.rs +++ b/utils/binary-merkle-tree/src/lib.rs @@ -202,7 +202,7 @@ where collect_proof .proof .iter() - .map(|s| array_bytes::bytes2hex("", s.as_ref())) + .map(|s| array_bytes::bytes2hex("", s)) .collect::>() ); @@ -272,10 +272,10 @@ where #[cfg(feature = "debug")] log::debug!( "[verify_proof]: (a, b) {:?}, {:?} => {:?} ({:?}) hash", - array_bytes::bytes2hex("", &a.as_ref()), - array_bytes::bytes2hex("", &b.as_ref()), - array_bytes::bytes2hex("", &hash.as_ref()), - array_bytes::bytes2hex("", &combined.as_ref()) + array_bytes::bytes2hex("", a), + array_bytes::bytes2hex("", b), + array_bytes::bytes2hex("", hash), + array_bytes::bytes2hex("", &combined) ); position /= 2; width = ((width - 1) / 2) + 1; @@ -316,8 +316,8 @@ where #[cfg(feature = "debug")] log::debug!( " {:?}\n {:?}", - a.as_ref().map(|s| array_bytes::bytes2hex("", s.as_ref())), - b.as_ref().map(|s| array_bytes::bytes2hex("", s.as_ref())) + a.as_ref().map(|s| array_bytes::bytes2hex("", s)), + b.as_ref().map(|s| array_bytes::bytes2hex("", s)) ); index += 2; @@ -339,7 +339,7 @@ where #[cfg(feature = "debug")] log::debug!( "[merkelize_row] Next: {:?}", - next.iter().map(|s| array_bytes::bytes2hex("", s.as_ref())).collect::>() + next.iter().map(|s| array_bytes::bytes2hex("", s)).collect::>() ); return Err(next) }, @@ -364,7 +364,7 @@ mod tests { // then assert_eq!( - array_bytes::bytes2hex("", out.as_ref()), + array_bytes::bytes2hex("", out), "0000000000000000000000000000000000000000000000000000000000000000" ); } @@ -373,7 +373,7 @@ mod tests { fn should_generate_single_root() { // given let _ = env_logger::try_init(); - let data = vec![array_bytes::hex2array_unchecked::<20>( + let data = vec![array_bytes::hex2array_unchecked::<_, 20>( "E04CC55ebEE1cBCE552f250e85c57B70B2E2625b", )]; @@ -382,7 +382,7 @@ mod tests { // then assert_eq!( - array_bytes::bytes2hex("", out.as_ref()), + array_bytes::bytes2hex("", out), "aeb47a269393297f4b0a3c9c9cfd00c7a4195255274cf39d83dabc2fcc9ff3d7" ); } @@ -392,8 +392,8 @@ mod tests { // given let _ = env_logger::try_init(); let data = vec![ - array_bytes::hex2array_unchecked::<20>("E04CC55ebEE1cBCE552f250e85c57B70B2E2625b"), - array_bytes::hex2array_unchecked::<20>("25451A4de12dcCc2D166922fA938E900fCc4ED24"), + array_bytes::hex2array_unchecked::<_, 20>("E04CC55ebEE1cBCE552f250e85c57B70B2E2625b"), + array_bytes::hex2array_unchecked::<_, 20>("25451A4de12dcCc2D166922fA938E900fCc4ED24"), ]; // when @@ -401,7 +401,7 @@ mod tests { // then assert_eq!( - array_bytes::bytes2hex("", out.as_ref()), + array_bytes::bytes2hex("", out), "697ea2a8fe5b03468548a7a413424a6292ab44a82a6f5cc594c3fa7dda7ce402" ); } @@ -410,10 +410,7 @@ mod tests { fn should_generate_root_complex() { let _ = env_logger::try_init(); let test = |root, data| { - assert_eq!( - array_bytes::bytes2hex("", &merkle_root::(data).as_ref()), - root - ); + assert_eq!(array_bytes::bytes2hex("", &merkle_root::(data)), root); }; test( @@ -473,12 +470,12 @@ mod tests { // then assert_eq!( - array_bytes::bytes2hex("", &proof0.root.as_ref()), - array_bytes::bytes2hex("", &proof1.root.as_ref()) + array_bytes::bytes2hex("", &proof0.root), + array_bytes::bytes2hex("", &proof1.root) ); assert_eq!( - array_bytes::bytes2hex("", &proof2.root.as_ref()), - array_bytes::bytes2hex("", &proof1.root.as_ref()) + array_bytes::bytes2hex("", &proof2.root), + array_bytes::bytes2hex("", &proof1.root) ); assert!(!verify_proof::( @@ -762,10 +759,7 @@ mod tests { for l in 0..data.len() { // when let proof = merkle_proof::(data.clone(), l); - assert_eq!( - array_bytes::bytes2hex("", &proof.root.as_ref()), - array_bytes::bytes2hex("", &root.as_ref()) - ); + assert_eq!(array_bytes::bytes2hex("", &proof.root), array_bytes::bytes2hex("", &root)); assert_eq!(proof.leaf_index, l); assert_eq!(&proof.leaf, &data[l]); @@ -805,7 +799,7 @@ mod tests { ], number_of_leaves: data.len(), leaf_index: data.len() - 1, - leaf: array_bytes::hex2array_unchecked::<20>( + leaf: array_bytes::hex2array_unchecked::<_, 20>( "c26B34D375533fFc4c5276282Fa5D660F3d8cbcB" ) .to_vec(), diff --git a/utils/frame/benchmarking-cli/Cargo.toml b/utils/frame/benchmarking-cli/Cargo.toml index d960068a01bd4..f6dadf4a98a79 100644 --- a/utils/frame/benchmarking-cli/Cargo.toml +++ b/utils/frame/benchmarking-cli/Cargo.toml @@ -13,7 +13,7 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = "4.1" +array-bytes = "6.1" chrono = "0.4" clap = { version = "4.2.5", features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.6.1" } From 5745e3282ce5fccba72538ad03c218124b93b146 Mon Sep 17 00:00:00 2001 From: Liam Aharon Date: Fri, 7 Jul 2023 07:35:55 +1000 Subject: [PATCH 03/39] run tests with --experimental flag (#14502) --- scripts/ci/gitlab/pipeline/test.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/scripts/ci/gitlab/pipeline/test.yml b/scripts/ci/gitlab/pipeline/test.yml index 2e5495cb82a3e..dc41895b3a16e 100644 --- a/scripts/ci/gitlab/pipeline/test.yml +++ b/scripts/ci/gitlab/pipeline/test.yml @@ -155,21 +155,21 @@ node-bench-regression-guard: --compare-with artifacts/benches/$CI_COMMIT_REF_NAME-$CI_COMMIT_SHORT_SHA" after_script: [""] -cargo-check-try-runtime: +cargo-check-try-runtime-and-experimental: stage: test extends: - .docker-env - .test-refs script: - rusty-cachier snapshot create - - time cargo check --locked --features try-runtime + - time cargo check --locked --features try-runtime,experimental - rusty-cachier cache upload test-deterministic-wasm: stage: test # this is an artificial job dependency, for pipeline optimization using GitLab's DAGs needs: - - job: cargo-check-try-runtime + - job: cargo-check-try-runtime-and-experimental artifacts: false extends: - .docker-env @@ -221,7 +221,7 @@ test-linux-stable: --locked --release --verbose - --features runtime-benchmarks,try-runtime + --features runtime-benchmarks,try-runtime,experimental --manifest-path ./bin/node/cli/Cargo.toml --partition count:${CI_NODE_INDEX}/${CI_NODE_TOTAL} # we need to update cache only from one job @@ -258,8 +258,8 @@ test-frame-support: script: - rusty-cachier snapshot create - cat /cargo_target_dir/debug/.fingerprint/memory_units-759eddf317490d2b/lib-memory_units.json || true - - time cargo test --verbose --locked -p frame-support-test --features=frame-feature-testing,no-metadata-docs,try-runtime --manifest-path ./frame/support/test/Cargo.toml - - time cargo test --verbose --locked -p frame-support-test --features=frame-feature-testing,frame-feature-testing-2,no-metadata-docs,try-runtime --manifest-path ./frame/support/test/Cargo.toml + - time cargo test --verbose --locked -p frame-support-test --features=frame-feature-testing,no-metadata-docs,try-runtime,experimental --manifest-path ./frame/support/test/Cargo.toml + - time cargo test --verbose --locked -p frame-support-test --features=frame-feature-testing,frame-feature-testing-2,no-metadata-docs,try-runtime,experimental --manifest-path ./frame/support/test/Cargo.toml - SUBSTRATE_TEST_TIMEOUT=1 time cargo test -p substrate-test-utils --release --verbose --locked -- --ignored timeout - cat /cargo_target_dir/debug/.fingerprint/memory_units-759eddf317490d2b/lib-memory_units.json || true - rusty-cachier cache upload From 06689cbbdad85cf9fcab87a26b0c3b8e93b375ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Miko=C5=82ajczyk?= Date: Fri, 7 Jul 2023 09:38:29 +0200 Subject: [PATCH 04/39] Add `try-state` hook to pallet aura (#14363) * Add aura try-state hook * Trigger checks after unit tests --- frame/aura/src/lib.rs | 54 +++++++++++++++++++++++++++++++++++++++++ frame/aura/src/mock.rs | 16 +++++++++--- frame/aura/src/tests.rs | 12 ++++----- 3 files changed, 72 insertions(+), 10 deletions(-) diff --git a/frame/aura/src/lib.rs b/frame/aura/src/lib.rs index 3cd0e9ec2e6cc..e02d24d7c237e 100644 --- a/frame/aura/src/lib.rs +++ b/frame/aura/src/lib.rs @@ -132,6 +132,11 @@ pub mod pallet { T::DbWeight::get().reads(1) } } + + #[cfg(feature = "try-runtime")] + fn try_state(_: T::BlockNumber) -> Result<(), sp_runtime::TryRuntimeError> { + Self::do_try_state() + } } /// The current authority set. @@ -217,6 +222,55 @@ impl Pallet { // the majority of its slot. ::MinimumPeriod::get().saturating_mul(2u32.into()) } + + /// Ensure the correctness of the state of this pallet. + /// + /// This should be valid before or after each state transition of this pallet. + /// + /// # Invariants + /// + /// ## `CurrentSlot` + /// + /// If we don't allow for multiple blocks per slot, then the current slot must be less than the + /// maximal slot number. Otherwise, it can be arbitrary. + /// + /// ## `Authorities` + /// + /// * The authorities must be non-empty. + /// * The current authority cannot be disabled. + /// * The number of authorities must be less than or equal to `T::MaxAuthorities`. This however, + /// is guarded by the type system. + #[cfg(any(test, feature = "try-runtime"))] + pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> { + // We don't have any guarantee that we are already after `on_initialize` and thus we have to + // check the current slot from the digest or take the last known slot. + let current_slot = + Self::current_slot_from_digests().unwrap_or_else(|| CurrentSlot::::get()); + + // Check that the current slot is less than the maximal slot number, unless we allow for + // multiple blocks per slot. + if !T::AllowMultipleBlocksPerSlot::get() { + frame_support::ensure!( + current_slot < u64::MAX, + "Current slot has reached maximum value and cannot be incremented further.", + ); + } + + let authorities_len = + >::decode_len().ok_or("Failed to decode authorities length")?; + + // Check that the authorities are non-empty. + frame_support::ensure!(!authorities_len.is_zero(), "Authorities must be non-empty."); + + // Check that the current authority is not disabled. + let authority_index = *current_slot % authorities_len as u64; + frame_support::ensure!( + !T::DisabledValidators::is_disabled(authority_index as u32), + "Current validator is disabled and should not be attempting to author blocks.", + ); + + Ok(()) + } } impl sp_runtime::BoundToRuntimeAppPublic for Pallet { diff --git a/frame/aura/src/mock.rs b/frame/aura/src/mock.rs index c95b7451d0bd4..5ae443b4f7685 100644 --- a/frame/aura/src/mock.rs +++ b/frame/aura/src/mock.rs @@ -110,12 +110,20 @@ impl pallet_aura::Config for Test { type AllowMultipleBlocksPerSlot = AllowMultipleBlocksPerSlot; } -pub fn new_test_ext(authorities: Vec) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); +fn build_ext(authorities: Vec) -> sp_io::TestExternalities { + let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); pallet_aura::GenesisConfig:: { authorities: authorities.into_iter().map(|a| UintAuthorityId(a).to_public_key()).collect(), } - .assimilate_storage(&mut t) + .assimilate_storage(&mut storage) .unwrap(); - t.into() + storage.into() +} + +pub fn build_ext_and_execute_test(authorities: Vec, test: impl FnOnce() -> ()) { + let mut ext = build_ext(authorities); + ext.execute_with(|| { + test(); + Aura::do_try_state().expect("Storage invariants should hold") + }); } diff --git a/frame/aura/src/tests.rs b/frame/aura/src/tests.rs index d5e5f19d65ea5..d3ce877d3e60d 100644 --- a/frame/aura/src/tests.rs +++ b/frame/aura/src/tests.rs @@ -19,7 +19,7 @@ #![cfg(test)] -use crate::mock::{new_test_ext, Aura, MockDisabledValidators, System}; +use crate::mock::{build_ext_and_execute_test, Aura, MockDisabledValidators, System}; use codec::Encode; use frame_support::traits::OnInitialize; use sp_consensus_aura::{Slot, AURA_ENGINE_ID}; @@ -27,7 +27,7 @@ use sp_runtime::{Digest, DigestItem}; #[test] fn initial_values() { - new_test_ext(vec![0, 1, 2, 3]).execute_with(|| { + build_ext_and_execute_test(vec![0, 1, 2, 3], || { assert_eq!(Aura::current_slot(), 0u64); assert_eq!(Aura::authorities().len(), 4); }); @@ -38,7 +38,7 @@ fn initial_values() { expected = "Validator with index 1 is disabled and should not be attempting to author blocks." )] fn disabled_validators_cannot_author_blocks() { - new_test_ext(vec![0, 1, 2, 3]).execute_with(|| { + build_ext_and_execute_test(vec![0, 1, 2, 3], || { // slot 1 should be authored by validator at index 1 let slot = Slot::from(1); let pre_digest = @@ -58,7 +58,7 @@ fn disabled_validators_cannot_author_blocks() { #[test] #[should_panic(expected = "Slot must increase")] fn pallet_requires_slot_to_increase_unless_allowed() { - new_test_ext(vec![0, 1, 2, 3]).execute_with(|| { + build_ext_and_execute_test(vec![0, 1, 2, 3], || { crate::mock::AllowMultipleBlocksPerSlot::set(false); let slot = Slot::from(1); @@ -76,7 +76,7 @@ fn pallet_requires_slot_to_increase_unless_allowed() { #[test] fn pallet_can_allow_unchanged_slot() { - new_test_ext(vec![0, 1, 2, 3]).execute_with(|| { + build_ext_and_execute_test(vec![0, 1, 2, 3], || { let slot = Slot::from(1); let pre_digest = Digest { logs: vec![DigestItem::PreRuntime(AURA_ENGINE_ID, slot.encode())] }; @@ -95,7 +95,7 @@ fn pallet_can_allow_unchanged_slot() { #[test] #[should_panic(expected = "Slot must not decrease")] fn pallet_always_rejects_decreasing_slot() { - new_test_ext(vec![0, 1, 2, 3]).execute_with(|| { + build_ext_and_execute_test(vec![0, 1, 2, 3], || { let slot = Slot::from(2); let pre_digest = Digest { logs: vec![DigestItem::PreRuntime(AURA_ENGINE_ID, slot.encode())] }; From 5584139e01ab7c60510e468312acc3518c1c34d4 Mon Sep 17 00:00:00 2001 From: cuteolaf Date: Fri, 7 Jul 2023 01:27:47 -0700 Subject: [PATCH 05/39] Update lib.rs (#14528) --- frame/benchmarking/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/benchmarking/src/lib.rs b/frame/benchmarking/src/lib.rs index e5ec61d622e95..8864cd1d88ddf 100644 --- a/frame/benchmarking/src/lib.rs +++ b/frame/benchmarking/src/lib.rs @@ -128,7 +128,7 @@ pub use v1::*; /// as `I` in the case of an `#[instance_benchmarks]` module. You should not add these to the /// function signature as this will be handled automatically for you based on whether this is a /// `#[benchmarks]` or `#[instance_benchmarks]` module and whatever [where clause](#where-clause) -/// you have defined for the the module. You should not manually add any generics to the +/// you have defined for the module. You should not manually add any generics to the /// signature of your benchmark function. /// /// Also note that the `// setup code` and `// verification code` comments shown above are not From 7aacdf1755e63ba2b1aa3ace65aea063db421230 Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Fri, 7 Jul 2023 15:46:16 +0200 Subject: [PATCH 06/39] contracts: Refactor instantiate with code (#14503) * wip * fixes * rm comment * join fns * clippy * Fix limits * reduce diff * fix * fix * fix typo * refactor store to use self * refactor run to take self by value * pass tests * rm comment * fixes * fix typo * rm * fix fmt * clippy * ".git/.scripts/commands/bench/bench.sh" pallet dev pallet_contracts * Update frame/contracts/src/lib.rs Co-authored-by: Sasha Gryaznov * Update frame/contracts/src/wasm/mod.rs Co-authored-by: Sasha Gryaznov * Update frame/contracts/src/wasm/mod.rs Co-authored-by: Sasha Gryaznov * PR review, rm duplicate increment_refcount * PR review * Update frame/contracts/src/wasm/prepare.rs Co-authored-by: Sasha Gryaznov * Add test for failing storage_deposit * fix lint * ".git/.scripts/commands/bench/bench.sh" pallet dev pallet_contracts --------- Co-authored-by: command-bot <> Co-authored-by: Sasha Gryaznov --- frame/contracts/primitives/src/lib.rs | 6 - frame/contracts/src/lib.rs | 183 ++-- frame/contracts/src/migration/v11.rs | 4 +- frame/contracts/src/tests.rs | 74 +- frame/contracts/src/wasm/mod.rs | 103 +-- frame/contracts/src/wasm/prepare.rs | 53 +- frame/contracts/src/weights.rs | 1166 ++++++++++++------------- 7 files changed, 780 insertions(+), 809 deletions(-) diff --git a/frame/contracts/primitives/src/lib.rs b/frame/contracts/primitives/src/lib.rs index 3f830ca92486d..ddd97d99b2f59 100644 --- a/frame/contracts/primitives/src/lib.rs +++ b/frame/contracts/primitives/src/lib.rs @@ -161,12 +161,6 @@ pub enum Code { Existing(Hash), } -impl>, Hash> From for Code { - fn from(from: T) -> Self { - Code::Upload(from.into()) - } -} - /// The amount of balance that was either charged or refunded in order to pay for storage. #[derive(Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug, Clone, TypeInfo)] pub enum StorageDeposit { diff --git a/frame/contracts/src/lib.rs b/frame/contracts/src/lib.rs index bf6fd6309c822..d36a0f93f339b 100644 --- a/frame/contracts/src/lib.rs +++ b/frame/contracts/src/lib.rs @@ -75,8 +75,8 @@ //! allowed to code owner. //! * [`Pallet::set_code`] - Changes the code of an existing contract. Only allowed to `Root` //! origin. -//! * [`Pallet::migrate`] - Runs migration steps of curent multi-block migration in priority, before -//! [`Hooks::on_idle`][frame_support::traits::Hooks::on_idle] activates. +//! * [`Pallet::migrate`] - Runs migration steps of current multi-block migration in priority, +//! before [`Hooks::on_idle`][frame_support::traits::Hooks::on_idle] activates. //! //! ## Usage //! @@ -105,7 +105,7 @@ use crate::{ exec::{AccountIdOf, ErrorOrigin, ExecError, Executable, Key, Stack as ExecStack}, gas::GasMeter, storage::{meter::Meter as StorageMeter, ContractInfo, DeletionQueueManager}, - wasm::{CodeInfo, TryInstantiate, WasmBlob}, + wasm::{CodeInfo, WasmBlob}, }; use codec::{Codec, Decode, Encode, HasCompact}; use environmental::*; @@ -695,24 +695,40 @@ pub mod pallet { salt: Vec, ) -> DispatchResultWithPostInfo { Migration::::ensure_migrated()?; + let origin = ensure_signed(origin)?; let code_len = code.len() as u32; + + let (module, upload_deposit) = Self::try_upload_code( + origin.clone(), + code, + storage_deposit_limit.clone().map(Into::into), + Determinism::Enforced, + None, + )?; + + // Reduces the storage deposit limit by the amount that was reserved for the upload. + let storage_deposit_limit = + storage_deposit_limit.map(|limit| limit.into().saturating_sub(upload_deposit)); + let data_len = data.len() as u32; let salt_len = salt.len() as u32; let common = CommonInput { - origin: Origin::from_runtime_origin(origin)?, + origin: Origin::from_account_id(origin), value, data, gas_limit, - storage_deposit_limit: storage_deposit_limit.map(Into::into), + storage_deposit_limit, debug_message: None, }; + let mut output = - InstantiateInput:: { code: Code::Upload(code), salt }.run_guarded(common); + InstantiateInput:: { code: WasmCode::Wasm(module), salt }.run_guarded(common); if let Ok(retval) = &output.result { if retval.1.did_revert() { output.result = Err(>::ContractReverted.into()); } } + output.gas_meter.into_dispatch_result( output.result.map(|(_address, result)| result), T::WeightInfo::instantiate_with_code(code_len, data_len, salt_len), @@ -748,8 +764,8 @@ pub mod pallet { storage_deposit_limit: storage_deposit_limit.map(Into::into), debug_message: None, }; - let mut output = - InstantiateInput:: { code: Code::Existing(code_hash), salt }.run_guarded(common); + let mut output = InstantiateInput:: { code: WasmCode::CodeHash(code_hash), salt } + .run_guarded(common); if let Ok(retval) = &output.result { if retval.1.did_revert() { output.result = Err(>::ContractReverted.into()); @@ -1052,9 +1068,15 @@ struct CallInput { determinism: Determinism, } +/// Reference to an existing code hash or a new wasm module. +enum WasmCode { + Wasm(WasmBlob), + CodeHash(CodeHash), +} + /// Input specific to a contract instantiation invocation. struct InstantiateInput { - code: Code>, + code: WasmCode, salt: Vec, } @@ -1099,7 +1121,7 @@ struct InternalOutput { /// Helper trait to wrap contract execution entry points into a single function /// [`Invokable::run_guarded`]. -trait Invokable { +trait Invokable: Sized { /// What is returned as a result of a successful invocation. type Output; @@ -1111,7 +1133,7 @@ trait Invokable { /// /// We enforce a re-entrancy guard here by initializing and checking a boolean flag through a /// global reference. - fn run_guarded(&self, common: CommonInput) -> InternalOutput { + fn run_guarded(self, common: CommonInput) -> InternalOutput { // Set up a global reference to the boolean flag used for the re-entrancy guard. environmental!(executing_contract: bool); @@ -1159,11 +1181,8 @@ trait Invokable { /// contract or a instantiation of a new one. /// /// Called by dispatchables and public functions through the [`Invokable::run_guarded`]. - fn run( - &self, - common: CommonInput, - gas_meter: GasMeter, - ) -> InternalOutput; + fn run(self, common: CommonInput, gas_meter: GasMeter) + -> InternalOutput; /// This method ensures that the given `origin` is allowed to invoke the current `Invokable`. /// @@ -1175,7 +1194,7 @@ impl Invokable for CallInput { type Output = ExecReturnValue; fn run( - &self, + self, common: CommonInput, mut gas_meter: GasMeter, ) -> InternalOutput { @@ -1201,7 +1220,7 @@ impl Invokable for CallInput { value, data.clone(), debug_message, - *determinism, + determinism, ); match storage_meter.try_into_deposit(&origin) { @@ -1223,8 +1242,8 @@ impl Invokable for InstantiateInput { type Output = (AccountIdOf, ExecReturnValue); fn run( - &self, - mut common: CommonInput, + self, + common: CommonInput, mut gas_meter: GasMeter, ) -> InternalOutput { let mut storage_deposit = Default::default(); @@ -1233,37 +1252,15 @@ impl Invokable for InstantiateInput { let InstantiateInput { salt, .. } = self; let CommonInput { origin: contract_origin, .. } = common; let origin = contract_origin.account_id()?; - let (extra_deposit, executable) = match &self.code { - Code::Upload(binary) => { - let executable = WasmBlob::from_code( - binary.clone(), - &schedule, - origin.clone(), - Determinism::Enforced, - TryInstantiate::Skip, - ) - .map_err(|(err, msg)| { - common - .debug_message - .as_mut() - .map(|buffer| buffer.try_extend(&mut msg.bytes())); - err - })?; - // The open deposit will be charged during execution when the - // uploaded module does not already exist. This deposit is not part of the - // storage meter because it is not transferred to the contract but - // reserved on the uploading account. - (executable.open_deposit(&executable.code_info()), executable) - }, - Code::Existing(hash) => - (Default::default(), WasmBlob::from_storage(*hash, &mut gas_meter)?), + + let executable = match self.code { + WasmCode::Wasm(module) => module, + WasmCode::CodeHash(code_hash) => WasmBlob::from_storage(code_hash, &mut gas_meter)?, }; + let contract_origin = Origin::from_account_id(origin.clone()); - let mut storage_meter = StorageMeter::new( - &contract_origin, - common.storage_deposit_limit, - common.value.saturating_add(extra_deposit), - )?; + let mut storage_meter = + StorageMeter::new(&contract_origin, common.storage_deposit_limit, common.value)?; let CommonInput { value, data, debug_message, .. } = common; let result = ExecStack::>::run_instantiate( origin.clone(), @@ -1277,9 +1274,7 @@ impl Invokable for InstantiateInput { debug_message, ); - storage_deposit = storage_meter - .try_into_deposit(&contract_origin)? - .saturating_add(&StorageDeposit::Charge(extra_deposit)); + storage_deposit = storage_meter.try_into_deposit(&contract_origin)?; result }; InternalOutput { result: try_exec(), gas_meter, storage_deposit } @@ -1383,7 +1378,7 @@ impl Pallet { origin: T::AccountId, value: BalanceOf, gas_limit: Weight, - storage_deposit_limit: Option>, + mut storage_deposit_limit: Option>, code: Code>, data: Vec, salt: Vec, @@ -1397,6 +1392,45 @@ impl Pallet { } else { None }; + // collect events if CollectEvents is UnsafeCollect + let events = || { + if collect_events == CollectEvents::UnsafeCollect { + Some(System::::read_events_no_consensus().map(|e| *e).collect()) + } else { + None + } + }; + + let (code, upload_deposit): (WasmCode, BalanceOf) = match code { + Code::Upload(code) => { + let result = Self::try_upload_code( + origin.clone(), + code, + storage_deposit_limit.map(Into::into), + Determinism::Enforced, + debug_message.as_mut(), + ); + + let (module, deposit) = match result { + Ok(result) => result, + Err(error) => + return ContractResult { + gas_consumed: Zero::zero(), + gas_required: Zero::zero(), + storage_deposit: Default::default(), + debug_message: debug_message.unwrap_or(Default::default()).into(), + result: Err(error), + events: events(), + }, + }; + + storage_deposit_limit = + storage_deposit_limit.map(|l| l.saturating_sub(deposit.into())); + (WasmCode::Wasm(module), deposit) + }, + Code::Existing(hash) => (WasmCode::CodeHash(hash), Default::default()), + }; + let common = CommonInput { origin: Origin::from_account_id(origin), value, @@ -1405,13 +1439,8 @@ impl Pallet { storage_deposit_limit, debug_message: debug_message.as_mut(), }; + let output = InstantiateInput:: { code, salt }.run_guarded(common); - // collect events if CollectEvents is UnsafeCollect - let events = if collect_events == CollectEvents::UnsafeCollect { - Some(System::::read_events_no_consensus().map(|e| *e).collect()) - } else { - None - }; ContractInstantiateResult { result: output .result @@ -1419,9 +1448,11 @@ impl Pallet { .map_err(|e| e.error), gas_consumed: output.gas_meter.gas_consumed(), gas_required: output.gas_meter.gas_required(), - storage_deposit: output.storage_deposit, + storage_deposit: output + .storage_deposit + .saturating_add(&StorageDeposit::Charge(upload_deposit)), debug_message: debug_message.unwrap_or_default().to_vec(), - events, + events: events(), } } @@ -1436,17 +1467,31 @@ impl Pallet { determinism: Determinism, ) -> CodeUploadResult, BalanceOf> { Migration::::ensure_migrated()?; + let (module, deposit) = + Self::try_upload_code(origin, code, storage_deposit_limit, determinism, None)?; + Ok(CodeUploadReturnValue { code_hash: *module.code_hash(), deposit }) + } + + /// Uploads new code and returns the Wasm blob and deposit amount collected. + fn try_upload_code( + origin: T::AccountId, + code: Vec, + storage_deposit_limit: Option>, + determinism: Determinism, + mut debug_message: Option<&mut DebugBufferVec>, + ) -> Result<(WasmBlob, BalanceOf), DispatchError> { let schedule = T::Schedule::get(); - let module = - WasmBlob::from_code(code, &schedule, origin, determinism, TryInstantiate::Instantiate) - .map_err(|(err, _)| err)?; - let deposit = module.open_deposit(&module.code_info()); + let mut module = + WasmBlob::from_code(code, &schedule, origin, determinism).map_err(|(err, msg)| { + debug_message.as_mut().map(|d| d.try_extend(msg.bytes())); + err + })?; + let deposit = module.store_code()?; if let Some(storage_deposit_limit) = storage_deposit_limit { ensure!(storage_deposit_limit >= deposit, >::StorageDepositLimitExhausted); } - let result = CodeUploadReturnValue { code_hash: *module.code_hash(), deposit }; - module.store()?; - Ok(result) + + Ok((module, deposit)) } /// Query storage of a specified contract under a specified key. @@ -1490,7 +1535,7 @@ impl Pallet { owner: T::AccountId, ) -> frame_support::dispatch::DispatchResult { let schedule = T::Schedule::get(); - WasmBlob::store_code_unchecked(code, &schedule, owner)?; + WasmBlob::::from_code_unchecked(code, &schedule, owner)?.store_code()?; Ok(()) } diff --git a/frame/contracts/src/migration/v11.rs b/frame/contracts/src/migration/v11.rs index 67740cfaf6c80..8123d73aee560 100644 --- a/frame/contracts/src/migration/v11.rs +++ b/frame/contracts/src/migration/v11.rs @@ -80,7 +80,9 @@ impl MigrationStep for Migration { } fn step(&mut self) -> (IsFinished, Weight) { - let Some(old_queue) = old::DeletionQueue::::take() else { return (IsFinished::Yes, Weight::zero()) }; + let Some(old_queue) = old::DeletionQueue::::take() else { + return (IsFinished::Yes, Weight::zero()) + }; let len = old_queue.len(); log::debug!( diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index 2e9d1176213ee..f67be602695d6 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -3753,6 +3753,19 @@ fn instantiate_with_zero_balance_works() { assert_eq!( System::events(), vec![ + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Reserved { + who: ALICE, + amount: deposit_expected, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::CodeStored { code_hash }), + topics: vec![code_hash], + }, EventRecord { phase: Phase::Initialization, event: RuntimeEvent::System(frame_system::Event::NewAccount { @@ -3801,19 +3814,6 @@ fn instantiate_with_zero_balance_works() { }), topics: vec![], }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Balances(pallet_balances::Event::Reserved { - who: ALICE, - amount: deposit_expected, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::CodeStored { code_hash }), - topics: vec![code_hash], - }, EventRecord { phase: Phase::Initialization, event: RuntimeEvent::Contracts(crate::Event::Instantiated { @@ -3865,6 +3865,19 @@ fn instantiate_with_below_existential_deposit_works() { assert_eq!( System::events(), vec![ + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Reserved { + who: ALICE, + amount: deposit_expected, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::CodeStored { code_hash }), + topics: vec![code_hash], + }, EventRecord { phase: Phase::Initialization, event: RuntimeEvent::System(frame_system::Event::NewAccount { @@ -3922,19 +3935,6 @@ fn instantiate_with_below_existential_deposit_works() { }), topics: vec![], }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Balances(pallet_balances::Event::Reserved { - who: ALICE, - amount: deposit_expected, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::CodeStored { code_hash }), - topics: vec![code_hash], - }, EventRecord { phase: Phase::Initialization, event: RuntimeEvent::Contracts(crate::Event::Instantiated { @@ -4587,11 +4587,29 @@ fn set_code_hash() { #[test] fn storage_deposit_limit_is_enforced() { + let ed = 200; let (wasm, _code_hash) = compile_module::("store_call").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + ExtBuilder::default().existential_deposit(ed).build().execute_with(|| { let _ = Balances::deposit_creating(&ALICE, 1_000_000); let min_balance = ::Currency::minimum_balance(); + // Setting insufficient storage_deposit should fail. + assert_err!( + Contracts::bare_instantiate( + ALICE, + 0, + GAS_LIMIT, + Some((2 * ed + 3 - 1).into()), // expected deposit is 2 * ed + 3 for the call + Code::Upload(wasm.clone()), + vec![], + vec![], + DebugInfo::Skip, + CollectEvents::Skip, + ) + .result, + >::StorageDepositLimitExhausted, + ); + // Instantiate the BOB contract. let addr = Contracts::bare_instantiate( ALICE, @@ -5591,7 +5609,7 @@ fn root_cannot_instantiate_with_code() { vec![], vec![], ), - DispatchError::RootNotAllowed, + DispatchError::BadOrigin ); }); } diff --git a/frame/contracts/src/wasm/mod.rs b/frame/contracts/src/wasm/mod.rs index 01075b2a4c9d9..fa05de3f33ac0 100644 --- a/frame/contracts/src/wasm/mod.rs +++ b/frame/contracts/src/wasm/mod.rs @@ -27,12 +27,9 @@ pub use crate::wasm::runtime::api_doc; #[cfg(test)] pub use tests::MockExt; -pub use crate::wasm::{ - prepare::TryInstantiate, - runtime::{ - AllowDeprecatedInterface, AllowUnstableInterface, CallFlags, Environment, ReturnCode, - Runtime, RuntimeCosts, - }, +pub use crate::wasm::runtime::{ + AllowDeprecatedInterface, AllowUnstableInterface, CallFlags, Environment, ReturnCode, Runtime, + RuntimeCosts, }; use crate::{ @@ -147,33 +144,20 @@ impl Token for CodeLoadToken { impl WasmBlob { /// Create the module by checking the `code`. - /// - /// This does **not** store the module. For this one need to either call [`Self::store`] - /// or [`::execute`][`Executable::execute`]. pub fn from_code( code: Vec, schedule: &Schedule, owner: AccountIdOf, determinism: Determinism, - try_instantiate: TryInstantiate, ) -> Result { prepare::prepare::( code.try_into().map_err(|_| (>::CodeTooLarge.into(), ""))?, schedule, owner, determinism, - try_instantiate, ) } - /// Store the code without instantiating it. - /// - /// Otherwise the code is stored when [`::execute`][`Executable::execute`] - /// is called. - pub fn store(self) -> DispatchResult { - Self::store_code(self, false) - } - /// Remove the code from storage and refund the deposit to its owner. /// /// Applies all necessary checks before removing the code. @@ -181,18 +165,6 @@ impl WasmBlob { Self::try_remove_code(origin, code_hash) } - /// Returns whether there is a deposit to be paid for this module. - /// - /// Returns `0` if the module is already in storage and hence no deposit will - /// be charged for storing it. - pub fn open_deposit(&self, code_info: &CodeInfo) -> BalanceOf { - if >::contains_key(self.code_hash()) { - 0u32.into() - } else { - code_info.deposit - } - } - /// Creates and returns an instance of the supplied code. /// /// This is either used for later executing a contract or for validation of a contract. @@ -227,7 +199,7 @@ impl WasmBlob { // Query wasmi for memory limits specified in the module's import entry. let memory_limits = contract.scan_imports::(schedule)?; // Here we allocate this memory in the _store_. It allocates _inital_ value, but allows it - // to grow up to maximum number of memory pages, if neccesary. + // to grow up to maximum number of memory pages, if necessary. let qed = "We checked the limits versus our Schedule, which specifies the max amount of memory pages well below u16::MAX; qed"; @@ -250,50 +222,26 @@ impl WasmBlob { Ok((store, memory, instance)) } - /// Getter method for the code_info. - pub fn code_info(&self) -> &CodeInfo { - &self.code_info - } - - /// Put the module blob into storage. - /// - /// Increments the reference count of the in-storage `WasmBlob`, if it already exists in - /// storage. - fn store_code(mut module: Self, instantiated: bool) -> DispatchResult { - let code_hash = &module.code_hash().clone(); + /// Puts the module blob into storage, and returns the deposit collected for the storage. + pub fn store_code(&mut self) -> Result, Error> { + let code_hash = *self.code_hash(); >::mutate(code_hash, |stored_code_info| { match stored_code_info { - // Instantiate existing contract. - Some(stored_code_info) if instantiated => { - stored_code_info.refcount = stored_code_info.refcount.checked_add(1).expect( - " - refcount is 64bit. Generating this overflow would require to store - _at least_ 18 exabyte of data assuming that a contract consumes only - one byte of data. Any node would run out of storage space before hitting - this overflow; - qed - ", - ); - Ok(()) - }, // Contract code is already stored in storage. Nothing to be done here. - Some(_) => Ok(()), + Some(_) => Ok(Default::default()), // Upload a new contract code. - // // We need to store the code and its code_info, and collect the deposit. + // This `None` case happens only with freshly uploaded modules. This means that + // the `owner` is always the origin of the current transaction. None => { - // This `None` case happens only in freshly uploaded modules. This means that - // the `owner` is always the origin of the current transaction. - T::Currency::reserve(&module.code_info.owner, module.code_info.deposit) + let deposit = self.code_info.deposit; + T::Currency::reserve(&self.code_info.owner, deposit) .map_err(|_| >::StorageDepositNotEnoughFunds)?; - module.code_info.refcount = if instantiated { 1 } else { 0 }; - >::insert(code_hash, module.code); - *stored_code_info = Some(module.code_info); - >::deposit_event( - vec![*code_hash], - Event::CodeStored { code_hash: *code_hash }, - ); - Ok(()) + self.code_info.refcount = 0; + >::insert(code_hash, &self.code); + *stored_code_info = Some(self.code_info.clone()); + >::deposit_event(vec![code_hash], Event::CodeStored { code_hash }); + Ok(deposit) }, } }) @@ -331,17 +279,6 @@ impl WasmBlob { Ok(code) } - /// See [`Self::from_code_unchecked`]. - #[cfg(feature = "runtime-benchmarks")] - pub fn store_code_unchecked( - code: Vec, - schedule: &Schedule, - owner: T::AccountId, - ) -> DispatchResult { - let executable = Self::from_code_unchecked(code, schedule, owner)?; - Self::store_code(executable, false) - } - /// Create the module without checking the passed code. /// /// # Note @@ -350,7 +287,7 @@ impl WasmBlob { /// our results. This also does not collect any deposit from the `owner`. Also useful /// during testing when we want to deploy codes that do not pass the instantiation checks. #[cfg(any(test, feature = "runtime-benchmarks"))] - fn from_code_unchecked( + pub fn from_code_unchecked( code: Vec, schedule: &Schedule, owner: T::AccountId, @@ -450,9 +387,8 @@ impl Executable for WasmBlob { Error::::CodeRejected })?; - // We store before executing so that the code hash is available in the constructor. if let &ExportedFunction::Constructor = function { - Self::store_code(self, true)?; + WasmBlob::::increment_refcount(self.code_hash)?; } let result = exported_func.call(&mut store, &[], &mut []); @@ -790,7 +726,6 @@ mod tests { ext.borrow_mut().schedule(), ALICE, Determinism::Enforced, - TryInstantiate::Instantiate, ) .map_err(|err| err.0)? }; diff --git a/frame/contracts/src/wasm/prepare.rs b/frame/contracts/src/wasm/prepare.rs index 5647d5458e659..ee89aae642b4a 100644 --- a/frame/contracts/src/wasm/prepare.rs +++ b/frame/contracts/src/wasm/prepare.rs @@ -41,21 +41,6 @@ use wasmi::{ /// compiler toolchains might not support specifying other modules than "env" for memory imports. pub const IMPORT_MODULE_MEMORY: &str = "env"; -/// Determines whether a module should be instantiated during preparation. -pub enum TryInstantiate { - /// Do the instantiation to make sure that the module is valid. - /// - /// This should be used if a module is only uploaded but not executed. We need - /// to make sure that it can be actually instantiated. - Instantiate, - /// Skip the instantiation during preparation. - /// - /// This makes sense when the preparation takes place as part of an instantiation. Then - /// this instantiation would fail the whole transaction and an extra check is not - /// necessary. - Skip, -} - /// The inner deserialized module is valid and contains only allowed WebAssembly features. /// This is checked by loading it into wasmi interpreter `engine`. pub struct LoadedModule { @@ -237,7 +222,6 @@ fn validate( code: &[u8], schedule: &Schedule, determinism: Determinism, - try_instantiate: TryInstantiate, ) -> Result<(), (DispatchError, &'static str)> where E: Environment<()>, @@ -261,23 +245,22 @@ where // // - It doesn't use any unknown imports. // - It doesn't explode the wasmi bytecode generation. - if matches!(try_instantiate, TryInstantiate::Instantiate) { - // We don't actually ever run any code so we can get away with a minimal stack which - // reduces the amount of memory that needs to be zeroed. - let stack_limits = StackLimits::new(1, 1, 0).expect("initial <= max; qed"); - WasmBlob::::instantiate::( - &code, - (), - schedule, - determinism, - stack_limits, - AllowDeprecatedInterface::No, - ) - .map_err(|err| { - log::debug!(target: LOG_TARGET, "{}", err); - (Error::::CodeRejected.into(), "New code rejected on wasmi instantiation!") - })?; - } + // + // We don't actually ever execute this instance so we can get away with a minimal stack which + // reduces the amount of memory that needs to be zeroed. + let stack_limits = StackLimits::new(1, 1, 0).expect("initial <= max; qed"); + WasmBlob::::instantiate::( + &code, + (), + schedule, + determinism, + stack_limits, + AllowDeprecatedInterface::No, + ) + .map_err(|err| { + log::debug!(target: LOG_TARGET, "{}", err); + (Error::::CodeRejected.into(), "New code rejected on wasmi instantiation!") + })?; Ok(()) } @@ -295,13 +278,12 @@ pub fn prepare( schedule: &Schedule, owner: AccountIdOf, determinism: Determinism, - try_instantiate: TryInstantiate, ) -> Result, (DispatchError, &'static str)> where E: Environment<()>, T: Config, { - validate::(code.as_ref(), schedule, determinism, try_instantiate)?; + validate::(code.as_ref(), schedule, determinism)?; // Calculate deposit for storing contract code and `code_info` in two different storage items. let bytes_added = code.len().saturating_add(>::max_encoded_len()) as u32; @@ -416,7 +398,6 @@ mod tests { &schedule, ALICE, Determinism::Enforced, - TryInstantiate::Instantiate, ); assert_matches::assert_matches!(r.map_err(|(_, msg)| msg), $($expected)*); } diff --git a/frame/contracts/src/weights.rs b/frame/contracts/src/weights.rs index fccc17a0a79ad..754a28fc22926 100644 --- a/frame/contracts/src/weights.rs +++ b/frame/contracts/src/weights.rs @@ -18,7 +18,7 @@ //! Autogenerated weights for pallet_contracts //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-07-03, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-07-06, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `runner-xerhrdyb-project-145-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 @@ -137,8 +137,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `1627` - // Minimum execution time: 2_546_000 picoseconds. - Weight::from_parts(2_671_000, 1627) + // Minimum execution time: 2_519_000 picoseconds. + Weight::from_parts(2_660_000, 1627) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: Skipped Metadata (r:0 w:0) @@ -148,10 +148,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `451 + k * (69 ±0)` // Estimated: `441 + k * (70 ±0)` - // Minimum execution time: 13_398_000 picoseconds. - Weight::from_parts(13_771_000, 441) - // Standard Error: 1_033 - .saturating_add(Weight::from_parts(1_231_963, 0).saturating_mul(k.into())) + // Minimum execution time: 13_096_000 picoseconds. + Weight::from_parts(13_395_000, 441) + // Standard Error: 1_046 + .saturating_add(Weight::from_parts(1_246_238, 0).saturating_mul(k.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(k.into()))) .saturating_add(T::DbWeight::get().writes(2_u64)) @@ -165,10 +165,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `211 + c * (1 ±0)` // Estimated: `6149 + c * (1 ±0)` - // Minimum execution time: 8_335_000 picoseconds. - Weight::from_parts(9_172_574, 6149) + // Minimum execution time: 8_409_000 picoseconds. + Weight::from_parts(9_006_438, 6149) // Standard Error: 1 - .saturating_add(Weight::from_parts(1_388, 0).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(1_345, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -181,8 +181,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `510` // Estimated: `6450` - // Minimum execution time: 17_087_000 picoseconds. - Weight::from_parts(17_840_000, 6450) + // Minimum execution time: 16_962_000 picoseconds. + Weight::from_parts(17_716_000, 6450) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -195,10 +195,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `171 + k * (1 ±0)` // Estimated: `3635 + k * (1 ±0)` - // Minimum execution time: 4_016_000 picoseconds. - Weight::from_parts(655_916, 3635) - // Standard Error: 1_202 - .saturating_add(Weight::from_parts(1_158_002, 0).saturating_mul(k.into())) + // Minimum execution time: 3_763_000 picoseconds. + Weight::from_parts(2_401_625, 3635) + // Standard Error: 2_827 + .saturating_add(Weight::from_parts(1_201_671, 0).saturating_mul(k.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(k.into()))) @@ -217,10 +217,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `325 + c * (1 ±0)` // Estimated: `6263 + c * (1 ±0)` - // Minimum execution time: 17_500_000 picoseconds. - Weight::from_parts(17_675_710, 6263) + // Minimum execution time: 17_490_000 picoseconds. + Weight::from_parts(17_712_278, 6263) // Standard Error: 0 - .saturating_add(Weight::from_parts(488, 0).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(427, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -231,8 +231,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `1627` - // Minimum execution time: 3_278_000 picoseconds. - Weight::from_parts(3_501_000, 1627) + // Minimum execution time: 3_282_000 picoseconds. + Weight::from_parts(3_536_000, 1627) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -244,8 +244,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `166` // Estimated: `3631` - // Minimum execution time: 12_489_000 picoseconds. - Weight::from_parts(12_850_000, 3631) + // Minimum execution time: 12_973_000 picoseconds. + Weight::from_parts(13_366_000, 3631) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -255,8 +255,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 4_788_000 picoseconds. - Weight::from_parts(5_099_000, 3607) + // Minimum execution time: 4_764_000 picoseconds. + Weight::from_parts(5_000_000, 3607) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: unknown `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) @@ -267,8 +267,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `167` // Estimated: `3632` - // Minimum execution time: 6_850_000 picoseconds. - Weight::from_parts(7_146_000, 3632) + // Minimum execution time: 6_616_000 picoseconds. + Weight::from_parts(6_935_000, 3632) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// Storage: unknown `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) @@ -279,8 +279,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 7_078_000 picoseconds. - Weight::from_parts(7_452_000, 3607) + // Minimum execution time: 6_953_000 picoseconds. + Weight::from_parts(7_440_000, 3607) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -303,10 +303,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `786` // Estimated: `6735 + c * (1 ±0)` - // Minimum execution time: 366_103_000 picoseconds. - Weight::from_parts(335_256_535, 6735) - // Standard Error: 81 - .saturating_add(Weight::from_parts(38_395, 0).saturating_mul(c.into())) + // Minimum execution time: 302_714_000 picoseconds. + Weight::from_parts(271_320_595, 6735) + // Standard Error: 72 + .saturating_add(Weight::from_parts(38_474, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -315,6 +315,8 @@ impl WeightInfo for SubstrateWeight { /// Proof: Contracts MigrationInProgress (max_values: Some(1), max_size: Some(1026), added: 1521, mode: Measured) /// Storage: Contracts CodeInfoOf (r:1 w:1) /// Proof: Contracts CodeInfoOf (max_values: None, max_size: Some(89), added: 2564, mode: Measured) + /// Storage: System EventTopics (r:3 w:3) + /// Proof Skipped: System EventTopics (max_values: None, max_size: None, mode: Measured) /// Storage: Contracts Nonce (r:1 w:1) /// Proof: Contracts Nonce (max_values: Some(1), max_size: Some(8), added: 503, mode: Measured) /// Storage: Contracts ContractInfoOf (r:1 w:1) @@ -323,8 +325,6 @@ impl WeightInfo for SubstrateWeight { /// Proof: Timestamp Now (max_values: Some(1), max_size: Some(8), added: 503, mode: Measured) /// Storage: System Account (r:2 w:2) /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: Measured) - /// Storage: System EventTopics (r:3 w:3) - /// Proof Skipped: System EventTopics (max_values: None, max_size: None, mode: Measured) /// Storage: Contracts PristineCode (r:0 w:1) /// Proof: Contracts PristineCode (max_values: None, max_size: Some(125988), added: 128463, mode: Measured) /// The range of component `c` is `[0, 125952]`. @@ -334,14 +334,14 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `303` // Estimated: `8745` - // Minimum execution time: 4_289_681_000 picoseconds. - Weight::from_parts(331_057_751, 8745) - // Standard Error: 206 - .saturating_add(Weight::from_parts(76_366, 0).saturating_mul(c.into())) - // Standard Error: 24 - .saturating_add(Weight::from_parts(1_938, 0).saturating_mul(i.into())) - // Standard Error: 24 - .saturating_add(Weight::from_parts(2_026, 0).saturating_mul(s.into())) + // Minimum execution time: 4_506_957_000 picoseconds. + Weight::from_parts(643_316_921, 8745) + // Standard Error: 278 + .saturating_add(Weight::from_parts(112_835, 0).saturating_mul(c.into())) + // Standard Error: 33 + .saturating_add(Weight::from_parts(1_830, 0).saturating_mul(i.into())) + // Standard Error: 33 + .saturating_add(Weight::from_parts(2_022, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(10_u64)) .saturating_add(T::DbWeight::get().writes(9_u64)) } @@ -367,12 +367,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `523` // Estimated: `6513` - // Minimum execution time: 2_122_622_000 picoseconds. - Weight::from_parts(348_487_014, 6513) + // Minimum execution time: 2_103_482_000 picoseconds. + Weight::from_parts(316_666_183, 6513) // Standard Error: 7 - .saturating_add(Weight::from_parts(1_944, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(1_933, 0).saturating_mul(i.into())) // Standard Error: 7 - .saturating_add(Weight::from_parts(1_816, 0).saturating_mul(s.into())) + .saturating_add(Weight::from_parts(1_803, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(10_u64)) .saturating_add(T::DbWeight::get().writes(7_u64)) } @@ -394,8 +394,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `820` // Estimated: `6760` - // Minimum execution time: 209_114_000 picoseconds. - Weight::from_parts(216_139_000, 6760) + // Minimum execution time: 207_530_000 picoseconds. + Weight::from_parts(217_243_000, 6760) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -412,10 +412,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 323_131_000 picoseconds. - Weight::from_parts(331_460_802, 3607) - // Standard Error: 104 - .saturating_add(Weight::from_parts(73_534, 0).saturating_mul(c.into())) + // Minimum execution time: 246_381_000 picoseconds. + Weight::from_parts(242_933_576, 3607) + // Standard Error: 100 + .saturating_add(Weight::from_parts(74_645, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -431,8 +431,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `255` // Estimated: `3720` - // Minimum execution time: 34_960_000 picoseconds. - Weight::from_parts(36_057_000, 3720) + // Minimum execution time: 35_519_000 picoseconds. + Weight::from_parts(36_813_000, 3720) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -448,8 +448,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `575` // Estimated: `8990` - // Minimum execution time: 37_375_000 picoseconds. - Weight::from_parts(38_310_000, 8990) + // Minimum execution time: 37_769_000 picoseconds. + Weight::from_parts(39_349_000, 8990) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -472,10 +472,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `860 + r * (6 ±0)` // Estimated: `6801 + r * (6 ±0)` - // Minimum execution time: 332_418_000 picoseconds. - Weight::from_parts(344_417_681, 6801) - // Standard Error: 840 - .saturating_add(Weight::from_parts(349_564, 0).saturating_mul(r.into())) + // Minimum execution time: 273_355_000 picoseconds. + Weight::from_parts(280_115_308, 6801) + // Standard Error: 662 + .saturating_add(Weight::from_parts(351_066, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -499,10 +499,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `918 + r * (240 ±0)` // Estimated: `6822 + r * (2715 ±0)` - // Minimum execution time: 336_949_000 picoseconds. - Weight::from_parts(172_018_300, 6822) - // Standard Error: 6_859 - .saturating_add(Weight::from_parts(3_732_788, 0).saturating_mul(r.into())) + // Minimum execution time: 264_066_000 picoseconds. + Weight::from_parts(103_474_597, 6822) + // Standard Error: 7_010 + .saturating_add(Weight::from_parts(3_917_988, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(3_u64)) @@ -527,10 +527,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `910 + r * (244 ±0)` // Estimated: `6826 + r * (2719 ±0)` - // Minimum execution time: 331_580_000 picoseconds. - Weight::from_parts(166_444_295, 6826) - // Standard Error: 6_323 - .saturating_add(Weight::from_parts(4_651_680, 0).saturating_mul(r.into())) + // Minimum execution time: 275_726_000 picoseconds. + Weight::from_parts(111_512_451, 6826) + // Standard Error: 6_673 + .saturating_add(Weight::from_parts(4_626_511, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(3_u64)) @@ -555,10 +555,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `867 + r * (6 ±0)` // Estimated: `6809 + r * (6 ±0)` - // Minimum execution time: 332_922_000 picoseconds. - Weight::from_parts(347_945_106, 6809) - // Standard Error: 503 - .saturating_add(Weight::from_parts(420_506, 0).saturating_mul(r.into())) + // Minimum execution time: 274_377_000 picoseconds. + Weight::from_parts(286_299_699, 6809) + // Standard Error: 521 + .saturating_add(Weight::from_parts(419_417, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -582,10 +582,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `857 + r * (3 ±0)` // Estimated: `6802 + r * (3 ±0)` - // Minimum execution time: 331_926_000 picoseconds. - Weight::from_parts(342_482_786, 6802) - // Standard Error: 382 - .saturating_add(Weight::from_parts(185_631, 0).saturating_mul(r.into())) + // Minimum execution time: 265_297_000 picoseconds. + Weight::from_parts(283_474_927, 6802) + // Standard Error: 376 + .saturating_add(Weight::from_parts(186_214, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 3).saturating_mul(r.into())) @@ -607,10 +607,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `747 + r * (3 ±0)` // Estimated: `6687 + r * (3 ±0)` - // Minimum execution time: 317_584_000 picoseconds. - Weight::from_parts(335_305_634, 6687) - // Standard Error: 413 - .saturating_add(Weight::from_parts(160_105, 0).saturating_mul(r.into())) + // Minimum execution time: 258_385_000 picoseconds. + Weight::from_parts(269_869_790, 6687) + // Standard Error: 334 + .saturating_add(Weight::from_parts(164_806, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 3).saturating_mul(r.into())) @@ -634,10 +634,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `861 + r * (6 ±0)` // Estimated: `6803 + r * (6 ±0)` - // Minimum execution time: 329_683_000 picoseconds. - Weight::from_parts(350_664_785, 6803) - // Standard Error: 1_164 - .saturating_add(Weight::from_parts(342_540, 0).saturating_mul(r.into())) + // Minimum execution time: 271_351_000 picoseconds. + Weight::from_parts(286_390_305, 6803) + // Standard Error: 628 + .saturating_add(Weight::from_parts(339_374, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -661,10 +661,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `857 + r * (6 ±0)` // Estimated: `6798 + r * (6 ±0)` - // Minimum execution time: 337_992_000 picoseconds. - Weight::from_parts(349_845_008, 6798) - // Standard Error: 2_273 - .saturating_add(Weight::from_parts(544_647, 0).saturating_mul(r.into())) + // Minimum execution time: 273_060_000 picoseconds. + Weight::from_parts(285_959_049, 6798) + // Standard Error: 813 + .saturating_add(Weight::from_parts(544_941, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -688,10 +688,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1001 + r * (6 ±0)` // Estimated: `6925 + r * (6 ±0)` - // Minimum execution time: 333_494_000 picoseconds. - Weight::from_parts(346_208_587, 6925) - // Standard Error: 2_719 - .saturating_add(Weight::from_parts(1_609_679, 0).saturating_mul(r.into())) + // Minimum execution time: 273_717_000 picoseconds. + Weight::from_parts(301_053_119, 6925) + // Standard Error: 3_314 + .saturating_add(Weight::from_parts(1_645_480, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -715,10 +715,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `871 + r * (6 ±0)` // Estimated: `6820 + r * (6 ±0)` - // Minimum execution time: 333_877_000 picoseconds. - Weight::from_parts(345_594_741, 6820) - // Standard Error: 645 - .saturating_add(Weight::from_parts(338_480, 0).saturating_mul(r.into())) + // Minimum execution time: 273_480_000 picoseconds. + Weight::from_parts(284_751_212, 6820) + // Standard Error: 501 + .saturating_add(Weight::from_parts(334_063, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -742,10 +742,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `869 + r * (6 ±0)` // Estimated: `6818 + r * (6 ±0)` - // Minimum execution time: 332_219_000 picoseconds. - Weight::from_parts(344_126_186, 6818) - // Standard Error: 511 - .saturating_add(Weight::from_parts(338_886, 0).saturating_mul(r.into())) + // Minimum execution time: 278_938_000 picoseconds. + Weight::from_parts(284_829_302, 6818) + // Standard Error: 488 + .saturating_add(Weight::from_parts(338_782, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -769,10 +769,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `866 + r * (6 ±0)` // Estimated: `6816 + r * (6 ±0)` - // Minimum execution time: 335_740_000 picoseconds. - Weight::from_parts(347_465_239, 6816) - // Standard Error: 821 - .saturating_add(Weight::from_parts(332_457, 0).saturating_mul(r.into())) + // Minimum execution time: 276_799_000 picoseconds. + Weight::from_parts(290_353_700, 6816) + // Standard Error: 675 + .saturating_add(Weight::from_parts(323_565, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -796,10 +796,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `857 + r * (6 ±0)` // Estimated: `6802 + r * (6 ±0)` - // Minimum execution time: 332_370_000 picoseconds. - Weight::from_parts(347_892_383, 6802) - // Standard Error: 551 - .saturating_add(Weight::from_parts(326_597, 0).saturating_mul(r.into())) + // Minimum execution time: 267_740_000 picoseconds. + Weight::from_parts(287_560_339, 6802) + // Standard Error: 479 + .saturating_add(Weight::from_parts(329_276, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -825,10 +825,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `931 + r * (14 ±0)` // Estimated: `6864 + r * (14 ±0)` - // Minimum execution time: 334_272_000 picoseconds. - Weight::from_parts(356_868_168, 6864) - // Standard Error: 2_385 - .saturating_add(Weight::from_parts(1_446_019, 0).saturating_mul(r.into())) + // Minimum execution time: 275_471_000 picoseconds. + Weight::from_parts(297_332_107, 6864) + // Standard Error: 2_230 + .saturating_add(Weight::from_parts(1_484_476, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 14).saturating_mul(r.into())) @@ -852,10 +852,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `859 + r * (6 ±0)` // Estimated: `6803 + r * (6 ±0)` - // Minimum execution time: 331_916_000 picoseconds. - Weight::from_parts(343_895_372, 6803) - // Standard Error: 484 - .saturating_add(Weight::from_parts(296_685, 0).saturating_mul(r.into())) + // Minimum execution time: 255_279_000 picoseconds. + Weight::from_parts(282_649_020, 6803) + // Standard Error: 429 + .saturating_add(Weight::from_parts(290_527, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -879,10 +879,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `863` // Estimated: `6803` - // Minimum execution time: 338_879_000 picoseconds. - Weight::from_parts(295_207_774, 6803) - // Standard Error: 22 - .saturating_add(Weight::from_parts(1_098, 0).saturating_mul(n.into())) + // Minimum execution time: 268_029_000 picoseconds. + Weight::from_parts(231_474_232, 6803) + // Standard Error: 23 + .saturating_add(Weight::from_parts(1_050, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -905,10 +905,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `847 + r * (45 ±0)` // Estimated: `6787 + r * (45 ±0)` - // Minimum execution time: 327_574_000 picoseconds. - Weight::from_parts(338_834_161, 6787) - // Standard Error: 865_283 - .saturating_add(Weight::from_parts(3_500_538, 0).saturating_mul(r.into())) + // Minimum execution time: 252_126_000 picoseconds. + Weight::from_parts(277_677_710, 6787) + // Standard Error: 770_704 + .saturating_add(Weight::from_parts(2_678_989, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 45).saturating_mul(r.into())) @@ -932,10 +932,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `857` // Estimated: `6810` - // Minimum execution time: 334_360_000 picoseconds. - Weight::from_parts(343_561_211, 6810) + // Minimum execution time: 271_967_000 picoseconds. + Weight::from_parts(282_988_484, 6810) // Standard Error: 0 - .saturating_add(Weight::from_parts(448, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(387, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -962,10 +962,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `889 + r * (300 ±0)` // Estimated: `6829 + r * (7725 ±0)` - // Minimum execution time: 331_544_000 picoseconds. - Weight::from_parts(343_944_959, 6829) - // Standard Error: 861_931 - .saturating_add(Weight::from_parts(128_736_840, 0).saturating_mul(r.into())) + // Minimum execution time: 257_246_000 picoseconds. + Weight::from_parts(280_196_561, 6829) + // Standard Error: 815_845 + .saturating_add(Weight::from_parts(127_831_338, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().reads((5_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(3_u64)) @@ -993,10 +993,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `938 + r * (10 ±0)` // Estimated: `6879 + r * (10 ±0)` - // Minimum execution time: 335_545_000 picoseconds. - Weight::from_parts(362_097_658, 6879) - // Standard Error: 3_732 - .saturating_add(Weight::from_parts(1_954_016, 0).saturating_mul(r.into())) + // Minimum execution time: 270_074_000 picoseconds. + Weight::from_parts(292_298_331, 6879) + // Standard Error: 2_123 + .saturating_add(Weight::from_parts(2_089_487, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 10).saturating_mul(r.into())) @@ -1020,10 +1020,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `857 + r * (10 ±0)` // Estimated: `6802 + r * (10 ±0)` - // Minimum execution time: 334_465_000 picoseconds. - Weight::from_parts(347_040_544, 6802) - // Standard Error: 3_209 - .saturating_add(Weight::from_parts(3_867_402, 0).saturating_mul(r.into())) + // Minimum execution time: 267_080_000 picoseconds. + Weight::from_parts(298_470_496, 6802) + // Standard Error: 3_004 + .saturating_add(Weight::from_parts(3_898_460, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 10).saturating_mul(r.into())) @@ -1048,12 +1048,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `876 + t * (32 ±0)` // Estimated: `6823 + t * (2508 ±0)` - // Minimum execution time: 353_043_000 picoseconds. - Weight::from_parts(350_570_845, 6823) - // Standard Error: 90_604 - .saturating_add(Weight::from_parts(3_376_302, 0).saturating_mul(t.into())) - // Standard Error: 25 - .saturating_add(Weight::from_parts(920, 0).saturating_mul(n.into())) + // Minimum execution time: 277_152_000 picoseconds. + Weight::from_parts(290_745_178, 6823) + // Standard Error: 88_577 + .saturating_add(Weight::from_parts(2_476_405, 0).saturating_mul(t.into())) + // Standard Error: 24 + .saturating_add(Weight::from_parts(702, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(t.into()))) .saturating_add(T::DbWeight::get().writes(3_u64)) @@ -1079,10 +1079,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `856 + r * (7 ±0)` // Estimated: `6800 + r * (7 ±0)` - // Minimum execution time: 174_100_000 picoseconds. - Weight::from_parts(185_023_142, 6800) - // Standard Error: 377 - .saturating_add(Weight::from_parts(244_850, 0).saturating_mul(r.into())) + // Minimum execution time: 168_782_000 picoseconds. + Weight::from_parts(179_694_331, 6800) + // Standard Error: 338 + .saturating_add(Weight::from_parts(246_541, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 7).saturating_mul(r.into())) @@ -1106,10 +1106,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `125807` // Estimated: `131749` - // Minimum execution time: 499_963_000 picoseconds. - Weight::from_parts(472_468_910, 131749) - // Standard Error: 13 - .saturating_add(Weight::from_parts(1_151, 0).saturating_mul(i.into())) + // Minimum execution time: 428_673_000 picoseconds. + Weight::from_parts(398_928_494, 131749) + // Standard Error: 12 + .saturating_add(Weight::from_parts(1_106, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -1120,10 +1120,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `924 + r * (292 ±0)` // Estimated: `922 + r * (293 ±0)` - // Minimum execution time: 334_917_000 picoseconds. - Weight::from_parts(231_957_251, 922) - // Standard Error: 11_080 - .saturating_add(Weight::from_parts(7_071_706, 0).saturating_mul(r.into())) + // Minimum execution time: 271_384_000 picoseconds. + Weight::from_parts(147_677_611, 922) + // Standard Error: 13_371 + .saturating_add(Weight::from_parts(7_085_478, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(3_u64)) @@ -1137,10 +1137,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1383` // Estimated: `1359` - // Minimum execution time: 351_914_000 picoseconds. - Weight::from_parts(395_438_997, 1359) - // Standard Error: 55 - .saturating_add(Weight::from_parts(935, 0).saturating_mul(n.into())) + // Minimum execution time: 279_587_000 picoseconds. + Weight::from_parts(335_690_918, 1359) + // Standard Error: 57 + .saturating_add(Weight::from_parts(708, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(10_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -1151,10 +1151,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1246 + n * (1 ±0)` // Estimated: `1246 + n * (1 ±0)` - // Minimum execution time: 350_334_000 picoseconds. - Weight::from_parts(360_616_821, 1246) - // Standard Error: 32 - .saturating_add(Weight::from_parts(441, 0).saturating_mul(n.into())) + // Minimum execution time: 275_572_000 picoseconds. + Weight::from_parts(300_309_544, 1246) + // Standard Error: 35 + .saturating_add(Weight::from_parts(299, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -1166,10 +1166,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `920 + r * (288 ±0)` // Estimated: `924 + r * (289 ±0)` - // Minimum execution time: 337_287_000 picoseconds. - Weight::from_parts(228_593_823, 924) - // Standard Error: 12_420 - .saturating_add(Weight::from_parts(6_871_018, 0).saturating_mul(r.into())) + // Minimum execution time: 271_875_000 picoseconds. + Weight::from_parts(153_680_437, 924) + // Standard Error: 13_050 + .saturating_add(Weight::from_parts(6_892_925, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(3_u64)) @@ -1183,10 +1183,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1242 + n * (1 ±0)` // Estimated: `1242 + n * (1 ±0)` - // Minimum execution time: 348_450_000 picoseconds. - Weight::from_parts(359_145_658, 1242) - // Standard Error: 31 - .saturating_add(Weight::from_parts(309, 0).saturating_mul(n.into())) + // Minimum execution time: 272_682_000 picoseconds. + Weight::from_parts(301_025_128, 1242) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -1198,10 +1196,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `914 + r * (296 ±0)` // Estimated: `919 + r * (297 ±0)` - // Minimum execution time: 337_918_000 picoseconds. - Weight::from_parts(252_634_761, 919) - // Standard Error: 10_301 - .saturating_add(Weight::from_parts(5_658_982, 0).saturating_mul(r.into())) + // Minimum execution time: 271_796_000 picoseconds. + Weight::from_parts(183_856_480, 919) + // Standard Error: 10_064 + .saturating_add(Weight::from_parts(5_660_636, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(3_u64)) @@ -1214,10 +1212,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1258 + n * (1 ±0)` // Estimated: `1258 + n * (1 ±0)` - // Minimum execution time: 349_865_000 picoseconds. - Weight::from_parts(364_637_455, 1258) - // Standard Error: 43 - .saturating_add(Weight::from_parts(627, 0).saturating_mul(n.into())) + // Minimum execution time: 273_102_000 picoseconds. + Weight::from_parts(297_455_692, 1258) + // Standard Error: 35 + .saturating_add(Weight::from_parts(868, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -1229,10 +1227,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `935 + r * (288 ±0)` // Estimated: `936 + r * (289 ±0)` - // Minimum execution time: 334_501_000 picoseconds. - Weight::from_parts(256_737_953, 936) - // Standard Error: 8_494 - .saturating_add(Weight::from_parts(5_452_683, 0).saturating_mul(r.into())) + // Minimum execution time: 271_323_000 picoseconds. + Weight::from_parts(190_080_834, 936) + // Standard Error: 9_143 + .saturating_add(Weight::from_parts(5_488_362, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(3_u64)) @@ -1245,10 +1243,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1245 + n * (1 ±0)` // Estimated: `1245 + n * (1 ±0)` - // Minimum execution time: 349_107_000 picoseconds. - Weight::from_parts(359_995_568, 1245) - // Standard Error: 30 - .saturating_add(Weight::from_parts(109, 0).saturating_mul(n.into())) + // Minimum execution time: 270_399_000 picoseconds. + Weight::from_parts(296_679_410, 1245) + // Standard Error: 34 + .saturating_add(Weight::from_parts(161, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -1260,10 +1258,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `908 + r * (296 ±0)` // Estimated: `915 + r * (297 ±0)` - // Minimum execution time: 333_339_000 picoseconds. - Weight::from_parts(235_980_883, 915) - // Standard Error: 11_633 - .saturating_add(Weight::from_parts(7_018_977, 0).saturating_mul(r.into())) + // Minimum execution time: 271_645_000 picoseconds. + Weight::from_parts(147_320_521, 915) + // Standard Error: 13_502 + .saturating_add(Weight::from_parts(7_074_778, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(3_u64)) @@ -1277,10 +1275,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1259 + n * (1 ±0)` // Estimated: `1259 + n * (1 ±0)` - // Minimum execution time: 353_005_000 picoseconds. - Weight::from_parts(364_276_314, 1259) - // Standard Error: 30 - .saturating_add(Weight::from_parts(759, 0).saturating_mul(n.into())) + // Minimum execution time: 280_680_000 picoseconds. + Weight::from_parts(304_043_474, 1259) + // Standard Error: 29 + .saturating_add(Weight::from_parts(644, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -1304,10 +1302,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1452 + r * (45 ±0)` // Estimated: `7349 + r * (2520 ±0)` - // Minimum execution time: 333_452_000 picoseconds. - Weight::from_parts(142_147_982, 7349) - // Standard Error: 36_619 - .saturating_add(Weight::from_parts(39_660_249, 0).saturating_mul(r.into())) + // Minimum execution time: 274_928_000 picoseconds. + Weight::from_parts(192_111_339, 7349) + // Standard Error: 42_436 + .saturating_add(Weight::from_parts(40_323_660, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(4_u64)) @@ -1333,10 +1331,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1296 + r * (276 ±0)` // Estimated: `9481 + r * (2752 ±0)` - // Minimum execution time: 337_964_000 picoseconds. - Weight::from_parts(343_202_000, 9481) - // Standard Error: 105_016 - .saturating_add(Weight::from_parts(309_034_946, 0).saturating_mul(r.into())) + // Minimum execution time: 275_293_000 picoseconds. + Weight::from_parts(278_243_000, 9481) + // Standard Error: 119_869 + .saturating_add(Weight::from_parts(245_114_905, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(11_u64)) .saturating_add(T::DbWeight::get().reads((2_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(4_u64)) @@ -1361,11 +1359,11 @@ impl WeightInfo for SubstrateWeight { fn seal_delegate_call(r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + r * (572 ±0)` - // Estimated: `6806 + r * (2633 ±10)` - // Minimum execution time: 333_861_000 picoseconds. - Weight::from_parts(337_550_000, 6806) - // Standard Error: 139_004 - .saturating_add(Weight::from_parts(306_928_468, 0).saturating_mul(r.into())) + // Estimated: `6806 + r * (2633 ±3)` + // Minimum execution time: 271_857_000 picoseconds. + Weight::from_parts(278_276_000, 6806) + // Standard Error: 152_056 + .saturating_add(Weight::from_parts(243_744_830, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(3_u64)) @@ -1392,12 +1390,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1328 + t * (310 ±0)` // Estimated: `12218 + t * (5260 ±0)` - // Minimum execution time: 538_804_000 picoseconds. - Weight::from_parts(153_868_010, 12218) - // Standard Error: 11_323_037 - .saturating_add(Weight::from_parts(350_086_502, 0).saturating_mul(t.into())) + // Minimum execution time: 463_865_000 picoseconds. + Weight::from_parts(70_396_050, 12218) + // Standard Error: 11_489_598 + .saturating_add(Weight::from_parts(359_195_747, 0).saturating_mul(t.into())) // Standard Error: 16 - .saturating_add(Weight::from_parts(1_099, 0).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(1_090, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(13_u64)) .saturating_add(T::DbWeight::get().reads((2_u64).saturating_mul(t.into()))) .saturating_add(T::DbWeight::get().writes(6_u64)) @@ -1425,10 +1423,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1383 + r * (251 ±0)` // Estimated: `7207 + r * (5202 ±0)` - // Minimum execution time: 778_214_000 picoseconds. - Weight::from_parts(786_870_000, 7207) - // Standard Error: 332_116 - .saturating_add(Weight::from_parts(457_145_100, 0).saturating_mul(r.into())) + // Minimum execution time: 660_947_000 picoseconds. + Weight::from_parts(668_346_000, 7207) + // Standard Error: 357_950 + .saturating_add(Weight::from_parts(397_202_020, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(10_u64)) .saturating_add(T::DbWeight::get().reads((6_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(6_u64)) @@ -1458,12 +1456,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1232 + t * (156 ±0)` // Estimated: `9662 + t * (2578 ±2)` - // Minimum execution time: 2_540_848_000 picoseconds. - Weight::from_parts(1_403_859_093, 9662) - // Standard Error: 18 - .saturating_add(Weight::from_parts(1_194, 0).saturating_mul(i.into())) - // Standard Error: 18 - .saturating_add(Weight::from_parts(1_277, 0).saturating_mul(s.into())) + // Minimum execution time: 2_419_720_000 picoseconds. + Weight::from_parts(1_328_224_119, 9662) + // Standard Error: 17 + .saturating_add(Weight::from_parts(1_171, 0).saturating_mul(i.into())) + // Standard Error: 17 + .saturating_add(Weight::from_parts(1_263, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(15_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(t.into()))) .saturating_add(T::DbWeight::get().writes(10_u64)) @@ -1489,10 +1487,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `856 + r * (8 ±0)` // Estimated: `6797 + r * (8 ±0)` - // Minimum execution time: 332_530_000 picoseconds. - Weight::from_parts(344_690_108, 6797) - // Standard Error: 475 - .saturating_add(Weight::from_parts(414_505, 0).saturating_mul(r.into())) + // Minimum execution time: 263_620_000 picoseconds. + Weight::from_parts(285_686_431, 6797) + // Standard Error: 605 + .saturating_add(Weight::from_parts(393_863, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 8).saturating_mul(r.into())) @@ -1516,10 +1514,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `864` // Estimated: `6804` - // Minimum execution time: 333_818_000 picoseconds. - Weight::from_parts(326_455_409, 6804) + // Minimum execution time: 271_378_000 picoseconds. + Weight::from_parts(266_737_832, 6804) // Standard Error: 1 - .saturating_add(Weight::from_parts(1_190, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_124, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -1542,10 +1540,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `858 + r * (8 ±0)` // Estimated: `6800 + r * (8 ±0)` - // Minimum execution time: 332_527_000 picoseconds. - Weight::from_parts(340_624_458, 6800) - // Standard Error: 702 - .saturating_add(Weight::from_parts(830_440, 0).saturating_mul(r.into())) + // Minimum execution time: 269_277_000 picoseconds. + Weight::from_parts(282_723_951, 6800) + // Standard Error: 577 + .saturating_add(Weight::from_parts(808_522, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 8).saturating_mul(r.into())) @@ -1569,10 +1567,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `866` // Estimated: `6808` - // Minimum execution time: 337_558_000 picoseconds. - Weight::from_parts(345_319_444, 6808) + // Minimum execution time: 254_252_000 picoseconds. + Weight::from_parts(277_589_498, 6808) // Standard Error: 1 - .saturating_add(Weight::from_parts(3_443, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(3_394, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -1595,10 +1593,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `858 + r * (8 ±0)` // Estimated: `6803 + r * (8 ±0)` - // Minimum execution time: 333_576_000 picoseconds. - Weight::from_parts(342_567_918, 6803) - // Standard Error: 517 - .saturating_add(Weight::from_parts(469_999, 0).saturating_mul(r.into())) + // Minimum execution time: 254_411_000 picoseconds. + Weight::from_parts(283_572_987, 6803) + // Standard Error: 549 + .saturating_add(Weight::from_parts(455_436, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 8).saturating_mul(r.into())) @@ -1622,10 +1620,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `866` // Estimated: `6812` - // Minimum execution time: 333_643_000 picoseconds. - Weight::from_parts(332_234_962, 6812) + // Minimum execution time: 264_371_000 picoseconds. + Weight::from_parts(269_330_603, 6812) // Standard Error: 0 - .saturating_add(Weight::from_parts(1_299, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_249, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -1648,10 +1646,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `858 + r * (8 ±0)` // Estimated: `6804 + r * (8 ±0)` - // Minimum execution time: 335_949_000 picoseconds. - Weight::from_parts(339_586_300, 6804) - // Standard Error: 712 - .saturating_add(Weight::from_parts(475_318, 0).saturating_mul(r.into())) + // Minimum execution time: 257_896_000 picoseconds. + Weight::from_parts(286_738_151, 6804) + // Standard Error: 680 + .saturating_add(Weight::from_parts(459_525, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 8).saturating_mul(r.into())) @@ -1675,10 +1673,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `866` // Estimated: `6806` - // Minimum execution time: 331_102_000 picoseconds. - Weight::from_parts(335_444_569, 6806) + // Minimum execution time: 272_952_000 picoseconds. + Weight::from_parts(271_516_361, 6806) // Standard Error: 0 - .saturating_add(Weight::from_parts(1_292, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_242, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -1701,10 +1699,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `991 + n * (1 ±0)` // Estimated: `6928 + n * (1 ±0)` - // Minimum execution time: 399_687_000 picoseconds. - Weight::from_parts(412_562_252, 6928) - // Standard Error: 11 - .saturating_add(Weight::from_parts(6_107, 0).saturating_mul(n.into())) + // Minimum execution time: 351_363_000 picoseconds. + Weight::from_parts(356_558_856, 6928) + // Standard Error: 10 + .saturating_add(Weight::from_parts(6_085, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -1726,12 +1724,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `r` is `[0, 160]`. fn seal_sr25519_verify(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `806 + r * (112 ±0)` + // Measured: `801 + r * (112 ±0)` // Estimated: `6745 + r * (112 ±0)` - // Minimum execution time: 340_992_000 picoseconds. - Weight::from_parts(385_744_518, 6745) - // Standard Error: 10_987 - .saturating_add(Weight::from_parts(56_047_105, 0).saturating_mul(r.into())) + // Minimum execution time: 261_688_000 picoseconds. + Weight::from_parts(338_043_015, 6745) + // Standard Error: 13_532 + .saturating_add(Weight::from_parts(56_420_806, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 112).saturating_mul(r.into())) @@ -1753,12 +1751,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `r` is `[0, 160]`. fn seal_ecdsa_recover(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `900 + r * (76 ±0)` + // Measured: `901 + r * (76 ±0)` // Estimated: `6795 + r * (77 ±0)` - // Minimum execution time: 335_366_000 picoseconds. - Weight::from_parts(395_811_523, 6795) - // Standard Error: 14_268 - .saturating_add(Weight::from_parts(46_194_718, 0).saturating_mul(r.into())) + // Minimum execution time: 267_401_000 picoseconds. + Weight::from_parts(345_773_771, 6795) + // Standard Error: 14_486 + .saturating_add(Weight::from_parts(46_180_739, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 77).saturating_mul(r.into())) @@ -1782,10 +1780,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `871 + r * (42 ±0)` // Estimated: `6810 + r * (42 ±0)` - // Minimum execution time: 333_708_000 picoseconds. - Weight::from_parts(375_822_414, 6810) - // Standard Error: 15_535 - .saturating_add(Weight::from_parts(38_534_300, 0).saturating_mul(r.into())) + // Minimum execution time: 277_890_000 picoseconds. + Weight::from_parts(319_211_194, 6810) + // Standard Error: 9_132 + .saturating_add(Weight::from_parts(12_128_696, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 42).saturating_mul(r.into())) @@ -1808,11 +1806,11 @@ impl WeightInfo for SubstrateWeight { fn seal_set_code_hash(r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + r * (961 ±0)` - // Estimated: `6801 + r * (3087 ±7)` - // Minimum execution time: 329_668_000 picoseconds. - Weight::from_parts(337_256_000, 6801) - // Standard Error: 64_733 - .saturating_add(Weight::from_parts(25_506_246, 0).saturating_mul(r.into())) + // Estimated: `6801 + r * (3087 ±10)` + // Minimum execution time: 259_692_000 picoseconds. + Weight::from_parts(278_327_000, 6801) + // Standard Error: 60_024 + .saturating_add(Weight::from_parts(25_758_805, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(3_u64)) @@ -1838,10 +1836,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `852 + r * (3 ±0)` // Estimated: `6802 + r * (3 ±0)` - // Minimum execution time: 332_021_000 picoseconds. - Weight::from_parts(343_753_442, 6802) - // Standard Error: 406 - .saturating_add(Weight::from_parts(178_908, 0).saturating_mul(r.into())) + // Minimum execution time: 258_907_000 picoseconds. + Weight::from_parts(285_755_890, 6802) + // Standard Error: 378 + .saturating_add(Weight::from_parts(179_649, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 3).saturating_mul(r.into())) @@ -1865,10 +1863,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `2092 + r * (39 ±0)` // Estimated: `7919 + r * (40 ±0)` - // Minimum execution time: 334_122_000 picoseconds. - Weight::from_parts(410_992_486, 7919) - // Standard Error: 1_583 - .saturating_add(Weight::from_parts(316_027, 0).saturating_mul(r.into())) + // Minimum execution time: 260_415_000 picoseconds. + Weight::from_parts(363_871_048, 7919) + // Standard Error: 2_010 + .saturating_add(Weight::from_parts(317_607, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 40).saturating_mul(r.into())) @@ -1894,10 +1892,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `855 + r * (3 ±0)` // Estimated: `6802 + r * (3 ±0)` - // Minimum execution time: 331_093_000 picoseconds. - Weight::from_parts(345_663_437, 6802) - // Standard Error: 374 - .saturating_add(Weight::from_parts(157_207, 0).saturating_mul(r.into())) + // Minimum execution time: 257_725_000 picoseconds. + Weight::from_parts(283_441_372, 6802) + // Standard Error: 371 + .saturating_add(Weight::from_parts(157_674, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) .saturating_add(Weight::from_parts(0, 3).saturating_mul(r.into())) @@ -1907,10 +1905,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_483_000 picoseconds. - Weight::from_parts(1_672_465, 0) - // Standard Error: 24 - .saturating_add(Weight::from_parts(10_591, 0).saturating_mul(r.into())) + // Minimum execution time: 1_635_000 picoseconds. + Weight::from_parts(2_990_110, 0) + // Standard Error: 31 + .saturating_add(Weight::from_parts(10_213, 0).saturating_mul(r.into())) } } @@ -1922,8 +1920,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `1627` - // Minimum execution time: 2_546_000 picoseconds. - Weight::from_parts(2_671_000, 1627) + // Minimum execution time: 2_519_000 picoseconds. + Weight::from_parts(2_660_000, 1627) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: Skipped Metadata (r:0 w:0) @@ -1933,10 +1931,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `451 + k * (69 ±0)` // Estimated: `441 + k * (70 ±0)` - // Minimum execution time: 13_398_000 picoseconds. - Weight::from_parts(13_771_000, 441) - // Standard Error: 1_033 - .saturating_add(Weight::from_parts(1_231_963, 0).saturating_mul(k.into())) + // Minimum execution time: 13_096_000 picoseconds. + Weight::from_parts(13_395_000, 441) + // Standard Error: 1_046 + .saturating_add(Weight::from_parts(1_246_238, 0).saturating_mul(k.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(k.into()))) .saturating_add(RocksDbWeight::get().writes(2_u64)) @@ -1950,10 +1948,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `211 + c * (1 ±0)` // Estimated: `6149 + c * (1 ±0)` - // Minimum execution time: 8_335_000 picoseconds. - Weight::from_parts(9_172_574, 6149) + // Minimum execution time: 8_409_000 picoseconds. + Weight::from_parts(9_006_438, 6149) // Standard Error: 1 - .saturating_add(Weight::from_parts(1_388, 0).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(1_345, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -1966,8 +1964,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `510` // Estimated: `6450` - // Minimum execution time: 17_087_000 picoseconds. - Weight::from_parts(17_840_000, 6450) + // Minimum execution time: 16_962_000 picoseconds. + Weight::from_parts(17_716_000, 6450) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1980,10 +1978,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `171 + k * (1 ±0)` // Estimated: `3635 + k * (1 ±0)` - // Minimum execution time: 4_016_000 picoseconds. - Weight::from_parts(655_916, 3635) - // Standard Error: 1_202 - .saturating_add(Weight::from_parts(1_158_002, 0).saturating_mul(k.into())) + // Minimum execution time: 3_763_000 picoseconds. + Weight::from_parts(2_401_625, 3635) + // Standard Error: 2_827 + .saturating_add(Weight::from_parts(1_201_671, 0).saturating_mul(k.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(k.into()))) @@ -2002,10 +2000,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `325 + c * (1 ±0)` // Estimated: `6263 + c * (1 ±0)` - // Minimum execution time: 17_500_000 picoseconds. - Weight::from_parts(17_675_710, 6263) + // Minimum execution time: 17_490_000 picoseconds. + Weight::from_parts(17_712_278, 6263) // Standard Error: 0 - .saturating_add(Weight::from_parts(488, 0).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(427, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -2016,8 +2014,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `1627` - // Minimum execution time: 3_278_000 picoseconds. - Weight::from_parts(3_501_000, 1627) + // Minimum execution time: 3_282_000 picoseconds. + Weight::from_parts(3_536_000, 1627) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -2029,8 +2027,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `166` // Estimated: `3631` - // Minimum execution time: 12_489_000 picoseconds. - Weight::from_parts(12_850_000, 3631) + // Minimum execution time: 12_973_000 picoseconds. + Weight::from_parts(13_366_000, 3631) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -2040,8 +2038,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 4_788_000 picoseconds. - Weight::from_parts(5_099_000, 3607) + // Minimum execution time: 4_764_000 picoseconds. + Weight::from_parts(5_000_000, 3607) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: unknown `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) @@ -2052,8 +2050,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `167` // Estimated: `3632` - // Minimum execution time: 6_850_000 picoseconds. - Weight::from_parts(7_146_000, 3632) + // Minimum execution time: 6_616_000 picoseconds. + Weight::from_parts(6_935_000, 3632) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// Storage: unknown `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) @@ -2064,8 +2062,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 7_078_000 picoseconds. - Weight::from_parts(7_452_000, 3607) + // Minimum execution time: 6_953_000 picoseconds. + Weight::from_parts(7_440_000, 3607) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -2088,10 +2086,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `786` // Estimated: `6735 + c * (1 ±0)` - // Minimum execution time: 366_103_000 picoseconds. - Weight::from_parts(335_256_535, 6735) - // Standard Error: 81 - .saturating_add(Weight::from_parts(38_395, 0).saturating_mul(c.into())) + // Minimum execution time: 302_714_000 picoseconds. + Weight::from_parts(271_320_595, 6735) + // Standard Error: 72 + .saturating_add(Weight::from_parts(38_474, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -2100,6 +2098,8 @@ impl WeightInfo for () { /// Proof: Contracts MigrationInProgress (max_values: Some(1), max_size: Some(1026), added: 1521, mode: Measured) /// Storage: Contracts CodeInfoOf (r:1 w:1) /// Proof: Contracts CodeInfoOf (max_values: None, max_size: Some(89), added: 2564, mode: Measured) + /// Storage: System EventTopics (r:3 w:3) + /// Proof Skipped: System EventTopics (max_values: None, max_size: None, mode: Measured) /// Storage: Contracts Nonce (r:1 w:1) /// Proof: Contracts Nonce (max_values: Some(1), max_size: Some(8), added: 503, mode: Measured) /// Storage: Contracts ContractInfoOf (r:1 w:1) @@ -2108,8 +2108,6 @@ impl WeightInfo for () { /// Proof: Timestamp Now (max_values: Some(1), max_size: Some(8), added: 503, mode: Measured) /// Storage: System Account (r:2 w:2) /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: Measured) - /// Storage: System EventTopics (r:3 w:3) - /// Proof Skipped: System EventTopics (max_values: None, max_size: None, mode: Measured) /// Storage: Contracts PristineCode (r:0 w:1) /// Proof: Contracts PristineCode (max_values: None, max_size: Some(125988), added: 128463, mode: Measured) /// The range of component `c` is `[0, 125952]`. @@ -2119,14 +2117,14 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `303` // Estimated: `8745` - // Minimum execution time: 4_289_681_000 picoseconds. - Weight::from_parts(331_057_751, 8745) - // Standard Error: 206 - .saturating_add(Weight::from_parts(76_366, 0).saturating_mul(c.into())) - // Standard Error: 24 - .saturating_add(Weight::from_parts(1_938, 0).saturating_mul(i.into())) - // Standard Error: 24 - .saturating_add(Weight::from_parts(2_026, 0).saturating_mul(s.into())) + // Minimum execution time: 4_506_957_000 picoseconds. + Weight::from_parts(643_316_921, 8745) + // Standard Error: 278 + .saturating_add(Weight::from_parts(112_835, 0).saturating_mul(c.into())) + // Standard Error: 33 + .saturating_add(Weight::from_parts(1_830, 0).saturating_mul(i.into())) + // Standard Error: 33 + .saturating_add(Weight::from_parts(2_022, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(10_u64)) .saturating_add(RocksDbWeight::get().writes(9_u64)) } @@ -2152,12 +2150,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `523` // Estimated: `6513` - // Minimum execution time: 2_122_622_000 picoseconds. - Weight::from_parts(348_487_014, 6513) + // Minimum execution time: 2_103_482_000 picoseconds. + Weight::from_parts(316_666_183, 6513) // Standard Error: 7 - .saturating_add(Weight::from_parts(1_944, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(1_933, 0).saturating_mul(i.into())) // Standard Error: 7 - .saturating_add(Weight::from_parts(1_816, 0).saturating_mul(s.into())) + .saturating_add(Weight::from_parts(1_803, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(10_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } @@ -2179,8 +2177,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `820` // Estimated: `6760` - // Minimum execution time: 209_114_000 picoseconds. - Weight::from_parts(216_139_000, 6760) + // Minimum execution time: 207_530_000 picoseconds. + Weight::from_parts(217_243_000, 6760) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -2197,10 +2195,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 323_131_000 picoseconds. - Weight::from_parts(331_460_802, 3607) - // Standard Error: 104 - .saturating_add(Weight::from_parts(73_534, 0).saturating_mul(c.into())) + // Minimum execution time: 246_381_000 picoseconds. + Weight::from_parts(242_933_576, 3607) + // Standard Error: 100 + .saturating_add(Weight::from_parts(74_645, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -2216,8 +2214,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `255` // Estimated: `3720` - // Minimum execution time: 34_960_000 picoseconds. - Weight::from_parts(36_057_000, 3720) + // Minimum execution time: 35_519_000 picoseconds. + Weight::from_parts(36_813_000, 3720) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -2233,8 +2231,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `575` // Estimated: `8990` - // Minimum execution time: 37_375_000 picoseconds. - Weight::from_parts(38_310_000, 8990) + // Minimum execution time: 37_769_000 picoseconds. + Weight::from_parts(39_349_000, 8990) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -2257,10 +2255,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `860 + r * (6 ±0)` // Estimated: `6801 + r * (6 ±0)` - // Minimum execution time: 332_418_000 picoseconds. - Weight::from_parts(344_417_681, 6801) - // Standard Error: 840 - .saturating_add(Weight::from_parts(349_564, 0).saturating_mul(r.into())) + // Minimum execution time: 273_355_000 picoseconds. + Weight::from_parts(280_115_308, 6801) + // Standard Error: 662 + .saturating_add(Weight::from_parts(351_066, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -2284,10 +2282,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `918 + r * (240 ±0)` // Estimated: `6822 + r * (2715 ±0)` - // Minimum execution time: 336_949_000 picoseconds. - Weight::from_parts(172_018_300, 6822) - // Standard Error: 6_859 - .saturating_add(Weight::from_parts(3_732_788, 0).saturating_mul(r.into())) + // Minimum execution time: 264_066_000 picoseconds. + Weight::from_parts(103_474_597, 6822) + // Standard Error: 7_010 + .saturating_add(Weight::from_parts(3_917_988, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(3_u64)) @@ -2312,10 +2310,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `910 + r * (244 ±0)` // Estimated: `6826 + r * (2719 ±0)` - // Minimum execution time: 331_580_000 picoseconds. - Weight::from_parts(166_444_295, 6826) - // Standard Error: 6_323 - .saturating_add(Weight::from_parts(4_651_680, 0).saturating_mul(r.into())) + // Minimum execution time: 275_726_000 picoseconds. + Weight::from_parts(111_512_451, 6826) + // Standard Error: 6_673 + .saturating_add(Weight::from_parts(4_626_511, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(3_u64)) @@ -2340,10 +2338,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `867 + r * (6 ±0)` // Estimated: `6809 + r * (6 ±0)` - // Minimum execution time: 332_922_000 picoseconds. - Weight::from_parts(347_945_106, 6809) - // Standard Error: 503 - .saturating_add(Weight::from_parts(420_506, 0).saturating_mul(r.into())) + // Minimum execution time: 274_377_000 picoseconds. + Weight::from_parts(286_299_699, 6809) + // Standard Error: 521 + .saturating_add(Weight::from_parts(419_417, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -2367,10 +2365,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `857 + r * (3 ±0)` // Estimated: `6802 + r * (3 ±0)` - // Minimum execution time: 331_926_000 picoseconds. - Weight::from_parts(342_482_786, 6802) - // Standard Error: 382 - .saturating_add(Weight::from_parts(185_631, 0).saturating_mul(r.into())) + // Minimum execution time: 265_297_000 picoseconds. + Weight::from_parts(283_474_927, 6802) + // Standard Error: 376 + .saturating_add(Weight::from_parts(186_214, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 3).saturating_mul(r.into())) @@ -2392,10 +2390,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `747 + r * (3 ±0)` // Estimated: `6687 + r * (3 ±0)` - // Minimum execution time: 317_584_000 picoseconds. - Weight::from_parts(335_305_634, 6687) - // Standard Error: 413 - .saturating_add(Weight::from_parts(160_105, 0).saturating_mul(r.into())) + // Minimum execution time: 258_385_000 picoseconds. + Weight::from_parts(269_869_790, 6687) + // Standard Error: 334 + .saturating_add(Weight::from_parts(164_806, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 3).saturating_mul(r.into())) @@ -2419,10 +2417,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `861 + r * (6 ±0)` // Estimated: `6803 + r * (6 ±0)` - // Minimum execution time: 329_683_000 picoseconds. - Weight::from_parts(350_664_785, 6803) - // Standard Error: 1_164 - .saturating_add(Weight::from_parts(342_540, 0).saturating_mul(r.into())) + // Minimum execution time: 271_351_000 picoseconds. + Weight::from_parts(286_390_305, 6803) + // Standard Error: 628 + .saturating_add(Weight::from_parts(339_374, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -2446,10 +2444,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `857 + r * (6 ±0)` // Estimated: `6798 + r * (6 ±0)` - // Minimum execution time: 337_992_000 picoseconds. - Weight::from_parts(349_845_008, 6798) - // Standard Error: 2_273 - .saturating_add(Weight::from_parts(544_647, 0).saturating_mul(r.into())) + // Minimum execution time: 273_060_000 picoseconds. + Weight::from_parts(285_959_049, 6798) + // Standard Error: 813 + .saturating_add(Weight::from_parts(544_941, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -2473,10 +2471,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1001 + r * (6 ±0)` // Estimated: `6925 + r * (6 ±0)` - // Minimum execution time: 333_494_000 picoseconds. - Weight::from_parts(346_208_587, 6925) - // Standard Error: 2_719 - .saturating_add(Weight::from_parts(1_609_679, 0).saturating_mul(r.into())) + // Minimum execution time: 273_717_000 picoseconds. + Weight::from_parts(301_053_119, 6925) + // Standard Error: 3_314 + .saturating_add(Weight::from_parts(1_645_480, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -2500,10 +2498,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `871 + r * (6 ±0)` // Estimated: `6820 + r * (6 ±0)` - // Minimum execution time: 333_877_000 picoseconds. - Weight::from_parts(345_594_741, 6820) - // Standard Error: 645 - .saturating_add(Weight::from_parts(338_480, 0).saturating_mul(r.into())) + // Minimum execution time: 273_480_000 picoseconds. + Weight::from_parts(284_751_212, 6820) + // Standard Error: 501 + .saturating_add(Weight::from_parts(334_063, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -2527,10 +2525,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `869 + r * (6 ±0)` // Estimated: `6818 + r * (6 ±0)` - // Minimum execution time: 332_219_000 picoseconds. - Weight::from_parts(344_126_186, 6818) - // Standard Error: 511 - .saturating_add(Weight::from_parts(338_886, 0).saturating_mul(r.into())) + // Minimum execution time: 278_938_000 picoseconds. + Weight::from_parts(284_829_302, 6818) + // Standard Error: 488 + .saturating_add(Weight::from_parts(338_782, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -2554,10 +2552,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `866 + r * (6 ±0)` // Estimated: `6816 + r * (6 ±0)` - // Minimum execution time: 335_740_000 picoseconds. - Weight::from_parts(347_465_239, 6816) - // Standard Error: 821 - .saturating_add(Weight::from_parts(332_457, 0).saturating_mul(r.into())) + // Minimum execution time: 276_799_000 picoseconds. + Weight::from_parts(290_353_700, 6816) + // Standard Error: 675 + .saturating_add(Weight::from_parts(323_565, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -2581,10 +2579,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `857 + r * (6 ±0)` // Estimated: `6802 + r * (6 ±0)` - // Minimum execution time: 332_370_000 picoseconds. - Weight::from_parts(347_892_383, 6802) - // Standard Error: 551 - .saturating_add(Weight::from_parts(326_597, 0).saturating_mul(r.into())) + // Minimum execution time: 267_740_000 picoseconds. + Weight::from_parts(287_560_339, 6802) + // Standard Error: 479 + .saturating_add(Weight::from_parts(329_276, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -2610,10 +2608,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `931 + r * (14 ±0)` // Estimated: `6864 + r * (14 ±0)` - // Minimum execution time: 334_272_000 picoseconds. - Weight::from_parts(356_868_168, 6864) - // Standard Error: 2_385 - .saturating_add(Weight::from_parts(1_446_019, 0).saturating_mul(r.into())) + // Minimum execution time: 275_471_000 picoseconds. + Weight::from_parts(297_332_107, 6864) + // Standard Error: 2_230 + .saturating_add(Weight::from_parts(1_484_476, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 14).saturating_mul(r.into())) @@ -2637,10 +2635,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `859 + r * (6 ±0)` // Estimated: `6803 + r * (6 ±0)` - // Minimum execution time: 331_916_000 picoseconds. - Weight::from_parts(343_895_372, 6803) - // Standard Error: 484 - .saturating_add(Weight::from_parts(296_685, 0).saturating_mul(r.into())) + // Minimum execution time: 255_279_000 picoseconds. + Weight::from_parts(282_649_020, 6803) + // Standard Error: 429 + .saturating_add(Weight::from_parts(290_527, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 6).saturating_mul(r.into())) @@ -2664,10 +2662,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `863` // Estimated: `6803` - // Minimum execution time: 338_879_000 picoseconds. - Weight::from_parts(295_207_774, 6803) - // Standard Error: 22 - .saturating_add(Weight::from_parts(1_098, 0).saturating_mul(n.into())) + // Minimum execution time: 268_029_000 picoseconds. + Weight::from_parts(231_474_232, 6803) + // Standard Error: 23 + .saturating_add(Weight::from_parts(1_050, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -2690,10 +2688,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `847 + r * (45 ±0)` // Estimated: `6787 + r * (45 ±0)` - // Minimum execution time: 327_574_000 picoseconds. - Weight::from_parts(338_834_161, 6787) - // Standard Error: 865_283 - .saturating_add(Weight::from_parts(3_500_538, 0).saturating_mul(r.into())) + // Minimum execution time: 252_126_000 picoseconds. + Weight::from_parts(277_677_710, 6787) + // Standard Error: 770_704 + .saturating_add(Weight::from_parts(2_678_989, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 45).saturating_mul(r.into())) @@ -2717,10 +2715,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `857` // Estimated: `6810` - // Minimum execution time: 334_360_000 picoseconds. - Weight::from_parts(343_561_211, 6810) + // Minimum execution time: 271_967_000 picoseconds. + Weight::from_parts(282_988_484, 6810) // Standard Error: 0 - .saturating_add(Weight::from_parts(448, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(387, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -2747,10 +2745,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `889 + r * (300 ±0)` // Estimated: `6829 + r * (7725 ±0)` - // Minimum execution time: 331_544_000 picoseconds. - Weight::from_parts(343_944_959, 6829) - // Standard Error: 861_931 - .saturating_add(Weight::from_parts(128_736_840, 0).saturating_mul(r.into())) + // Minimum execution time: 257_246_000 picoseconds. + Weight::from_parts(280_196_561, 6829) + // Standard Error: 815_845 + .saturating_add(Weight::from_parts(127_831_338, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().reads((5_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(3_u64)) @@ -2778,10 +2776,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `938 + r * (10 ±0)` // Estimated: `6879 + r * (10 ±0)` - // Minimum execution time: 335_545_000 picoseconds. - Weight::from_parts(362_097_658, 6879) - // Standard Error: 3_732 - .saturating_add(Weight::from_parts(1_954_016, 0).saturating_mul(r.into())) + // Minimum execution time: 270_074_000 picoseconds. + Weight::from_parts(292_298_331, 6879) + // Standard Error: 2_123 + .saturating_add(Weight::from_parts(2_089_487, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 10).saturating_mul(r.into())) @@ -2805,10 +2803,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `857 + r * (10 ±0)` // Estimated: `6802 + r * (10 ±0)` - // Minimum execution time: 334_465_000 picoseconds. - Weight::from_parts(347_040_544, 6802) - // Standard Error: 3_209 - .saturating_add(Weight::from_parts(3_867_402, 0).saturating_mul(r.into())) + // Minimum execution time: 267_080_000 picoseconds. + Weight::from_parts(298_470_496, 6802) + // Standard Error: 3_004 + .saturating_add(Weight::from_parts(3_898_460, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 10).saturating_mul(r.into())) @@ -2833,12 +2831,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `876 + t * (32 ±0)` // Estimated: `6823 + t * (2508 ±0)` - // Minimum execution time: 353_043_000 picoseconds. - Weight::from_parts(350_570_845, 6823) - // Standard Error: 90_604 - .saturating_add(Weight::from_parts(3_376_302, 0).saturating_mul(t.into())) - // Standard Error: 25 - .saturating_add(Weight::from_parts(920, 0).saturating_mul(n.into())) + // Minimum execution time: 277_152_000 picoseconds. + Weight::from_parts(290_745_178, 6823) + // Standard Error: 88_577 + .saturating_add(Weight::from_parts(2_476_405, 0).saturating_mul(t.into())) + // Standard Error: 24 + .saturating_add(Weight::from_parts(702, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(t.into()))) .saturating_add(RocksDbWeight::get().writes(3_u64)) @@ -2864,10 +2862,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `856 + r * (7 ±0)` // Estimated: `6800 + r * (7 ±0)` - // Minimum execution time: 174_100_000 picoseconds. - Weight::from_parts(185_023_142, 6800) - // Standard Error: 377 - .saturating_add(Weight::from_parts(244_850, 0).saturating_mul(r.into())) + // Minimum execution time: 168_782_000 picoseconds. + Weight::from_parts(179_694_331, 6800) + // Standard Error: 338 + .saturating_add(Weight::from_parts(246_541, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 7).saturating_mul(r.into())) @@ -2891,10 +2889,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `125807` // Estimated: `131749` - // Minimum execution time: 499_963_000 picoseconds. - Weight::from_parts(472_468_910, 131749) - // Standard Error: 13 - .saturating_add(Weight::from_parts(1_151, 0).saturating_mul(i.into())) + // Minimum execution time: 428_673_000 picoseconds. + Weight::from_parts(398_928_494, 131749) + // Standard Error: 12 + .saturating_add(Weight::from_parts(1_106, 0).saturating_mul(i.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -2905,10 +2903,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `924 + r * (292 ±0)` // Estimated: `922 + r * (293 ±0)` - // Minimum execution time: 334_917_000 picoseconds. - Weight::from_parts(231_957_251, 922) - // Standard Error: 11_080 - .saturating_add(Weight::from_parts(7_071_706, 0).saturating_mul(r.into())) + // Minimum execution time: 271_384_000 picoseconds. + Weight::from_parts(147_677_611, 922) + // Standard Error: 13_371 + .saturating_add(Weight::from_parts(7_085_478, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(3_u64)) @@ -2922,10 +2920,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1383` // Estimated: `1359` - // Minimum execution time: 351_914_000 picoseconds. - Weight::from_parts(395_438_997, 1359) - // Standard Error: 55 - .saturating_add(Weight::from_parts(935, 0).saturating_mul(n.into())) + // Minimum execution time: 279_587_000 picoseconds. + Weight::from_parts(335_690_918, 1359) + // Standard Error: 57 + .saturating_add(Weight::from_parts(708, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(10_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -2936,10 +2934,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1246 + n * (1 ±0)` // Estimated: `1246 + n * (1 ±0)` - // Minimum execution time: 350_334_000 picoseconds. - Weight::from_parts(360_616_821, 1246) - // Standard Error: 32 - .saturating_add(Weight::from_parts(441, 0).saturating_mul(n.into())) + // Minimum execution time: 275_572_000 picoseconds. + Weight::from_parts(300_309_544, 1246) + // Standard Error: 35 + .saturating_add(Weight::from_parts(299, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -2951,10 +2949,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `920 + r * (288 ±0)` // Estimated: `924 + r * (289 ±0)` - // Minimum execution time: 337_287_000 picoseconds. - Weight::from_parts(228_593_823, 924) - // Standard Error: 12_420 - .saturating_add(Weight::from_parts(6_871_018, 0).saturating_mul(r.into())) + // Minimum execution time: 271_875_000 picoseconds. + Weight::from_parts(153_680_437, 924) + // Standard Error: 13_050 + .saturating_add(Weight::from_parts(6_892_925, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(3_u64)) @@ -2968,10 +2966,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1242 + n * (1 ±0)` // Estimated: `1242 + n * (1 ±0)` - // Minimum execution time: 348_450_000 picoseconds. - Weight::from_parts(359_145_658, 1242) - // Standard Error: 31 - .saturating_add(Weight::from_parts(309, 0).saturating_mul(n.into())) + // Minimum execution time: 272_682_000 picoseconds. + Weight::from_parts(301_025_128, 1242) .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -2983,10 +2979,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `914 + r * (296 ±0)` // Estimated: `919 + r * (297 ±0)` - // Minimum execution time: 337_918_000 picoseconds. - Weight::from_parts(252_634_761, 919) - // Standard Error: 10_301 - .saturating_add(Weight::from_parts(5_658_982, 0).saturating_mul(r.into())) + // Minimum execution time: 271_796_000 picoseconds. + Weight::from_parts(183_856_480, 919) + // Standard Error: 10_064 + .saturating_add(Weight::from_parts(5_660_636, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(3_u64)) @@ -2999,10 +2995,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1258 + n * (1 ±0)` // Estimated: `1258 + n * (1 ±0)` - // Minimum execution time: 349_865_000 picoseconds. - Weight::from_parts(364_637_455, 1258) - // Standard Error: 43 - .saturating_add(Weight::from_parts(627, 0).saturating_mul(n.into())) + // Minimum execution time: 273_102_000 picoseconds. + Weight::from_parts(297_455_692, 1258) + // Standard Error: 35 + .saturating_add(Weight::from_parts(868, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -3014,10 +3010,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `935 + r * (288 ±0)` // Estimated: `936 + r * (289 ±0)` - // Minimum execution time: 334_501_000 picoseconds. - Weight::from_parts(256_737_953, 936) - // Standard Error: 8_494 - .saturating_add(Weight::from_parts(5_452_683, 0).saturating_mul(r.into())) + // Minimum execution time: 271_323_000 picoseconds. + Weight::from_parts(190_080_834, 936) + // Standard Error: 9_143 + .saturating_add(Weight::from_parts(5_488_362, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(3_u64)) @@ -3030,10 +3026,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1245 + n * (1 ±0)` // Estimated: `1245 + n * (1 ±0)` - // Minimum execution time: 349_107_000 picoseconds. - Weight::from_parts(359_995_568, 1245) - // Standard Error: 30 - .saturating_add(Weight::from_parts(109, 0).saturating_mul(n.into())) + // Minimum execution time: 270_399_000 picoseconds. + Weight::from_parts(296_679_410, 1245) + // Standard Error: 34 + .saturating_add(Weight::from_parts(161, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -3045,10 +3041,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `908 + r * (296 ±0)` // Estimated: `915 + r * (297 ±0)` - // Minimum execution time: 333_339_000 picoseconds. - Weight::from_parts(235_980_883, 915) - // Standard Error: 11_633 - .saturating_add(Weight::from_parts(7_018_977, 0).saturating_mul(r.into())) + // Minimum execution time: 271_645_000 picoseconds. + Weight::from_parts(147_320_521, 915) + // Standard Error: 13_502 + .saturating_add(Weight::from_parts(7_074_778, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(3_u64)) @@ -3062,10 +3058,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1259 + n * (1 ±0)` // Estimated: `1259 + n * (1 ±0)` - // Minimum execution time: 353_005_000 picoseconds. - Weight::from_parts(364_276_314, 1259) - // Standard Error: 30 - .saturating_add(Weight::from_parts(759, 0).saturating_mul(n.into())) + // Minimum execution time: 280_680_000 picoseconds. + Weight::from_parts(304_043_474, 1259) + // Standard Error: 29 + .saturating_add(Weight::from_parts(644, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -3089,10 +3085,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1452 + r * (45 ±0)` // Estimated: `7349 + r * (2520 ±0)` - // Minimum execution time: 333_452_000 picoseconds. - Weight::from_parts(142_147_982, 7349) - // Standard Error: 36_619 - .saturating_add(Weight::from_parts(39_660_249, 0).saturating_mul(r.into())) + // Minimum execution time: 274_928_000 picoseconds. + Weight::from_parts(192_111_339, 7349) + // Standard Error: 42_436 + .saturating_add(Weight::from_parts(40_323_660, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(4_u64)) @@ -3118,10 +3114,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1296 + r * (276 ±0)` // Estimated: `9481 + r * (2752 ±0)` - // Minimum execution time: 337_964_000 picoseconds. - Weight::from_parts(343_202_000, 9481) - // Standard Error: 105_016 - .saturating_add(Weight::from_parts(309_034_946, 0).saturating_mul(r.into())) + // Minimum execution time: 275_293_000 picoseconds. + Weight::from_parts(278_243_000, 9481) + // Standard Error: 119_869 + .saturating_add(Weight::from_parts(245_114_905, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(11_u64)) .saturating_add(RocksDbWeight::get().reads((2_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(4_u64)) @@ -3146,11 +3142,11 @@ impl WeightInfo for () { fn seal_delegate_call(r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + r * (572 ±0)` - // Estimated: `6806 + r * (2633 ±10)` - // Minimum execution time: 333_861_000 picoseconds. - Weight::from_parts(337_550_000, 6806) - // Standard Error: 139_004 - .saturating_add(Weight::from_parts(306_928_468, 0).saturating_mul(r.into())) + // Estimated: `6806 + r * (2633 ±3)` + // Minimum execution time: 271_857_000 picoseconds. + Weight::from_parts(278_276_000, 6806) + // Standard Error: 152_056 + .saturating_add(Weight::from_parts(243_744_830, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().reads((3_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(3_u64)) @@ -3177,12 +3173,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1328 + t * (310 ±0)` // Estimated: `12218 + t * (5260 ±0)` - // Minimum execution time: 538_804_000 picoseconds. - Weight::from_parts(153_868_010, 12218) - // Standard Error: 11_323_037 - .saturating_add(Weight::from_parts(350_086_502, 0).saturating_mul(t.into())) + // Minimum execution time: 463_865_000 picoseconds. + Weight::from_parts(70_396_050, 12218) + // Standard Error: 11_489_598 + .saturating_add(Weight::from_parts(359_195_747, 0).saturating_mul(t.into())) // Standard Error: 16 - .saturating_add(Weight::from_parts(1_099, 0).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(1_090, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(13_u64)) .saturating_add(RocksDbWeight::get().reads((2_u64).saturating_mul(t.into()))) .saturating_add(RocksDbWeight::get().writes(6_u64)) @@ -3210,10 +3206,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1383 + r * (251 ±0)` // Estimated: `7207 + r * (5202 ±0)` - // Minimum execution time: 778_214_000 picoseconds. - Weight::from_parts(786_870_000, 7207) - // Standard Error: 332_116 - .saturating_add(Weight::from_parts(457_145_100, 0).saturating_mul(r.into())) + // Minimum execution time: 660_947_000 picoseconds. + Weight::from_parts(668_346_000, 7207) + // Standard Error: 357_950 + .saturating_add(Weight::from_parts(397_202_020, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(10_u64)) .saturating_add(RocksDbWeight::get().reads((6_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(6_u64)) @@ -3243,12 +3239,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1232 + t * (156 ±0)` // Estimated: `9662 + t * (2578 ±2)` - // Minimum execution time: 2_540_848_000 picoseconds. - Weight::from_parts(1_403_859_093, 9662) - // Standard Error: 18 - .saturating_add(Weight::from_parts(1_194, 0).saturating_mul(i.into())) - // Standard Error: 18 - .saturating_add(Weight::from_parts(1_277, 0).saturating_mul(s.into())) + // Minimum execution time: 2_419_720_000 picoseconds. + Weight::from_parts(1_328_224_119, 9662) + // Standard Error: 17 + .saturating_add(Weight::from_parts(1_171, 0).saturating_mul(i.into())) + // Standard Error: 17 + .saturating_add(Weight::from_parts(1_263, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(15_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(t.into()))) .saturating_add(RocksDbWeight::get().writes(10_u64)) @@ -3274,10 +3270,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `856 + r * (8 ±0)` // Estimated: `6797 + r * (8 ±0)` - // Minimum execution time: 332_530_000 picoseconds. - Weight::from_parts(344_690_108, 6797) - // Standard Error: 475 - .saturating_add(Weight::from_parts(414_505, 0).saturating_mul(r.into())) + // Minimum execution time: 263_620_000 picoseconds. + Weight::from_parts(285_686_431, 6797) + // Standard Error: 605 + .saturating_add(Weight::from_parts(393_863, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 8).saturating_mul(r.into())) @@ -3301,10 +3297,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `864` // Estimated: `6804` - // Minimum execution time: 333_818_000 picoseconds. - Weight::from_parts(326_455_409, 6804) + // Minimum execution time: 271_378_000 picoseconds. + Weight::from_parts(266_737_832, 6804) // Standard Error: 1 - .saturating_add(Weight::from_parts(1_190, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_124, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -3327,10 +3323,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `858 + r * (8 ±0)` // Estimated: `6800 + r * (8 ±0)` - // Minimum execution time: 332_527_000 picoseconds. - Weight::from_parts(340_624_458, 6800) - // Standard Error: 702 - .saturating_add(Weight::from_parts(830_440, 0).saturating_mul(r.into())) + // Minimum execution time: 269_277_000 picoseconds. + Weight::from_parts(282_723_951, 6800) + // Standard Error: 577 + .saturating_add(Weight::from_parts(808_522, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 8).saturating_mul(r.into())) @@ -3354,10 +3350,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `866` // Estimated: `6808` - // Minimum execution time: 337_558_000 picoseconds. - Weight::from_parts(345_319_444, 6808) + // Minimum execution time: 254_252_000 picoseconds. + Weight::from_parts(277_589_498, 6808) // Standard Error: 1 - .saturating_add(Weight::from_parts(3_443, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(3_394, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -3380,10 +3376,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `858 + r * (8 ±0)` // Estimated: `6803 + r * (8 ±0)` - // Minimum execution time: 333_576_000 picoseconds. - Weight::from_parts(342_567_918, 6803) - // Standard Error: 517 - .saturating_add(Weight::from_parts(469_999, 0).saturating_mul(r.into())) + // Minimum execution time: 254_411_000 picoseconds. + Weight::from_parts(283_572_987, 6803) + // Standard Error: 549 + .saturating_add(Weight::from_parts(455_436, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 8).saturating_mul(r.into())) @@ -3407,10 +3403,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `866` // Estimated: `6812` - // Minimum execution time: 333_643_000 picoseconds. - Weight::from_parts(332_234_962, 6812) + // Minimum execution time: 264_371_000 picoseconds. + Weight::from_parts(269_330_603, 6812) // Standard Error: 0 - .saturating_add(Weight::from_parts(1_299, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_249, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -3433,10 +3429,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `858 + r * (8 ±0)` // Estimated: `6804 + r * (8 ±0)` - // Minimum execution time: 335_949_000 picoseconds. - Weight::from_parts(339_586_300, 6804) - // Standard Error: 712 - .saturating_add(Weight::from_parts(475_318, 0).saturating_mul(r.into())) + // Minimum execution time: 257_896_000 picoseconds. + Weight::from_parts(286_738_151, 6804) + // Standard Error: 680 + .saturating_add(Weight::from_parts(459_525, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 8).saturating_mul(r.into())) @@ -3460,10 +3456,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `866` // Estimated: `6806` - // Minimum execution time: 331_102_000 picoseconds. - Weight::from_parts(335_444_569, 6806) + // Minimum execution time: 272_952_000 picoseconds. + Weight::from_parts(271_516_361, 6806) // Standard Error: 0 - .saturating_add(Weight::from_parts(1_292, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_242, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -3486,10 +3482,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `991 + n * (1 ±0)` // Estimated: `6928 + n * (1 ±0)` - // Minimum execution time: 399_687_000 picoseconds. - Weight::from_parts(412_562_252, 6928) - // Standard Error: 11 - .saturating_add(Weight::from_parts(6_107, 0).saturating_mul(n.into())) + // Minimum execution time: 351_363_000 picoseconds. + Weight::from_parts(356_558_856, 6928) + // Standard Error: 10 + .saturating_add(Weight::from_parts(6_085, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -3511,12 +3507,12 @@ impl WeightInfo for () { /// The range of component `r` is `[0, 160]`. fn seal_sr25519_verify(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `806 + r * (112 ±0)` + // Measured: `801 + r * (112 ±0)` // Estimated: `6745 + r * (112 ±0)` - // Minimum execution time: 340_992_000 picoseconds. - Weight::from_parts(385_744_518, 6745) - // Standard Error: 10_987 - .saturating_add(Weight::from_parts(56_047_105, 0).saturating_mul(r.into())) + // Minimum execution time: 261_688_000 picoseconds. + Weight::from_parts(338_043_015, 6745) + // Standard Error: 13_532 + .saturating_add(Weight::from_parts(56_420_806, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 112).saturating_mul(r.into())) @@ -3538,12 +3534,12 @@ impl WeightInfo for () { /// The range of component `r` is `[0, 160]`. fn seal_ecdsa_recover(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `900 + r * (76 ±0)` + // Measured: `901 + r * (76 ±0)` // Estimated: `6795 + r * (77 ±0)` - // Minimum execution time: 335_366_000 picoseconds. - Weight::from_parts(395_811_523, 6795) - // Standard Error: 14_268 - .saturating_add(Weight::from_parts(46_194_718, 0).saturating_mul(r.into())) + // Minimum execution time: 267_401_000 picoseconds. + Weight::from_parts(345_773_771, 6795) + // Standard Error: 14_486 + .saturating_add(Weight::from_parts(46_180_739, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 77).saturating_mul(r.into())) @@ -3567,10 +3563,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `871 + r * (42 ±0)` // Estimated: `6810 + r * (42 ±0)` - // Minimum execution time: 333_708_000 picoseconds. - Weight::from_parts(375_822_414, 6810) - // Standard Error: 15_535 - .saturating_add(Weight::from_parts(38_534_300, 0).saturating_mul(r.into())) + // Minimum execution time: 277_890_000 picoseconds. + Weight::from_parts(319_211_194, 6810) + // Standard Error: 9_132 + .saturating_add(Weight::from_parts(12_128_696, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 42).saturating_mul(r.into())) @@ -3593,11 +3589,11 @@ impl WeightInfo for () { fn seal_set_code_hash(r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + r * (961 ±0)` - // Estimated: `6801 + r * (3087 ±7)` - // Minimum execution time: 329_668_000 picoseconds. - Weight::from_parts(337_256_000, 6801) - // Standard Error: 64_733 - .saturating_add(Weight::from_parts(25_506_246, 0).saturating_mul(r.into())) + // Estimated: `6801 + r * (3087 ±10)` + // Minimum execution time: 259_692_000 picoseconds. + Weight::from_parts(278_327_000, 6801) + // Standard Error: 60_024 + .saturating_add(Weight::from_parts(25_758_805, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().reads((3_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(3_u64)) @@ -3623,10 +3619,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `852 + r * (3 ±0)` // Estimated: `6802 + r * (3 ±0)` - // Minimum execution time: 332_021_000 picoseconds. - Weight::from_parts(343_753_442, 6802) - // Standard Error: 406 - .saturating_add(Weight::from_parts(178_908, 0).saturating_mul(r.into())) + // Minimum execution time: 258_907_000 picoseconds. + Weight::from_parts(285_755_890, 6802) + // Standard Error: 378 + .saturating_add(Weight::from_parts(179_649, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 3).saturating_mul(r.into())) @@ -3650,10 +3646,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `2092 + r * (39 ±0)` // Estimated: `7919 + r * (40 ±0)` - // Minimum execution time: 334_122_000 picoseconds. - Weight::from_parts(410_992_486, 7919) - // Standard Error: 1_583 - .saturating_add(Weight::from_parts(316_027, 0).saturating_mul(r.into())) + // Minimum execution time: 260_415_000 picoseconds. + Weight::from_parts(363_871_048, 7919) + // Standard Error: 2_010 + .saturating_add(Weight::from_parts(317_607, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 40).saturating_mul(r.into())) @@ -3679,10 +3675,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `855 + r * (3 ±0)` // Estimated: `6802 + r * (3 ±0)` - // Minimum execution time: 331_093_000 picoseconds. - Weight::from_parts(345_663_437, 6802) - // Standard Error: 374 - .saturating_add(Weight::from_parts(157_207, 0).saturating_mul(r.into())) + // Minimum execution time: 257_725_000 picoseconds. + Weight::from_parts(283_441_372, 6802) + // Standard Error: 371 + .saturating_add(Weight::from_parts(157_674, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) .saturating_add(Weight::from_parts(0, 3).saturating_mul(r.into())) @@ -3692,9 +3688,9 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_483_000 picoseconds. - Weight::from_parts(1_672_465, 0) - // Standard Error: 24 - .saturating_add(Weight::from_parts(10_591, 0).saturating_mul(r.into())) + // Minimum execution time: 1_635_000 picoseconds. + Weight::from_parts(2_990_110, 0) + // Standard Error: 31 + .saturating_add(Weight::from_parts(10_213, 0).saturating_mul(r.into())) } } From 70c0547f40daa8b550ef1a849514d07c385f963e Mon Sep 17 00:00:00 2001 From: Oliver Tale-Yazdi Date: Fri, 7 Jul 2023 17:33:17 +0200 Subject: [PATCH 07/39] Fix spellcheck for benchmarking comments (#14535) * Benchmarking spellcheck fix Put everything that could cause spellcheck issues into backticks. Signed-off-by: Oliver Tale-Yazdi * Also in templates Signed-off-by: Oliver Tale-Yazdi * ".git/.scripts/commands/bench/bench.sh" pallet dev pallet-balances --------- Signed-off-by: Oliver Tale-Yazdi Co-authored-by: command-bot <> --- .maintain/frame-weight-template.hbs | 4 +- frame/balances/src/weights.rs | 156 +++++++++--------- .../benchmarking-cli/src/pallet/template.hbs | 2 +- .../benchmarking-cli/src/pallet/writer.rs | 10 +- 4 files changed, 85 insertions(+), 87 deletions(-) diff --git a/.maintain/frame-weight-template.hbs b/.maintain/frame-weight-template.hbs index 38bb4de26362f..4ab509f8e446c 100644 --- a/.maintain/frame-weight-template.hbs +++ b/.maintain/frame-weight-template.hbs @@ -5,7 +5,7 @@ //! DATE: {{date}}, STEPS: `{{cmd.steps}}`, REPEAT: `{{cmd.repeat}}`, LOW RANGE: `{{cmd.lowest_range_values}}`, HIGH RANGE: `{{cmd.highest_range_values}}` //! WORST CASE MAP SIZE: `{{cmd.worst_case_map_values}}` //! HOSTNAME: `{{hostname}}`, CPU: `{{cpuname}}` -//! EXECUTION: {{cmd.execution}}, WASM-EXECUTION: {{cmd.wasm_execution}}, CHAIN: {{cmd.chain}}, DB CACHE: {{cmd.db_cache}} +//! EXECUTION: `{{cmd.execution}}`, WASM-EXECUTION: `{{cmd.wasm_execution}}`, CHAIN: `{{cmd.chain}}`, DB CACHE: `{{cmd.db_cache}}` // Executed Command: {{#each args as |arg|}} @@ -78,7 +78,7 @@ impl WeightInfo for SubstrateWeight { {{/each}} } -// For backwards compatibility and tests +// For backwards compatibility and tests. impl WeightInfo for () { {{#each benchmarks as |benchmark|}} {{#each benchmark.comments as |comment|}} diff --git a/frame/balances/src/weights.rs b/frame/balances/src/weights.rs index d7657708dce30..d394666a40923 100644 --- a/frame/balances/src/weights.rs +++ b/frame/balances/src/weights.rs @@ -18,28 +18,26 @@ //! Autogenerated weights for pallet_balances //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-06-16, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-07-07, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-e8ezs4ez-project-145-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 +//! HOSTNAME: `runner-xerhrdyb-project-145-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: `Some(Wasm)`, WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: -// ./target/production/substrate +// target/production/substrate // benchmark // pallet -// --chain=dev // --steps=50 // --repeat=20 -// --pallet=pallet_balances -// --no-storage-info -// --no-median-slopes -// --no-min-squares // --extrinsic=* // --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 -// --output=./frame/balances/src/weights.rs +// --json-file=/builds/parity/mirrors/substrate/.git/.artifacts/bench.json +// --pallet=pallet-balances +// --chain=dev // --header=./HEADER-APACHE2 +// --output=./frame/balances/src/weights.rs // --template=./.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -65,190 +63,190 @@ pub trait WeightInfo { /// Weights for pallet_balances using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer_allow_death() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 57_153_000 picoseconds. - Weight::from_parts(58_106_000, 3593) + // Minimum execution time: 58_450_000 picoseconds. + Weight::from_parts(59_566_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer_keep_alive() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 43_680_000 picoseconds. - Weight::from_parts(44_207_000, 3593) + // Minimum execution time: 44_753_000 picoseconds. + Weight::from_parts(46_235_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn force_set_balance_creating() -> Weight { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 16_365_000 picoseconds. - Weight::from_parts(16_940_000, 3593) + // Minimum execution time: 16_771_000 picoseconds. + Weight::from_parts(17_172_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn force_set_balance_killing() -> Weight { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 23_853_000 picoseconds. - Weight::from_parts(24_547_000, 3593) + // Minimum execution time: 24_196_000 picoseconds. + Weight::from_parts(24_925_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - /// Storage: System Account (r:2 w:2) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn force_transfer() -> Weight { // Proof Size summary in bytes: // Measured: `103` // Estimated: `6196` - // Minimum execution time: 58_563_000 picoseconds. - Weight::from_parts(59_787_000, 6196) + // Minimum execution time: 60_133_000 picoseconds. + Weight::from_parts(61_069_000, 6196) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer_all() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 52_902_000 picoseconds. - Weight::from_parts(53_795_000, 3593) + // Minimum execution time: 53_938_000 picoseconds. + Weight::from_parts(55_123_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn force_unreserve() -> Weight { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 19_335_000 picoseconds. - Weight::from_parts(20_068_000, 3593) + // Minimum execution time: 19_914_000 picoseconds. + Weight::from_parts(20_435_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - /// Storage: System Account (r:999 w:999) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:999 w:999) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `u` is `[1, 1000]`. fn upgrade_accounts(u: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + u * (135 ±0)` // Estimated: `990 + u * (2603 ±0)` - // Minimum execution time: 19_014_000 picoseconds. - Weight::from_parts(19_284_000, 990) - // Standard Error: 12_468 - .saturating_add(Weight::from_parts(16_099_927, 0).saturating_mul(u.into())) + // Minimum execution time: 19_319_000 picoseconds. + Weight::from_parts(19_644_000, 990) + // Standard Error: 11_800 + .saturating_add(Weight::from_parts(16_340_188, 0).saturating_mul(u.into())) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(u.into()))) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(u.into()))) .saturating_add(Weight::from_parts(0, 2603).saturating_mul(u.into())) } } -// For backwards compatibility and tests +// For backwards compatibility and tests. impl WeightInfo for () { - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer_allow_death() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 57_153_000 picoseconds. - Weight::from_parts(58_106_000, 3593) + // Minimum execution time: 58_450_000 picoseconds. + Weight::from_parts(59_566_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer_keep_alive() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 43_680_000 picoseconds. - Weight::from_parts(44_207_000, 3593) + // Minimum execution time: 44_753_000 picoseconds. + Weight::from_parts(46_235_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn force_set_balance_creating() -> Weight { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 16_365_000 picoseconds. - Weight::from_parts(16_940_000, 3593) + // Minimum execution time: 16_771_000 picoseconds. + Weight::from_parts(17_172_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn force_set_balance_killing() -> Weight { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 23_853_000 picoseconds. - Weight::from_parts(24_547_000, 3593) + // Minimum execution time: 24_196_000 picoseconds. + Weight::from_parts(24_925_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: System Account (r:2 w:2) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn force_transfer() -> Weight { // Proof Size summary in bytes: // Measured: `103` // Estimated: `6196` - // Minimum execution time: 58_563_000 picoseconds. - Weight::from_parts(59_787_000, 6196) + // Minimum execution time: 60_133_000 picoseconds. + Weight::from_parts(61_069_000, 6196) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer_all() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 52_902_000 picoseconds. - Weight::from_parts(53_795_000, 3593) + // Minimum execution time: 53_938_000 picoseconds. + Weight::from_parts(55_123_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn force_unreserve() -> Weight { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 19_335_000 picoseconds. - Weight::from_parts(20_068_000, 3593) + // Minimum execution time: 19_914_000 picoseconds. + Weight::from_parts(20_435_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: System Account (r:999 w:999) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:999 w:999) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `u` is `[1, 1000]`. fn upgrade_accounts(u: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + u * (135 ±0)` // Estimated: `990 + u * (2603 ±0)` - // Minimum execution time: 19_014_000 picoseconds. - Weight::from_parts(19_284_000, 990) - // Standard Error: 12_468 - .saturating_add(Weight::from_parts(16_099_927, 0).saturating_mul(u.into())) + // Minimum execution time: 19_319_000 picoseconds. + Weight::from_parts(19_644_000, 990) + // Standard Error: 11_800 + .saturating_add(Weight::from_parts(16_340_188, 0).saturating_mul(u.into())) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(u.into()))) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(u.into()))) .saturating_add(Weight::from_parts(0, 2603).saturating_mul(u.into())) diff --git a/utils/frame/benchmarking-cli/src/pallet/template.hbs b/utils/frame/benchmarking-cli/src/pallet/template.hbs index 85b0e86caad96..e524fbd5018e2 100644 --- a/utils/frame/benchmarking-cli/src/pallet/template.hbs +++ b/utils/frame/benchmarking-cli/src/pallet/template.hbs @@ -5,7 +5,7 @@ //! DATE: {{date}}, STEPS: `{{cmd.steps}}`, REPEAT: `{{cmd.repeat}}`, LOW RANGE: `{{cmd.lowest_range_values}}`, HIGH RANGE: `{{cmd.highest_range_values}}` //! WORST CASE MAP SIZE: `{{cmd.worst_case_map_values}}` //! HOSTNAME: `{{hostname}}`, CPU: `{{cpuname}}` -//! EXECUTION: {{cmd.execution}}, WASM-EXECUTION: {{cmd.wasm_execution}}, CHAIN: {{cmd.chain}}, DB CACHE: {{cmd.db_cache}} +//! EXECUTION: `{{cmd.execution}}`, WASM-EXECUTION: `{{cmd.wasm_execution}}`, CHAIN: `{{cmd.chain}}`, DB CACHE: {{cmd.db_cache}} // Executed Command: {{#each args as |arg|}} diff --git a/utils/frame/benchmarking-cli/src/pallet/writer.rs b/utils/frame/benchmarking-cli/src/pallet/writer.rs index c8da658ea82ef..fd1b92b90c181 100644 --- a/utils/frame/benchmarking-cli/src/pallet/writer.rs +++ b/utils/frame/benchmarking-cli/src/pallet/writer.rs @@ -666,7 +666,7 @@ pub(crate) fn process_storage_results( match key_info { Some(key_info) => { let comment = format!( - "Storage: {} {} (r:{} w:{})", + "Storage: `{}::{}` (r:{} w:{})", String::from_utf8(key_info.pallet_name.clone()) .expect("encoded from string"), String::from_utf8(key_info.storage_name.clone()) @@ -678,7 +678,7 @@ pub(crate) fn process_storage_results( }, None => { let comment = format!( - "Storage: unknown `0x{}` (r:{} w:{})", + "Storage: UNKNOWN KEY `0x{}` (r:{} w:{})", HexDisplay::from(key), reads, writes, @@ -700,7 +700,7 @@ pub(crate) fn process_storage_results( ) { Some(new_pov) => { let comment = format!( - "Proof: {} {} (max_values: {:?}, max_size: {:?}, added: {}, mode: {:?})", + "Proof: `{}::{}` (`max_values`: {:?}, `max_size`: {:?}, added: {}, mode: `{:?}`)", String::from_utf8(key_info.pallet_name.clone()) .expect("encoded from string"), String::from_utf8(key_info.storage_name.clone()) @@ -718,7 +718,7 @@ pub(crate) fn process_storage_results( let item = String::from_utf8(key_info.storage_name.clone()) .expect("encoded from string"); let comment = format!( - "Proof Skipped: {} {} (max_values: {:?}, max_size: {:?}, mode: {:?})", + "Proof: `{}::{}` (`max_values`: {:?}, `max_size`: {:?}, mode: `{:?}`)", pallet, item, key_info.max_values, key_info.max_size, used_pov_mode, ); @@ -728,7 +728,7 @@ pub(crate) fn process_storage_results( }, None => { let comment = format!( - "Proof Skipped: unknown `0x{}` (r:{} w:{})", + "Proof: UNKNOWN KEY `0x{}` (r:{} w:{})", HexDisplay::from(key), reads, writes, From 3fee5c7a8d657909aecd829d4b276305f0828a16 Mon Sep 17 00:00:00 2001 From: Kian Paimani <5588131+kianenigma@users.noreply.github.com> Date: Sun, 9 Jul 2023 14:46:18 +0200 Subject: [PATCH 08/39] remove `OnStakerSlash` replace with `OnStakingEvents` (#14527) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * remove 'OnStakerSlash', replace with 'OnStakingEvents' * fix other features in pallets * small fixes * fix docs * fix docs * fix docs * Update primitives/staking/src/lib.rs Co-authored-by: Gonçalo Pestana --------- Co-authored-by: Gonçalo Pestana --- Cargo.lock | 3 + bin/node/runtime/src/lib.rs | 8 +- frame/babe/src/mock.rs | 4 +- frame/beefy/src/mock.rs | 4 +- .../test-staking-e2e/src/mock.rs | 4 +- frame/elections-phragmen/Cargo.toml | 1 + frame/elections-phragmen/src/lib.rs | 9 +- frame/fast-unstake/src/mock.rs | 4 +- frame/grandpa/src/mock.rs | 4 +- .../nomination-pools/benchmarking/src/mock.rs | 4 +- frame/nomination-pools/src/lib.rs | 10 +- frame/nomination-pools/src/mock.rs | 1 + .../nomination-pools/test-staking/src/mock.rs | 4 +- frame/offences/benchmarking/src/mock.rs | 4 +- frame/root-offences/src/mock.rs | 15 +-- frame/session/benchmarking/src/mock.rs | 4 +- frame/staking/src/benchmarking.rs | 4 +- frame/staking/src/lib.rs | 7 +- frame/staking/src/mock.rs | 15 ++- frame/staking/src/pallet/impls.rs | 7 +- frame/staking/src/pallet/mod.rs | 12 +- frame/support/src/traits.rs | 5 +- frame/support/src/traits/voting.rs | 73 +---------- primitives/staking/Cargo.toml | 8 +- primitives/staking/src/currency_to_vote.rs | 101 +++++++++++++++ primitives/staking/src/lib.rs | 119 +++++++++++++----- utils/frame/generate-bags/Cargo.toml | 1 + utils/frame/generate-bags/src/lib.rs | 5 +- 28 files changed, 262 insertions(+), 178 deletions(-) create mode 100644 primitives/staking/src/currency_to_vote.rs diff --git a/Cargo.lock b/Cargo.lock index fe67e1bec2df0..e2a20ece4d0f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3159,6 +3159,7 @@ dependencies = [ "frame-system", "num-format", "pallet-staking", + "sp-staking", ] [[package]] @@ -6528,6 +6529,7 @@ dependencies = [ "sp-io", "sp-npos-elections", "sp-runtime", + "sp-staking", "sp-std", "sp-tracing", "substrate-test-utils", @@ -11507,6 +11509,7 @@ dependencies = [ name = "sp-staking" version = "4.0.0-dev" dependencies = [ + "impl-trait-for-tuples", "parity-scale-codec", "scale-info", "serde", diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index e1434f0504bd3..058f43dad00b1 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -38,7 +38,7 @@ use frame_support::{ tokens::{nonfungibles_v2::Inspect, GetSalary, PayFromAccount}, AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU16, ConstU32, Currency, EitherOfDiverse, EqualPrivilegeOnly, Everything, Imbalance, InstanceFilter, KeyOwnerProofSystem, - LockIdentifier, Nothing, OnUnbalanced, U128CurrencyToVote, WithdrawReasons, + LockIdentifier, Nothing, OnUnbalanced, WithdrawReasons, }, weights::{ constants::{ @@ -575,7 +575,7 @@ impl pallet_staking::Config for Runtime { type Currency = Balances; type CurrencyBalance = Balance; type UnixTime = Timestamp; - type CurrencyToVote = U128CurrencyToVote; + type CurrencyToVote = sp_staking::currency_to_vote::U128CurrencyToVote; type RewardRemainder = Treasury; type RuntimeEvent = RuntimeEvent; type Slash = Treasury; // send the slashed funds to the treasury. @@ -600,7 +600,7 @@ impl pallet_staking::Config for Runtime { type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; type HistoryDepth = HistoryDepth; - type OnStakerSlash = NominationPools; + type EventListeners = NominationPools; type WeightInfo = pallet_staking::weights::SubstrateWeight; type BenchmarkingConfig = StakingBenchmarkingConfig; } @@ -1047,7 +1047,7 @@ impl pallet_elections_phragmen::Config for Runtime { // NOTE: this implies that council's genesis members cannot be set directly and must come from // this module. type InitializeMembers = Council; - type CurrencyToVote = U128CurrencyToVote; + type CurrencyToVote = sp_staking::currency_to_vote::U128CurrencyToVote; type CandidacyBond = CandidacyBond; type VotingBondBase = VotingBondBase; type VotingBondFactor = VotingBondFactor; diff --git a/frame/babe/src/mock.rs b/frame/babe/src/mock.rs index c0ccc9a8acd32..ccc24050d53ba 100644 --- a/frame/babe/src/mock.rs +++ b/frame/babe/src/mock.rs @@ -182,7 +182,7 @@ impl onchain::Config for OnChainSeqPhragmen { impl pallet_staking::Config for Test { type MaxNominations = ConstU32<16>; type RewardRemainder = (); - type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; + type CurrencyToVote = (); type RuntimeEvent = RuntimeEvent; type Currency = Balances; type CurrencyBalance = ::Balance; @@ -204,7 +204,7 @@ impl pallet_staking::Config for Test { type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; type HistoryDepth = ConstU32<84>; - type OnStakerSlash = (); + type EventListeners = (); type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; type WeightInfo = (); } diff --git a/frame/beefy/src/mock.rs b/frame/beefy/src/mock.rs index 7edf4d339758c..270097e346c8f 100644 --- a/frame/beefy/src/mock.rs +++ b/frame/beefy/src/mock.rs @@ -206,7 +206,7 @@ impl onchain::Config for OnChainSeqPhragmen { impl pallet_staking::Config for Test { type MaxNominations = ConstU32<16>; type RewardRemainder = (); - type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; + type CurrencyToVote = (); type RuntimeEvent = RuntimeEvent; type Currency = Balances; type CurrencyBalance = ::Balance; @@ -228,7 +228,7 @@ impl pallet_staking::Config for Test { type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; type HistoryDepth = ConstU32<84>; - type OnStakerSlash = (); + type EventListeners = (); type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; type WeightInfo = (); } diff --git a/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs b/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs index da7ccf6dce9ce..8c641d6137c53 100644 --- a/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs +++ b/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs @@ -265,7 +265,7 @@ impl pallet_staking::Config for Runtime { type Currency = Balances; type CurrencyBalance = Balance; type UnixTime = Timestamp; - type CurrencyToVote = traits::SaturatingCurrencyToVote; + type CurrencyToVote = (); type RewardRemainder = (); type RuntimeEvent = RuntimeEvent; type Slash = (); // burn slashes @@ -285,7 +285,7 @@ impl pallet_staking::Config for Runtime { type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; type HistoryDepth = HistoryDepth; - type OnStakerSlash = (); + type EventListeners = (); type WeightInfo = pallet_staking::weights::SubstrateWeight; type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; } diff --git a/frame/elections-phragmen/Cargo.toml b/frame/elections-phragmen/Cargo.toml index 20ca29fff6b83..9b26e1e367a91 100644 --- a/frame/elections-phragmen/Cargo.toml +++ b/frame/elections-phragmen/Cargo.toml @@ -26,6 +26,7 @@ sp-io = { version = "23.0.0", default-features = false, path = "../../primitives sp-npos-elections = { version = "4.0.0-dev", default-features = false, path = "../../primitives/npos-elections" } sp-runtime = { version = "24.0.0", default-features = false, path = "../../primitives/runtime" } sp-std = { version = "8.0.0", default-features = false, path = "../../primitives/std" } +sp-staking = { default-features = false, path = "../../primitives/staking" } [dev-dependencies] pallet-balances = { version = "4.0.0-dev", path = "../balances" } diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index ee8bcc1de50a4..7a4fb61970215 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -101,9 +101,9 @@ use codec::{Decode, Encode}; use frame_support::{ traits::{ - defensive_prelude::*, ChangeMembers, Contains, ContainsLengthBound, Currency, - CurrencyToVote, Get, InitializeMembers, LockIdentifier, LockableCurrency, OnUnbalanced, - ReservableCurrency, SortedMembers, WithdrawReasons, + defensive_prelude::*, ChangeMembers, Contains, ContainsLengthBound, Currency, Get, + InitializeMembers, LockIdentifier, LockableCurrency, OnUnbalanced, ReservableCurrency, + SortedMembers, WithdrawReasons, }, weights::Weight, }; @@ -113,6 +113,7 @@ use sp_runtime::{ traits::{Saturating, StaticLookup, Zero}, DispatchError, Perbill, RuntimeDebug, }; +use sp_staking::currency_to_vote::CurrencyToVote; use sp_std::{cmp::Ordering, prelude::*}; #[cfg(any(feature = "try-runtime", test))] @@ -1424,7 +1425,7 @@ mod tests { type PalletId = ElectionsPhragmenPalletId; type RuntimeEvent = RuntimeEvent; type Currency = Balances; - type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; + type CurrencyToVote = (); type ChangeMembers = TestChangeMembers; type InitializeMembers = (); type CandidacyBond = CandidacyBond; diff --git a/frame/fast-unstake/src/mock.rs b/frame/fast-unstake/src/mock.rs index 101ad90881171..ecdbad9ff7745 100644 --- a/frame/fast-unstake/src/mock.rs +++ b/frame/fast-unstake/src/mock.rs @@ -137,7 +137,7 @@ impl pallet_staking::Config for Runtime { type Currency = Balances; type CurrencyBalance = Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; + type CurrencyToVote = (); type RewardRemainder = (); type RuntimeEvent = RuntimeEvent; type Slash = (); @@ -157,7 +157,7 @@ impl pallet_staking::Config for Runtime { type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; - type OnStakerSlash = (); + type EventListeners = (); type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; type WeightInfo = (); } diff --git a/frame/grandpa/src/mock.rs b/frame/grandpa/src/mock.rs index df012ab9dc6e8..3a13385d35320 100644 --- a/frame/grandpa/src/mock.rs +++ b/frame/grandpa/src/mock.rs @@ -187,7 +187,7 @@ impl onchain::Config for OnChainSeqPhragmen { impl pallet_staking::Config for Test { type MaxNominations = ConstU32<16>; type RewardRemainder = (); - type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; + type CurrencyToVote = (); type RuntimeEvent = RuntimeEvent; type Currency = Balances; type CurrencyBalance = ::Balance; @@ -209,7 +209,7 @@ impl pallet_staking::Config for Test { type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; type HistoryDepth = ConstU32<84>; - type OnStakerSlash = (); + type EventListeners = (); type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; type WeightInfo = (); } diff --git a/frame/nomination-pools/benchmarking/src/mock.rs b/frame/nomination-pools/benchmarking/src/mock.rs index d94c63d1bf5b5..62655690a2d63 100644 --- a/frame/nomination-pools/benchmarking/src/mock.rs +++ b/frame/nomination-pools/benchmarking/src/mock.rs @@ -99,7 +99,7 @@ impl pallet_staking::Config for Runtime { type Currency = Balances; type CurrencyBalance = Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; + type CurrencyToVote = (); type RewardRemainder = (); type RuntimeEvent = RuntimeEvent; type Slash = (); @@ -120,7 +120,7 @@ impl pallet_staking::Config for Runtime { type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; type HistoryDepth = ConstU32<84>; - type OnStakerSlash = Pools; + type EventListeners = Pools; type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; type WeightInfo = (); } diff --git a/frame/nomination-pools/src/lib.rs b/frame/nomination-pools/src/lib.rs index 8518ca58bab5c..a356ba529aa44 100644 --- a/frame/nomination-pools/src/lib.rs +++ b/frame/nomination-pools/src/lib.rs @@ -326,7 +326,7 @@ //! //! This section assumes that the slash computation is executed by //! `pallet_staking::StakingLedger::slash`, which passes the information to this pallet via -//! [`sp_staking::OnStakerSlash::on_slash`]. +//! [`sp_staking::OnStakingUpdate::on_slash`]. //! //! Unbonding pools need to be slashed to ensure all nominators whom where in the bonded pool while //! it was backing a validator that equivocated are punished. Without these measures a member could @@ -341,10 +341,6 @@ //! in addition to the unbonding pools. For maintenance simplicity these are not implemented. //! Related: //! -//! **Relevant methods:** -//! -//! * [`Pallet::on_slash`] -//! //! ### Limitations //! //! * PoolMembers cannot vote with their staked funds because they are transferred into the pools @@ -375,7 +371,7 @@ use sp_runtime::{ }, FixedPointNumber, Perbill, }; -use sp_staking::{EraIndex, OnStakerSlash, StakingInterface}; +use sp_staking::{EraIndex, StakingInterface}; use sp_std::{collections::btree_map::BTreeMap, fmt::Debug, ops::Div, vec::Vec}; #[cfg(any(feature = "try-runtime", feature = "fuzzing", test, debug_assertions))] @@ -3265,7 +3261,7 @@ impl Pallet { } } -impl OnStakerSlash> for Pallet { +impl sp_staking::OnStakingUpdate> for Pallet { fn on_slash( pool_account: &T::AccountId, // Bonded balance is always read directly from staking, therefore we don't need to update diff --git a/frame/nomination-pools/src/mock.rs b/frame/nomination-pools/src/mock.rs index f0b73bbea28da..0a404603496ec 100644 --- a/frame/nomination-pools/src/mock.rs +++ b/frame/nomination-pools/src/mock.rs @@ -47,6 +47,7 @@ impl StakingMock { impl sp_staking::StakingInterface for StakingMock { type Balance = Balance; type AccountId = AccountId; + type CurrencyToVote = (); fn minimum_nominator_bond() -> Self::Balance { StakingMinBond::get() diff --git a/frame/nomination-pools/test-staking/src/mock.rs b/frame/nomination-pools/test-staking/src/mock.rs index a9c64508564cd..6d73615c8055b 100644 --- a/frame/nomination-pools/test-staking/src/mock.rs +++ b/frame/nomination-pools/test-staking/src/mock.rs @@ -113,7 +113,7 @@ impl pallet_staking::Config for Runtime { type Currency = Balances; type CurrencyBalance = Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; + type CurrencyToVote = (); type RewardRemainder = (); type RuntimeEvent = RuntimeEvent; type Slash = (); @@ -134,7 +134,7 @@ impl pallet_staking::Config for Runtime { type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; type HistoryDepth = ConstU32<84>; - type OnStakerSlash = Pools; + type EventListeners = Pools; type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; type WeightInfo = (); } diff --git a/frame/offences/benchmarking/src/mock.rs b/frame/offences/benchmarking/src/mock.rs index 6bb3b9d7f4ee8..d6c1f95117c61 100644 --- a/frame/offences/benchmarking/src/mock.rs +++ b/frame/offences/benchmarking/src/mock.rs @@ -162,7 +162,7 @@ impl pallet_staking::Config for Test { type Currency = Balances; type CurrencyBalance = ::Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; + type CurrencyToVote = (); type RewardRemainder = (); type RuntimeEvent = RuntimeEvent; type Slash = (); @@ -182,7 +182,7 @@ impl pallet_staking::Config for Test { type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; type HistoryDepth = ConstU32<84>; - type OnStakerSlash = (); + type EventListeners = (); type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; type WeightInfo = (); } diff --git a/frame/root-offences/src/mock.rs b/frame/root-offences/src/mock.rs index 8c48e34e4e04a..65fd788e05f25 100644 --- a/frame/root-offences/src/mock.rs +++ b/frame/root-offences/src/mock.rs @@ -149,17 +149,6 @@ impl onchain::Config for OnChainSeqPhragmen { type TargetsBound = ConstU32<{ u32::MAX }>; } -pub struct OnStakerSlashMock(core::marker::PhantomData); -impl sp_staking::OnStakerSlash for OnStakerSlashMock { - fn on_slash( - _pool_account: &AccountId, - slashed_bonded: Balance, - slashed_chunks: &BTreeMap, - ) { - LedgerSlashPerEra::set((slashed_bonded, slashed_chunks.clone())); - } -} - parameter_types! { pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE; pub static Offset: BlockNumber = 0; @@ -176,7 +165,7 @@ impl pallet_staking::Config for Test { type Currency = Balances; type CurrencyBalance = ::Balance; type UnixTime = Timestamp; - type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; + type CurrencyToVote = (); type RewardRemainder = (); type RuntimeEvent = RuntimeEvent; type Slash = (); @@ -196,7 +185,7 @@ impl pallet_staking::Config for Test { type MaxUnlockingChunks = ConstU32<32>; type HistoryDepth = ConstU32<84>; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; - type OnStakerSlash = OnStakerSlashMock; + type EventListeners = (); type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; type WeightInfo = (); } diff --git a/frame/session/benchmarking/src/mock.rs b/frame/session/benchmarking/src/mock.rs index 3b027492e0a6a..d4866a46079af 100644 --- a/frame/session/benchmarking/src/mock.rs +++ b/frame/session/benchmarking/src/mock.rs @@ -164,7 +164,7 @@ impl pallet_staking::Config for Test { type Currency = Balances; type CurrencyBalance = ::Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; + type CurrencyToVote = (); type RewardRemainder = (); type RuntimeEvent = RuntimeEvent; type Slash = (); @@ -184,7 +184,7 @@ impl pallet_staking::Config for Test { type HistoryDepth = ConstU32<84>; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; - type OnStakerSlash = (); + type EventListeners = (); type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; type WeightInfo = (); } diff --git a/frame/staking/src/benchmarking.rs b/frame/staking/src/benchmarking.rs index 53589ecfe4dbc..8d6eb7459074c 100644 --- a/frame/staking/src/benchmarking.rs +++ b/frame/staking/src/benchmarking.rs @@ -26,13 +26,13 @@ use frame_election_provider_support::SortedListProvider; use frame_support::{ dispatch::UnfilteredDispatchable, pallet_prelude::*, - traits::{Currency, CurrencyToVote, Get, Imbalance}, + traits::{Currency, Get, Imbalance}, }; use sp_runtime::{ traits::{Bounded, One, StaticLookup, TrailingZeroInput, Zero}, Perbill, Percent, }; -use sp_staking::SessionIndex; +use sp_staking::{currency_to_vote::CurrencyToVote, SessionIndex}; use sp_std::prelude::*; pub use frame_benchmarking::v1::{ diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index 344c4ecb4f949..99622a64f8dc2 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -314,7 +314,7 @@ use sp_runtime::{ pub use sp_staking::StakerStatus; use sp_staking::{ offence::{Offence, OffenceError, ReportOffence}, - EraIndex, SessionIndex, + EraIndex, OnStakingUpdate, SessionIndex, }; use sp_std::{collections::btree_map::BTreeMap, prelude::*}; pub use weights::WeightInfo; @@ -549,7 +549,7 @@ impl StakingLedger { /// /// `slash_era` is the era in which the slash (which is being enacted now) actually happened. /// - /// This calls `Config::OnStakerSlash::on_slash` with information as to how the slash was + /// This calls `Config::OnStakingUpdate::on_slash` with information as to how the slash was /// applied. pub fn slash( &mut self, @@ -562,7 +562,6 @@ impl StakingLedger { } use sp_runtime::PerThing as _; - use sp_staking::OnStakerSlash as _; let mut remaining_slash = slash_amount; let pre_slash_total = self.total; @@ -667,7 +666,7 @@ impl StakingLedger { // clean unlocking chunks that are set to zero. self.unlocking.retain(|c| !c.value.is_zero()); - T::OnStakerSlash::on_slash(&self.stash, self.active, &slashed_unlocking); + T::EventListeners::on_slash(&self.stash, self.active, &slashed_unlocking); pre_slash_total.saturating_sub(self.total) } } diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index f9af9f5003b43..19529ca08735d 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -236,7 +236,6 @@ parameter_types! { pub static HistoryDepth: u32 = 80; pub static MaxUnlockingChunks: u32 = 32; pub static RewardOnUnbalanceWasCalled: bool = false; - pub static LedgerSlashPerEra: (BalanceOf, BTreeMap>) = (Zero::zero(), BTreeMap::new()); pub static MaxWinners: u32 = 100; } @@ -268,8 +267,14 @@ impl OnUnbalanced> for MockReward { } } -pub struct OnStakerSlashMock(core::marker::PhantomData); -impl sp_staking::OnStakerSlash for OnStakerSlashMock { +parameter_types! { + pub static LedgerSlashPerEra: + (BalanceOf, BTreeMap>) = + (Zero::zero(), BTreeMap::new()); +} + +pub struct EventListenerMock; +impl OnStakingUpdate for EventListenerMock { fn on_slash( _pool_account: &AccountId, slashed_bonded: Balance, @@ -284,7 +289,7 @@ impl crate::pallet::pallet::Config for Test { type Currency = Balances; type CurrencyBalance = ::Balance; type UnixTime = Timestamp; - type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; + type CurrencyToVote = (); type RewardRemainder = RewardRemainderMock; type RuntimeEvent = RuntimeEvent; type Slash = (); @@ -305,7 +310,7 @@ impl crate::pallet::pallet::Config for Test { type TargetList = UseValidatorsMap; type MaxUnlockingChunks = MaxUnlockingChunks; type HistoryDepth = HistoryDepth; - type OnStakerSlash = OnStakerSlashMock; + type EventListeners = EventListenerMock; type BenchmarkingConfig = TestBenchmarkingConfig; type WeightInfo = (); } diff --git a/frame/staking/src/pallet/impls.rs b/frame/staking/src/pallet/impls.rs index 44d5674f2f816..5166608a97aab 100644 --- a/frame/staking/src/pallet/impls.rs +++ b/frame/staking/src/pallet/impls.rs @@ -26,8 +26,8 @@ use frame_support::{ dispatch::WithPostDispatchInfo, pallet_prelude::*, traits::{ - Currency, CurrencyToVote, Defensive, DefensiveResult, EstimateNextNewSession, Get, - Imbalance, LockableCurrency, OnUnbalanced, TryCollect, UnixTime, WithdrawReasons, + Currency, Defensive, DefensiveResult, EstimateNextNewSession, Get, Imbalance, + LockableCurrency, OnUnbalanced, TryCollect, UnixTime, WithdrawReasons, }, weights::Weight, }; @@ -38,6 +38,7 @@ use sp_runtime::{ Perbill, }; use sp_staking::{ + currency_to_vote::CurrencyToVote, offence::{DisableStrategy, OffenceDetails, OnOffenceHandler}, EraIndex, SessionIndex, Stake, StakingInterface, }; @@ -1568,10 +1569,10 @@ impl SortedListProvider for UseNominatorsAndValidatorsM } } -// NOTE: in this entire impl block, the assumption is that `who` is a stash account. impl StakingInterface for Pallet { type AccountId = T::AccountId; type Balance = BalanceOf; + type CurrencyToVote = T::CurrencyToVote; fn minimum_nominator_bond() -> Self::Balance { MinNominatorBond::::get() diff --git a/frame/staking/src/pallet/mod.rs b/frame/staking/src/pallet/mod.rs index bff51312e7121..0163d6543f2ab 100644 --- a/frame/staking/src/pallet/mod.rs +++ b/frame/staking/src/pallet/mod.rs @@ -24,7 +24,7 @@ use frame_support::{ dispatch::Codec, pallet_prelude::*, traits::{ - Currency, CurrencyToVote, Defensive, DefensiveResult, DefensiveSaturating, EnsureOrigin, + Currency, Defensive, DefensiveResult, DefensiveSaturating, EnsureOrigin, EstimateNextNewSession, Get, LockIdentifier, LockableCurrency, OnUnbalanced, TryCollect, UnixTime, }, @@ -113,7 +113,7 @@ pub mod pallet { /// in 128. /// Consequently, the backward convert is used convert the u128s from sp-elections back to a /// [`BalanceOf`]. - type CurrencyToVote: CurrencyToVote>; + type CurrencyToVote: sp_staking::currency_to_vote::CurrencyToVote>; /// Something that provides the election functionality. type ElectionProvider: ElectionProvider< @@ -261,9 +261,11 @@ pub mod pallet { #[pallet::constant] type MaxUnlockingChunks: Get; - /// A hook called when any staker is slashed. Mostly likely this can be a no-op unless - /// other pallets exist that are affected by slashing per-staker. - type OnStakerSlash: sp_staking::OnStakerSlash>; + /// Something that listens to staking updates and performs actions based on the data it + /// receives. + /// + /// WARNING: this only reports slashing events for the time being. + type EventListeners: sp_staking::OnStakingUpdate>; /// Some parameters of the benchmarking. type BenchmarkingConfig: BenchmarkingConfig; diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index 5b34a77df448a..f34a0b5d87bcf 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -102,10 +102,7 @@ pub use dispatch::{ }; mod voting; -pub use voting::{ - ClassCountOf, CurrencyToVote, PollStatus, Polling, SaturatingCurrencyToVote, - U128CurrencyToVote, VoteTally, -}; +pub use voting::{ClassCountOf, PollStatus, Polling, VoteTally}; mod preimages; pub use preimages::{Bounded, BoundedInline, FetchResult, Hash, QueryPreimage, StorePreimage}; diff --git a/frame/support/src/traits/voting.rs b/frame/support/src/traits/voting.rs index caec472785782..4201b8d48d157 100644 --- a/frame/support/src/traits/voting.rs +++ b/frame/support/src/traits/voting.rs @@ -20,81 +20,10 @@ use crate::dispatch::{DispatchError, Parameter}; use codec::{HasCompact, MaxEncodedLen}; -use sp_arithmetic::{ - traits::{SaturatedConversion, UniqueSaturatedFrom, UniqueSaturatedInto}, - Perbill, -}; +use sp_arithmetic::Perbill; use sp_runtime::traits::Member; use sp_std::prelude::*; -/// A trait similar to `Convert` to convert values from `B` an abstract balance type -/// into u64 and back from u128. (This conversion is used in election and other places where complex -/// calculation over balance type is needed) -/// -/// Total issuance of the currency is passed in, but an implementation of this trait may or may not -/// use it. -/// -/// # WARNING -/// -/// the total issuance being passed in implies that the implementation must be aware of the fact -/// that its values can affect the outcome. This implies that if the vote value is dependent on the -/// total issuance, it should never ber written to storage for later re-use. -pub trait CurrencyToVote { - /// Convert balance to u64. - fn to_vote(value: B, issuance: B) -> u64; - - /// Convert u128 to balance. - fn to_currency(value: u128, issuance: B) -> B; -} - -/// An implementation of `CurrencyToVote` tailored for chain's that have a balance type of u128. -/// -/// The factor is the `(total_issuance / u64::MAX).max(1)`, represented as u64. Let's look at the -/// important cases: -/// -/// If the chain's total issuance is less than u64::MAX, this will always be 1, which means that -/// the factor will not have any effect. In this case, any account's balance is also less. Thus, -/// both of the conversions are basically an `as`; Any balance can fit in u64. -/// -/// If the chain's total issuance is more than 2*u64::MAX, then a factor might be multiplied and -/// divided upon conversion. -pub struct U128CurrencyToVote; - -impl U128CurrencyToVote { - fn factor(issuance: u128) -> u128 { - (issuance / u64::MAX as u128).max(1) - } -} - -impl CurrencyToVote for U128CurrencyToVote { - fn to_vote(value: u128, issuance: u128) -> u64 { - (value / Self::factor(issuance)).saturated_into() - } - - fn to_currency(value: u128, issuance: u128) -> u128 { - value.saturating_mul(Self::factor(issuance)) - } -} - -/// A naive implementation of `CurrencyConvert` that simply saturates all conversions. -/// -/// # Warning -/// -/// This is designed to be used mostly for testing. Use with care, and think about the consequences. -pub struct SaturatingCurrencyToVote; - -impl + UniqueSaturatedFrom> CurrencyToVote - for SaturatingCurrencyToVote -{ - fn to_vote(value: B, _: B) -> u64 { - value.unique_saturated_into() - } - - fn to_currency(value: u128, _: B) -> B { - B::unique_saturated_from(value) - } -} - pub trait VoteTally { fn new(_: Class) -> Self; fn ayes(&self, class: Class) -> Votes; diff --git a/primitives/staking/Cargo.toml b/primitives/staking/Cargo.toml index 0191a34491cef..c6aee3cbcdb36 100644 --- a/primitives/staking/Cargo.toml +++ b/primitives/staking/Cargo.toml @@ -16,9 +16,11 @@ targets = ["x86_64-unknown-linux-gnu"] serde = { version = "1.0.163", default-features = false, features = ["derive", "alloc"], optional = true } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.5.0", default-features = false, features = ["derive"] } -sp-core = { version = "21.0.0", default-features = false, path = "../core" } -sp-runtime = { version = "24.0.0", default-features = false, path = "../runtime" } -sp-std = { version = "8.0.0", default-features = false, path = "../std" } +impl-trait-for-tuples = "0.2.2" + +sp-core = { default-features = false, path = "../core" } +sp-runtime = { default-features = false, path = "../runtime" } +sp-std = { default-features = false, path = "../std" } [features] default = ["std"] diff --git a/primitives/staking/src/currency_to_vote.rs b/primitives/staking/src/currency_to_vote.rs new file mode 100644 index 0000000000000..556e5bd210426 --- /dev/null +++ b/primitives/staking/src/currency_to_vote.rs @@ -0,0 +1,101 @@ +// This file is part of Substrate. + +// Copyright (C) 2019-2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use sp_runtime::{ + traits::{UniqueSaturatedFrom, UniqueSaturatedInto}, + SaturatedConversion, +}; + +/// A trait similar to `Convert` to convert values from `B` an abstract balance type +/// into u64 and back from u128. (This conversion is used in election and other places where complex +/// calculation over balance type is needed) +/// +/// Total issuance of the currency is passed in, but an implementation of this trait may or may not +/// use it. +/// +/// # WARNING +/// +/// the total issuance being passed in implies that the implementation must be aware of the fact +/// that its values can affect the outcome. This implies that if the vote value is dependent on the +/// total issuance, it should never ber written to storage for later re-use. +pub trait CurrencyToVote { + /// Convert balance to u64. + fn to_vote(value: B, issuance: B) -> u64; + + /// Convert u128 to balance. + fn to_currency(value: u128, issuance: B) -> B; +} + +/// An implementation of `CurrencyToVote` tailored for chain's that have a balance type of u128. +/// +/// The factor is the `(total_issuance / u64::MAX).max(1)`, represented as u64. Let's look at the +/// important cases: +/// +/// If the chain's total issuance is less than u64::MAX, this will always be 1, which means that +/// the factor will not have any effect. In this case, any account's balance is also less. Thus, +/// both of the conversions are basically an `as`; Any balance can fit in u64. +/// +/// If the chain's total issuance is more than 2*u64::MAX, then a factor might be multiplied and +/// divided upon conversion. +pub struct U128CurrencyToVote; + +impl U128CurrencyToVote { + fn factor(issuance: u128) -> u128 { + (issuance / u64::MAX as u128).max(1) + } +} + +impl CurrencyToVote for U128CurrencyToVote { + fn to_vote(value: u128, issuance: u128) -> u64 { + (value / Self::factor(issuance)).saturated_into() + } + + fn to_currency(value: u128, issuance: u128) -> u128 { + value.saturating_mul(Self::factor(issuance)) + } +} + +/// A naive implementation of `CurrencyConvert` that simply saturates all conversions. +/// +/// # Warning +/// +/// This is designed to be used mostly for testing. Use with care, and think about the consequences. +pub struct SaturatingCurrencyToVote; + +impl + UniqueSaturatedFrom> CurrencyToVote + for SaturatingCurrencyToVote +{ + fn to_vote(value: B, _: B) -> u64 { + value.unique_saturated_into() + } + + fn to_currency(value: u128, _: B) -> B { + B::unique_saturated_from(value) + } +} + +#[cfg(feature = "std")] +impl + UniqueSaturatedFrom> CurrencyToVote for () { + fn to_vote(value: B, issuance: B) -> u64 { + SaturatingCurrencyToVote::to_vote(value, issuance) + } + + /// Convert u128 to balance. + fn to_currency(value: u128, issuance: B) -> B { + SaturatingCurrencyToVote::to_currency(value, issuance) + } +} diff --git a/primitives/staking/src/lib.rs b/primitives/staking/src/lib.rs index 2fd5c6acc6a04..1621af164b375 100644 --- a/primitives/staking/src/lib.rs +++ b/primitives/staking/src/lib.rs @@ -20,13 +20,17 @@ //! A crate which contains primitives that are useful for implementation that uses staking //! approaches in general. Definitions related to sessions, slashing, etc go here. +use crate::currency_to_vote::CurrencyToVote; +use codec::{FullCodec, MaxEncodedLen}; use scale_info::TypeInfo; use sp_core::RuntimeDebug; -use sp_runtime::{DispatchError, DispatchResult}; -use sp_std::{collections::btree_map::BTreeMap, vec::Vec}; +use sp_runtime::{DispatchError, DispatchResult, Saturating}; +use sp_std::{collections::btree_map::BTreeMap, ops::Sub, vec::Vec}; pub mod offence; +pub mod currency_to_vote; + /// Simple index type with which we can count sessions. pub type SessionIndex = u32; @@ -45,32 +49,9 @@ pub enum StakerStatus { Nominator(Vec), } -/// Trait describing something that implements a hook for any operations to perform when a staker is -/// slashed. -pub trait OnStakerSlash { - /// A hook for any operations to perform when a staker is slashed. - /// - /// # Arguments - /// - /// * `stash` - The stash of the staker whom the slash was applied to. - /// * `slashed_active` - The new bonded balance of the staker after the slash was applied. - /// * `slashed_unlocking` - A map of slashed eras, and the balance of that unlocking chunk after - /// the slash is applied. Any era not present in the map is not affected at all. - fn on_slash( - stash: &AccountId, - slashed_active: Balance, - slashed_unlocking: &BTreeMap, - ); -} - -impl OnStakerSlash for () { - fn on_slash(_: &AccountId, _: Balance, _: &BTreeMap) { - // Nothing to do here - } -} - /// A struct that reflects stake that an account has in the staking system. Provides a set of /// methods to operate on it's properties. Aimed at making `StakingInterface` more concise. +#[derive(RuntimeDebug, Clone, Copy, Eq, PartialEq, Default)] pub struct Stake { /// The total stake that `stash` has in the staking system. This includes the /// `active` stake, and any funds currently in the process of unbonding via @@ -87,16 +68,88 @@ pub struct Stake { pub active: Balance, } +/// A generic staking event listener. +/// +/// Note that the interface is designed in a way that the events are fired post-action, so any +/// pre-action data that is needed needs to be passed to interface methods. The rest of the data can +/// be retrieved by using `StakingInterface`. +#[impl_trait_for_tuples::impl_for_tuples(10)] +pub trait OnStakingUpdate { + /// Fired when the stake amount of someone updates. + /// + /// This is effectively any changes to the bond amount, such as bonding more funds, and + /// unbonding. + fn on_stake_update(_who: &AccountId, _prev_stake: Option>) {} + + /// Fired when someone sets their intention to nominate. + /// + /// This should never be fired for existing nominators. + fn on_nominator_add(_who: &AccountId) {} + + /// Fired when an existing nominator updates their nominations. + /// + /// Note that this is not fired when a nominator changes their stake. For that, + /// `on_stake_update` should be used, followed by querying whether `who` was a validator or a + /// nominator. + fn on_nominator_update(_who: &AccountId, _prev_nominations: Vec) {} + + /// Fired when someone removes their intention to nominate, either due to chill or validating. + /// + /// The set of nominations at the time of removal is provided as it can no longer be fetched in + /// any way. + fn on_nominator_remove(_who: &AccountId, _nominations: Vec) {} + + /// Fired when someone sets their intention to validate. + /// + /// Note validator preference changes are not communicated, but could be added if needed. + fn on_validator_add(_who: &AccountId) {} + + /// Fired when an existing validator updates their preferences. + /// + /// Note validator preference changes are not communicated, but could be added if needed. + fn on_validator_update(_who: &AccountId) {} + + /// Fired when someone removes their intention to validate, either due to chill or nominating. + fn on_validator_remove(_who: &AccountId) {} + + /// Fired when someone is fully unstaked. + fn on_unstake(_who: &AccountId) {} + + /// Fired when a staker is slashed. + /// + /// * `stash` - The stash of the staker whom the slash was applied to. + /// * `slashed_active` - The new bonded balance of the staker after the slash was applied. + /// * `slashed_unlocking` - A map of slashed eras, and the balance of that unlocking chunk after + /// the slash is applied. Any era not present in the map is not affected at all. + fn on_slash( + _stash: &AccountId, + _slashed_active: Balance, + _slashed_unlocking: &BTreeMap, + ) { + } +} + /// A generic representation of a staking implementation. /// /// This interface uses the terminology of NPoS, but it is aims to be generic enough to cover other /// implementations as well. pub trait StakingInterface { /// Balance type used by the staking system. - type Balance: PartialEq; - - /// AccountId type used by the staking system - type AccountId; + type Balance: Sub + + Ord + + PartialEq + + Default + + Copy + + MaxEncodedLen + + FullCodec + + TypeInfo + + Saturating; + + /// AccountId type used by the staking system. + type AccountId: Clone + sp_std::fmt::Debug; + + /// Means of converting Currency to VoteWeight. + type CurrencyToVote: CurrencyToVote; /// The minimum amount required to bond in order to set nomination intentions. This does not /// necessarily mean the nomination will be counted in an election, but instead just enough to @@ -195,8 +248,12 @@ pub trait StakingInterface { /// Return the status of the given staker, `None` if not staked at all. fn status(who: &Self::AccountId) -> Result, DispatchError>; + /// Checks whether or not this is a validator account. + fn is_validator(who: &Self::AccountId) -> bool { + Self::status(who).map(|s| matches!(s, StakerStatus::Validator)).unwrap_or(false) + } + /// Get the nominations of a stash, if they are a nominator, `None` otherwise. - #[cfg(feature = "runtime-benchmarks")] fn nominations(who: &Self::AccountId) -> Option> { match Self::status(who) { Ok(StakerStatus::Nominator(t)) => Some(t), diff --git a/utils/frame/generate-bags/Cargo.toml b/utils/frame/generate-bags/Cargo.toml index e47c838440f91..e8d7d51ead897 100644 --- a/utils/frame/generate-bags/Cargo.toml +++ b/utils/frame/generate-bags/Cargo.toml @@ -14,6 +14,7 @@ frame-support = { version = "4.0.0-dev", path = "../../../frame/support" } frame-election-provider-support = { version = "4.0.0-dev", path = "../../../frame/election-provider-support" } frame-system = { version = "4.0.0-dev", path = "../../../frame/system" } pallet-staking = { version = "4.0.0-dev", path = "../../../frame/staking" } +sp-staking = { version = "4.0.0-dev", path = "../../../primitives/staking" } # third party chrono = { version = "0.4.19" } diff --git a/utils/frame/generate-bags/src/lib.rs b/utils/frame/generate-bags/src/lib.rs index fda78692cb0f3..923017261a44b 100644 --- a/utils/frame/generate-bags/src/lib.rs +++ b/utils/frame/generate-bags/src/lib.rs @@ -18,8 +18,7 @@ //! Support code to ease the process of generating bag thresholds. //! //! NOTE: this assume the runtime implements [`pallet_staking::Config`], as it requires an -//! implementation of the traits [`frame_support::traits::Currency`] and -//! [`frame_support::traits::CurrencyToVote`]. +//! implementation of the traits [`frame_support::traits::Currency`] and `CurrencyToVote`. //! //! The process of adding bags to a runtime requires only four steps. //! @@ -70,7 +69,7 @@ fn existential_weight( total_issuance: u128, minimum_balance: u128, ) -> VoteWeight { - use frame_support::traits::CurrencyToVote; + use sp_staking::currency_to_vote::CurrencyToVote; T::CurrencyToVote::to_vote( minimum_balance From 2cc26466b74fcf7835cb33a9ab48a2798698d912 Mon Sep 17 00:00:00 2001 From: Qinxuan Chen Date: Mon, 10 Jul 2023 05:24:23 +0800 Subject: [PATCH 09/39] replace lru with schnellru (#14539) --- Cargo.lock | 8 ++--- client/executor/Cargo.toml | 2 +- client/executor/src/wasm_runtime.rs | 17 +++++------ client/network-gossip/Cargo.toml | 2 +- client/network-gossip/src/state_machine.rs | 29 +++++++++---------- client/network/sync/Cargo.toml | 2 +- .../network/sync/src/block_request_handler.rs | 16 +++++----- client/network/sync/src/engine.rs | 17 +++++------ .../network/sync/src/state_request_handler.rs | 16 +++++----- primitives/blockchain/Cargo.toml | 2 +- primitives/blockchain/src/header_metadata.rs | 18 +++++------- 11 files changed, 58 insertions(+), 71 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e2a20ece4d0f7..76f3459b16603 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9502,7 +9502,6 @@ dependencies = [ "assert_matches", "criterion", "env_logger 0.9.3", - "lru", "num_cpus", "parity-scale-codec", "parking_lot 0.12.1", @@ -9512,6 +9511,7 @@ dependencies = [ "sc-executor-wasmtime", "sc-runtime-test", "sc-tracing", + "schnellru", "sp-api", "sp-core", "sp-externalities", @@ -9699,10 +9699,10 @@ dependencies = [ "futures-timer", "libp2p", "log", - "lru", "quickcheck", "sc-network", "sc-network-common", + "schnellru", "sp-runtime", "substrate-prometheus-endpoint", "substrate-test-runtime-client", @@ -9759,7 +9759,6 @@ dependencies = [ "futures-timer", "libp2p", "log", - "lru", "mockall", "parity-scale-codec", "prost", @@ -9771,6 +9770,7 @@ dependencies = [ "sc-network", "sc-network-common", "sc-utils", + "schnellru", "smallvec", "sp-arithmetic", "sp-blockchain", @@ -10990,9 +10990,9 @@ version = "4.0.0-dev" dependencies = [ "futures", "log", - "lru", "parity-scale-codec", "parking_lot 0.12.1", + "schnellru", "sp-api", "sp-consensus", "sp-database", diff --git a/client/executor/Cargo.toml b/client/executor/Cargo.toml index 790dd5a9846a2..449fd22e3ffc1 100644 --- a/client/executor/Cargo.toml +++ b/client/executor/Cargo.toml @@ -14,8 +14,8 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -lru = "0.10.0" parking_lot = "0.12.1" +schnellru = "0.2.1" tracing = "0.1.29" codec = { package = "parity-scale-codec", version = "3.6.1" } diff --git a/client/executor/src/wasm_runtime.rs b/client/executor/src/wasm_runtime.rs index dea84467963c3..6dec3abdb20cf 100644 --- a/client/executor/src/wasm_runtime.rs +++ b/client/executor/src/wasm_runtime.rs @@ -22,24 +22,24 @@ //! components of the runtime that are expensive to initialize. use crate::error::{Error, WasmError}; + use codec::Decode; -use lru::LruCache; use parking_lot::Mutex; use sc_executor_common::{ runtime_blob::RuntimeBlob, wasm_runtime::{HeapAllocStrategy, WasmInstance, WasmModule}, }; +use schnellru::{ByLength, LruMap}; use sp_core::traits::{Externalities, FetchRuntimeCode, RuntimeCode}; use sp_version::RuntimeVersion; +use sp_wasm_interface::HostFunctions; + use std::{ - num::NonZeroUsize, panic::AssertUnwindSafe, path::{Path, PathBuf}, sync::Arc, }; -use sp_wasm_interface::HostFunctions; - /// Specification of different methods of executing the runtime Wasm code. #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] pub enum WasmExecutionMethod { @@ -163,7 +163,7 @@ pub struct RuntimeCache { /// A cache of runtimes along with metadata. /// /// Runtimes sorted by recent usage. The most recently used is at the front. - runtimes: Mutex>>, + runtimes: Mutex>>, /// The size of the instances cache for each runtime. max_runtime_instances: usize, cache_path: Option, @@ -185,9 +185,8 @@ impl RuntimeCache { cache_path: Option, runtime_cache_size: u8, ) -> RuntimeCache { - let cap = - NonZeroUsize::new(runtime_cache_size.max(1) as usize).expect("cache size is not zero"); - RuntimeCache { runtimes: Mutex::new(LruCache::new(cap)), max_runtime_instances, cache_path } + let cap = ByLength::new(runtime_cache_size.max(1) as u32); + RuntimeCache { runtimes: Mutex::new(LruMap::new(cap)), max_runtime_instances, cache_path } } /// Prepares a WASM module instance and executes given function for it. @@ -275,7 +274,7 @@ impl RuntimeCache { let versioned_runtime = Arc::new(result?); // Save new versioned wasm runtime in cache - runtimes.put(versioned_runtime_id, versioned_runtime.clone()); + runtimes.insert(versioned_runtime_id, versioned_runtime.clone()); versioned_runtime }; diff --git a/client/network-gossip/Cargo.toml b/client/network-gossip/Cargo.toml index a3616b403aca7..e25a769587dab 100644 --- a/client/network-gossip/Cargo.toml +++ b/client/network-gossip/Cargo.toml @@ -19,7 +19,7 @@ futures = "0.3.21" futures-timer = "3.0.1" libp2p = "0.51.3" log = "0.4.17" -lru = "0.10.0" +schnellru = "0.2.1" tracing = "0.1.29" prometheus-endpoint = { package = "substrate-prometheus-endpoint", version = "0.10.0-dev", path = "../../utils/prometheus" } sc-network = { version = "0.10.0-dev", path = "../network/" } diff --git a/client/network-gossip/src/state_machine.rs b/client/network-gossip/src/state_machine.rs index 24373cd402513..f874a5c15b38b 100644 --- a/client/network-gossip/src/state_machine.rs +++ b/client/network-gossip/src/state_machine.rs @@ -20,12 +20,13 @@ use crate::{MessageIntent, Network, ValidationResult, Validator, ValidatorContex use ahash::AHashSet; use libp2p::PeerId; -use lru::LruCache; +use schnellru::{ByLength, LruMap}; + use prometheus_endpoint::{register, Counter, PrometheusError, Registry, U64}; use sc_network::types::ProtocolName; use sc_network_common::role::ObservedRole; use sp_runtime::traits::{Block as BlockT, Hash, HashFor}; -use std::{collections::HashMap, iter, num::NonZeroUsize, sync::Arc, time, time::Instant}; +use std::{collections::HashMap, iter, sync::Arc, time, time::Instant}; // FIXME: Add additional spam/DoS attack protection: https://github.com/paritytech/substrate/issues/1115 // NOTE: The current value is adjusted based on largest production network deployment (Kusama) and @@ -36,7 +37,7 @@ use std::{collections::HashMap, iter, num::NonZeroUsize, sync::Arc, time, time:: // // Assuming that each known message is tracked with a 32 byte hash (common for `Block::Hash`), then // this cache should take about 256 KB of memory. -const KNOWN_MESSAGES_CACHE_SIZE: usize = 8192; +const KNOWN_MESSAGES_CACHE_SIZE: u32 = 8192; const REBROADCAST_INTERVAL: time::Duration = time::Duration::from_millis(750); @@ -155,7 +156,7 @@ where pub struct ConsensusGossip { peers: HashMap>, messages: Vec>, - known_messages: LruCache, + known_messages: LruMap, protocol: ProtocolName, validator: Arc>, next_broadcast: Instant, @@ -181,11 +182,7 @@ impl ConsensusGossip { ConsensusGossip { peers: HashMap::new(), messages: Default::default(), - known_messages: { - let cap = NonZeroUsize::new(KNOWN_MESSAGES_CACHE_SIZE) - .expect("cache capacity is not zero"); - LruCache::new(cap) - }, + known_messages: { LruMap::new(ByLength::new(KNOWN_MESSAGES_CACHE_SIZE)) }, protocol, validator, next_broadcast: Instant::now() + REBROADCAST_INTERVAL, @@ -216,7 +213,7 @@ impl ConsensusGossip { message: Vec, sender: Option, ) { - if self.known_messages.put(message_hash, ()).is_none() { + if self.known_messages.insert(message_hash, ()) { self.messages.push(MessageEntry { message_hash, topic, message, sender }); if let Some(ref metrics) = self.metrics { @@ -313,7 +310,7 @@ impl ConsensusGossip { ); for (_, ref mut peer) in self.peers.iter_mut() { - peer.known_messages.retain(|h| known_messages.contains(h)); + peer.known_messages.retain(|h| known_messages.get(h).is_some()); } } @@ -348,7 +345,7 @@ impl ConsensusGossip { for message in messages { let message_hash = HashFor::::hash(&message[..]); - if self.known_messages.contains(&message_hash) { + if self.known_messages.get(&message_hash).is_some() { tracing::trace!( target: "gossip", %who, @@ -545,7 +542,7 @@ mod tests { macro_rules! push_msg { ($consensus:expr, $topic:expr, $hash: expr, $m:expr) => { - if $consensus.known_messages.put($hash, ()).is_none() { + if $consensus.known_messages.insert($hash, ()) { $consensus.messages.push(MessageEntry { message_hash: $hash, topic: $topic, @@ -720,8 +717,8 @@ mod tests { push_msg!(consensus, prev_hash, m1_hash, m1); push_msg!(consensus, best_hash, m2_hash, m2); - consensus.known_messages.put(m1_hash, ()); - consensus.known_messages.put(m2_hash, ()); + consensus.known_messages.insert(m1_hash, ()); + consensus.known_messages.insert(m2_hash, ()); consensus.collect_garbage(); assert_eq!(consensus.messages.len(), 2); @@ -734,7 +731,7 @@ mod tests { assert_eq!(consensus.messages.len(), 1); // known messages are only pruned based on size. assert_eq!(consensus.known_messages.len(), 2); - assert!(consensus.known_messages.contains(&m2_hash)); + assert!(consensus.known_messages.get(&m2_hash).is_some()); } #[test] diff --git a/client/network/sync/Cargo.toml b/client/network/sync/Cargo.toml index 5afc92265e26f..1feb1316dbcde 100644 --- a/client/network/sync/Cargo.toml +++ b/client/network/sync/Cargo.toml @@ -24,9 +24,9 @@ futures = "0.3.21" futures-timer = "3.0.2" libp2p = "0.51.3" log = "0.4.17" -lru = "0.10.0" mockall = "0.11.3" prost = "0.11" +schnellru = "0.2.1" smallvec = "1.8.0" thiserror = "1.0" fork-tree = { version = "3.0.0", path = "../../../utils/fork-tree" } diff --git a/client/network/sync/src/block_request_handler.rs b/client/network/sync/src/block_request_handler.rs index 4fa5de3ca3c84..1c576c6188619 100644 --- a/client/network/sync/src/block_request_handler.rs +++ b/client/network/sync/src/block_request_handler.rs @@ -26,8 +26,8 @@ use codec::{Decode, Encode}; use futures::{channel::oneshot, stream::StreamExt}; use libp2p::PeerId; use log::debug; -use lru::LruCache; use prost::Message; +use schnellru::{ByLength, LruMap}; use sc_client_api::BlockBackend; use sc_network::{ @@ -44,7 +44,6 @@ use sp_runtime::{ use std::{ cmp::min, hash::{Hash, Hasher}, - num::NonZeroUsize, sync::Arc, time::Duration, }; @@ -137,7 +136,7 @@ pub struct BlockRequestHandler { /// Maps from request to number of times we have seen this request. /// /// This is used to check if a peer is spamming us with the same request. - seen_requests: LruCache, SeenRequestsValue>, + seen_requests: LruMap, SeenRequestsValue>, } impl BlockRequestHandler @@ -167,9 +166,8 @@ where ); protocol_config.inbound_queue = Some(tx); - let capacity = - NonZeroUsize::new(num_peer_hint.max(1) * 2).expect("cache capacity is not zero"); - let seen_requests = LruCache::new(capacity); + let capacity = ByLength::new(num_peer_hint.max(1) as u32 * 2); + let seen_requests = LruMap::new(capacity); (Self { client, request_receiver, seen_requests }, protocol_config) } @@ -236,7 +234,7 @@ where .difference(BlockAttributes::HEADER | BlockAttributes::JUSTIFICATION) .is_empty(); - match self.seen_requests.get_mut(&key) { + match self.seen_requests.get(&key) { Some(SeenRequestsValue::First) => {}, Some(SeenRequestsValue::Fulfilled(ref mut requests)) => { *requests = requests.saturating_add(1); @@ -250,7 +248,7 @@ where } }, None => { - self.seen_requests.put(key.clone(), SeenRequestsValue::First); + self.seen_requests.insert(key.clone(), SeenRequestsValue::First); }, } @@ -277,7 +275,7 @@ where .iter() .any(|b| !b.header.is_empty() || !b.body.is_empty() || b.is_empty_justification) { - if let Some(value) = self.seen_requests.get_mut(&key) { + if let Some(value) = self.seen_requests.get(&key) { // If this is the first time we have processed this request, we need to change // it to `Fulfilled`. if let SeenRequestsValue::First = value { diff --git a/client/network/sync/src/engine.rs b/client/network/sync/src/engine.rs index 773b6b40f4241..1c57e4a275978 100644 --- a/client/network/sync/src/engine.rs +++ b/client/network/sync/src/engine.rs @@ -28,10 +28,10 @@ use codec::{Decode, Encode}; use futures::{FutureExt, StreamExt}; use futures_timer::Delay; use libp2p::PeerId; -use lru::LruCache; use prometheus_endpoint::{ register, Gauge, GaugeVec, MetricSource, Opts, PrometheusError, Registry, SourcedGauge, U64, }; +use schnellru::{ByLength, LruMap}; use sc_client_api::{BlockBackend, HeaderBackend, ProofProvider}; use sc_consensus::import_queue::ImportQueueService; @@ -239,7 +239,7 @@ pub struct SyncingEngine { default_peers_set_num_light: usize, /// A cache for the data that was associated to a block announcement. - block_announce_data_cache: LruCache>, + block_announce_data_cache: LruMap>, /// The `PeerId`'s of all boot nodes. boot_node_ids: HashSet, @@ -294,12 +294,9 @@ where } else { net_config.network_config.max_blocks_per_request }; - let cache_capacity = NonZeroUsize::new( - (net_config.network_config.default_peers_set.in_peers as usize + - net_config.network_config.default_peers_set.out_peers as usize) - .max(1), - ) - .expect("cache capacity is not zero"); + let cache_capacity = (net_config.network_config.default_peers_set.in_peers + + net_config.network_config.default_peers_set.out_peers) + .max(1); let important_peers = { let mut imp_p = HashSet::new(); for reserved in &net_config.network_config.default_peers_set.reserved_nodes { @@ -381,7 +378,7 @@ where network_service, peers: HashMap::new(), evicted: HashSet::new(), - block_announce_data_cache: LruCache::new(cache_capacity), + block_announce_data_cache: LruMap::new(ByLength::new(cache_capacity)), block_announce_protocol_name, num_connected: num_connected.clone(), is_major_syncing: is_major_syncing.clone(), @@ -465,7 +462,7 @@ where if let Some(data) = announce.data { if !data.is_empty() { - self.block_announce_data_cache.put(announce.header.hash(), data); + self.block_announce_data_cache.insert(announce.header.hash(), data); } } }, diff --git a/client/network/sync/src/state_request_handler.rs b/client/network/sync/src/state_request_handler.rs index 5e2d0ae48f62b..f3af9a3844300 100644 --- a/client/network/sync/src/state_request_handler.rs +++ b/client/network/sync/src/state_request_handler.rs @@ -23,8 +23,8 @@ use codec::{Decode, Encode}; use futures::{channel::oneshot, stream::StreamExt}; use libp2p::PeerId; use log::{debug, trace}; -use lru::LruCache; use prost::Message; +use schnellru::{ByLength, LruMap}; use sc_client_api::{BlockBackend, ProofProvider}; use sc_network::{ @@ -35,7 +35,6 @@ use sp_runtime::traits::Block as BlockT; use std::{ hash::{Hash, Hasher}, - num::NonZeroUsize, sync::Arc, time::Duration, }; @@ -115,7 +114,7 @@ pub struct StateRequestHandler { /// Maps from request to number of times we have seen this request. /// /// This is used to check if a peer is spamming us with the same request. - seen_requests: LruCache, SeenRequestsValue>, + seen_requests: LruMap, SeenRequestsValue>, } impl StateRequestHandler @@ -145,9 +144,8 @@ where ); protocol_config.inbound_queue = Some(tx); - let capacity = - NonZeroUsize::new(num_peer_hint.max(1) * 2).expect("cache capacity is not zero"); - let seen_requests = LruCache::new(capacity); + let capacity = ByLength::new(num_peer_hint.max(1) as u32 * 2); + let seen_requests = LruMap::new(capacity); (Self { client, request_receiver, seen_requests }, protocol_config) } @@ -180,7 +178,7 @@ where let mut reputation_changes = Vec::new(); - match self.seen_requests.get_mut(&key) { + match self.seen_requests.get(&key) { Some(SeenRequestsValue::First) => {}, Some(SeenRequestsValue::Fulfilled(ref mut requests)) => { *requests = requests.saturating_add(1); @@ -190,7 +188,7 @@ where } }, None => { - self.seen_requests.put(key.clone(), SeenRequestsValue::First); + self.seen_requests.insert(key.clone(), SeenRequestsValue::First); }, } @@ -247,7 +245,7 @@ where .last() .map(|e| sp_core::hexdisplay::HexDisplay::from(&e.key))), ); - if let Some(value) = self.seen_requests.get_mut(&key) { + if let Some(value) = self.seen_requests.get(&key) { // If this is the first time we have processed this request, we need to change // it to `Fulfilled`. if let SeenRequestsValue::First = value { diff --git a/primitives/blockchain/Cargo.toml b/primitives/blockchain/Cargo.toml index 725b21a6ba5ad..6320fab9390b9 100644 --- a/primitives/blockchain/Cargo.toml +++ b/primitives/blockchain/Cargo.toml @@ -17,8 +17,8 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } futures = "0.3.21" log = "0.4.17" -lru = "0.10.0" parking_lot = "0.12.1" +schnellru = "0.2.1" thiserror = "1.0.30" sp-api = { version = "4.0.0-dev", path = "../api" } sp-consensus = { version = "0.10.0-dev", path = "../consensus/common" } diff --git a/primitives/blockchain/src/header_metadata.rs b/primitives/blockchain/src/header_metadata.rs index 1d406dd0f4ed4..08b3c9ab3dfbd 100644 --- a/primitives/blockchain/src/header_metadata.rs +++ b/primitives/blockchain/src/header_metadata.rs @@ -18,13 +18,12 @@ //! Implements tree backend, cached header metadata and algorithms //! to compute routes efficiently over the tree of headers. -use lru::LruCache; use parking_lot::RwLock; +use schnellru::{ByLength, LruMap}; use sp_runtime::traits::{Block as BlockT, Header, NumberFor, One}; -use std::num::NonZeroUsize; /// Set to the expected max difference between `best` and `finalized` blocks at sync. -const LRU_CACHE_SIZE: usize = 5_000; +const LRU_CACHE_SIZE: u32 = 5_000; /// Get lowest common ancestor between two blocks in the tree. /// @@ -243,20 +242,19 @@ pub trait HeaderMetadata { /// Caches header metadata in an in-memory LRU cache. pub struct HeaderMetadataCache { - cache: RwLock>>, + cache: RwLock>>, } impl HeaderMetadataCache { /// Creates a new LRU header metadata cache with `capacity`. - pub fn new(capacity: NonZeroUsize) -> Self { - HeaderMetadataCache { cache: RwLock::new(LruCache::new(capacity)) } + pub fn new(capacity: u32) -> Self { + HeaderMetadataCache { cache: RwLock::new(LruMap::new(ByLength::new(capacity))) } } } impl Default for HeaderMetadataCache { fn default() -> Self { - let cap = NonZeroUsize::new(LRU_CACHE_SIZE).expect("cache capacity is not zero"); - HeaderMetadataCache { cache: RwLock::new(LruCache::new(cap)) } + HeaderMetadataCache { cache: RwLock::new(LruMap::new(ByLength::new(LRU_CACHE_SIZE))) } } } @@ -266,11 +264,11 @@ impl HeaderMetadataCache { } pub fn insert_header_metadata(&self, hash: Block::Hash, metadata: CachedHeaderMetadata) { - self.cache.write().put(hash, metadata); + self.cache.write().insert(hash, metadata); } pub fn remove_header_metadata(&self, hash: Block::Hash) { - self.cache.write().pop(&hash); + self.cache.write().remove(&hash); } } From b9e97232900a285b64d13986177edd1328efc525 Mon Sep 17 00:00:00 2001 From: Guillaume Yu Thiolliere Date: Mon, 10 Jul 2023 16:39:37 +0900 Subject: [PATCH 10/39] Better handling of error in inherents logic. (#14521) * impl * trigger CI * Revert "trigger CI" This reverts commit 9426361416cb051b0507576b010efbc1a6ac65b7. * Fix * fix * fix * fix --- .../src/construct_runtime/expand/inherent.rs | 40 ++++++++++++++++--- frame/support/src/lib.rs | 6 +++ 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/frame/support/procedural/src/construct_runtime/expand/inherent.rs b/frame/support/procedural/src/construct_runtime/expand/inherent.rs index 2f1cf75ab7ce9..8218f3746e2c3 100644 --- a/frame/support/procedural/src/construct_runtime/expand/inherent.rs +++ b/frame/support/procedural/src/construct_runtime/expand/inherent.rs @@ -90,9 +90,37 @@ pub fn expand_outer_inherent( use #scrate::inherent::{ProvideInherent, IsFatalError}; use #scrate::traits::{IsSubType, ExtrinsicCall}; use #scrate::sp_runtime::traits::Block as _; + use #scrate::_private::sp_inherents::Error; + use #scrate::log; let mut result = #scrate::inherent::CheckInherentsResult::new(); + // This handle assume we abort on the first fatal error. + fn handle_put_error_result(res: Result<(), Error>) { + const LOG_TARGET: &str = "runtime::inherent"; + match res { + Ok(()) => (), + Err(Error::InherentDataExists(id)) => + log::debug!( + target: LOG_TARGET, + "Some error already reported for inherent {:?}, new non fatal \ + error is ignored", + id + ), + Err(Error::FatalErrorReported) => + log::error!( + target: LOG_TARGET, + "Fatal error already reported, unexpected considering there is \ + only one fatal error", + ), + Err(_) => + log::error!( + target: LOG_TARGET, + "Unexpected error from `put_error` operation", + ), + } + } + for xt in block.extrinsics() { // Inherents are before any other extrinsics. // And signed extrinsics are not inherents. @@ -110,9 +138,9 @@ pub fn expand_outer_inherent( if #pallet_names::is_inherent(call) { is_inherent = true; if let Err(e) = #pallet_names::check_inherent(call, self) { - result.put_error( + handle_put_error_result(result.put_error( #pallet_names::INHERENT_IDENTIFIER, &e - ).expect("There is only one fatal error; qed"); + )); if e.is_fatal_error() { return result; } @@ -153,9 +181,9 @@ pub fn expand_outer_inherent( }); if !found { - result.put_error( + handle_put_error_result(result.put_error( #pallet_names::INHERENT_IDENTIFIER, &e - ).expect("There is only one fatal error; qed"); + )); if e.is_fatal_error() { return result; } @@ -163,9 +191,9 @@ pub fn expand_outer_inherent( }, Ok(None) => (), Err(e) => { - result.put_error( + handle_put_error_result(result.put_error( #pallet_names::INHERENT_IDENTIFIER, &e - ).expect("There is only one fatal error; qed"); + )); if e.is_fatal_error() { return result; } diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 01eec8d2ef79f..2a183b00ee14a 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -1521,6 +1521,12 @@ pub mod tests { } } +/// Private module re-exporting items used by frame support macros. +#[doc(hidden)] +pub mod _private { + pub use sp_inherents; +} + /// Prelude to be used for pallet testing, for ease of use. #[cfg(feature = "std")] pub mod testing_prelude { From 2b76b44e6f7e948c8dffb7ff72d349f0702f5acf Mon Sep 17 00:00:00 2001 From: Oliver Tale-Yazdi Date: Mon, 10 Jul 2023 16:34:05 +0200 Subject: [PATCH 11/39] Add missing workspace members (#14537) Signed-off-by: Oliver Tale-Yazdi --- Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.toml b/Cargo.toml index d616c03c71f61..95acf0b9702cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -244,6 +244,7 @@ members = [ "primitives/weights", "scripts/ci/node-template-release", "test-utils", + "test-utils/cli", "test-utils/client", "test-utils/derive", "test-utils/runtime", From 4b6e735f0fab0c50f13e5b7f656512c101cacdeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Tue, 11 Jul 2023 11:26:44 +0200 Subject: [PATCH 12/39] CI: Do not fail on junit upload failure (#14545) * CI: Do not fail on junit upload failure * fix yaml for test-linux-stable --------- Co-authored-by: alvicsam --- scripts/ci/gitlab/pipeline/test.yml | 31 +++++++++++++++-------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/scripts/ci/gitlab/pipeline/test.yml b/scripts/ci/gitlab/pipeline/test.yml index dc41895b3a16e..2aa67bbf44feb 100644 --- a/scripts/ci/gitlab/pipeline/test.yml +++ b/scripts/ci/gitlab/pipeline/test.yml @@ -37,7 +37,7 @@ cargo-deny-licenses: - echo "___The complete log is in the artifacts___" - $CARGO_DENY_CMD 2> deny.log - if [ $CI_JOB_STATUS != 'success' ]; then - echo 'Please check license of your crate or add an exception to scripts/ci/deny.toml'; + echo 'Please check license of your crate or add an exception to scripts/ci/deny.toml'; fi artifacts: name: $CI_COMMIT_SHORT_SHA @@ -90,15 +90,15 @@ cargo-check-benches: - !reference [.pipeline-stopper-vars, script] # merges in the master branch on PRs. skip if base is not master - 'if [ $CI_COMMIT_REF_NAME != "master" ]; then - BASE=$(curl -s -H "Authorization: Bearer ${GITHUB_PR_TOKEN}" https://api.github.com/repos/paritytech/substrate/pulls/${CI_COMMIT_REF_NAME} | jq -r .base.ref); - printf "Merging base branch %s\n" "${BASE:=master}"; - if [ $BASE != "master" ]; then - echo "$BASE is not master, skipping merge"; - else - git config user.email "ci@gitlab.parity.io"; - git fetch origin "refs/heads/${BASE}"; - git merge --verbose --no-edit FETCH_HEAD; - fi + BASE=$(curl -s -H "Authorization: Bearer ${GITHUB_PR_TOKEN}" https://api.github.com/repos/paritytech/substrate/pulls/${CI_COMMIT_REF_NAME} | jq -r .base.ref); + printf "Merging base branch %s\n" "${BASE:=master}"; + if [ $BASE != "master" ]; then + echo "$BASE is not master, skipping merge"; + else + git config user.email "ci@gitlab.parity.io"; + git fetch origin "refs/heads/${BASE}"; + git merge --verbose --no-edit FETCH_HEAD; + fi fi' parallel: 2 script: @@ -229,11 +229,12 @@ test-linux-stable: # Upload tests results to Elasticsearch - echo "Upload test results to Elasticsearch" - cat target/nextest/default/junit.xml | xq . > target/nextest/default/junit.json - - "curl -v -XPOST --http1.1 - -u ${ELASTIC_USERNAME}:${ELASTIC_PASSWORD} - https://elasticsearch.parity-build.parity.io/unit-tests/_doc/${CI_JOB_ID} - -H 'Content-Type: application/json' - -d @target/nextest/default/junit.json" + - | + curl -v -XPOST --http1.1 \ + -u ${ELASTIC_USERNAME}:${ELASTIC_PASSWORD} \ + https://elasticsearch.parity-build.parity.io/unit-tests/_doc/${CI_JOB_ID} \ + -H 'Content-Type: application/json' \ + -d @target/nextest/default/junit.json || echo "failed to upload junit report" artifacts: when: always paths: From 63246b699d7e2645c8b12aae46f8f0765c682183 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Tue, 11 Jul 2023 16:21:38 +0200 Subject: [PATCH 13/39] Removal of execution strategies (#14387) * Start * More work! * Moar * More changes * More fixes * More worrk * More fixes * More fixes to make it compile * Adds `NoOffchainStorage` * Pass the extensions * Small basti making small progress * Fix merge errors and remove `ExecutionContext` * Move registration of `ReadRuntimeVersionExt` to `ExecutionExtension` Instead of registering `ReadRuntimeVersionExt` in `sp-state-machine` it is moved to `ExecutionExtension` which provides the default extensions. * Fix compilation * Register the global extensions inside runtime api instance * Fixes * Fix `generate_initial_session_keys` by passing the keystore extension * Fix the grandpa tests * Fix more tests * Fix more tests * Don't set any heap pages if there isn't an override * Fix small fallout * FMT * Fix tests * More tests * Offchain worker custom extensions * More fixes * Make offchain tx pool creation reusable Introduces an `OffchainTransactionPoolFactory` for creating offchain transactions pools that can be registered in the runtime externalities context. This factory will be required for a later pr to make the creation of offchain transaction pools easier. * Fixes * Fixes * Set offchain transaction pool in BABE before using it in the runtime * Add the `offchain_tx_pool` to Grandpa as well * Fix the nodes * Print some error when using the old warnings * Fix merge issues * Fix compilation * Rename `babe_link` * Rename to `offchain_tx_pool_factory` * Cleanup * FMT * Fix benchmark name * Fix `try-runtime` * Remove `--execution` CLI args * Make clippy happy * Forward bls functions * Fix docs * Update UI tests * Update client/api/src/execution_extensions.rs Co-authored-by: Michal Kucharczyk <1728078+michalkucharczyk@users.noreply.github.com> * Apply suggestions from code review Co-authored-by: Koute * Update client/cli/src/params/import_params.rs Co-authored-by: Koute * Update client/api/src/execution_extensions.rs Co-authored-by: Koute * Pass the offchain storage to the MMR RPC * Update client/api/src/execution_extensions.rs Co-authored-by: Sebastian Kunert * Review comments * Fixes --------- Co-authored-by: Michal Kucharczyk <1728078+michalkucharczyk@users.noreply.github.com> Co-authored-by: Koute Co-authored-by: Sebastian Kunert --- Cargo.lock | 17 +- bin/node-template/node/Cargo.toml | 2 + bin/node-template/node/src/service.rs | 29 +- .../pallets/template/src/weights.rs | 1 - bin/node/bench/src/construct.rs | 16 +- bin/node/bench/src/import.rs | 23 +- bin/node/bench/src/main.rs | 37 ++- bin/node/bench/src/txpool.rs | 4 +- bin/node/cli/Cargo.toml | 1 + bin/node/cli/benches/block_production.rs | 11 - bin/node/cli/benches/transaction_pool.rs | 9 - bin/node/cli/src/service.rs | 80 ++++-- bin/node/cli/tests/benchmark_block_works.rs | 2 +- bin/node/rpc/src/lib.rs | 35 ++- bin/node/testing/src/bench.rs | 65 +---- client/api/Cargo.toml | 1 - client/api/src/call_executor.rs | 9 +- client/api/src/execution_extensions.rs | 187 +----------- client/api/src/lib.rs | 2 +- client/block-builder/src/lib.rs | 34 +-- client/cli/src/arg_enums.rs | 24 -- client/cli/src/config.rs | 17 -- client/cli/src/params/import_params.rs | 56 ++-- client/cli/src/runner.rs | 1 - client/consensus/aura/src/import_queue.rs | 6 +- client/consensus/babe/Cargo.toml | 1 + client/consensus/babe/rpc/Cargo.toml | 1 + client/consensus/babe/rpc/src/lib.rs | 27 +- client/consensus/babe/src/lib.rs | 76 +++-- client/consensus/babe/src/tests.rs | 4 + client/consensus/grandpa/Cargo.toml | 1 + client/consensus/grandpa/src/environment.rs | 12 +- client/consensus/grandpa/src/lib.rs | 16 +- client/consensus/grandpa/src/tests.rs | 22 +- client/consensus/pow/src/lib.rs | 5 +- client/merkle-mountain-range/rpc/src/lib.rs | 47 ++-- client/offchain/Cargo.toml | 5 + client/offchain/src/api.rs | 114 +------- client/offchain/src/lib.rs | 265 ++++++++++++------ client/rpc-spec-v2/Cargo.toml | 1 + .../rpc-spec-v2/src/chain_head/chain_head.rs | 8 +- .../src/chain_head/subscription/inner.rs | 1 - .../rpc-spec-v2/src/chain_head/test_utils.rs | 8 + client/rpc-spec-v2/src/chain_head/tests.rs | 4 +- client/rpc/Cargo.toml | 1 + client/rpc/src/author/mod.rs | 11 +- client/rpc/src/author/tests.rs | 3 +- client/rpc/src/state/state_full.rs | 8 +- client/rpc/src/state/tests.rs | 2 +- client/service/Cargo.toml | 1 - client/service/src/builder.rs | 47 +--- client/service/src/client/call_executor.rs | 54 +--- client/service/src/client/client.rs | 37 +-- client/service/src/config.rs | 3 - client/service/src/lib.rs | 4 +- client/service/test/src/client/mod.rs | 60 ++-- client/service/test/src/lib.rs | 1 - client/statement-store/src/lib.rs | 12 +- client/transaction-pool/api/src/lib.rs | 58 +++- client/transaction-pool/src/lib.rs | 9 +- frame/benchmarking/README.md | 1 - frame/nfts/src/weights.rs | 1 - primitives/api/Cargo.toml | 2 + .../api/proc-macro/src/decl_runtime_apis.rs | 34 +-- .../api/proc-macro/src/impl_runtime_apis.rs | 39 ++- .../proc-macro/src/mock_impl_runtime_apis.rs | 49 +--- primitives/api/src/lib.rs | 29 +- primitives/api/test/benches/bench.rs | 11 +- primitives/api/test/tests/runtime_calls.rs | 39 +-- .../tests/ui/mock_only_self_reference.stderr | 39 --- .../application-crypto/test/src/ecdsa.rs | 13 +- .../application-crypto/test/src/ed25519.rs | 13 +- .../application-crypto/test/src/sr25519.rs | 13 +- primitives/consensus/common/src/lib.rs | 10 - primitives/core/Cargo.toml | 2 + primitives/core/src/lib.rs | 39 --- primitives/core/src/offchain/mod.rs | 26 +- primitives/core/src/offchain/storage.rs | 96 ++++++- primitives/externalities/src/extensions.rs | 14 + primitives/keystore/src/lib.rs | 171 ++++++++++- primitives/runtime/src/runtime_logger.rs | 7 +- primitives/session/Cargo.toml | 2 + primitives/session/src/lib.rs | 7 +- primitives/state-machine/src/lib.rs | 255 ++--------------- scripts/ci/gitlab/pipeline/test.yml | 6 +- scripts/run_all_benchmarks.sh | 2 - test-utils/client/src/lib.rs | 35 +-- test-utils/runtime/src/genesismap.rs | 7 +- test-utils/runtime/src/lib.rs | 58 ++-- .../runtime/src/substrate_test_pallet.rs | 4 +- utils/frame/benchmarking-cli/src/block/cmd.rs | 4 +- .../benchmarking-cli/src/overhead/README.md | 5 +- .../benchmarking-cli/src/pallet/command.rs | 21 +- .../frame/benchmarking-cli/src/pallet/mod.rs | 8 +- .../benchmarking-cli/src/pallet/writer.rs | 2 - utils/frame/try-runtime/cli/src/lib.rs | 12 +- 96 files changed, 1175 insertions(+), 1499 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 76f3459b16603..0fb4223f5390e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5415,6 +5415,7 @@ dependencies = [ "sc-network-common", "sc-network-statement", "sc-network-sync", + "sc-offchain", "sc-rpc", "sc-service", "sc-service-test", @@ -5577,8 +5578,10 @@ dependencies = [ "sc-consensus-grandpa", "sc-executor", "sc-network", + "sc-offchain", "sc-rpc-api", "sc-service", + "sc-statement-store", "sc-telemetry", "sc-transaction-pool", "sc-transaction-pool-api", @@ -9087,7 +9090,6 @@ dependencies = [ "sp-core", "sp-database", "sp-externalities", - "sp-keystore", "sp-runtime", "sp-state-machine", "sp-statement-store", @@ -9216,6 +9218,7 @@ dependencies = [ "sc-network", "sc-network-test", "sc-telemetry", + "sc-transaction-pool-api", "scale-info", "sp-api", "sp-application-crypto", @@ -9248,6 +9251,7 @@ dependencies = [ "sc-consensus-epochs", "sc-keystore", "sc-rpc-api", + "sc-transaction-pool-api", "serde", "serde_json", "sp-api", @@ -9365,6 +9369,7 @@ dependencies = [ "sc-network-gossip", "sc-network-test", "sc-telemetry", + "sc-transaction-pool-api", "sc-utils", "serde", "serde_json", @@ -9846,6 +9851,7 @@ dependencies = [ "hyper-rustls 0.24.0", "lazy_static", "libp2p", + "log", "num_cpus", "once_cell", "parity-scale-codec", @@ -9855,12 +9861,15 @@ dependencies = [ "sc-client-api", "sc-client-db", "sc-network", + "sc-network-common", "sc-transaction-pool", "sc-transaction-pool-api", "sc-utils", "sp-api", "sp-consensus", "sp-core", + "sp-externalities", + "sp-keystore", "sp-offchain", "sp-runtime", "sp-tracing", @@ -9889,6 +9898,7 @@ dependencies = [ "log", "parity-scale-codec", "parking_lot 0.12.1", + "pretty_assertions", "sc-block-builder", "sc-chain-spec", "sc-client-api", @@ -9961,6 +9971,7 @@ dependencies = [ "log", "parity-scale-codec", "parking_lot 0.12.1", + "pretty_assertions", "sc-block-builder", "sc-chain-spec", "sc-client-api", @@ -10024,7 +10035,6 @@ dependencies = [ "sc-network-light", "sc-network-sync", "sc-network-transactions", - "sc-offchain", "sc-rpc", "sc-rpc-server", "sc-rpc-spec-v2", @@ -10770,6 +10780,7 @@ dependencies = [ "scale-info", "sp-api-proc-macro", "sp-core", + "sp-externalities", "sp-metadata-ir", "sp-runtime", "sp-state-machine", @@ -11153,6 +11164,7 @@ dependencies = [ "substrate-bip39", "thiserror", "tiny-bip39", + "tracing", "w3f-bls", "zeroize", ] @@ -11500,6 +11512,7 @@ dependencies = [ "scale-info", "sp-api", "sp-core", + "sp-keystore", "sp-runtime", "sp-staking", "sp-std", diff --git a/bin/node-template/node/Cargo.toml b/bin/node-template/node/Cargo.toml index a1d1fe1848c33..39f60f52c8344 100644 --- a/bin/node-template/node/Cargo.toml +++ b/bin/node-template/node/Cargo.toml @@ -28,6 +28,8 @@ sc-service = { version = "0.10.0-dev", path = "../../../client/service" } sc-telemetry = { version = "4.0.0-dev", path = "../../../client/telemetry" } sc-transaction-pool = { version = "4.0.0-dev", path = "../../../client/transaction-pool" } sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../../client/transaction-pool/api" } +sc-offchain = { version = "4.0.0-dev", path = "../../../client/offchain" } +sc-statement-store = { version = "4.0.0-dev", path = "../../../client/statement-store" } sc-consensus-aura = { version = "0.10.0-dev", path = "../../../client/consensus/aura" } sp-consensus-aura = { version = "0.10.0-dev", path = "../../../primitives/consensus/aura" } sc-consensus = { version = "0.10.0-dev", path = "../../../client/consensus/common" } diff --git a/bin/node-template/node/src/service.rs b/bin/node-template/node/src/service.rs index 07006925fbb68..355e24c95620b 100644 --- a/bin/node-template/node/src/service.rs +++ b/bin/node-template/node/src/service.rs @@ -1,12 +1,14 @@ //! Service and ServiceFactory implementation. Specialized wrapper over substrate service. +use futures::FutureExt; use node_template_runtime::{self, opaque::Block, RuntimeApi}; -use sc_client_api::BlockBackend; +use sc_client_api::{Backend, BlockBackend}; use sc_consensus_aura::{ImportQueueParams, SlotProportion, StartAuraParams}; use sc_consensus_grandpa::SharedVoterState; pub use sc_executor::NativeElseWasmExecutor; use sc_service::{error::Error as ServiceError, Configuration, TaskManager, WarpSyncParams}; use sc_telemetry::{Telemetry, TelemetryWorker}; +use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sp_consensus_aura::sr25519::AuthorityPair as AuraPair; use std::{sync::Arc, time::Duration}; @@ -179,11 +181,23 @@ pub fn new_full(config: Configuration) -> Result { })?; if config.offchain_worker.enabled { - sc_service::build_offchain_workers( - &config, - task_manager.spawn_handle(), - client.clone(), - network.clone(), + task_manager.spawn_handle().spawn( + "offchain-workers-runner", + "offchain-worker", + sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions { + runtime_api_provider: client.clone(), + is_validator: config.role.is_authority(), + keystore: Some(keystore_container.keystore()), + offchain_db: backend.offchain_storage(), + transaction_pool: Some(OffchainTransactionPoolFactory::new( + transaction_pool.clone(), + )), + network_provider: network.clone(), + enable_http_requests: true, + custom_extensions: |_| vec![], + }) + .run(client.clone(), task_manager.spawn_handle()) + .boxed(), ); } @@ -224,7 +238,7 @@ pub fn new_full(config: Configuration) -> Result { let proposer_factory = sc_basic_authorship::ProposerFactory::new( task_manager.spawn_handle(), client.clone(), - transaction_pool, + transaction_pool.clone(), prometheus_registry.as_ref(), telemetry.as_ref().map(|x| x.handle()), ); @@ -300,6 +314,7 @@ pub fn new_full(config: Configuration) -> Result { prometheus_registry, shared_voter_state: SharedVoterState::empty(), telemetry: telemetry.as_ref().map(|x| x.handle()), + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new(transaction_pool), }; // the GRANDPA voter task is considered infallible, i.e. diff --git a/bin/node-template/pallets/template/src/weights.rs b/bin/node-template/pallets/template/src/weights.rs index e8fbc09bad8e9..7c42936e09f29 100644 --- a/bin/node-template/pallets/template/src/weights.rs +++ b/bin/node-template/pallets/template/src/weights.rs @@ -19,7 +19,6 @@ // * // --steps=50 // --repeat=20 -// --execution=wasm // --wasm-execution=compiled // --output // pallets/template/src/weights.rs diff --git a/bin/node/bench/src/construct.rs b/bin/node/bench/src/construct.rs index ec2a829f692a6..4f3ca07f86b9d 100644 --- a/bin/node/bench/src/construct.rs +++ b/bin/node/bench/src/construct.rs @@ -28,7 +28,7 @@ use futures::Future; use std::{borrow::Cow, collections::HashMap, pin::Pin, sync::Arc}; use node_primitives::Block; -use node_testing::bench::{BenchDb, BlockType, DatabaseType, KeyTypes, Profile}; +use node_testing::bench::{BenchDb, BlockType, DatabaseType, KeyTypes}; use sc_transaction_pool_api::{ ImportNotificationStream, PoolFuture, PoolStatus, ReadyTransactions, TransactionFor, TransactionSource, TransactionStatusStreamFor, TxHash, @@ -43,7 +43,6 @@ use crate::{ }; pub struct ConstructionBenchmarkDescription { - pub profile: Profile, pub key_types: KeyTypes, pub block_type: BlockType, pub size: SizeType, @@ -51,7 +50,6 @@ pub struct ConstructionBenchmarkDescription { } pub struct ConstructionBenchmark { - profile: Profile, database: BenchDb, transactions: Transactions, } @@ -60,11 +58,6 @@ impl core::BenchmarkDescription for ConstructionBenchmarkDescription { fn path(&self) -> Path { let mut path = Path::new(&["node", "proposer"]); - match self.profile { - Profile::Wasm => path.push("wasm"), - Profile::Native => path.push("native"), - } - match self.key_types { KeyTypes::Sr25519 => path.push("sr25519"), KeyTypes::Ed25519 => path.push("ed25519"), @@ -99,7 +92,6 @@ impl core::BenchmarkDescription for ConstructionBenchmarkDescription { } Box::new(ConstructionBenchmark { - profile: self.profile, database: bench_db, transactions: Transactions(extrinsics), }) @@ -107,8 +99,8 @@ impl core::BenchmarkDescription for ConstructionBenchmarkDescription { fn name(&self) -> Cow<'static, str> { format!( - "Block construction ({:?}/{}, {:?}, {:?} backend)", - self.block_type, self.size, self.profile, self.database_type, + "Block construction ({:?}/{}, {:?} backend)", + self.block_type, self.size, self.database_type, ) .into() } @@ -116,7 +108,7 @@ impl core::BenchmarkDescription for ConstructionBenchmarkDescription { impl core::Benchmark for ConstructionBenchmark { fn run(&mut self, mode: Mode) -> std::time::Duration { - let context = self.database.create_context(self.profile); + let context = self.database.create_context(); let _ = context .client diff --git a/bin/node/bench/src/import.rs b/bin/node/bench/src/import.rs index 167377ea9a220..78b280076e0bd 100644 --- a/bin/node/bench/src/import.rs +++ b/bin/node/bench/src/import.rs @@ -33,7 +33,7 @@ use std::borrow::Cow; use node_primitives::Block; -use node_testing::bench::{BenchDb, BlockType, DatabaseType, KeyTypes, Profile}; +use node_testing::bench::{BenchDb, BlockType, DatabaseType, KeyTypes}; use sc_client_api::backend::Backend; use sp_state_machine::InspectState; @@ -43,7 +43,6 @@ use crate::{ }; pub struct ImportBenchmarkDescription { - pub profile: Profile, pub key_types: KeyTypes, pub block_type: BlockType, pub size: SizeType, @@ -51,7 +50,6 @@ pub struct ImportBenchmarkDescription { } pub struct ImportBenchmark { - profile: Profile, database: BenchDb, block: Block, block_type: BlockType, @@ -61,11 +59,6 @@ impl core::BenchmarkDescription for ImportBenchmarkDescription { fn path(&self) -> Path { let mut path = Path::new(&["node", "import"]); - match self.profile { - Profile::Wasm => path.push("wasm"), - Profile::Native => path.push("native"), - } - match self.key_types { KeyTypes::Sr25519 => path.push("sr25519"), KeyTypes::Ed25519 => path.push("ed25519"), @@ -88,21 +81,15 @@ impl core::BenchmarkDescription for ImportBenchmarkDescription { } fn setup(self: Box) -> Box { - let profile = self.profile; let mut bench_db = BenchDb::with_key_types(self.database_type, 50_000, self.key_types); let block = bench_db.generate_block(self.block_type.to_content(self.size.transactions())); - Box::new(ImportBenchmark { - database: bench_db, - block_type: self.block_type, - block, - profile, - }) + Box::new(ImportBenchmark { database: bench_db, block_type: self.block_type, block }) } fn name(&self) -> Cow<'static, str> { format!( - "Block import ({:?}/{}, {:?}, {:?} backend)", - self.block_type, self.size, self.profile, self.database_type, + "Block import ({:?}/{}, {:?} backend)", + self.block_type, self.size, self.database_type, ) .into() } @@ -110,7 +97,7 @@ impl core::BenchmarkDescription for ImportBenchmarkDescription { impl core::Benchmark for ImportBenchmark { fn run(&mut self, mode: Mode) -> std::time::Duration { - let mut context = self.database.create_context(self.profile); + let mut context = self.database.create_context(); let _ = context .client diff --git a/bin/node/bench/src/main.rs b/bin/node/bench/src/main.rs index 051d8ddb9bf55..1f69c97695801 100644 --- a/bin/node/bench/src/main.rs +++ b/bin/node/bench/src/main.rs @@ -30,7 +30,7 @@ mod txpool; use clap::Parser; -use node_testing::bench::{BlockType, DatabaseType as BenchDataBaseType, KeyTypes, Profile}; +use node_testing::bench::{BlockType, DatabaseType as BenchDataBaseType, KeyTypes}; use crate::{ common::SizeType, @@ -85,31 +85,28 @@ fn main() { let mut import_benchmarks = Vec::new(); - for profile in [Profile::Wasm, Profile::Native] { - for size in [ - SizeType::Empty, - SizeType::Small, - SizeType::Medium, - SizeType::Large, - SizeType::Full, - SizeType::Custom(opt.transactions.unwrap_or(0)), + for size in [ + SizeType::Empty, + SizeType::Small, + SizeType::Medium, + SizeType::Large, + SizeType::Full, + SizeType::Custom(opt.transactions.unwrap_or(0)), + ] { + for block_type in [ + BlockType::RandomTransfersKeepAlive, + BlockType::RandomTransfersReaping, + BlockType::Noop, ] { - for block_type in [ - BlockType::RandomTransfersKeepAlive, - BlockType::RandomTransfersReaping, - BlockType::Noop, - ] { - for database_type in [BenchDataBaseType::RocksDb, BenchDataBaseType::ParityDb] { - import_benchmarks.push((profile, size, block_type, database_type)); - } + for database_type in [BenchDataBaseType::RocksDb, BenchDataBaseType::ParityDb] { + import_benchmarks.push((size, block_type, database_type)); } } } let benchmarks = matrix!( - (profile, size, block_type, database_type) in import_benchmarks.into_iter() => + (size, block_type, database_type) in import_benchmarks.into_iter() => ImportBenchmarkDescription { - profile, key_types: KeyTypes::Sr25519, size, block_type, @@ -138,14 +135,12 @@ fn main() { .iter().map(move |db_type| (size, db_type))) => TrieWriteBenchmarkDescription { database_size: *size, database_type: *db_type }, ConstructionBenchmarkDescription { - profile: Profile::Wasm, key_types: KeyTypes::Sr25519, block_type: BlockType::RandomTransfersKeepAlive, size: SizeType::Medium, database_type: BenchDataBaseType::RocksDb, }, ConstructionBenchmarkDescription { - profile: Profile::Wasm, key_types: KeyTypes::Sr25519, block_type: BlockType::RandomTransfersKeepAlive, size: SizeType::Large, diff --git a/bin/node/bench/src/txpool.rs b/bin/node/bench/src/txpool.rs index 4e8e5c0d9a4fd..a3524ac5bc890 100644 --- a/bin/node/bench/src/txpool.rs +++ b/bin/node/bench/src/txpool.rs @@ -23,7 +23,7 @@ use std::borrow::Cow; -use node_testing::bench::{BenchDb, BlockType, DatabaseType, KeyTypes, Profile}; +use node_testing::bench::{BenchDb, BlockType, DatabaseType, KeyTypes}; use sc_transaction_pool::BasicPool; use sc_transaction_pool_api::{TransactionPool, TransactionSource}; @@ -57,7 +57,7 @@ impl core::BenchmarkDescription for PoolBenchmarkDescription { impl core::Benchmark for PoolBenchmark { fn run(&mut self, mode: Mode) -> std::time::Duration { - let context = self.database.create_context(Profile::Wasm); + let context = self.database.create_context(); let _ = context .client diff --git a/bin/node/cli/Cargo.toml b/bin/node/cli/Cargo.toml index d9b3ebee995d8..032ba271f3c81 100644 --- a/bin/node/cli/Cargo.toml +++ b/bin/node/cli/Cargo.toml @@ -83,6 +83,7 @@ sc-authority-discovery = { version = "0.10.0-dev", path = "../../../client/autho sc-sync-state-rpc = { version = "0.10.0-dev", path = "../../../client/sync-state-rpc" } sc-sysinfo = { version = "6.0.0-dev", path = "../../../client/sysinfo" } sc-storage-monitor = { version = "0.1.0", path = "../../../client/storage-monitor" } +sc-offchain = { version = "4.0.0-dev", path = "../../../client/offchain" } # frame dependencies frame-system = { version = "4.0.0-dev", path = "../../../frame/system" } diff --git a/bin/node/cli/benches/block_production.rs b/bin/node/cli/benches/block_production.rs index 527b145c62c46..5ee538d18d6a8 100644 --- a/bin/node/cli/benches/block_production.rs +++ b/bin/node/cli/benches/block_production.rs @@ -21,7 +21,6 @@ use criterion::{criterion_group, criterion_main, BatchSize, Criterion, Throughpu use kitchensink_runtime::{constants::currency::*, BalancesCall}; use node_cli::service::{create_extrinsic, FullClient}; use sc_block_builder::{BlockBuilderProvider, BuiltBlock, RecordProof}; -use sc_client_api::execution_extensions::ExecutionStrategies; use sc_consensus::{ block_import::{BlockImportParams, ForkChoiceStrategy}, BlockImport, StateAction, @@ -56,9 +55,6 @@ fn new_node(tokio_handle: Handle) -> node_cli::service::NewFullBase { let spec = Box::new(node_cli::chain_spec::development_config()); - // NOTE: We enforce the use of the WASM runtime to benchmark block production using WASM. - let execution_strategy = sc_client_api::ExecutionStrategy::AlwaysWasm; - let config = Configuration { impl_name: "BenchmarkImpl".into(), impl_version: "1.0".into(), @@ -77,13 +73,6 @@ fn new_node(tokio_handle: Handle) -> node_cli::service::NewFullBase { wasm_method: WasmExecutionMethod::Compiled { instantiation_strategy: WasmtimeInstantiationStrategy::PoolingCopyOnWrite, }, - execution_strategies: ExecutionStrategies { - syncing: execution_strategy, - importing: execution_strategy, - block_construction: execution_strategy, - offchain_worker: execution_strategy, - other: execution_strategy, - }, rpc_addr: None, rpc_max_connections: Default::default(), rpc_cors: None, diff --git a/bin/node/cli/benches/transaction_pool.rs b/bin/node/cli/benches/transaction_pool.rs index 44ebe1e7d4fe6..d3e8c02a958f7 100644 --- a/bin/node/cli/benches/transaction_pool.rs +++ b/bin/node/cli/benches/transaction_pool.rs @@ -23,7 +23,6 @@ use futures::{future, StreamExt}; use kitchensink_runtime::{constants::currency::*, BalancesCall, SudoCall}; use node_cli::service::{create_extrinsic, fetch_nonce, FullClient, TransactionPool}; use node_primitives::AccountId; -use sc_client_api::execution_extensions::ExecutionStrategies; use sc_service::{ config::{ BlocksPruning, DatabaseSource, KeystoreConfig, NetworkConfiguration, OffchainWorkerConfig, @@ -70,14 +69,6 @@ fn new_node(tokio_handle: Handle) -> node_cli::service::NewFullBase { blocks_pruning: BlocksPruning::KeepAll, chain_spec: spec, wasm_method: Default::default(), - // NOTE: we enforce the use of the native runtime to make the errors more debuggable - execution_strategies: ExecutionStrategies { - syncing: sc_client_api::ExecutionStrategy::NativeWhenPossible, - importing: sc_client_api::ExecutionStrategy::NativeWhenPossible, - block_construction: sc_client_api::ExecutionStrategy::NativeWhenPossible, - offchain_worker: sc_client_api::ExecutionStrategy::NativeWhenPossible, - other: sc_client_api::ExecutionStrategy::NativeWhenPossible, - }, rpc_addr: None, rpc_max_connections: Default::default(), rpc_cors: None, diff --git a/bin/node/cli/src/service.rs b/bin/node/cli/src/service.rs index 81f4575384473..487c6c48f0061 100644 --- a/bin/node/cli/src/service.rs +++ b/bin/node/cli/src/service.rs @@ -28,7 +28,7 @@ use futures::prelude::*; use kitchensink_runtime::RuntimeApi; use node_executor::ExecutorDispatch; use node_primitives::Block; -use sc_client_api::BlockBackend; +use sc_client_api::{Backend, BlockBackend}; use sc_consensus_babe::{self, SlotProportion}; use sc_executor::NativeElseWasmExecutor; use sc_network::{event::Event, NetworkEventStream, NetworkService}; @@ -37,6 +37,7 @@ use sc_network_sync::SyncingService; use sc_service::{config::Configuration, error::Error as ServiceError, RpcHandlers, TaskManager}; use sc_statement_store::Store as StatementStore; use sc_telemetry::{Telemetry, TelemetryWorker}; +use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sp_api::ProvideRuntimeApi; use sp_core::crypto::Pair; use sp_runtime::{generic, traits::Block as BlockT, SaturatedConversion}; @@ -205,27 +206,29 @@ pub fn new_partial( )?; let slot_duration = babe_link.config().slot_duration(); - let (import_queue, babe_worker_handle) = sc_consensus_babe::import_queue( - babe_link.clone(), - block_import.clone(), - Some(Box::new(justification_import)), - client.clone(), - select_chain.clone(), - move |_, ()| async move { - let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); + let (import_queue, babe_worker_handle) = + sc_consensus_babe::import_queue(sc_consensus_babe::ImportQueueParams { + link: babe_link.clone(), + block_import: block_import.clone(), + justification_import: Some(Box::new(justification_import)), + client: client.clone(), + select_chain: select_chain.clone(), + create_inherent_data_providers: move |_, ()| async move { + let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); - let slot = + let slot = sp_consensus_babe::inherents::InherentDataProvider::from_timestamp_and_slot_duration( *timestamp, slot_duration, ); - Ok((slot, timestamp)) - }, - &task_manager.spawn_essential_handle(), - config.prometheus_registry(), - telemetry.as_ref().map(|x| x.handle()), - )?; + Ok((slot, timestamp)) + }, + spawner: &task_manager.spawn_essential_handle(), + registry: config.prometheus_registry(), + telemetry: telemetry.as_ref().map(|x| x.handle()), + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new(transaction_pool.clone()), + })?; let import_setup = (block_import, grandpa_link, babe_link); @@ -278,9 +281,10 @@ pub fn new_partial( finality_provider: finality_proof_provider.clone(), }, statement_store: rpc_statement_store.clone(), + backend: rpc_backend.clone(), }; - node_rpc::create_full(deps, rpc_backend.clone()).map_err(Into::into) + node_rpc::create_full(deps).map_err(Into::into) }; (rpc_extensions_builder, shared_voter_state2) @@ -381,15 +385,6 @@ pub fn new_full_base( warp_sync_params: Some(WarpSyncParams::WithProvider(warp_sync)), })?; - if config.offchain_worker.enabled { - sc_service::build_offchain_workers( - &config, - task_manager.spawn_handle(), - client.clone(), - network.clone(), - ); - } - let role = config.role.clone(); let force_authoring = config.force_authoring; let backoff_authoring_blocks = @@ -397,10 +392,11 @@ pub fn new_full_base( let name = config.network.node_name.clone(); let enable_grandpa = !config.disable_grandpa; let prometheus_registry = config.prometheus_registry().cloned(); + let enable_offchain_worker = config.offchain_worker.enabled; let rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams { config, - backend, + backend: backend.clone(), client: client.clone(), keystore: keystore_container.keystore(), network: network.clone(), @@ -525,14 +521,14 @@ pub fn new_full_base( // need a keystore, regardless of which protocol we use below. let keystore = if role.is_authority() { Some(keystore_container.keystore()) } else { None }; - let config = grandpa::Config { + let grandpa_config = grandpa::Config { // FIXME #1578 make this available through chainspec gossip_duration: std::time::Duration::from_millis(333), justification_period: 512, name: Some(name), observer_enabled: false, keystore, - local_role: role, + local_role: role.clone(), telemetry: telemetry.as_ref().map(|x| x.handle()), protocol_name: grandpa_protocol_name, }; @@ -545,7 +541,7 @@ pub fn new_full_base( // been tested extensively yet and having most nodes in a network run it // could lead to finality stalls. let grandpa_config = grandpa::GrandpaParams { - config, + config: grandpa_config, link: grandpa_link, network: network.clone(), sync: Arc::new(sync_service.clone()), @@ -553,6 +549,7 @@ pub fn new_full_base( voting_rule: grandpa::VotingRulesBuilder::default().build(), prometheus_registry: prometheus_registry.clone(), shared_voter_state, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new(transaction_pool.clone()), }; // the GRANDPA voter task is considered infallible, i.e. @@ -584,6 +581,29 @@ pub fn new_full_base( statement_handler.run(), ); + if enable_offchain_worker { + task_manager.spawn_handle().spawn( + "offchain-workers-runner", + "offchain-work", + sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions { + runtime_api_provider: client.clone(), + keystore: Some(keystore_container.keystore()), + offchain_db: backend.offchain_storage(), + transaction_pool: Some(OffchainTransactionPoolFactory::new( + transaction_pool.clone(), + )), + network_provider: network.clone(), + is_validator: role.is_authority(), + enable_http_requests: true, + custom_extensions: move |_| { + vec![Box::new(statement_store.clone().as_statement_store_ext()) as Box<_>] + }, + }) + .run(client.clone(), task_manager.spawn_handle()) + .boxed(), + ); + } + network_starter.start_network(); Ok(NewFullBase { task_manager, diff --git a/bin/node/cli/tests/benchmark_block_works.rs b/bin/node/cli/tests/benchmark_block_works.rs index 50103a66a4d40..09c2f262e2c29 100644 --- a/bin/node/cli/tests/benchmark_block_works.rs +++ b/bin/node/cli/tests/benchmark_block_works.rs @@ -39,7 +39,7 @@ async fn benchmark_block_works() { .arg(base_dir.path()) .args(["--from", "1", "--to", "1"]) .args(["--repeat", "1"]) - .args(["--execution", "wasm", "--wasm-execution", "compiled"]) + .args(["--wasm-execution", "compiled"]) .status() .unwrap(); diff --git a/bin/node/rpc/src/lib.rs b/bin/node/rpc/src/lib.rs index 5ab96bf1c7064..40c4741dbc1c8 100644 --- a/bin/node/rpc/src/lib.rs +++ b/bin/node/rpc/src/lib.rs @@ -90,12 +90,23 @@ pub struct FullDeps { pub grandpa: GrandpaDeps, /// Shared statement store reference. pub statement_store: Arc, + /// The backend used by the node. + pub backend: Arc, } /// Instantiate all Full RPC extensions. pub fn create_full( - deps: FullDeps, - backend: Arc, + FullDeps { + client, + pool, + select_chain, + chain_spec, + deny_unsafe, + babe, + grandpa, + statement_store, + backend, + }: FullDeps, ) -> Result, Box> where C: ProvideRuntimeApi @@ -130,16 +141,6 @@ where use substrate_state_trie_migration_rpc::{StateMigration, StateMigrationApiServer}; let mut io = RpcModule::new(()); - let FullDeps { - client, - pool, - select_chain, - chain_spec, - deny_unsafe, - babe, - grandpa, - statement_store, - } = deps; let BabeDeps { keystore, babe_worker_handle } = babe; let GrandpaDeps { @@ -159,7 +160,15 @@ where // Making synchronous calls in light client freezes the browser currently, // more context: https://github.com/paritytech/substrate/pull/3480 // These RPCs should use an asynchronous caller instead. - io.merge(Mmr::new(client.clone()).into_rpc())?; + io.merge( + Mmr::new( + client.clone(), + backend + .offchain_storage() + .ok_or_else(|| "Backend doesn't provide an offchain storage")?, + ) + .into_rpc(), + )?; io.merge(TransactionPayment::new(client.clone()).into_rpc())?; io.merge( Babe::new(client.clone(), babe_worker_handle.clone(), keystore, select_chain, deny_unsafe) diff --git a/bin/node/testing/src/bench.rs b/bin/node/testing/src/bench.rs index 9708b2c343263..f1ab2212239b1 100644 --- a/bin/node/testing/src/bench.rs +++ b/bin/node/testing/src/bench.rs @@ -40,17 +40,14 @@ use kitchensink_runtime::{ }; use node_primitives::Block; use sc_block_builder::BlockBuilderProvider; -use sc_client_api::{ - execution_extensions::{ExecutionExtensions, ExecutionStrategies}, - ExecutionStrategy, -}; +use sc_client_api::execution_extensions::ExecutionExtensions; use sc_client_db::PruningMode; use sc_consensus::{BlockImport, BlockImportParams, ForkChoiceStrategy, ImportResult, ImportedAux}; use sc_executor::{NativeElseWasmExecutor, WasmExecutionMethod, WasmtimeInstantiationStrategy}; use sp_api::ProvideRuntimeApi; use sp_block_builder::BlockBuilder; use sp_consensus::BlockOrigin; -use sp_core::{blake2_256, ed25519, sr25519, traits::SpawnNamed, ExecutionContext, Pair, Public}; +use sp_core::{blake2_256, ed25519, sr25519, traits::SpawnNamed, Pair, Public}; use sp_inherents::InherentData; use sp_runtime::{ traits::{Block as BlockT, IdentifyAccount, Verify}, @@ -354,7 +351,7 @@ impl BenchDb { dir.path().to_string_lossy(), ); let (_client, _backend, _task_executor) = - Self::bench_client(database_type, dir.path(), Profile::Native, &keyring); + Self::bench_client(database_type, dir.path(), &keyring); let directory_guard = Guard(dir); BenchDb { keyring, directory_guard, database_type } @@ -380,7 +377,6 @@ impl BenchDb { fn bench_client( database_type: DatabaseType, dir: &std::path::Path, - profile: Profile, keyring: &BenchKeyring, ) -> (Client, std::sync::Arc, TaskExecutor) { let db_config = sc_client_db::DatabaseSettings { @@ -415,12 +411,7 @@ impl BenchDb { genesis_block_builder, None, None, - ExecutionExtensions::new( - profile.into_execution_strategies(), - None, - None, - Arc::new(executor), - ), + ExecutionExtensions::new(None, Arc::new(executor)), Box::new(task_executor.clone()), None, None, @@ -444,11 +435,7 @@ impl BenchDb { client .runtime_api() - .inherent_extrinsics_with_context( - client.chain_info().genesis_hash, - ExecutionContext::BlockConstruction, - inherent_data, - ) + .inherent_extrinsics(client.chain_info().genesis_hash, inherent_data) .expect("Get inherents failed") } @@ -459,12 +446,8 @@ impl BenchDb { /// Get cliet for this database operations. pub fn client(&mut self) -> Client { - let (client, _backend, _task_executor) = Self::bench_client( - self.database_type, - self.directory_guard.path(), - Profile::Wasm, - &self.keyring, - ); + let (client, _backend, _task_executor) = + Self::bench_client(self.database_type, self.directory_guard.path(), &self.keyring); client } @@ -507,10 +490,10 @@ impl BenchDb { } /// Clone this database and create context for testing/benchmarking. - pub fn create_context(&self, profile: Profile) -> BenchContext { + pub fn create_context(&self) -> BenchContext { let BenchDb { directory_guard, keyring, database_type } = self.clone(); let (client, backend, task_executor) = - Self::bench_client(database_type, directory_guard.path(), profile, &keyring); + Self::bench_client(database_type, directory_guard.path(), &keyring); BenchContext { client: Arc::new(client), @@ -611,36 +594,6 @@ impl BenchKeyring { } } -/// Profile for exetion strategies. -#[derive(Clone, Copy, Debug)] -pub enum Profile { - /// As native as possible. - Native, - /// As wasm as possible. - Wasm, -} - -impl Profile { - fn into_execution_strategies(self) -> ExecutionStrategies { - match self { - Profile::Wasm => ExecutionStrategies { - syncing: ExecutionStrategy::AlwaysWasm, - importing: ExecutionStrategy::AlwaysWasm, - block_construction: ExecutionStrategy::AlwaysWasm, - offchain_worker: ExecutionStrategy::AlwaysWasm, - other: ExecutionStrategy::AlwaysWasm, - }, - Profile::Native => ExecutionStrategies { - syncing: ExecutionStrategy::NativeElseWasm, - importing: ExecutionStrategy::NativeElseWasm, - block_construction: ExecutionStrategy::NativeElseWasm, - offchain_worker: ExecutionStrategy::NativeElseWasm, - other: ExecutionStrategy::NativeElseWasm, - }, - } - } -} - struct Guard(tempfile::TempDir); impl Guard { diff --git a/client/api/Cargo.toml b/client/api/Cargo.toml index be47c2931abbd..17f9747c39bc1 100644 --- a/client/api/Cargo.toml +++ b/client/api/Cargo.toml @@ -31,7 +31,6 @@ sp-consensus = { version = "0.10.0-dev", path = "../../primitives/consensus/comm sp-core = { version = "21.0.0", default-features = false, path = "../../primitives/core" } sp-database = { version = "4.0.0-dev", path = "../../primitives/database" } sp-externalities = { version = "0.19.0", path = "../../primitives/externalities" } -sp-keystore = { version = "0.27.0", default-features = false, path = "../../primitives/keystore" } sp-runtime = { version = "24.0.0", default-features = false, path = "../../primitives/runtime" } sp-state-machine = { version = "0.28.0", path = "../../primitives/state-machine" } sp-statement-store = { version = "4.0.0-dev", path = "../../primitives/statement-store" } diff --git a/client/api/src/call_executor.rs b/client/api/src/call_executor.rs index db8e4d8495af2..cecc1053d1b9d 100644 --- a/client/api/src/call_executor.rs +++ b/client/api/src/call_executor.rs @@ -20,12 +20,13 @@ use sc_executor::{RuntimeVersion, RuntimeVersionOf}; use sp_core::traits::CallContext; +use sp_externalities::Extensions; use sp_runtime::traits::Block as BlockT; -use sp_state_machine::{ExecutionStrategy, OverlayedChanges, StorageProof}; +use sp_state_machine::{OverlayedChanges, StorageProof}; use std::cell::RefCell; use crate::execution_extensions::ExecutionExtensions; -use sp_api::{ExecutionContext, ProofRecorder, StorageTransactionCache}; +use sp_api::{ProofRecorder, StorageTransactionCache}; /// Executor Provider pub trait ExecutorProvider { @@ -58,7 +59,6 @@ pub trait CallExecutor: RuntimeVersionOf { at_hash: B::Hash, method: &str, call_data: &[u8], - strategy: ExecutionStrategy, context: CallContext, ) -> Result, sp_blockchain::Error>; @@ -79,7 +79,8 @@ pub trait CallExecutor: RuntimeVersionOf { >, >, proof_recorder: &Option>, - context: ExecutionContext, + call_context: CallContext, + extensions: &RefCell, ) -> sp_blockchain::Result>; /// Extract RuntimeVersion of given block diff --git a/client/api/src/execution_extensions.rs b/client/api/src/execution_extensions.rs index 20dc34d19b1de..6f927105df0bf 100644 --- a/client/api/src/execution_extensions.rs +++ b/client/api/src/execution_extensions.rs @@ -23,48 +23,10 @@ //! extensions to support APIs for particular execution context & capabilities. use parking_lot::RwLock; -use sc_transaction_pool_api::OffchainTransactionPoolFactory; -use sp_core::{ - offchain::{self, OffchainDbExt, OffchainWorkerExt}, - traits::{ReadRuntimeVersion, ReadRuntimeVersionExt}, - ExecutionContext, -}; +use sp_core::traits::{ReadRuntimeVersion, ReadRuntimeVersionExt}; use sp_externalities::{Extension, Extensions}; -use sp_keystore::{KeystoreExt, KeystorePtr}; use sp_runtime::traits::{Block as BlockT, NumberFor}; -pub use sp_state_machine::ExecutionStrategy; -use sp_state_machine::{DefaultHandler, ExecutionManager}; -use std::{ - marker::PhantomData, - sync::{Arc, Weak}, -}; - -/// Execution strategies settings. -#[derive(Debug, Clone)] -pub struct ExecutionStrategies { - /// Execution strategy used when syncing. - pub syncing: ExecutionStrategy, - /// Execution strategy used when importing blocks. - pub importing: ExecutionStrategy, - /// Execution strategy used when constructing blocks. - pub block_construction: ExecutionStrategy, - /// Execution strategy used for offchain workers. - pub offchain_worker: ExecutionStrategy, - /// Execution strategy used in other cases. - pub other: ExecutionStrategy, -} - -impl Default for ExecutionStrategies { - fn default() -> ExecutionStrategies { - ExecutionStrategies { - syncing: ExecutionStrategy::NativeElseWasm, - importing: ExecutionStrategy::NativeElseWasm, - block_construction: ExecutionStrategy::AlwaysWasm, - offchain_worker: ExecutionStrategy::NativeWhenPossible, - other: ExecutionStrategy::NativeElseWasm, - } - } -} +use std::{marker::PhantomData, sync::Arc}; /// Generate the starting set of [`Extensions`]. /// @@ -74,22 +36,12 @@ pub trait ExtensionsFactory: Send + Sync { /// /// - `block_hash`: The hash of the block in the context that extensions will be used. /// - `block_number`: The number of the block in the context that extensions will be used. - /// - `capabilities`: The capabilities - fn extensions_for( - &self, - block_hash: Block::Hash, - block_number: NumberFor, - capabilities: offchain::Capabilities, - ) -> Extensions; + fn extensions_for(&self, block_hash: Block::Hash, block_number: NumberFor) + -> Extensions; } impl ExtensionsFactory for () { - fn extensions_for( - &self, - _: Block::Hash, - _: NumberFor, - _capabilities: offchain::Capabilities, - ) -> Extensions { + fn extensions_for(&self, _: Block::Hash, _: NumberFor) -> Extensions { Extensions::new() } } @@ -99,10 +51,9 @@ impl> ExtensionsFactory for Ve &self, block_hash: Block::Hash, block_number: NumberFor, - capabilities: offchain::Capabilities, ) -> Extensions { let mut exts = Extensions::new(); - exts.extend(self.iter().map(|e| e.extensions_for(block_hash, block_number, capabilities))); + exts.extend(self.iter().map(|e| e.extensions_for(block_hash, block_number))); exts } } @@ -125,12 +76,7 @@ impl ExtensionBeforeBlock { impl ExtensionsFactory for ExtensionBeforeBlock { - fn extensions_for( - &self, - _: Block::Hash, - block_number: NumberFor, - _: offchain::Capabilities, - ) -> Extensions { + fn extensions_for(&self, _: Block::Hash, block_number: NumberFor) -> Extensions { let mut exts = Extensions::new(); if block_number < self.before { @@ -141,154 +87,47 @@ impl ExtensionsFactory } } -/// Create a Offchain DB accessor object. -pub trait DbExternalitiesFactory: Send + Sync { - /// Create [`offchain::DbExternalities`] instance. - fn create(&self) -> Box; -} - -impl DbExternalitiesFactory for T { - fn create(&self) -> Box { - Box::new(self.clone()) - } -} - /// A producer of execution extensions for offchain calls. /// /// This crate aggregates extensions available for the offchain calls /// and is responsible for producing a correct `Extensions` object. /// for each call, based on required `Capabilities`. pub struct ExecutionExtensions { - strategies: ExecutionStrategies, - keystore: Option, - offchain_db: Option>, - // FIXME: these three are only RwLock because of https://github.com/paritytech/substrate/issues/4587 - // remove when fixed. - transaction_pool_factory: RwLock>>, extensions_factory: RwLock>>, - statement_store: RwLock>>, read_runtime_version: Arc, } impl ExecutionExtensions { - /// Create new `ExecutionExtensions` given a `keystore` and `ExecutionStrategies`. + /// Create new `ExecutionExtensions` given an `extensions_factory`. pub fn new( - strategies: ExecutionStrategies, - keystore: Option, - offchain_db: Option>, + extensions_factory: Option>>, read_runtime_version: Arc, ) -> Self { - let transaction_pool = RwLock::new(None); - let statement_store = RwLock::new(None); - let extensions_factory = Box::new(()); Self { - strategies, - keystore, - offchain_db, - extensions_factory: RwLock::new(extensions_factory), - transaction_pool_factory: transaction_pool, - statement_store, + extensions_factory: extensions_factory + .map(RwLock::new) + .unwrap_or_else(|| RwLock::new(Box::new(()))), read_runtime_version, } } - /// Get a reference to the execution strategies. - pub fn strategies(&self) -> &ExecutionStrategies { - &self.strategies - } - /// Set the new extensions_factory pub fn set_extensions_factory(&self, maker: impl ExtensionsFactory + 'static) { *self.extensions_factory.write() = Box::new(maker); } - /// Register transaction pool extension. - pub fn register_transaction_pool_factory( - &self, - factory: OffchainTransactionPoolFactory, - ) { - *self.transaction_pool_factory.write() = Some(factory); - } - - /// Register statement store extension. - pub fn register_statement_store(&self, store: Arc) { - *self.statement_store.write() = Some(Arc::downgrade(&store) as _); - } - /// Based on the execution context and capabilities it produces /// the extensions object to support desired set of APIs. pub fn extensions( &self, block_hash: Block::Hash, block_number: NumberFor, - context: ExecutionContext, ) -> Extensions { - let capabilities = context.capabilities(); - let mut extensions = - self.extensions_factory - .read() - .extensions_for(block_hash, block_number, capabilities); - - if capabilities.contains(offchain::Capabilities::KEYSTORE) { - if let Some(ref keystore) = self.keystore { - extensions.register(KeystoreExt(keystore.clone())); - } - } - - if capabilities.contains(offchain::Capabilities::TRANSACTION_POOL) { - if let Some(pool) = self.transaction_pool_factory.read().as_ref() { - extensions.register(pool.offchain_transaction_pool(block_hash)); - } - } - - if capabilities.contains(offchain::Capabilities::STATEMENT_STORE) { - if let Some(store) = self.statement_store.read().as_ref().and_then(|x| x.upgrade()) { - extensions.register(sp_statement_store::runtime_api::StatementStoreExt(store)); - } - } - if capabilities.contains(offchain::Capabilities::OFFCHAIN_DB_READ) || - capabilities.contains(offchain::Capabilities::OFFCHAIN_DB_WRITE) - { - if let Some(offchain_db) = self.offchain_db.as_ref() { - extensions.register(OffchainDbExt::new(offchain::LimitedExternalities::new( - capabilities, - offchain_db.create(), - ))); - } - } - - if let ExecutionContext::OffchainCall(Some(ext)) = context { - extensions.register(OffchainWorkerExt::new(offchain::LimitedExternalities::new( - capabilities, - ext.0, - ))); - } + self.extensions_factory.read().extensions_for(block_hash, block_number); extensions.register(ReadRuntimeVersionExt::new(self.read_runtime_version.clone())); extensions } - - /// Create `ExecutionManager` and `Extensions` for given offchain call. - /// - /// Based on the execution context and capabilities it produces - /// the right manager and extensions object to support desired set of APIs. - pub fn manager_and_extensions( - &self, - block_hash: Block::Hash, - block_number: NumberFor, - context: ExecutionContext, - ) -> (ExecutionManager>, Extensions) { - let manager = match context { - ExecutionContext::BlockConstruction => self.strategies.block_construction.get_manager(), - ExecutionContext::Syncing => self.strategies.syncing.get_manager(), - ExecutionContext::Importing => self.strategies.importing.get_manager(), - ExecutionContext::OffchainCall(Some((_, capabilities))) if capabilities.is_all() => - self.strategies.offchain_worker.get_manager(), - ExecutionContext::OffchainCall(_) => self.strategies.other.get_manager(), - }; - - (manager, self.extensions(block_hash, block_number, context)) - } } diff --git a/client/api/src/lib.rs b/client/api/src/lib.rs index 0faddc10fe016..faadf3663a59d 100644 --- a/client/api/src/lib.rs +++ b/client/api/src/lib.rs @@ -36,7 +36,7 @@ pub use proof_provider::*; pub use sp_blockchain as blockchain; pub use sp_blockchain::HeaderBackend; -pub use sp_state_machine::{CompactProof, ExecutionStrategy, StorageProof}; +pub use sp_state_machine::{CompactProof, StorageProof}; pub use sp_storage::{ChildInfo, PrefixedStorageKey, StorageData, StorageKey}; /// Usage Information Provider interface diff --git a/client/block-builder/src/lib.rs b/client/block-builder/src/lib.rs index f055d4688822a..7c57c77f3dad5 100644 --- a/client/block-builder/src/lib.rs +++ b/client/block-builder/src/lib.rs @@ -32,7 +32,7 @@ use sp_api::{ ApiExt, ApiRef, Core, ProvideRuntimeApi, StorageChanges, StorageProof, TransactionOutcome, }; use sp_blockchain::{ApplyExtrinsicFailed, Error}; -use sp_core::ExecutionContext; +use sp_core::traits::CallContext; use sp_runtime::{ legacy, traits::{Block as BlockT, Hash, HashFor, Header as HeaderT, NumberFor, One}, @@ -178,11 +178,9 @@ where api.record_proof(); } - api.initialize_block_with_context( - parent_hash, - ExecutionContext::BlockConstruction, - &header, - )?; + api.set_call_context(CallContext::Onchain); + + api.initialize_block(parent_hash, &header)?; let version = api .api_version::>(parent_hash)? @@ -209,18 +207,10 @@ where self.api.execute_in_transaction(|api| { let res = if version < 6 { #[allow(deprecated)] - api.apply_extrinsic_before_version_6_with_context( - parent_hash, - ExecutionContext::BlockConstruction, - xt.clone(), - ) - .map(legacy::byte_sized_error::convert_to_latest) + api.apply_extrinsic_before_version_6(parent_hash, xt.clone()) + .map(legacy::byte_sized_error::convert_to_latest) } else { - api.apply_extrinsic_with_context( - parent_hash, - ExecutionContext::BlockConstruction, - xt.clone(), - ) + api.apply_extrinsic(parent_hash, xt.clone()) }; match res { @@ -242,9 +232,7 @@ where /// supplied by `self.api`, combined as [`BuiltBlock`]. /// The storage proof will be `Some(_)` when proof recording was enabled. pub fn build(mut self) -> Result>, Error> { - let header = self - .api - .finalize_block_with_context(self.parent_hash, ExecutionContext::BlockConstruction)?; + let header = self.api.finalize_block(self.parent_hash)?; debug_assert_eq!( header.extrinsics_root().clone(), @@ -282,11 +270,7 @@ where .execute_in_transaction(move |api| { // `create_inherents` should not change any state, to ensure this we always rollback // the transaction. - TransactionOutcome::Rollback(api.inherent_extrinsics_with_context( - parent_hash, - ExecutionContext::BlockConstruction, - inherent_data, - )) + TransactionOutcome::Rollback(api.inherent_extrinsics(parent_hash, inherent_data)) }) .map_err(|e| Error::Application(Box::new(e))) } diff --git a/client/cli/src/arg_enums.rs b/client/cli/src/arg_enums.rs index 982979605a32d..40d86fd97988d 100644 --- a/client/cli/src/arg_enums.rs +++ b/client/cli/src/arg_enums.rs @@ -161,17 +161,6 @@ pub enum ExecutionStrategy { NativeElseWasm, } -impl Into for ExecutionStrategy { - fn into(self) -> sc_client_api::ExecutionStrategy { - match self { - ExecutionStrategy::Native => sc_client_api::ExecutionStrategy::NativeWhenPossible, - ExecutionStrategy::Wasm => sc_client_api::ExecutionStrategy::AlwaysWasm, - ExecutionStrategy::Both => sc_client_api::ExecutionStrategy::Both, - ExecutionStrategy::NativeElseWasm => sc_client_api::ExecutionStrategy::NativeElseWasm, - } - } -} - /// Available RPC methods. #[allow(missing_docs)] #[derive(Debug, Copy, Clone, PartialEq, ValueEnum)] @@ -270,16 +259,3 @@ impl Into for SyncMode { } } } - -/// Default value for the `--execution-syncing` parameter. -pub const DEFAULT_EXECUTION_SYNCING: ExecutionStrategy = ExecutionStrategy::Wasm; -/// Default value for the `--execution-import-block` parameter. -pub const DEFAULT_EXECUTION_IMPORT_BLOCK: ExecutionStrategy = ExecutionStrategy::Wasm; -/// Default value for the `--execution-import-block` parameter when the node is a validator. -pub const DEFAULT_EXECUTION_IMPORT_BLOCK_VALIDATOR: ExecutionStrategy = ExecutionStrategy::Wasm; -/// Default value for the `--execution-block-construction` parameter. -pub const DEFAULT_EXECUTION_BLOCK_CONSTRUCTION: ExecutionStrategy = ExecutionStrategy::Wasm; -/// Default value for the `--execution-offchain-worker` parameter. -pub const DEFAULT_EXECUTION_OFFCHAIN_WORKER: ExecutionStrategy = ExecutionStrategy::Wasm; -/// Default value for the `--execution-other` parameter. -pub const DEFAULT_EXECUTION_OTHER: ExecutionStrategy = ExecutionStrategy::Wasm; diff --git a/client/cli/src/config.rs b/client/cli/src/config.rs index 04c62a73b40ed..4d218da6aa898 100644 --- a/client/cli/src/config.rs +++ b/client/cli/src/config.rs @@ -24,7 +24,6 @@ use crate::{ }; use log::warn; use names::{Generator, Name}; -use sc_client_api::execution_extensions::ExecutionStrategies; use sc_service::{ config::{ BasePath, Configuration, DatabaseSource, KeystoreConfig, NetworkConfiguration, @@ -291,21 +290,6 @@ pub trait CliConfiguration: Sized { self.import_params().map(|x| x.wasm_runtime_overrides()).unwrap_or_default() } - /// Get the execution strategies. - /// - /// By default this is retrieved from `ImportParams` if it is available. Otherwise its - /// `ExecutionStrategies::default()`. - fn execution_strategies( - &self, - is_dev: bool, - is_validator: bool, - ) -> Result { - Ok(self - .import_params() - .map(|x| x.execution_strategies(is_dev, is_validator)) - .unwrap_or_default()) - } - /// Get the RPC address. fn rpc_addr(&self, _default_listen_port: u16) -> Result> { Ok(None) @@ -508,7 +492,6 @@ pub trait CliConfiguration: Sized { blocks_pruning: self.blocks_pruning()?, wasm_method: self.wasm_method()?, wasm_runtime_overrides: self.wasm_runtime_overrides(), - execution_strategies: self.execution_strategies(is_dev, is_validator)?, rpc_addr: self.rpc_addr(DCV::rpc_listen_port())?, rpc_methods: self.rpc_methods()?, rpc_max_connections: self.rpc_max_connections()?, diff --git a/client/cli/src/params/import_params.rs b/client/cli/src/params/import_params.rs index 9e57a017e51ca..bfa54a35058f6 100644 --- a/client/cli/src/params/import_params.rs +++ b/client/cli/src/params/import_params.rs @@ -19,15 +19,11 @@ use crate::{ arg_enums::{ ExecutionStrategy, WasmExecutionMethod, WasmtimeInstantiationStrategy, - DEFAULT_EXECUTION_BLOCK_CONSTRUCTION, DEFAULT_EXECUTION_IMPORT_BLOCK, - DEFAULT_EXECUTION_IMPORT_BLOCK_VALIDATOR, DEFAULT_EXECUTION_OFFCHAIN_WORKER, - DEFAULT_EXECUTION_OTHER, DEFAULT_EXECUTION_SYNCING, DEFAULT_WASMTIME_INSTANTIATION_STRATEGY, DEFAULT_WASM_EXECUTION_METHOD, }, params::{DatabaseParams, PruningParams}, }; use clap::Args; -use sc_client_api::execution_extensions::ExecutionStrategies; use std::path::PathBuf; /// Parameters for block import. @@ -104,6 +100,8 @@ impl ImportParams { /// Get the WASM execution method from the parameters pub fn wasm_method(&self) -> sc_service::config::WasmExecutionMethod { + self.execution_strategies.check_usage_and_print_deprecation_warning(); + crate::execution_method_from_cli(self.wasm_method, self.wasmtime_instantiation_strategy) } @@ -112,36 +110,6 @@ impl ImportParams { pub fn wasm_runtime_overrides(&self) -> Option { self.wasm_runtime_overrides.clone() } - - /// Get execution strategies for the parameters - pub fn execution_strategies(&self, is_dev: bool, is_validator: bool) -> ExecutionStrategies { - let exec = &self.execution_strategies; - let exec_all_or = |strat: Option, default: ExecutionStrategy| { - let default = if is_dev { ExecutionStrategy::Native } else { default }; - - exec.execution.unwrap_or_else(|| strat.unwrap_or(default)).into() - }; - - let default_execution_import_block = if is_validator { - DEFAULT_EXECUTION_IMPORT_BLOCK_VALIDATOR - } else { - DEFAULT_EXECUTION_IMPORT_BLOCK - }; - - ExecutionStrategies { - syncing: exec_all_or(exec.execution_syncing, DEFAULT_EXECUTION_SYNCING), - importing: exec_all_or(exec.execution_import_block, default_execution_import_block), - block_construction: exec_all_or( - exec.execution_block_construction, - DEFAULT_EXECUTION_BLOCK_CONSTRUCTION, - ), - offchain_worker: exec_all_or( - exec.execution_offchain_worker, - DEFAULT_EXECUTION_OFFCHAIN_WORKER, - ), - other: exec_all_or(exec.execution_other, DEFAULT_EXECUTION_OTHER), - } - } } /// Execution strategies parameters. @@ -186,3 +154,23 @@ pub struct ExecutionStrategiesParams { )] pub execution: Option, } + +impl ExecutionStrategiesParams { + /// Check if one of the parameters is still passed and print a warning if so. + fn check_usage_and_print_deprecation_warning(&self) { + for (param, name) in [ + (&self.execution_syncing, "execution-syncing"), + (&self.execution_import_block, "execution-import-block"), + (&self.execution_block_construction, "execution-block-construction"), + (&self.execution_offchain_worker, "execution-offchain-worker"), + (&self.execution_other, "execution-other"), + (&self.execution, "execution"), + ] { + if param.is_some() { + eprintln!( + "CLI parameter `--{name}` has no effect anymore and will be removed in the future!" + ); + } + } + } +} diff --git a/client/cli/src/runner.rs b/client/cli/src/runner.rs index 66c3fe41b6c21..c96f494354f9a 100644 --- a/client/cli/src/runner.rs +++ b/client/cli/src/runner.rs @@ -265,7 +265,6 @@ mod tests { )), wasm_method: Default::default(), wasm_runtime_overrides: None, - execution_strategies: Default::default(), rpc_addr: None, rpc_max_connections: Default::default(), rpc_cors: None, diff --git a/client/consensus/aura/src/import_queue.rs b/client/consensus/aura/src/import_queue.rs index ef7a2a1cc865b..0b9ceb4fe7760 100644 --- a/client/consensus/aura/src/import_queue.rs +++ b/client/consensus/aura/src/import_queue.rs @@ -38,7 +38,7 @@ use sp_blockchain::HeaderBackend; use sp_consensus::Error as ConsensusError; use sp_consensus_aura::{inherents::AuraInherentData, AuraApi}; use sp_consensus_slots::Slot; -use sp_core::{crypto::Pair, ExecutionContext}; +use sp_core::crypto::Pair; use sp_inherents::{CreateInherentDataProviders, InherentDataProvider as _}; use sp_runtime::{ traits::{Block as BlockT, Header, NumberFor}, @@ -138,7 +138,6 @@ where at_hash: B::Hash, inherent_data: sp_inherents::InherentData, create_inherent_data_providers: CIDP::InherentDataProviders, - execution_context: ExecutionContext, ) -> Result<(), Error> where C: ProvideRuntimeApi, @@ -148,7 +147,7 @@ where let inherent_res = self .client .runtime_api() - .check_inherents_with_context(at_hash, execution_context, block, inherent_data) + .check_inherents(at_hash, block, inherent_data) .map_err(|e| Error::Client(e.into()))?; if !inherent_res.ok() { @@ -249,7 +248,6 @@ where parent_hash, inherent_data, create_inherent_data_providers, - block.origin.into(), ) .await .map_err(|e| e.to_string())?; diff --git a/client/consensus/babe/Cargo.toml b/client/consensus/babe/Cargo.toml index 28bd28c812b32..e036ff1e64cd1 100644 --- a/client/consensus/babe/Cargo.toml +++ b/client/consensus/babe/Cargo.toml @@ -31,6 +31,7 @@ sc-consensus = { version = "0.10.0-dev", path = "../../../client/consensus/commo sc-consensus-epochs = { version = "0.10.0-dev", path = "../epochs" } sc-consensus-slots = { version = "0.10.0-dev", path = "../slots" } sc-telemetry = { version = "4.0.0-dev", path = "../../telemetry" } +sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../transaction-pool/api" } sp-api = { version = "4.0.0-dev", path = "../../../primitives/api" } sp-application-crypto = { version = "23.0.0", path = "../../../primitives/application-crypto" } sp-block-builder = { version = "4.0.0-dev", path = "../../../primitives/block-builder" } diff --git a/client/consensus/babe/rpc/Cargo.toml b/client/consensus/babe/rpc/Cargo.toml index c0b20eb11c95a..7b16ea84c4366 100644 --- a/client/consensus/babe/rpc/Cargo.toml +++ b/client/consensus/babe/rpc/Cargo.toml @@ -34,5 +34,6 @@ serde_json = "1.0.85" tokio = "1.22.0" sc-consensus = { version = "0.10.0-dev", path = "../../../consensus/common" } sc-keystore = { version = "4.0.0-dev", path = "../../../keystore" } +sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../../transaction-pool/api" } sp-keyring = { version = "24.0.0", path = "../../../../primitives/keyring" } substrate-test-runtime-client = { version = "2.0.0", path = "../../../../test-utils/runtime/client" } diff --git a/client/consensus/babe/rpc/src/lib.rs b/client/consensus/babe/rpc/src/lib.rs index 1ae15cc5453d7..bffe026ea6ef6 100644 --- a/client/consensus/babe/rpc/src/lib.rs +++ b/client/consensus/babe/rpc/src/lib.rs @@ -186,6 +186,8 @@ impl From for JsonRpseeError { #[cfg(test)] mod tests { use super::*; + use sc_consensus_babe::ImportQueueParams; + use sc_transaction_pool_api::{OffchainTransactionPoolFactory, RejectAllTxPool}; use sp_consensus_babe::inherents::InherentDataProvider; use sp_core::{crypto::key_types::BABE, testing::TaskExecutor}; use sp_keyring::Sr25519Keyring; @@ -219,22 +221,25 @@ mod tests { sc_consensus_babe::block_import(config.clone(), client.clone(), client.clone()) .expect("can initialize block-import"); - let (_, babe_worker_handle) = sc_consensus_babe::import_queue( - link.clone(), - block_import.clone(), - None, - client.clone(), - longest_chain.clone(), - move |_, _| async move { + let (_, babe_worker_handle) = sc_consensus_babe::import_queue(ImportQueueParams { + link: link.clone(), + block_import: block_import.clone(), + justification_import: None, + client: client.clone(), + select_chain: longest_chain.clone(), + create_inherent_data_providers: move |_, _| async move { Ok((InherentDataProvider::from_timestamp_and_slot_duration( 0.into(), slot_duration, ),)) }, - &task_executor, - None, - None, - ) + spawner: &task_executor, + registry: None, + telemetry: None, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new( + RejectAllTxPool::default(), + ), + }) .unwrap(); Babe::new(client.clone(), babe_worker_handle, keystore, longest_chain, deny_unsafe) diff --git a/client/consensus/babe/src/lib.rs b/client/consensus/babe/src/lib.rs index 64ff00bb58c35..76bd670c20049 100644 --- a/client/consensus/babe/src/lib.rs +++ b/client/consensus/babe/src/lib.rs @@ -106,6 +106,7 @@ use sc_consensus_slots::{ SlotInfo, StorageChanges, }; use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_DEBUG, CONSENSUS_TRACE}; +use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_application_crypto::AppCrypto; use sp_block_builder::BlockBuilder as BlockBuilderApi; @@ -116,7 +117,7 @@ use sp_blockchain::{ use sp_consensus::{BlockOrigin, Environment, Error as ConsensusError, Proposer, SelectChain}; use sp_consensus_babe::inherents::BabeInherentData; use sp_consensus_slots::Slot; -use sp_core::ExecutionContext; +use sp_core::traits::SpawnEssentialNamed; use sp_inherents::{CreateInherentDataProviders, InherentData, InherentDataProvider}; use sp_keystore::KeystorePtr; use sp_runtime::{ @@ -992,6 +993,7 @@ pub struct BabeVerifier { config: BabeConfiguration, epoch_changes: SharedEpochChanges, telemetry: Option, + offchain_tx_pool_factory: OffchainTransactionPoolFactory, } impl BabeVerifier @@ -1008,12 +1010,11 @@ where at_hash: Block::Hash, inherent_data: InherentData, create_inherent_data_providers: CIDP::InherentDataProviders, - execution_context: ExecutionContext, ) -> Result<(), Error> { let inherent_res = self .client .runtime_api() - .check_inherents_with_context(at_hash, execution_context, block, inherent_data) + .check_inherents(at_hash, block, inherent_data) .map_err(Error::RuntimeApi)?; if !inherent_res.ok() { @@ -1098,8 +1099,13 @@ where }; // submit equivocation report at best block. - self.client - .runtime_api() + let mut runtime_api = self.client.runtime_api(); + + // Register the offchain tx pool to be able to use it from the runtime. + runtime_api + .register_extension(self.offchain_tx_pool_factory.offchain_transaction_pool(best_hash)); + + runtime_api .submit_report_equivocation_unsigned_extrinsic( best_hash, equivocation_proof, @@ -1250,7 +1256,6 @@ where parent_hash, inherent_data, create_inherent_data_providers, - block.origin.into(), ) .await?; } @@ -1768,6 +1773,38 @@ where Ok((import, link)) } +/// Parameters passed to [`import_queue`]. +pub struct ImportQueueParams<'a, Block: BlockT, BI, Client, CIDP, SelectChain, Spawn> { + /// The BABE link that is created by [`block_import`]. + pub link: BabeLink, + /// The block import that should be wrapped. + pub block_import: BI, + /// Optional justification import. + pub justification_import: Option>, + /// The client to interact with the internals of the node. + pub client: Arc, + /// A [`SelectChain`] implementation. + /// + /// Used to determine the best block that should be used as basis when sending an equivocation + /// report. + pub select_chain: SelectChain, + /// Used to crate the inherent data providers. + /// + /// These inherent data providers are then used to create the inherent data that is + /// passed to the `check_inherents` runtime call. + pub create_inherent_data_providers: CIDP, + /// Spawner for spawning futures. + pub spawner: &'a Spawn, + /// Registry for prometheus metrics. + pub registry: Option<&'a Registry>, + /// Optional telemetry handle to report telemetry events. + pub telemetry: Option, + /// The offchain transaction pool factory. + /// + /// Will be used when sending equivocation reports. + pub offchain_tx_pool_factory: OffchainTransactionPoolFactory, +} + /// Start an import queue for the BABE consensus algorithm. /// /// This method returns the import queue, some data that needs to be passed to the block authoring @@ -1777,19 +1814,22 @@ where /// /// The block import object provided must be the `BabeBlockImport` or a wrapper /// of it, otherwise crucial import logic will be omitted. -pub fn import_queue( - babe_link: BabeLink, - block_import: Inner, - justification_import: Option>, - client: Arc, - select_chain: SelectChain, - create_inherent_data_providers: CIDP, - spawner: &impl sp_core::traits::SpawnEssentialNamed, - registry: Option<&Registry>, - telemetry: Option, +pub fn import_queue( + ImportQueueParams { + link: babe_link, + block_import, + justification_import, + client, + select_chain, + create_inherent_data_providers, + spawner, + registry, + telemetry, + offchain_tx_pool_factory, + }: ImportQueueParams<'_, Block, BI, Client, CIDP, SelectChain, Spawn>, ) -> ClientResult<(DefaultImportQueue, BabeWorkerHandle)> where - Inner: BlockImport< + BI: BlockImport< Block, Error = ConsensusError, Transaction = sp_api::TransactionFor, @@ -1807,6 +1847,7 @@ where SelectChain: sp_consensus::SelectChain + 'static, CIDP: CreateInherentDataProviders + Send + Sync + 'static, CIDP::InherentDataProviders: InherentDataProviderExt + Send + Sync, + Spawn: SpawnEssentialNamed, { const HANDLE_BUFFER_SIZE: usize = 1024; @@ -1817,6 +1858,7 @@ where epoch_changes: babe_link.epoch_changes.clone(), telemetry, client: client.clone(), + offchain_tx_pool_factory, }; let (worker_tx, worker_rx) = channel(HANDLE_BUFFER_SIZE); diff --git a/client/consensus/babe/src/tests.rs b/client/consensus/babe/src/tests.rs index 59b4076e2fd01..384e45228b599 100644 --- a/client/consensus/babe/src/tests.rs +++ b/client/consensus/babe/src/tests.rs @@ -26,6 +26,7 @@ use sc_consensus::{BoxBlockImport, BoxJustificationImport}; use sc_consensus_epochs::{EpochIdentifier, EpochIdentifierPosition}; use sc_consensus_slots::BackoffAuthoringOnFinalizedHeadLagging; use sc_network_test::{Block as TestBlock, *}; +use sc_transaction_pool_api::RejectAllTxPool; use sp_application_crypto::key_types::BABE; use sp_consensus::{DisableProofRecording, NoNetwork as DummyOracle, Proposal}; use sp_consensus_babe::{ @@ -283,6 +284,9 @@ impl TestNetFactory for BabeTestNet { config: data.link.config.clone(), epoch_changes: data.link.epoch_changes.clone(), telemetry: None, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new( + RejectAllTxPool::default(), + ), }, mutator: MUTATOR.with(|m| m.borrow().clone()), } diff --git a/client/consensus/grandpa/Cargo.toml b/client/consensus/grandpa/Cargo.toml index 13b472dc70322..af39c640122b6 100644 --- a/client/consensus/grandpa/Cargo.toml +++ b/client/consensus/grandpa/Cargo.toml @@ -32,6 +32,7 @@ prometheus-endpoint = { package = "substrate-prometheus-endpoint", version = "0. sc-block-builder = { version = "0.10.0-dev", path = "../../block-builder" } sc-chain-spec = { version = "4.0.0-dev", path = "../../../client/chain-spec" } sc-client-api = { version = "4.0.0-dev", path = "../../api" } +sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../transaction-pool/api" } sc-consensus = { version = "0.10.0-dev", path = "../common" } sc-network = { version = "0.10.0-dev", path = "../../network" } sc-network-gossip = { version = "0.10.0-dev", path = "../../network-gossip" } diff --git a/client/consensus/grandpa/src/environment.rs b/client/consensus/grandpa/src/environment.rs index 67820a59cc943..eeb9ff4468291 100644 --- a/client/consensus/grandpa/src/environment.rs +++ b/client/consensus/grandpa/src/environment.rs @@ -40,6 +40,8 @@ use sc_client_api::{ utils::is_descendent_of, }; use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_DEBUG, CONSENSUS_INFO}; +use sc_transaction_pool_api::OffchainTransactionPoolFactory; +use sp_api::ApiExt; use sp_blockchain::HeaderMetadata; use sp_consensus::SelectChain as SelectChainT; use sp_consensus_grandpa::{ @@ -444,6 +446,7 @@ pub(crate) struct Environment< pub(crate) metrics: Option, pub(crate) justification_sender: Option>, pub(crate) telemetry: Option, + pub(crate) offchain_tx_pool_factory: OffchainTransactionPoolFactory, pub(crate) _phantom: PhantomData, } @@ -570,8 +573,13 @@ where // submit equivocation report at **best** block let equivocation_proof = EquivocationProof::new(authority_set.set_id, equivocation); - self.client - .runtime_api() + let mut runtime_api = self.client.runtime_api(); + + runtime_api.register_extension( + self.offchain_tx_pool_factory.offchain_transaction_pool(best_block_hash), + ); + + runtime_api .submit_report_equivocation_unsigned_extrinsic( best_block_hash, equivocation_proof, diff --git a/client/consensus/grandpa/src/lib.rs b/client/consensus/grandpa/src/lib.rs index 9c0aa60c24e1b..c888340f70a34 100644 --- a/client/consensus/grandpa/src/lib.rs +++ b/client/consensus/grandpa/src/lib.rs @@ -64,12 +64,13 @@ use prometheus_endpoint::{PrometheusError, Registry}; use sc_client_api::{ backend::{AuxStore, Backend}, utils::is_descendent_of, - BlockchainEvents, CallExecutor, ExecutionStrategy, ExecutorProvider, Finalizer, LockImportRun, - StorageProvider, TransactionFor, + BlockchainEvents, CallExecutor, ExecutorProvider, Finalizer, LockImportRun, StorageProvider, + TransactionFor, }; use sc_consensus::BlockImport; use sc_network::types::ProtocolName; use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_DEBUG, CONSENSUS_INFO}; +use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver}; use sp_api::ProvideRuntimeApi; use sp_application_crypto::AppCrypto; @@ -479,7 +480,6 @@ where self.expect_block_hash_from_id(&BlockId::Number(Zero::zero()))?, "GrandpaApi_grandpa_authorities", &[], - ExecutionStrategy::NativeElseWasm, CallContext::Offchain, ) .and_then(|call_result| { @@ -688,6 +688,11 @@ pub struct GrandpaParams { pub shared_voter_state: SharedVoterState, /// TelemetryHandle instance. pub telemetry: Option, + /// Offchain transaction pool factory. + /// + /// This will be used to create an offchain transaction pool instance for sending an + /// equivocation report from the runtime. + pub offchain_tx_pool_factory: OffchainTransactionPoolFactory, } /// Returns the configuration value to put in @@ -736,6 +741,7 @@ where prometheus_registry, shared_voter_state, telemetry, + offchain_tx_pool_factory, } = grandpa_params; // NOTE: we have recently removed `run_grandpa_observer` from the public @@ -810,6 +816,7 @@ where shared_voter_state, justification_sender, telemetry, + offchain_tx_pool_factory, ); let voter_work = voter_work.map(|res| match res { @@ -879,6 +886,7 @@ where shared_voter_state: SharedVoterState, justification_sender: GrandpaJustificationSender, telemetry: Option, + offchain_tx_pool_factory: OffchainTransactionPoolFactory, ) -> Self { let metrics = match prometheus_registry.as_ref().map(Metrics::register) { Some(Ok(metrics)) => Some(metrics), @@ -903,6 +911,7 @@ where metrics: metrics.as_ref().map(|m| m.environment.clone()), justification_sender: Some(justification_sender), telemetry: telemetry.clone(), + offchain_tx_pool_factory, _phantom: PhantomData, }); @@ -1054,6 +1063,7 @@ where metrics: self.env.metrics.clone(), justification_sender: self.env.justification_sender.clone(), telemetry: self.telemetry.clone(), + offchain_tx_pool_factory: self.env.offchain_tx_pool_factory.clone(), _phantom: PhantomData, }); diff --git a/client/consensus/grandpa/src/tests.rs b/client/consensus/grandpa/src/tests.rs index c46e249be485c..4fbeed71a1bf5 100644 --- a/client/consensus/grandpa/src/tests.rs +++ b/client/consensus/grandpa/src/tests.rs @@ -33,6 +33,7 @@ use sc_network_test::{ Block, BlockImportAdapter, FullPeerConfig, Hash, PassThroughVerifier, Peer, PeersClient, PeersFullClient, TestClient, TestNetFactory, }; +use sc_transaction_pool_api::RejectAllTxPool; use sp_api::{ApiRef, ProvideRuntimeApi}; use sp_consensus::{BlockOrigin, Error as ConsensusError, SelectChain}; use sp_consensus_grandpa::{ @@ -331,6 +332,9 @@ fn initialize_grandpa( voting_rule: (), prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new( + RejectAllTxPool::default(), + ), telemetry: None, }; let voter = @@ -481,6 +485,9 @@ async fn finalize_3_voters_1_full_observer() { prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), telemetry: None, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new( + RejectAllTxPool::default(), + ), }; run_grandpa_voter(grandpa_params).expect("all in order with client and network") @@ -573,6 +580,9 @@ async fn transition_3_voters_twice_1_full_observer() { prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), telemetry: None, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new( + RejectAllTxPool::default(), + ), }; voters @@ -1040,6 +1050,9 @@ async fn voter_persists_its_votes() { prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), telemetry: None, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new( + RejectAllTxPool::default(), + ), }; run_grandpa_voter(grandpa_params).expect("all in order with client and network") @@ -1083,6 +1096,9 @@ async fn voter_persists_its_votes() { prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), telemetry: None, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new( + RejectAllTxPool::default(), + ), }; run_grandpa_voter(grandpa_params) @@ -1293,6 +1309,9 @@ async fn voter_catches_up_to_latest_round_when_behind() { prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), telemetry: None, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new( + RejectAllTxPool::default(), + ), }; Box::pin(run_grandpa_voter(grandpa_params).expect("all in order with client and network")) @@ -1422,6 +1441,7 @@ where justification_sender: None, telemetry: None, _phantom: PhantomData, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new(RejectAllTxPool::default()), } } @@ -1986,7 +2006,7 @@ async fn grandpa_environment_doesnt_send_equivocation_reports_for_itself() { // keys it should work equivocation.identity = TryFrom::try_from(&[1; 32][..]).unwrap(); let equivocation_proof = sp_consensus_grandpa::Equivocation::Prevote(equivocation); - assert!(environment.report_equivocation(equivocation_proof).is_ok()); + environment.report_equivocation(equivocation_proof).unwrap(); } #[tokio::test] diff --git a/client/consensus/pow/src/lib.rs b/client/consensus/pow/src/lib.rs index 913686b7bf36d..763cf10e6cd4f 100644 --- a/client/consensus/pow/src/lib.rs +++ b/client/consensus/pow/src/lib.rs @@ -58,7 +58,6 @@ use sp_block_builder::BlockBuilder as BlockBuilderApi; use sp_blockchain::HeaderBackend; use sp_consensus::{Environment, Error as ConsensusError, Proposer, SelectChain, SyncOracle}; use sp_consensus_pow::{Seal, TotalDifficulty, POW_ENGINE_ID}; -use sp_core::ExecutionContext; use sp_inherents::{CreateInherentDataProviders, InherentDataProvider}; use sp_runtime::{ generic::{BlockId, Digest, DigestItem}, @@ -269,7 +268,6 @@ where block: B, at_hash: B::Hash, inherent_data_providers: CIDP::InherentDataProviders, - execution_context: ExecutionContext, ) -> Result<(), Error> { if *block.header().number() < self.check_inherents_after { return Ok(()) @@ -283,7 +281,7 @@ where let inherent_res = self .client .runtime_api() - .check_inherents_with_context(at_hash, execution_context, block, inherent_data) + .check_inherents(at_hash, block, inherent_data) .map_err(|e| Error::Client(e.into()))?; if !inherent_res.ok() { @@ -348,7 +346,6 @@ where self.create_inherent_data_providers .create_inherent_data_providers(parent_hash, ()) .await?, - block.origin.into(), ) .await?; } diff --git a/client/merkle-mountain-range/rpc/src/lib.rs b/client/merkle-mountain-range/rpc/src/lib.rs index daf2cd1ec298b..5be82b600d914 100644 --- a/client/merkle-mountain-range/rpc/src/lib.rs +++ b/client/merkle-mountain-range/rpc/src/lib.rs @@ -30,9 +30,12 @@ use jsonrpsee::{ }; use serde::{Deserialize, Serialize}; -use sp_api::{NumberFor, ProvideRuntimeApi}; +use sp_api::{ApiExt, NumberFor, ProvideRuntimeApi}; use sp_blockchain::HeaderBackend; -use sp_core::Bytes; +use sp_core::{ + offchain::{storage::OffchainDb, OffchainDbExt, OffchainStorage}, + Bytes, +}; use sp_mmr_primitives::{Error as MmrError, Proof}; use sp_runtime::traits::Block as BlockT; @@ -127,26 +130,28 @@ pub trait MmrApi { } /// MMR RPC methods. -pub struct Mmr { +pub struct Mmr { client: Arc, + offchain_db: OffchainDb, _marker: PhantomData, } -impl Mmr { +impl Mmr { /// Create new `Mmr` with the given reference to the client. - pub fn new(client: Arc) -> Self { - Self { client, _marker: Default::default() } + pub fn new(client: Arc, offchain_storage: S) -> Self { + Self { client, _marker: Default::default(), offchain_db: OffchainDb::new(offchain_storage) } } } #[async_trait] -impl MmrApiServer<::Hash, NumberFor, MmrHash> - for Mmr +impl MmrApiServer<::Hash, NumberFor, MmrHash> + for Mmr where Block: BlockT, Client: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, Client::Api: MmrRuntimeApi>, MmrHash: Codec + Send + Sync + 'static, + S: OffchainStorage + 'static, { fn mmr_root(&self, at: Option<::Hash>) -> RpcResult { let block_hash = at.unwrap_or_else(|| @@ -166,18 +171,15 @@ where best_known_block_number: Option>, at: Option<::Hash>, ) -> RpcResult::Hash>> { - let api = self.client.runtime_api(); + let mut api = self.client.runtime_api(); let block_hash = at.unwrap_or_else(|| // If the block hash is not supplied assume the best block. self.client.info().best_hash); + api.register_extension(OffchainDbExt::new(self.offchain_db.clone())); + let (leaves, proof) = api - .generate_proof_with_context( - block_hash, - sp_core::ExecutionContext::OffchainCall(None), - block_numbers, - best_known_block_number, - ) + .generate_proof(block_hash, block_numbers, best_known_block_number) .map_err(runtime_error_into_rpc_error)? .map_err(mmr_error_into_rpc_error)?; @@ -185,7 +187,7 @@ where } fn verify_proof(&self, proof: LeavesProof<::Hash>) -> RpcResult { - let api = self.client.runtime_api(); + let mut api = self.client.runtime_api(); let leaves = Decode::decode(&mut &proof.leaves.0[..]) .map_err(|e| CallError::InvalidParams(anyhow::Error::new(e)))?; @@ -193,14 +195,11 @@ where let decoded_proof = Decode::decode(&mut &proof.proof.0[..]) .map_err(|e| CallError::InvalidParams(anyhow::Error::new(e)))?; - api.verify_proof_with_context( - proof.block_hash, - sp_core::ExecutionContext::OffchainCall(None), - leaves, - decoded_proof, - ) - .map_err(runtime_error_into_rpc_error)? - .map_err(mmr_error_into_rpc_error)?; + api.register_extension(OffchainDbExt::new(self.offchain_db.clone())); + + api.verify_proof(proof.block_hash, leaves, decoded_proof) + .map_err(runtime_error_into_rpc_error)? + .map_err(mmr_error_into_rpc_error)?; Ok(true) } diff --git a/client/offchain/Cargo.toml b/client/offchain/Cargo.toml index 42504ec590c70..f52b0aa2878f6 100644 --- a/client/offchain/Cargo.toml +++ b/client/offchain/Cargo.toml @@ -30,11 +30,16 @@ threadpool = "1.7" tracing = "0.1.29" sc-client-api = { version = "4.0.0-dev", path = "../api" } sc-network = { version = "0.10.0-dev", path = "../network" } +sc-network-common = { version = "0.10.0-dev", path = "../network/common" } +sc-transaction-pool-api = { version = "4.0.0-dev", path = "../transaction-pool/api" } sc-utils = { version = "4.0.0-dev", path = "../utils" } sp-api = { version = "4.0.0-dev", path = "../../primitives/api" } sp-core = { version = "21.0.0", path = "../../primitives/core" } sp-offchain = { version = "4.0.0-dev", path = "../../primitives/offchain" } sp-runtime = { version = "24.0.0", path = "../../primitives/runtime" } +sp-keystore = { version = "0.27.0", path = "../../primitives/keystore" } +sp-externalities = { version = "0.19.0", path = "../../primitives/externalities" } +log = "0.4.17" [dev-dependencies] lazy_static = "1.4.0" diff --git a/client/offchain/src/api.rs b/client/offchain/src/api.rs index 33ddd46c7a306..e6b0e30f20378 100644 --- a/client/offchain/src/api.rs +++ b/client/offchain/src/api.rs @@ -25,8 +25,8 @@ pub use http::SharedClient; use libp2p::{Multiaddr, PeerId}; use sp_core::{ offchain::{ - self, HttpError, HttpRequestId, HttpRequestStatus, OffchainStorage, OpaqueMultiaddr, - OpaqueNetworkState, StorageKind, Timestamp, + self, HttpError, HttpRequestId, HttpRequestStatus, OpaqueMultiaddr, OpaqueNetworkState, + Timestamp, }, OpaquePeerId, }; @@ -36,110 +36,6 @@ mod http; mod timestamp; -fn unavailable_yet(name: &str) -> R { - tracing::error!( - target: super::LOG_TARGET, - "The {:?} API is not available for offchain workers yet. Follow \ - https://github.com/paritytech/substrate/issues/1458 for details", - name - ); - Default::default() -} - -const LOCAL_DB: &str = "LOCAL (fork-aware) DB"; - -/// Offchain DB reference. -#[derive(Debug, Clone)] -pub struct Db { - /// Persistent storage database. - persistent: Storage, -} - -impl Db { - /// Create new instance of Offchain DB. - pub fn new(persistent: Storage) -> Self { - Self { persistent } - } - - /// Create new instance of Offchain DB, backed by given backend. - pub fn factory_from_backend( - backend: &Backend, - ) -> Option> - where - Backend: sc_client_api::Backend, - Block: sp_runtime::traits::Block, - Storage: 'static, - { - sc_client_api::Backend::offchain_storage(backend).map(|db| Box::new(Self::new(db)) as _) - } -} - -impl offchain::DbExternalities for Db { - fn local_storage_set(&mut self, kind: StorageKind, key: &[u8], value: &[u8]) { - tracing::debug!( - target: "offchain-worker::storage", - ?kind, - key = ?array_bytes::bytes2hex("", key), - value = ?array_bytes::bytes2hex("", value), - "Write", - ); - match kind { - StorageKind::PERSISTENT => self.persistent.set(STORAGE_PREFIX, key, value), - StorageKind::LOCAL => unavailable_yet(LOCAL_DB), - } - } - - fn local_storage_clear(&mut self, kind: StorageKind, key: &[u8]) { - tracing::debug!( - target: "offchain-worker::storage", - ?kind, - key = ?array_bytes::bytes2hex("", key), - "Clear", - ); - match kind { - StorageKind::PERSISTENT => self.persistent.remove(STORAGE_PREFIX, key), - StorageKind::LOCAL => unavailable_yet(LOCAL_DB), - } - } - - fn local_storage_compare_and_set( - &mut self, - kind: StorageKind, - key: &[u8], - old_value: Option<&[u8]>, - new_value: &[u8], - ) -> bool { - tracing::debug!( - target: "offchain-worker::storage", - ?kind, - key = ?array_bytes::bytes2hex("", key), - new_value = ?array_bytes::bytes2hex("", new_value), - old_value = ?old_value.as_ref().map(|s| array_bytes::bytes2hex("", s)), - "CAS", - ); - match kind { - StorageKind::PERSISTENT => - self.persistent.compare_and_set(STORAGE_PREFIX, key, old_value, new_value), - StorageKind::LOCAL => unavailable_yet(LOCAL_DB), - } - } - - fn local_storage_get(&mut self, kind: StorageKind, key: &[u8]) -> Option> { - let result = match kind { - StorageKind::PERSISTENT => self.persistent.get(STORAGE_PREFIX, key), - StorageKind::LOCAL => unavailable_yet(LOCAL_DB), - }; - tracing::debug!( - target: "offchain-worker::storage", - ?kind, - key = ?array_bytes::bytes2hex("", key), - result = ?result.as_ref().map(|s| array_bytes::bytes2hex("", s)), - "Read", - ); - result - } -} - /// Asynchronous offchain API. /// /// NOTE this is done to prevent recursive calls into the runtime @@ -329,7 +225,7 @@ mod tests { config::MultiaddrWithPeerId, types::ProtocolName, NetworkPeers, NetworkStateInfo, ReputationChange, }; - use sp_core::offchain::{DbExternalities, Externalities}; + use sp_core::offchain::{storage::OffchainDb, DbExternalities, Externalities, StorageKind}; use std::time::SystemTime; pub(super) struct TestNetwork(); @@ -418,8 +314,8 @@ mod tests { AsyncApi::new(mock, false, shared_client) } - fn offchain_db() -> Db { - Db::new(LocalStorage::new_test()) + fn offchain_db() -> OffchainDb { + OffchainDb::new(LocalStorage::new_test()) } #[test] diff --git a/client/offchain/src/lib.rs b/client/offchain/src/lib.rs index 0945e39a3a881..4c11a5cb7294d 100644 --- a/client/offchain/src/lib.rs +++ b/client/offchain/src/lib.rs @@ -35,22 +35,26 @@ #![warn(missing_docs)] -use std::{fmt, marker::PhantomData, sync::Arc}; +use std::{fmt, sync::Arc}; use futures::{ future::{ready, Future}, prelude::*, }; use parking_lot::Mutex; +use sc_client_api::BlockchainEvents; use sc_network::{NetworkPeers, NetworkStateInfo}; +use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sp_api::{ApiExt, ProvideRuntimeApi}; -use sp_core::{offchain, traits::SpawnNamed, ExecutionContext}; +use sp_core::{offchain, traits::SpawnNamed}; +use sp_externalities::Extension; +use sp_keystore::{KeystoreExt, KeystorePtr}; use sp_runtime::traits::{self, Header}; use threadpool::ThreadPool; mod api; -pub use api::Db as OffchainDb; +pub use sp_core::offchain::storage::OffchainDb; pub use sp_offchain::{OffchainWorkerApi, STORAGE_PREFIX}; const LOG_TARGET: &str = "offchain-worker"; @@ -61,65 +65,160 @@ pub trait NetworkProvider: NetworkStateInfo + NetworkPeers {} impl NetworkProvider for T where T: NetworkStateInfo + NetworkPeers {} +/// Special type that implements [`OffchainStorage`](offchain::OffchainStorage). +/// +/// This type can not be constructed and should only be used when passing `None` as `offchain_db` to +/// [`OffchainWorkerOptions`] to make the compiler happy. +#[derive(Clone)] +pub enum NoOffchainStorage {} + +impl offchain::OffchainStorage for NoOffchainStorage { + fn set(&mut self, _: &[u8], _: &[u8], _: &[u8]) { + unimplemented!("`NoOffchainStorage` can not be constructed!") + } + + fn remove(&mut self, _: &[u8], _: &[u8]) { + unimplemented!("`NoOffchainStorage` can not be constructed!") + } + + fn get(&self, _: &[u8], _: &[u8]) -> Option> { + unimplemented!("`NoOffchainStorage` can not be constructed!") + } + + fn compare_and_set(&mut self, _: &[u8], _: &[u8], _: Option<&[u8]>, _: &[u8]) -> bool { + unimplemented!("`NoOffchainStorage` can not be constructed!") + } +} + /// Options for [`OffchainWorkers`] -pub struct OffchainWorkerOptions { +pub struct OffchainWorkerOptions { + /// Provides access to the runtime api. + pub runtime_api_provider: Arc, + /// Provides access to the keystore. + pub keystore: Option, + /// Provides access to the offchain database. + /// + /// Use [`NoOffchainStorage`] as type when passing `None` to have some type that works. + pub offchain_db: Option, + /// Provides access to the transaction pool. + pub transaction_pool: Option>, + /// Provides access to network information. + pub network_provider: Arc, + /// Is the node running as validator? + pub is_validator: bool, /// Enable http requests from offchain workers? /// /// If not enabled, any http request will panic. pub enable_http_requests: bool, + /// Callback to create custom [`Extension`]s that should be registered for the + /// `offchain_worker` runtime call. + /// + /// These [`Extension`]s are registered along-side the default extensions and are accessible in + /// the host functions. + /// + /// # Example: + /// + /// ```nocompile + /// custom_extensions: |block_hash| { + /// vec![MyCustomExtension::new()] + /// } + /// ``` + pub custom_extensions: CE, } /// An offchain workers manager. -pub struct OffchainWorkers { - client: Arc, - _block: PhantomData, +pub struct OffchainWorkers { + runtime_api_provider: Arc, thread_pool: Mutex, shared_http_client: api::SharedClient, - enable_http: bool, + enable_http_requests: bool, + keystore: Option, + offchain_db: Option>, + transaction_pool: Option>, + network_provider: Arc, + is_validator: bool, + custom_extensions: Box Vec> + Send>, } -impl OffchainWorkers { +impl OffchainWorkers { /// Creates new [`OffchainWorkers`]. - pub fn new(client: Arc) -> Self { - Self::new_with_options(client, OffchainWorkerOptions { enable_http_requests: true }) - } - - /// Creates new [`OffchainWorkers`] using the given `options`. - pub fn new_with_options(client: Arc, options: OffchainWorkerOptions) -> Self { + pub fn new Vec> + Send + 'static>( + OffchainWorkerOptions { + runtime_api_provider, + keystore, + offchain_db, + transaction_pool, + network_provider, + is_validator, + enable_http_requests, + custom_extensions, + }: OffchainWorkerOptions, + ) -> Self { Self { - client, - _block: PhantomData, + runtime_api_provider, thread_pool: Mutex::new(ThreadPool::with_name( "offchain-worker".into(), num_cpus::get(), )), shared_http_client: api::SharedClient::new(), - enable_http: options.enable_http_requests, + enable_http_requests, + keystore, + offchain_db: offchain_db.map(OffchainDb::new), + transaction_pool, + is_validator, + network_provider, + custom_extensions: Box::new(custom_extensions), } } } -impl fmt::Debug for OffchainWorkers { +impl fmt::Debug + for OffchainWorkers +{ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_tuple("OffchainWorkers").finish() } } -impl OffchainWorkers +impl OffchainWorkers where Block: traits::Block, - Client: ProvideRuntimeApi + Send + Sync + 'static, - Client::Api: OffchainWorkerApi, + RA: ProvideRuntimeApi + Send + Sync + 'static, + RA::Api: OffchainWorkerApi, + Storage: offchain::OffchainStorage + 'static, { + /// Run the offchain workers on every block import. + pub async fn run>( + self, + import_events: Arc, + spawner: impl SpawnNamed, + ) { + import_events + .import_notification_stream() + .for_each(move |n| { + if n.is_new_best { + spawner.spawn( + "offchain-on-block", + Some("offchain-worker"), + self.on_block_imported(&n.header).boxed(), + ); + } else { + tracing::debug!( + target: LOG_TARGET, + "Skipping offchain workers for non-canon block: {:?}", + n.header, + ) + } + + ready(()) + }) + .await; + } + /// Start the offchain workers after given block. #[must_use] - pub fn on_block_imported( - &self, - header: &Block::Header, - network_provider: Arc, - is_validator: bool, - ) -> impl Future { - let runtime = self.client.runtime_api(); + fn on_block_imported(&self, header: &Block::Header) -> impl Future { + let runtime = self.runtime_api_provider.runtime_api(); let hash = header.hash(); let has_api_v1 = runtime.has_api_with::, _>(hash, |v| v == 1); let has_api_v2 = runtime.has_api_with::, _>(hash, |v| v == 2); @@ -140,36 +239,59 @@ where }; tracing::debug!( target: LOG_TARGET, - "Checking offchain workers at {:?}: version:{}", - hash, - version + "Checking offchain workers at {hash:?}: version: {version}", ); + let process = (version > 0).then(|| { - let (api, runner) = - api::AsyncApi::new(network_provider, is_validator, self.shared_http_client.clone()); - tracing::debug!(target: LOG_TARGET, "Spawning offchain workers at {:?}", hash); + let (api, runner) = api::AsyncApi::new( + self.network_provider.clone(), + self.is_validator, + self.shared_http_client.clone(), + ); + tracing::debug!(target: LOG_TARGET, "Spawning offchain workers at {hash:?}"); let header = header.clone(); - let client = self.client.clone(); + let client = self.runtime_api_provider.clone(); let mut capabilities = offchain::Capabilities::all(); + capabilities.set(offchain::Capabilities::HTTP, self.enable_http_requests); + + let keystore = self.keystore.clone(); + let db = self.offchain_db.clone(); + let tx_pool = self.transaction_pool.clone(); + let custom_extensions = (*self.custom_extensions)(hash); - capabilities.set(offchain::Capabilities::HTTP, self.enable_http); self.spawn_worker(move || { - let runtime = client.runtime_api(); + let mut runtime = client.runtime_api(); let api = Box::new(api); - tracing::debug!(target: LOG_TARGET, "Running offchain workers at {:?}", hash); + tracing::debug!(target: LOG_TARGET, "Running offchain workers at {hash:?}"); + + if let Some(keystore) = keystore { + runtime.register_extension(KeystoreExt(keystore.clone())); + } + + if let Some(pool) = tx_pool { + runtime.register_extension(pool.offchain_transaction_pool(hash)); + } + + if let Some(offchain_db) = db { + runtime.register_extension(offchain::OffchainDbExt::new( + offchain::LimitedExternalities::new(capabilities, offchain_db.clone()), + )); + } + + runtime.register_extension(offchain::OffchainWorkerExt::new( + offchain::LimitedExternalities::new(capabilities, api), + )); + + custom_extensions.into_iter().for_each(|ext| runtime.register_extension(ext)); - let context = ExecutionContext::OffchainCall(Some((api, capabilities))); let run = if version == 2 { - runtime.offchain_worker_with_context(hash, context, &header) + runtime.offchain_worker(hash, &header) } else { #[allow(deprecated)] - runtime.offchain_worker_before_version_2_with_context( - hash, - context, - *header.number(), - ) + runtime.offchain_worker_before_version_2(hash, *header.number()) }; + if let Err(e) = run { tracing::error!( target: LOG_TARGET, @@ -201,44 +323,6 @@ where } } -/// Inform the offchain worker about new imported blocks -pub async fn notification_future( - is_validator: bool, - client: Arc, - offchain: Arc>, - spawner: Spawner, - network_provider: Arc, -) where - Block: traits::Block, - Client: - ProvideRuntimeApi + sc_client_api::BlockchainEvents + Send + Sync + 'static, - Client::Api: OffchainWorkerApi, - Spawner: SpawnNamed, -{ - client - .import_notification_stream() - .for_each(move |n| { - if n.is_new_best { - spawner.spawn( - "offchain-on-block", - Some("offchain-worker"), - offchain - .on_block_imported(&n.header, network_provider.clone(), is_validator) - .boxed(), - ); - } else { - tracing::debug!( - target: LOG_TARGET, - "Skipping offchain workers for non-canon block: {:?}", - n.header, - ) - } - - ready(()) - }) - .await; -} - #[cfg(test)] mod tests { use super::*; @@ -348,8 +432,17 @@ mod tests { let header = client.header(client.chain_info().genesis_hash).unwrap().unwrap(); // when - let offchain = OffchainWorkers::new(client); - futures::executor::block_on(offchain.on_block_imported(&header, network, false)); + let offchain = OffchainWorkers::new(OffchainWorkerOptions { + runtime_api_provider: client, + keystore: None, + offchain_db: None::, + transaction_pool: Some(OffchainTransactionPoolFactory::new(pool.clone())), + network_provider: network, + is_validator: false, + enable_http_requests: false, + custom_extensions: |_| Vec::new(), + }); + futures::executor::block_on(offchain.on_block_imported(&header)); // then assert_eq!(pool.status().ready, 1); diff --git a/client/rpc-spec-v2/Cargo.toml b/client/rpc-spec-v2/Cargo.toml index c691b7b05fcb4..4f5c11212a9b2 100644 --- a/client/rpc-spec-v2/Cargo.toml +++ b/client/rpc-spec-v2/Cargo.toml @@ -46,3 +46,4 @@ sc-block-builder = { version = "0.10.0-dev", path = "../block-builder" } sc-service = { version = "0.10.0-dev", features = ["test-helpers"], path = "../service" } sc-utils = { version = "4.0.0-dev", path = "../utils" } assert_matches = "1.3.0" +pretty_assertions = "1.2.1" diff --git a/client/rpc-spec-v2/src/chain_head/chain_head.rs b/client/rpc-spec-v2/src/chain_head/chain_head.rs index 0f2d55f100929..bb3599c0e4ae5 100644 --- a/client/rpc-spec-v2/src/chain_head/chain_head.rs +++ b/client/rpc-spec-v2/src/chain_head/chain_head.rs @@ -420,13 +420,7 @@ where let res = client .executor() - .call( - hash, - &function, - &call_parameters, - client.execution_extensions().strategies().other, - CallContext::Offchain, - ) + .call(hash, &function, &call_parameters, CallContext::Offchain) .map(|result| { let result = format!("0x{:?}", HexDisplay::from(&result)); ChainHeadEvent::Done(ChainHeadResult { result }) diff --git a/client/rpc-spec-v2/src/chain_head/subscription/inner.rs b/client/rpc-spec-v2/src/chain_head/subscription/inner.rs index bdb14e8de7172..adab64a01c875 100644 --- a/client/rpc-spec-v2/src/chain_head/subscription/inner.rs +++ b/client/rpc-spec-v2/src/chain_head/subscription/inner.rs @@ -539,7 +539,6 @@ mod tests { genesis_block_builder, None, None, - None, Box::new(TaskExecutor::new()), client_config, ) diff --git a/client/rpc-spec-v2/src/chain_head/test_utils.rs b/client/rpc-spec-v2/src/chain_head/test_utils.rs index ee563debb4502..54c585932a744 100644 --- a/client/rpc-spec-v2/src/chain_head/test_utils.rs +++ b/client/rpc-spec-v2/src/chain_head/test_utils.rs @@ -217,6 +217,14 @@ impl> CallApiAt for ChainHeadMock fn state_at(&self, at: Block::Hash) -> Result { self.client.state_at(at) } + + fn initialize_extensions( + &self, + at: ::Hash, + extensions: &mut sp_api::Extensions, + ) -> Result<(), sp_api::ApiError> { + self.client.initialize_extensions(at, extensions) + } } impl> BlockBackend diff --git a/client/rpc-spec-v2/src/chain_head/tests.rs b/client/rpc-spec-v2/src/chain_head/tests.rs index cb6e65f859133..5dd3cc3da6d3f 100644 --- a/client/rpc-spec-v2/src/chain_head/tests.rs +++ b/client/rpc-spec-v2/src/chain_head/tests.rs @@ -191,6 +191,7 @@ async fn follow_with_runtime() { [\"0xbc9d89904f5b923f\",1],[\"0xc6e9a76309f39b09\",2],[\"0xdd718d5cc53262d4\",1],\ [\"0xcbca25e39f142387\",2],[\"0xf78b278be53f454c\",2],[\"0xab3c0572291feb8b\",1],\ [\"0xed99c5acb25eedf5\",3]],\"transactionVersion\":1,\"stateVersion\":1}"; + let runtime: RuntimeVersion = serde_json::from_str(runtime_str).unwrap(); let finalized_block_runtime = @@ -201,7 +202,7 @@ async fn follow_with_runtime() { finalized_block_runtime, with_runtime: false, }); - assert_eq!(event, expected); + pretty_assertions::assert_eq!(event, expected); // Import a new block without runtime changes. // The runtime field must be None in this case. @@ -1365,7 +1366,6 @@ async fn pin_block_references() { genesis_block_builder, None, None, - None, Box::new(TaskExecutor::new()), client_config, ) diff --git a/client/rpc/Cargo.toml b/client/rpc/Cargo.toml index f9c36bf57c684..a3574ed84d011 100644 --- a/client/rpc/Cargo.toml +++ b/client/rpc/Cargo.toml @@ -50,6 +50,7 @@ sp-consensus = { version = "0.10.0-dev", path = "../../primitives/consensus/comm tokio = "1.22.0" sp-io = { version = "23.0.0", path = "../../primitives/io" } substrate-test-runtime-client = { version = "2.0.0", path = "../../test-utils/runtime/client" } +pretty_assertions = "1.2.1" [features] test-helpers = [] diff --git a/client/rpc/src/author/mod.rs b/client/rpc/src/author/mod.rs index 00a126500e26d..feee22641ef34 100644 --- a/client/rpc/src/author/mod.rs +++ b/client/rpc/src/author/mod.rs @@ -37,10 +37,10 @@ use sc_transaction_pool_api::{ error::IntoPoolError, BlockHash, InPoolTransaction, TransactionFor, TransactionPool, TransactionSource, TxHash, }; -use sp_api::ProvideRuntimeApi; +use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_blockchain::HeaderBackend; use sp_core::Bytes; -use sp_keystore::KeystorePtr; +use sp_keystore::{KeystoreExt, KeystorePtr}; use sp_runtime::{generic, traits::Block as BlockT}; use sp_session::SessionKeys; @@ -122,8 +122,11 @@ where self.deny_unsafe.check_if_safe()?; let best_block_hash = self.client.info().best_hash; - self.client - .runtime_api() + let mut runtime_api = self.client.runtime_api(); + + runtime_api.register_extension(KeystoreExt::from(self.keystore.clone())); + + runtime_api .generate_session_keys(best_block_hash, None) .map(Into::into) .map_err(|api_err| Error::Client(Box::new(api_err)).into()) diff --git a/client/rpc/src/author/tests.rs b/client/rpc/src/author/tests.rs index 1f688e8e85e05..f48b2f9571428 100644 --- a/client/rpc/src/author/tests.rs +++ b/client/rpc/src/author/tests.rs @@ -66,8 +66,7 @@ struct TestSetup { impl Default for TestSetup { fn default() -> Self { let keystore = Arc::new(MemoryKeystore::new()); - let client_builder = substrate_test_runtime_client::TestClientBuilder::new(); - let client = Arc::new(client_builder.set_keystore(keystore.clone()).build()); + let client = Arc::new(substrate_test_runtime_client::TestClientBuilder::new().build()); let spawner = sp_core::testing::TaskExecutor::new(); let pool = diff --git a/client/rpc/src/state/state_full.rs b/client/rpc/src/state/state_full.rs index 20ca5f7131e71..9604d9165f987 100644 --- a/client/rpc/src/state/state_full.rs +++ b/client/rpc/src/state/state_full.rs @@ -198,13 +198,7 @@ where .and_then(|block| { self.client .executor() - .call( - block, - &method, - &call_data, - self.client.execution_extensions().strategies().other, - CallContext::Offchain, - ) + .call(block, &method, &call_data, CallContext::Offchain) .map(Into::into) }) .map_err(client_err) diff --git a/client/rpc/src/state/tests.rs b/client/rpc/src/state/tests.rs index 9e00a04abe386..7c73c1e1cd8da 100644 --- a/client/rpc/src/state/tests.rs +++ b/client/rpc/src/state/tests.rs @@ -522,7 +522,7 @@ async fn should_return_runtime_version() { let runtime_version = api.runtime_version(None.into()).unwrap(); let serialized = serde_json::to_string(&runtime_version).unwrap(); - assert_eq!(serialized, result); + pretty_assertions::assert_eq!(serialized, result); let deserialized: RuntimeVersion = serde_json::from_str(result).unwrap(); assert_eq!(deserialized, runtime_version); diff --git a/client/service/Cargo.toml b/client/service/Cargo.toml index b77a6ef58e6cd..4f280503fbbcb 100644 --- a/client/service/Cargo.toml +++ b/client/service/Cargo.toml @@ -69,7 +69,6 @@ sc-rpc-spec-v2 = { version = "0.10.0-dev", path = "../rpc-spec-v2" } sc-block-builder = { version = "0.10.0-dev", path = "../block-builder" } sc-informant = { version = "0.10.0-dev", path = "../informant" } sc-telemetry = { version = "4.0.0-dev", path = "../telemetry" } -sc-offchain = { version = "4.0.0-dev", path = "../offchain" } prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus", version = "0.10.0-dev" } sc-tracing = { version = "4.0.0-dev", path = "../tracing" } sc-sysinfo = { version = "6.0.0-dev", path = "../sysinfo" } diff --git a/client/service/src/builder.rs b/client/service/src/builder.rs index 166e1b8785511..6b537e7ee48d5 100644 --- a/client/service/src/builder.rs +++ b/client/service/src/builder.rs @@ -187,9 +187,7 @@ where let client = { let extensions = sc_client_api::execution_extensions::ExecutionExtensions::new( - config.execution_strategies.clone(), - Some(keystore_container.keystore()), - sc_offchain::OffchainDb::factory_from_backend(&*backend), + None, Arc::new(executor.clone()), ); @@ -322,19 +320,14 @@ where /// Shared network instance implementing a set of mandatory traits. pub trait SpawnTaskNetwork: - sc_offchain::NetworkProvider + NetworkStateInfo + NetworkStatusProvider + Send + Sync + 'static + NetworkStateInfo + NetworkStatusProvider + Send + Sync + 'static { } impl SpawnTaskNetwork for T where Block: BlockT, - T: sc_offchain::NetworkProvider - + NetworkStateInfo - + NetworkStatusProvider - + Send - + Sync - + 'static, + T: NetworkStateInfo + NetworkStatusProvider + Send + Sync + 'static, { } @@ -368,38 +361,6 @@ pub struct SpawnTasksParams<'a, TBl: BlockT, TCl, TExPool, TRpc, Backend> { pub telemetry: Option<&'a mut Telemetry>, } -/// Build a shared offchain workers instance. -pub fn build_offchain_workers( - config: &Configuration, - spawn_handle: SpawnTaskHandle, - client: Arc, - network: Arc, -) -> Option>> -where - TBl: BlockT, - TCl: Send + Sync + ProvideRuntimeApi + BlockchainEvents + 'static, - >::Api: sc_offchain::OffchainWorkerApi, -{ - let offchain_workers = Some(Arc::new(sc_offchain::OffchainWorkers::new(client.clone()))); - - // Inform the offchain worker about new imported blocks - if let Some(offchain) = offchain_workers.clone() { - spawn_handle.spawn( - "offchain-notifications", - Some("offchain-worker"), - sc_offchain::notification_future( - config.role.is_authority(), - client, - offchain, - Clone::clone(&spawn_handle), - network, - ), - ); - } - - offchain_workers -} - /// Spawn the tasks that are required to run a node. pub fn spawn_tasks( params: SpawnTasksParams, @@ -420,7 +381,6 @@ where + Send + 'static, >::Api: sp_api::Metadata - + sc_offchain::OffchainWorkerApi + sp_transaction_pool::runtime_api::TaggedTransactionQueue + sp_session::SessionKeys + sp_api::ApiExt, @@ -451,6 +411,7 @@ where client.clone(), chain_info.best_hash, config.dev_key_seed.clone().map(|s| vec![s]).unwrap_or_default(), + keystore.clone(), ) .map_err(|e| Error::Application(Box::new(e)))?; diff --git a/client/service/src/client/call_executor.rs b/client/service/src/client/call_executor.rs index 7f83d62874c8e..facde72321db4 100644 --- a/client/service/src/client/call_executor.rs +++ b/client/service/src/client/call_executor.rs @@ -22,14 +22,10 @@ use sc_client_api::{ }; use sc_executor::{RuntimeVersion, RuntimeVersionOf}; use sp_api::{ProofRecorder, StorageTransactionCache}; -use sp_core::{ - traits::{CallContext, CodeExecutor, RuntimeCode}, - ExecutionContext, -}; +use sp_core::traits::{CallContext, CodeExecutor, RuntimeCode}; +use sp_externalities::Extensions; use sp_runtime::{generic::BlockId, traits::Block as BlockT}; -use sp_state_machine::{ - backend::AsTrieBackend, ExecutionStrategy, Ext, OverlayedChanges, StateMachine, StorageProof, -}; +use sp_state_machine::{backend::AsTrieBackend, Ext, OverlayedChanges, StateMachine, StorageProof}; use std::{cell::RefCell, sync::Arc}; /// Call executor that executes methods locally, querying all required @@ -166,7 +162,6 @@ where at_hash: Block::Hash, method: &str, call_data: &[u8], - strategy: ExecutionStrategy, context: CallContext, ) -> sp_blockchain::Result> { let mut changes = OverlayedChanges::default(); @@ -180,11 +175,7 @@ where let runtime_code = self.check_override(runtime_code, &state, at_hash)?.0; - let extensions = self.execution_extensions.extensions( - at_hash, - at_number, - ExecutionContext::OffchainCall(None), - ); + let mut extensions = self.execution_extensions.extensions(at_hash, at_number); let mut sm = StateMachine::new( &state, @@ -192,14 +183,13 @@ where &self.executor, method, call_data, - extensions, + &mut extensions, &runtime_code, context, ) .set_parent_hash(at_hash); - sm.execute_using_consensus_failure_handler(strategy.get_manager()) - .map_err(Into::into) + sm.execute().map_err(Into::into) } fn contextual_call( @@ -210,22 +200,13 @@ where changes: &RefCell, storage_transaction_cache: Option<&RefCell>>, recorder: &Option>, - context: ExecutionContext, + call_context: CallContext, + extensions: &RefCell, ) -> Result, sp_blockchain::Error> { let mut storage_transaction_cache = storage_transaction_cache.map(|c| c.borrow_mut()); - let at_number = - self.backend.blockchain().expect_block_number_from_id(&BlockId::Hash(at_hash))?; let state = self.backend.state_at(at_hash)?; - let call_context = match context { - ExecutionContext::OffchainCall(_) => CallContext::Offchain, - _ => CallContext::Onchain, - }; - - let (execution_manager, extensions) = - self.execution_extensions.manager_and_extensions(at_hash, at_number, context); - let changes = &mut *changes.borrow_mut(); // It is important to extract the runtime code here before we create the proof @@ -236,6 +217,7 @@ where let runtime_code = state_runtime_code.runtime_code().map_err(sp_blockchain::Error::RuntimeCode)?; let runtime_code = self.check_override(runtime_code, &state, at_hash)?.0; + let mut extensions = extensions.borrow_mut(); match recorder { Some(recorder) => { @@ -251,13 +233,13 @@ where &self.executor, method, call_data, - extensions, + &mut extensions, &runtime_code, call_context, ) .with_storage_transaction_cache(storage_transaction_cache.as_deref_mut()) .set_parent_hash(at_hash); - state_machine.execute_using_consensus_failure_handler(execution_manager) + state_machine.execute() }, None => { let mut state_machine = StateMachine::new( @@ -266,13 +248,13 @@ where &self.executor, method, call_data, - extensions, + &mut extensions, &runtime_code, call_context, ) .with_storage_transaction_cache(storage_transaction_cache.as_deref_mut()) .set_parent_hash(at_hash); - state_machine.execute_using_consensus_failure_handler(execution_manager) + state_machine.execute() }, } .map_err(Into::into) @@ -311,11 +293,7 @@ where method, call_data, &runtime_code, - self.execution_extensions.extensions( - at_hash, - at_number, - ExecutionContext::OffchainCall(None), - ), + &mut self.execution_extensions.extensions(at_hash, at_number), ) .map_err(Into::into) } @@ -411,7 +389,6 @@ mod tests { backend.clone(), executor.clone(), genesis_block_builder, - None, Box::new(TaskExecutor::new()), None, None, @@ -430,8 +407,6 @@ mod tests { ) .unwrap(), execution_extensions: Arc::new(ExecutionExtensions::new( - Default::default(), - None, None, Arc::new(executor.clone()), )), @@ -486,7 +461,6 @@ mod tests { backend.clone(), executor.clone(), genesis_block_builder, - None, Box::new(TaskExecutor::new()), None, None, diff --git a/client/service/src/client/client.rs b/client/service/src/client/client.rs index 3b1a526154d74..8c4b14fbddc24 100644 --- a/client/service/src/client/client.rs +++ b/client/service/src/client/client.rs @@ -62,10 +62,8 @@ use sp_core::{ well_known_keys, ChildInfo, ChildType, PrefixedStorageKey, StorageChild, StorageData, StorageKey, }, - traits::SpawnNamed, + traits::{CallContext, SpawnNamed}, }; -#[cfg(feature = "test-helpers")] -use sp_keystore::KeystorePtr; use sp_runtime::{ generic::{BlockId, SignedBlock}, traits::{ @@ -161,7 +159,6 @@ pub fn new_in_mem( backend: Arc>, executor: E, genesis_block_builder: G, - keystore: Option, prometheus_registry: Option, telemetry: Option, spawn_handle: Box, @@ -181,7 +178,6 @@ where backend, executor, genesis_block_builder, - keystore, spawn_handle, prometheus_registry, telemetry, @@ -224,7 +220,6 @@ pub fn new_with_backend( backend: Arc, executor: E, genesis_block_builder: G, - keystore: Option, spawn_handle: Box, prometheus_registry: Option, telemetry: Option, @@ -239,12 +234,7 @@ where Block: BlockT, B: backend::LocalBackend + 'static, { - let extensions = ExecutionExtensions::new( - Default::default(), - keystore, - sc_offchain::OffchainDb::factory_from_backend(&*backend), - Arc::new(executor.clone()), - ); + let extensions = ExecutionExtensions::new(None, Arc::new(executor.clone())); let call_executor = LocalCallExecutor::new(backend.clone(), executor, config.clone(), extensions)?; @@ -875,12 +865,12 @@ where // We should enact state, but don't have any storage changes, so we need to execute the // block. (true, None, Some(ref body)) => { - let runtime_api = self.runtime_api(); - let execution_context = import_block.origin.into(); + let mut runtime_api = self.runtime_api(); + + runtime_api.set_call_context(CallContext::Onchain); - runtime_api.execute_block_with_context( + runtime_api.execute_block( *parent_hash, - execution_context, Block::new(import_block.header.clone(), body.clone()), )?; @@ -1727,7 +1717,8 @@ where params.overlayed_changes, Some(params.storage_transaction_cache), params.recorder, - params.context, + params.call_context, + params.extensions, ) .map_err(Into::into) } @@ -1739,6 +1730,18 @@ where fn state_at(&self, at: Block::Hash) -> Result { self.state_at(at).map_err(Into::into) } + + fn initialize_extensions( + &self, + at: Block::Hash, + extensions: &mut sp_externalities::Extensions, + ) -> Result<(), sp_api::ApiError> { + let block_number = self.expect_block_number_from_id(&BlockId::Hash(at))?; + + extensions.merge(self.executor.execution_extensions().extensions(at, block_number)); + + Ok(()) + } } /// NOTE: only use this implementation when you are sure there are NO consensus-level BlockImport diff --git a/client/service/src/config.rs b/client/service/src/config.rs index 52e17c95e6783..39b7ee0507906 100644 --- a/client/service/src/config.rs +++ b/client/service/src/config.rs @@ -18,7 +18,6 @@ //! Service configuration. -pub use sc_client_api::execution_extensions::{ExecutionStrategies, ExecutionStrategy}; pub use sc_client_db::{BlocksPruning, Database, DatabaseSource, PruningMode}; pub use sc_executor::{WasmExecutionMethod, WasmtimeInstantiationStrategy}; pub use sc_network::{ @@ -81,8 +80,6 @@ pub struct Configuration { /// over on-chain runtimes when the spec version matches. Set to `None` to /// disable overrides (default). pub wasm_runtime_overrides: Option, - /// Execution strategies. - pub execution_strategies: ExecutionStrategies, /// JSON-RPC server binding address. pub rpc_addr: Option, /// Maximum number of connections for JSON-RPC server. diff --git a/client/service/src/lib.rs b/client/service/src/lib.rs index 4a896ecc87263..c987c2471907d 100644 --- a/client/service/src/lib.rs +++ b/client/service/src/lib.rs @@ -55,8 +55,8 @@ use sp_runtime::{ pub use self::{ builder::{ - build_network, build_offchain_workers, new_client, new_db_backend, new_full_client, - new_full_parts, new_full_parts_with_genesis_builder, new_native_or_wasm_executor, + build_network, new_client, new_db_backend, new_full_client, new_full_parts, + new_full_parts_with_genesis_builder, new_native_or_wasm_executor, new_wasm_executor, spawn_tasks, BuildNetworkParams, KeystoreContainer, NetworkStarter, SpawnTasksParams, TFullBackend, TFullCallExecutor, TFullClient, }, diff --git a/client/service/test/src/client/mod.rs b/client/service/test/src/client/mod.rs index 9c490a47a3b14..c40ac33da4bb9 100644 --- a/client/service/test/src/client/mod.rs +++ b/client/service/test/src/client/mod.rs @@ -37,9 +37,7 @@ use sp_runtime::{ traits::{BlakeTwo256, Block as BlockT, Header as HeaderT}, ConsensusEngineId, Justifications, StateVersion, }; -use sp_state_machine::{ - backend::Backend as _, ExecutionStrategy, InMemoryBackend, OverlayedChanges, StateMachine, -}; +use sp_state_machine::{backend::Backend as _, InMemoryBackend, OverlayedChanges, StateMachine}; use sp_storage::{ChildInfo, StorageKey}; use sp_trie::{LayoutV0, TrieConfiguration}; use std::{collections::HashSet, sync::Arc}; @@ -90,11 +88,11 @@ fn construct_block( &new_native_or_wasm_executor(), "Core_initialize_block", &header.encode(), - Default::default(), + &mut Default::default(), &runtime_code, CallContext::Onchain, ) - .execute(ExecutionStrategy::NativeElseWasm) + .execute() .unwrap(); for tx in transactions.iter() { @@ -104,11 +102,11 @@ fn construct_block( &new_native_or_wasm_executor(), "BlockBuilder_apply_extrinsic", &tx.encode(), - Default::default(), + &mut Default::default(), &runtime_code, CallContext::Onchain, ) - .execute(ExecutionStrategy::NativeElseWasm) + .execute() .unwrap(); } @@ -118,11 +116,11 @@ fn construct_block( &new_native_or_wasm_executor(), "BlockBuilder_finalize_block", &[], - Default::default(), + &mut Default::default(), &runtime_code, CallContext::Onchain, ) - .execute(ExecutionStrategy::NativeElseWasm) + .execute() .unwrap(); header = Header::decode(&mut &ret_data[..]).unwrap(); @@ -189,11 +187,11 @@ fn construct_genesis_should_work_with_native() { &new_native_or_wasm_executor(), "Core_execute_block", &b1data, - Default::default(), + &mut Default::default(), &runtime_code, CallContext::Onchain, ) - .execute(ExecutionStrategy::NativeElseWasm) + .execute() .unwrap(); } @@ -220,11 +218,11 @@ fn construct_genesis_should_work_with_wasm() { &new_native_or_wasm_executor(), "Core_execute_block", &b1data, - Default::default(), + &mut Default::default(), &runtime_code, CallContext::Onchain, ) - .execute(ExecutionStrategy::AlwaysWasm) + .execute() .unwrap(); } @@ -1670,22 +1668,21 @@ fn storage_keys_prefix_and_start_key_works() { let block_hash = client.info().best_hash; - let child_root = b":child_storage:default:child".to_vec(); + let child_root = array_bytes::bytes2hex("", b":child_storage:default:child"); let prefix = StorageKey(array_bytes::hex2bytes_unchecked("3a")); let child_prefix = StorageKey(b"sec".to_vec()); let res: Vec<_> = client .storage_keys(block_hash, Some(&prefix), None) .unwrap() - .map(|x| x.0) + .map(|x| array_bytes::bytes2hex("", &x.0)) .collect(); assert_eq!( res, [ - child_root.clone(), - array_bytes::hex2bytes_unchecked("3a636f6465"), //":code" - array_bytes::hex2bytes_unchecked("3a65787472696e7369635f696e646578"), //":extrinsic_index" - array_bytes::hex2bytes_unchecked("3a686561707061676573"), //":heappages" + &child_root, + "3a636f6465", //":code" + "3a65787472696e7369635f696e646578", //":extrinsic_index" ] ); @@ -1696,15 +1693,9 @@ fn storage_keys_prefix_and_start_key_works() { Some(&StorageKey(array_bytes::hex2bytes_unchecked("3a636f6465"))), ) .unwrap() - .map(|x| x.0) + .map(|x| array_bytes::bytes2hex("", &x.0)) .collect(); - assert_eq!( - res, - [ - array_bytes::hex2bytes_unchecked("3a65787472696e7369635f696e646578"), - array_bytes::hex2bytes_unchecked("3a686561707061676573") - ] - ); + assert_eq!(res, ["3a65787472696e7369635f696e646578",]); let res: Vec<_> = client .storage_keys( @@ -1737,7 +1728,7 @@ fn storage_keys_works() { sp_tracing::try_init_simple(); let expected_keys = - substrate_test_runtime::storage_key_generator::get_expected_storage_hashed_keys(); + substrate_test_runtime::storage_key_generator::get_expected_storage_hashed_keys(false); let client = substrate_test_runtime_client::new(); let block_hash = client.info().best_hash; @@ -1776,10 +1767,10 @@ fn storage_keys_works() { res, expected_keys .iter() - .filter(|&i| i > &"3a636f64".to_string()) + .filter(|&i| *i > "3a636f64") .take(8) .cloned() - .collect::>() + .collect::>() ); // Starting at a complete key the first key is skipped. @@ -1797,10 +1788,10 @@ fn storage_keys_works() { res, expected_keys .iter() - .filter(|&i| i > &"3a636f6465".to_string()) + .filter(|&i| *i > "3a636f6465") .take(8) .cloned() - .collect::>() + .collect::>() ); const SOME_BALANCE_KEY : &str = "26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9e2c1dc507e2035edbbd8776c440d870460c57f0008067cc01c5ff9eb2e2f9b3a94299a915a91198bd1021a6c55596f57"; @@ -1818,10 +1809,10 @@ fn storage_keys_works() { res, expected_keys .iter() - .filter(|&i| i > &SOME_BALANCE_KEY.to_string()) + .filter(|&i| *i > SOME_BALANCE_KEY) .take(8) .cloned() - .collect::>() + .collect::>() ); } @@ -1850,7 +1841,6 @@ fn cleans_up_closed_notification_sinks_on_block_import() { genesis_block_builder, None, None, - None, Box::new(TaskExecutor::new()), client_config, ) diff --git a/client/service/test/src/lib.rs b/client/service/test/src/lib.rs index 11c672db8cb90..38a811acc7401 100644 --- a/client/service/test/src/lib.rs +++ b/client/service/test/src/lib.rs @@ -245,7 +245,6 @@ fn node_config< chain_spec: Box::new((*spec).clone()), wasm_method: Default::default(), wasm_runtime_overrides: Default::default(), - execution_strategies: Default::default(), rpc_addr: Default::default(), rpc_max_connections: Default::default(), rpc_cors: None, diff --git a/client/statement-store/src/lib.rs b/client/statement-store/src/lib.rs index 4acb89a05f7d1..3b42641d9c5ab 100644 --- a/client/statement-store/src/lib.rs +++ b/client/statement-store/src/lib.rs @@ -59,7 +59,9 @@ use sp_blockchain::HeaderBackend; use sp_core::{hexdisplay::HexDisplay, traits::SpawnNamed, Decode, Encode}; use sp_runtime::traits::Block as BlockT; use sp_statement_store::{ - runtime_api::{InvalidStatement, StatementSource, ValidStatement, ValidateStatement}, + runtime_api::{ + InvalidStatement, StatementSource, StatementStoreExt, ValidStatement, ValidateStatement, + }, AccountId, BlockHash, Channel, DecryptionKey, Hash, NetworkPriority, Proof, Result, Statement, SubmitResult, Topic, }; @@ -491,8 +493,7 @@ impl Store { + 'static, Client::Api: ValidateStatement, { - let store = Arc::new(Self::new(path, options, client.clone(), prometheus)?); - client.execution_extensions().register_statement_store(store.clone()); + let store = Arc::new(Self::new(path, options, client, prometheus)?); // Perform periodic statement store maintenance let worker_store = store.clone(); @@ -696,6 +697,11 @@ impl Store { fn set_time(&mut self, time: u64) { self.time_override = Some(time); } + + /// Returns `self` as [`StatementStoreExt`]. + pub fn as_statement_store_ext(self: Arc) -> StatementStoreExt { + StatementStoreExt::new(self) + } } impl StatementStore for Store { diff --git a/client/transaction-pool/api/src/lib.rs b/client/transaction-pool/api/src/lib.rs index e7b3a9c5e16f8..32fe30f4584f0 100644 --- a/client/transaction-pool/api/src/lib.rs +++ b/client/transaction-pool/api/src/lib.rs @@ -29,12 +29,7 @@ use sp_runtime::{ generic::BlockId, traits::{Block as BlockT, Member, NumberFor}, }; -use std::{ - collections::HashMap, - hash::Hash, - pin::Pin, - sync::{Arc, Weak}, -}; +use std::{collections::HashMap, hash::Hash, marker::PhantomData, pin::Pin, sync::Arc}; const LOG_TARGET: &str = "txpool::api"; @@ -354,6 +349,22 @@ pub trait LocalTransactionPool: Send + Sync { ) -> Result; } +impl LocalTransactionPool for Arc { + type Block = T::Block; + + type Hash = T::Hash; + + type Error = T::Error; + + fn submit_local( + &self, + at: ::Hash, + xt: LocalTransactionFor, + ) -> Result { + (**self).submit_local(at, xt) + } +} + /// An abstraction for [`LocalTransactionPool`] /// /// We want to use a transaction pool in [`OffchainTransactionPoolFactory`] in a `Arc` without @@ -396,15 +407,13 @@ impl OffchainSubmitTransaction for TP /// the wasm execution environment to send transactions from an offchain call to the runtime. #[derive(Clone)] pub struct OffchainTransactionPoolFactory { - // To break retain cycle between `Client` and `TransactionPool` we require this - // extension to be a `Weak` reference. - pool: Weak>, + pool: Arc>, } impl OffchainTransactionPoolFactory { /// Creates a new instance using the given `tx_pool`. - pub fn new + 'static>(tx_pool: &Arc) -> Self { - Self { pool: Arc::downgrade(tx_pool) as Weak<_> } + pub fn new + 'static>(tx_pool: T) -> Self { + Self { pool: Arc::new(tx_pool) as Arc<_> } } /// Returns an instance of [`TransactionPoolExt`] bound to the given `block_hash`. @@ -419,7 +428,7 @@ impl OffchainTransactionPoolFactory { /// Wraps a `pool` and `block_hash` to implement [`sp_core::offchain::TransactionPool`]. struct OffchainTransactionPool { block_hash: Block::Hash, - pool: Weak>, + pool: Arc>, } impl sp_core::offchain::TransactionPool for OffchainTransactionPool { @@ -436,7 +445,7 @@ impl sp_core::offchain::TransactionPool for OffchainTransactionPo }, }; - self.pool.upgrade().ok_or(())?.submit_at(self.block_hash, extrinsic) + self.pool.submit_at(self.block_hash, extrinsic) } } @@ -463,6 +472,29 @@ mod v1_compatible { } } +/// Transaction pool that rejects all submitted transactions. +/// +/// Could be used for example in tests. +pub struct RejectAllTxPool(PhantomData); + +impl Default for RejectAllTxPool { + fn default() -> Self { + Self(PhantomData) + } +} + +impl LocalTransactionPool for RejectAllTxPool { + type Block = Block; + + type Hash = Block::Hash; + + type Error = error::Error; + + fn submit_local(&self, _: Block::Hash, _: Block::Extrinsic) -> Result { + Err(error::Error::ImmediatelyDropped) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/client/transaction-pool/src/lib.rs b/client/transaction-pool/src/lib.rs index 1b438bd7e4f2f..80e5925194c68 100644 --- a/client/transaction-pool/src/lib.rs +++ b/client/transaction-pool/src/lib.rs @@ -52,8 +52,8 @@ use std::{ use graph::{ExtrinsicHash, IsValidator}; use sc_transaction_pool_api::{ error::Error as TxPoolError, ChainEvent, ImportNotificationStream, MaintainedTransactionPool, - OffchainTransactionPoolFactory, PoolFuture, PoolStatus, ReadyTransactions, TransactionFor, - TransactionPool, TransactionSource, TransactionStatusStreamFor, TxHash, + PoolFuture, PoolStatus, ReadyTransactions, TransactionFor, TransactionPool, TransactionSource, + TransactionStatusStreamFor, TxHash, }; use sp_core::traits::SpawnEssentialNamed; use sp_runtime::{ @@ -396,11 +396,6 @@ where client.usage_info().chain.finalized_hash, )); - // make transaction pool available for off-chain runtime calls. - client - .execution_extensions() - .register_transaction_pool_factory(OffchainTransactionPoolFactory::new(&pool)); - pool } } diff --git a/frame/benchmarking/README.md b/frame/benchmarking/README.md index 76673c5f69b33..dc6a184435df6 100644 --- a/frame/benchmarking/README.md +++ b/frame/benchmarking/README.md @@ -175,7 +175,6 @@ Then you can run a benchmark like so: ```bash ./target/production/substrate benchmark pallet \ --chain dev \ # Configurable Chain Spec - --execution=wasm \ # Always test with Wasm --wasm-execution=compiled \ # Always used `wasm-time` --pallet pallet_balances \ # Select the pallet --extrinsic transfer \ # Select the extrinsic diff --git a/frame/nfts/src/weights.rs b/frame/nfts/src/weights.rs index 686fabb2a70b5..6b8c577bb12e5 100644 --- a/frame/nfts/src/weights.rs +++ b/frame/nfts/src/weights.rs @@ -35,7 +35,6 @@ // --no-median-slopes // --no-min-squares // --extrinsic=* -// --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/nfts/src/weights.rs diff --git a/primitives/api/Cargo.toml b/primitives/api/Cargo.toml index ded866ed48193..c6d197b8d35d5 100644 --- a/primitives/api/Cargo.toml +++ b/primitives/api/Cargo.toml @@ -18,6 +18,7 @@ sp-api-proc-macro = { version = "4.0.0-dev", path = "proc-macro" } sp-core = { version = "21.0.0", default-features = false, path = "../core" } sp-std = { version = "8.0.0", default-features = false, path = "../std" } sp-runtime = { version = "24.0.0", default-features = false, path = "../runtime" } +sp-externalities = { version = "0.19.0", default-features = false, optional = true, path = "../externalities" } sp-version = { version = "22.0.0", default-features = false, path = "../version" } sp-state-machine = { version = "0.28.0", default-features = false, optional = true, path = "../state-machine" } sp-trie = { version = "22.0.0", default-features = false, optional = true, path = "../trie" } @@ -35,6 +36,7 @@ default = ["std"] std = [ "codec/std", "sp-core/std", + "sp-externalities", "sp-std/std", "sp-runtime/std", "sp-state-machine/std", diff --git a/primitives/api/proc-macro/src/decl_runtime_apis.rs b/primitives/api/proc-macro/src/decl_runtime_apis.rs index 052dc896f2cc3..370735819f94c 100644 --- a/primitives/api/proc-macro/src/decl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/decl_runtime_apis.rs @@ -315,7 +315,6 @@ impl<'a> ToClientSideDecl<'a> { fn __runtime_api_internal_call_api_at( &self, at: #block_hash, - context: #crate_::ExecutionContext, params: std::vec::Vec, fn_name: &dyn Fn(#crate_::RuntimeVersion) -> &'static str, ) -> std::result::Result, #crate_::ApiError>; @@ -335,9 +334,8 @@ impl<'a> ToClientSideDecl<'a> { items.into_iter().for_each(|i| match i { TraitItem::Fn(method) => { - let (fn_decl, fn_decl_ctx) = self.fold_trait_item_fn(method, trait_generics_num); + let fn_decl = self.create_method_decl(method, trait_generics_num); result.push(fn_decl.into()); - result.push(fn_decl_ctx.into()); }, r => result.push(r), }); @@ -345,41 +343,12 @@ impl<'a> ToClientSideDecl<'a> { result } - fn fold_trait_item_fn( - &mut self, - method: TraitItemFn, - trait_generics_num: usize, - ) -> (TraitItemFn, TraitItemFn) { - let crate_ = self.crate_; - let context = quote!( #crate_::ExecutionContext::OffchainCall(None) ); - let fn_decl = self.create_method_decl(method.clone(), context, trait_generics_num); - let fn_decl_ctx = self.create_method_decl_with_context(method, trait_generics_num); - - (fn_decl, fn_decl_ctx) - } - - fn create_method_decl_with_context( - &mut self, - method: TraitItemFn, - trait_generics_num: usize, - ) -> TraitItemFn { - let crate_ = self.crate_; - let context_arg: syn::FnArg = parse_quote!( context: #crate_::ExecutionContext ); - let mut fn_decl_ctx = self.create_method_decl(method, quote!(context), trait_generics_num); - fn_decl_ctx.sig.ident = - Ident::new(&format!("{}_with_context", &fn_decl_ctx.sig.ident), Span::call_site()); - fn_decl_ctx.sig.inputs.insert(2, context_arg); - - fn_decl_ctx - } - /// Takes the method declared by the user and creates the declaration we require for the runtime /// api client side. This method will call by default the `method_runtime_api_impl` for doing /// the actual call into the runtime. fn create_method_decl( &mut self, mut method: TraitItemFn, - context: TokenStream, trait_generics_num: usize, ) -> TraitItemFn { let params = match extract_parameter_names_types_and_borrows( @@ -467,7 +436,6 @@ impl<'a> ToClientSideDecl<'a> { >::__runtime_api_internal_call_api_at( self, __runtime_api_at_param__, - #context, __runtime_api_impl_params_encoded__, &|_version| { #( diff --git a/primitives/api/proc-macro/src/impl_runtime_apis.rs b/primitives/api/proc-macro/src/impl_runtime_apis.rs index 028cc6a675ee5..e45f05029d9f3 100644 --- a/primitives/api/proc-macro/src/impl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/impl_runtime_apis.rs @@ -224,8 +224,8 @@ fn generate_runtime_api_base_structures() -> Result { Ok(quote!( pub struct RuntimeApi {} - /// Implements all runtime apis for the client side. #crate_::std_enabled! { + /// Implements all runtime apis for the client side. pub struct RuntimeApiImpl + 'static> { call: &'static C, transaction_depth: std::cell::RefCell, @@ -234,6 +234,9 @@ fn generate_runtime_api_base_structures() -> Result { #crate_::StorageTransactionCache >, recorder: std::option::Option<#crate_::ProofRecorder>, + call_context: #crate_::CallContext, + extensions: std::cell::RefCell<#crate_::Extensions>, + extensions_generated_for: std::cell::RefCell>, } impl> #crate_::ApiExt for @@ -321,6 +324,14 @@ fn generate_runtime_api_base_structures() -> Result { state_version, ) } + + fn set_call_context(&mut self, call_context: #crate_::CallContext) { + self.call_context = call_context; + } + + fn register_extension(&mut self, extension: E) { + std::cell::RefCell::borrow_mut(&self.extensions).register(extension); + } } impl #crate_::ConstructRuntimeApi @@ -339,6 +350,9 @@ fn generate_runtime_api_base_structures() -> Result { changes: std::default::Default::default(), recorder: std::default::Default::default(), storage_transaction_cache: std::default::Default::default(), + call_context: #crate_::CallContext::Offchain, + extensions: std::default::Default::default(), + extensions_generated_for: std::default::Default::default(), }.into() } } @@ -480,7 +494,6 @@ impl<'a> ApiRuntimeImplToApiRuntimeApiImpl<'a> { fn __runtime_api_internal_call_api_at( &self, at: <__SrApiBlock__ as #crate_::BlockT>::Hash, - context: #crate_::ExecutionContext, params: std::vec::Vec, fn_name: &dyn Fn(#crate_::RuntimeVersion) -> &'static str, ) -> std::result::Result, #crate_::ApiError> { @@ -498,14 +511,34 @@ impl<'a> ApiRuntimeImplToApiRuntimeApiImpl<'a> { at, )?; + match &mut *std::cell::RefCell::borrow_mut(&self.extensions_generated_for) { + Some(generated_for) => { + if *generated_for != at { + return std::result::Result::Err( + #crate_::ApiError::UsingSameInstanceForDifferentBlocks + ) + } + }, + generated_for @ None => { + #crate_::CallApiAt::<__SrApiBlock__>::initialize_extensions( + self.call, + at, + &mut std::cell::RefCell::borrow_mut(&self.extensions), + )?; + + *generated_for = Some(at); + } + } + let params = #crate_::CallApiAtParams { at, function: (*fn_name)(version), arguments: params, overlayed_changes: &self.changes, storage_transaction_cache: &self.storage_transaction_cache, - context, + call_context: self.call_context, recorder: &self.recorder, + extensions: &self.extensions, }; #crate_::CallApiAt::<__SrApiBlock__>::call_api_at( diff --git a/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs b/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs index be8c8ca0f8527..f85be81cc7f83 100644 --- a/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs @@ -121,13 +121,20 @@ fn implement_common_api_traits(block_type: TypePath, self_ty: Type) -> Result where Self: Sized { unimplemented!("`into_storage_changes` not implemented for runtime api mocks") } + + fn set_call_context(&mut self, _: #crate_::CallContext) { + unimplemented!("`set_call_context` not implemented for runtime api mocks") + } + + fn register_extension(&mut self, _: E) { + unimplemented!("`register_extension` not implemented for runtime api mocks") + } } impl #crate_::Core<#block_type> for #self_ty { fn __runtime_api_internal_call_api_at( &self, _: <#block_type as #crate_::BlockT>::Hash, - _: #crate_::ExecutionContext, _: std::vec::Vec, _: &dyn Fn(#crate_::RuntimeVersion) -> &'static str, ) -> std::result::Result, #crate_::ApiError> { @@ -141,14 +148,6 @@ fn implement_common_api_traits(block_type: TypePath, self_ty: Type) -> Result::Hash, - _: #crate_::ExecutionContext, - ) -> std::result::Result<#crate_::RuntimeVersion, #crate_::ApiError> { - unimplemented!("`Core::version` not implemented for runtime api mocks") - } - fn execute_block( &self, _: <#block_type as #crate_::BlockT>::Hash, @@ -157,15 +156,6 @@ fn implement_common_api_traits(block_type: TypePath, self_ty: Type) -> Result::Hash, - _: #crate_::ExecutionContext, - _: #block_type, - ) -> std::result::Result<(), #crate_::ApiError> { - unimplemented!("`Core::execute_block` not implemented for runtime api mocks") - } - fn initialize_block( &self, _: <#block_type as #crate_::BlockT>::Hash, @@ -173,15 +163,6 @@ fn implement_common_api_traits(block_type: TypePath, self_ty: Type) -> Result std::result::Result<(), #crate_::ApiError> { unimplemented!("`Core::initialize_block` not implemented for runtime api mocks") } - - fn initialize_block_with_context( - &self, - _: <#block_type as #crate_::BlockT>::Hash, - _: #crate_::ExecutionContext, - _: &<#block_type as #crate_::BlockT>::Header, - ) -> std::result::Result<(), #crate_::ApiError> { - unimplemented!("`Core::initialize_block` not implemented for runtime api mocks") - } } )) } @@ -255,26 +236,12 @@ impl<'a> FoldRuntimeApiImpl<'a> { let crate_ = generate_crate_access(); - // We also need to overwrite all the `_with_context` methods. To do this, - // we clone all methods and add them again with the new name plus one more argument. - impl_item.items.extend(impl_item.items.clone().into_iter().filter_map(|i| { - if let syn::ImplItem::Fn(mut m) = i { - m.sig.ident = quote::format_ident!("{}_with_context", m.sig.ident); - m.sig.inputs.insert(2, parse_quote!( _: #crate_::ExecutionContext )); - - Some(m.into()) - } else { - None - } - })); - let block_type = self.block_type; impl_item.items.push(parse_quote! { fn __runtime_api_internal_call_api_at( &self, _: <#block_type as #crate_::BlockT>::Hash, - _: #crate_::ExecutionContext, _: std::vec::Vec, _: &dyn Fn(#crate_::RuntimeVersion) -> &'static str, ) -> std::result::Result, #crate_::ApiError> { diff --git a/primitives/api/src/lib.rs b/primitives/api/src/lib.rs index 78c4cd73a18ae..e683d7aa637e9 100644 --- a/primitives/api/src/lib.rs +++ b/primitives/api/src/lib.rs @@ -78,11 +78,17 @@ pub use hash_db::Hasher; #[doc(hidden)] pub use scale_info; #[doc(hidden)] +pub use sp_core::offchain; +#[doc(hidden)] #[cfg(not(feature = "std"))] pub use sp_core::to_substrate_wasm_fn_return_value; +#[doc(hidden)] +#[cfg(feature = "std")] +pub use sp_core::traits::CallContext; use sp_core::OpaqueMetadata; #[doc(hidden)] -pub use sp_core::{offchain, ExecutionContext}; +#[cfg(feature = "std")] +pub use sp_externalities::{Extension, Extensions}; #[doc(hidden)] #[cfg(feature = "frame-metadata")] pub use sp_metadata_ir::{self as metadata_ir, frame_metadata as metadata}; @@ -518,6 +524,8 @@ pub enum ApiError { Application(#[from] Box), #[error("Api called for an unknown Block: {0}")] UnknownBlock(String), + #[error("Using the same api instance to call into multiple independent blocks.")] + UsingSameInstanceForDifferentBlocks, } /// Extends the runtime api implementation with some common functionality. @@ -581,6 +589,12 @@ pub trait ApiExt { ) -> Result, String> where Self: Sized; + + /// Set the [`CallContext`] to be used by the runtime api calls done by this instance. + fn set_call_context(&mut self, call_context: CallContext); + + /// Register an [`Extension`] that will be accessible while executing a runtime api call. + fn register_extension(&mut self, extension: E); } /// Parameters for [`CallApiAt::call_api_at`]. @@ -596,10 +610,12 @@ pub struct CallApiAtParams<'a, Block: BlockT, Backend: StateBackend, /// The cache for storage transactions. pub storage_transaction_cache: &'a RefCell>, - /// The context this function is executed in. - pub context: ExecutionContext, + /// The call context of this call. + pub call_context: CallContext, /// The optional proof recorder for recording storage accesses. pub recorder: &'a Option>, + /// The extensions that should be used for this call. + pub extensions: &'a RefCell, } /// Something that can call into the an api at a given block. @@ -620,6 +636,13 @@ pub trait CallApiAt { /// Get the state `at` the given block. fn state_at(&self, at: Block::Hash) -> Result; + + /// Initialize the `extensions` for the given block `at` by using the global extensions factory. + fn initialize_extensions( + &self, + at: Block::Hash, + extensions: &mut Extensions, + ) -> Result<(), ApiError>; } /// Auxiliary wrapper that holds an api instance and binds it to the given lifetime. diff --git a/primitives/api/test/benches/bench.rs b/primitives/api/test/benches/bench.rs index 88ebdbc6134aa..45bea08af6ded 100644 --- a/primitives/api/test/benches/bench.rs +++ b/primitives/api/test/benches/bench.rs @@ -17,7 +17,6 @@ use criterion::{criterion_group, criterion_main, Criterion}; use sp_api::ProvideRuntimeApi; -use sp_state_machine::ExecutionStrategy; use substrate_test_runtime_client::{ runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, }; @@ -56,17 +55,13 @@ fn sp_api_benchmark(c: &mut Criterion) { }); c.bench_function("calling function by function pointer in wasm", |b| { - let client = TestClientBuilder::new() - .set_execution_strategy(ExecutionStrategy::AlwaysWasm) - .build(); + let client = TestClientBuilder::new().build(); let best_hash = client.chain_info().best_hash; b.iter(|| client.runtime_api().benchmark_indirect_call(best_hash).unwrap()) }); - c.bench_function("calling function in wasm", |b| { - let client = TestClientBuilder::new() - .set_execution_strategy(ExecutionStrategy::AlwaysWasm) - .build(); + c.bench_function("calling function", |b| { + let client = TestClientBuilder::new().build(); let best_hash = client.chain_info().best_hash; b.iter(|| client.runtime_api().benchmark_direct_call(best_hash).unwrap()) }); diff --git a/primitives/api/test/tests/runtime_calls.rs b/primitives/api/test/tests/runtime_calls.rs index 344c2d31eb0a6..92118c16cdddc 100644 --- a/primitives/api/test/tests/runtime_calls.rs +++ b/primitives/api/test/tests/runtime_calls.rs @@ -22,9 +22,8 @@ use sp_runtime::{ traits::{HashFor, Header as HeaderT}, TransactionOutcome, }; -use sp_state_machine::{ - create_proof_check_backend, execution_proof_check_on_trie_backend, ExecutionStrategy, -}; +use sp_state_machine::{create_proof_check_backend, execution_proof_check_on_trie_backend}; + use substrate_test_runtime_client::{ prelude::*, runtime::{Block, Header, TestAPI, Transfer}, @@ -36,29 +35,18 @@ use sc_block_builder::BlockBuilderProvider; use sp_consensus::SelectChain; use substrate_test_runtime_client::sc_executor::WasmExecutor; -fn calling_function_with_strat(strat: ExecutionStrategy) { - let client = TestClientBuilder::new().set_execution_strategy(strat).build(); +#[test] +fn calling_runtime_function() { + let client = TestClientBuilder::new().build(); let runtime_api = client.runtime_api(); let best_hash = client.chain_info().best_hash; assert_eq!(runtime_api.benchmark_add_one(best_hash, &1).unwrap(), 2); } -#[test] -fn calling_native_runtime_function() { - calling_function_with_strat(ExecutionStrategy::NativeWhenPossible); -} - -#[test] -fn calling_wasm_runtime_function() { - calling_function_with_strat(ExecutionStrategy::AlwaysWasm); -} - #[test] fn calling_native_runtime_signature_changed_function() { - let client = TestClientBuilder::new() - .set_execution_strategy(ExecutionStrategy::NativeWhenPossible) - .build(); + let client = TestClientBuilder::new().build(); let runtime_api = client.runtime_api(); let best_hash = client.chain_info().best_hash; @@ -67,9 +55,7 @@ fn calling_native_runtime_signature_changed_function() { #[test] fn use_trie_function() { - let client = TestClientBuilder::new() - .set_execution_strategy(ExecutionStrategy::AlwaysWasm) - .build(); + let client = TestClientBuilder::new().build(); let runtime_api = client.runtime_api(); let best_hash = client.chain_info().best_hash; assert_eq!(runtime_api.use_trie(best_hash).unwrap(), 2); @@ -77,7 +63,7 @@ fn use_trie_function() { #[test] fn initialize_block_works() { - let client = TestClientBuilder::new().set_execution_strategy(ExecutionStrategy::Both).build(); + let client = TestClientBuilder::new().build(); let runtime_api = client.runtime_api(); let best_hash = client.chain_info().best_hash; runtime_api @@ -97,9 +83,7 @@ fn initialize_block_works() { #[test] fn record_proof_works() { - let (client, longest_chain) = TestClientBuilder::new() - .set_execution_strategy(ExecutionStrategy::Both) - .build_with_longest_chain(); + let (client, longest_chain) = TestClientBuilder::new().build_with_longest_chain(); let storage_root = *futures::executor::block_on(longest_chain.best_chain()).unwrap().state_root(); @@ -151,7 +135,7 @@ fn record_proof_works() { #[test] fn call_runtime_api_with_multiple_arguments() { - let client = TestClientBuilder::new().set_execution_strategy(ExecutionStrategy::Both).build(); + let client = TestClientBuilder::new().build(); let data = vec![1, 2, 4, 5, 6, 7, 8, 8, 10, 12]; let best_hash = client.chain_info().best_hash; @@ -166,8 +150,7 @@ fn disable_logging_works() { if std::env::var("RUN_TEST").is_ok() { sp_tracing::try_init_simple(); - let mut builder = - TestClientBuilder::new().set_execution_strategy(ExecutionStrategy::AlwaysWasm); + let mut builder = TestClientBuilder::new(); builder.genesis_init_mut().set_wasm_code( substrate_test_runtime_client::runtime::wasm_binary_logging_disabled_unwrap().to_vec(), ); diff --git a/primitives/api/test/tests/ui/mock_only_self_reference.stderr b/primitives/api/test/tests/ui/mock_only_self_reference.stderr index 430f63eee1660..f088e8f2de59d 100644 --- a/primitives/api/test/tests/ui/mock_only_self_reference.stderr +++ b/primitives/api/test/tests/ui/mock_only_self_reference.stderr @@ -48,42 +48,3 @@ error[E0050]: method `test2` has 2 parameters but the declaration in trait `Api: | |_^ expected 3 parameters, found 2 | = note: this error originates in the macro `sp_api::mock_impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0050]: method `test_with_context` has 3 parameters but the declaration in trait `Api::test_with_context` has 4 - --> tests/ui/mock_only_self_reference.rs:12:1 - | -3 | / sp_api::decl_runtime_apis! { -4 | | pub trait Api { -5 | | fn test(data: u64); - | |_________________________- trait requires 4 parameters -... -12 | / sp_api::mock_impl_runtime_apis! { -13 | | impl Api for MockApi { -14 | | fn test(self, data: u64) {} -15 | | -16 | | fn test2(&mut self, data: u64) {} -17 | | } -18 | | } - | |_^ expected 4 parameters, found 3 - | - = note: this error originates in the macro `sp_api::mock_impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0050]: method `test2_with_context` has 3 parameters but the declaration in trait `Api::test2_with_context` has 4 - --> tests/ui/mock_only_self_reference.rs:12:1 - | -3 | / sp_api::decl_runtime_apis! { -4 | | pub trait Api { -5 | | fn test(data: u64); -6 | | fn test2(data: u64); - | |__________________________- trait requires 4 parameters -... -12 | / sp_api::mock_impl_runtime_apis! { -13 | | impl Api for MockApi { -14 | | fn test(self, data: u64) {} -15 | | -16 | | fn test2(&mut self, data: u64) {} -17 | | } -18 | | } - | |_^ expected 4 parameters, found 3 - | - = note: this error originates in the macro `sp_api::mock_impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/primitives/application-crypto/test/src/ecdsa.rs b/primitives/application-crypto/test/src/ecdsa.rs index 99ca6f4c4adf2..396683a91ac02 100644 --- a/primitives/application-crypto/test/src/ecdsa.rs +++ b/primitives/application-crypto/test/src/ecdsa.rs @@ -16,13 +16,13 @@ // limitations under the License. //! Integration tests for ecdsa -use sp_api::ProvideRuntimeApi; +use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_application_crypto::ecdsa::AppPair; use sp_core::{ crypto::{ByteArray, Pair}, testing::ECDSA, }; -use sp_keystore::{testing::MemoryKeystore, Keystore}; +use sp_keystore::{testing::MemoryKeystore, Keystore, KeystoreExt}; use std::sync::Arc; use substrate_test_runtime_client::{ runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, @@ -31,9 +31,12 @@ use substrate_test_runtime_client::{ #[test] fn ecdsa_works_in_runtime() { let keystore = Arc::new(MemoryKeystore::new()); - let test_client = TestClientBuilder::new().set_keystore(keystore.clone()).build(); - let (signature, public) = test_client - .runtime_api() + let test_client = TestClientBuilder::new().build(); + + let mut runtime_api = test_client.runtime_api(); + runtime_api.register_extension(KeystoreExt::new(keystore.clone())); + + let (signature, public) = runtime_api .test_ecdsa_crypto(test_client.chain_info().genesis_hash) .expect("Tests `ecdsa` crypto."); diff --git a/primitives/application-crypto/test/src/ed25519.rs b/primitives/application-crypto/test/src/ed25519.rs index f4553f95bf1f8..f0ceccdcebfcd 100644 --- a/primitives/application-crypto/test/src/ed25519.rs +++ b/primitives/application-crypto/test/src/ed25519.rs @@ -17,13 +17,13 @@ //! Integration tests for ed25519 -use sp_api::ProvideRuntimeApi; +use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_application_crypto::ed25519::AppPair; use sp_core::{ crypto::{ByteArray, Pair}, testing::ED25519, }; -use sp_keystore::{testing::MemoryKeystore, Keystore}; +use sp_keystore::{testing::MemoryKeystore, Keystore, KeystoreExt}; use std::sync::Arc; use substrate_test_runtime_client::{ runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, @@ -32,9 +32,12 @@ use substrate_test_runtime_client::{ #[test] fn ed25519_works_in_runtime() { let keystore = Arc::new(MemoryKeystore::new()); - let test_client = TestClientBuilder::new().set_keystore(keystore.clone()).build(); - let (signature, public) = test_client - .runtime_api() + let test_client = TestClientBuilder::new().build(); + + let mut runtime_api = test_client.runtime_api(); + runtime_api.register_extension(KeystoreExt::new(keystore.clone())); + + let (signature, public) = runtime_api .test_ed25519_crypto(test_client.chain_info().genesis_hash) .expect("Tests `ed25519` crypto."); diff --git a/primitives/application-crypto/test/src/sr25519.rs b/primitives/application-crypto/test/src/sr25519.rs index 736521d7d9f3a..3c62270395f04 100644 --- a/primitives/application-crypto/test/src/sr25519.rs +++ b/primitives/application-crypto/test/src/sr25519.rs @@ -17,13 +17,13 @@ //! Integration tests for sr25519 -use sp_api::ProvideRuntimeApi; +use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_application_crypto::sr25519::AppPair; use sp_core::{ crypto::{ByteArray, Pair}, testing::SR25519, }; -use sp_keystore::{testing::MemoryKeystore, Keystore}; +use sp_keystore::{testing::MemoryKeystore, Keystore, KeystoreExt}; use std::sync::Arc; use substrate_test_runtime_client::{ runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, @@ -32,9 +32,12 @@ use substrate_test_runtime_client::{ #[test] fn sr25519_works_in_runtime() { let keystore = Arc::new(MemoryKeystore::new()); - let test_client = TestClientBuilder::new().set_keystore(keystore.clone()).build(); - let (signature, public) = test_client - .runtime_api() + let test_client = TestClientBuilder::new().build(); + + let mut runtime_api = test_client.runtime_api(); + runtime_api.register_extension(KeystoreExt::new(keystore.clone())); + + let (signature, public) = runtime_api .test_sr25519_crypto(test_client.chain_info().genesis_hash) .expect("Tests `sr25519` crypto."); diff --git a/primitives/consensus/common/src/lib.rs b/primitives/consensus/common/src/lib.rs index 215b4448b4a8e..d47f3bafc4220 100644 --- a/primitives/consensus/common/src/lib.rs +++ b/primitives/consensus/common/src/lib.rs @@ -71,16 +71,6 @@ pub enum BlockOrigin { File, } -impl From for sp_core::ExecutionContext { - fn from(origin: BlockOrigin) -> Self { - if origin == BlockOrigin::NetworkInitialSync { - sp_core::ExecutionContext::Syncing - } else { - sp_core::ExecutionContext::Importing - } - } -} - /// Environment for a Consensus instance. /// /// Creates proposer instance. diff --git a/primitives/core/Cargo.toml b/primitives/core/Cargo.toml index 65c252a523114..f0da73e8ec789 100644 --- a/primitives/core/Cargo.toml +++ b/primitives/core/Cargo.toml @@ -39,6 +39,7 @@ sp-externalities = { version = "0.19.0", optional = true, path = "../externaliti futures = { version = "0.3.21", optional = true } dyn-clonable = { version = "0.9.0", optional = true } thiserror = { version = "1.0.30", optional = true } +tracing = { version = "0.1.29", optional = true } bitflags = "1.3" paste = "1.0.7" @@ -113,6 +114,7 @@ std = [ "futures/thread-pool", "libsecp256k1/std", "dyn-clonable", + "tracing", ] # Serde support without relying on std features. diff --git a/primitives/core/src/lib.rs b/primitives/core/src/lib.rs index 951b481253b4e..da3b438190954 100644 --- a/primitives/core/src/lib.rs +++ b/primitives/core/src/lib.rs @@ -98,45 +98,6 @@ pub use sp_storage as storage; #[doc(hidden)] pub use sp_std; -/// Context for executing a call into the runtime. -pub enum ExecutionContext { - /// Context used for general block import (including locally authored blocks). - Importing, - /// Context used for importing blocks as part of an initial sync of the blockchain. - /// - /// We distinguish between major sync and import so that validators who are running - /// their initial sync (or catching up after some time offline) can use the faster - /// native runtime (since we can reasonably assume the network as a whole has already - /// come to a broad consensus on the block and it probably hasn't been crafted - /// specifically to attack this node), but when importing blocks at the head of the - /// chain in normal operation they can use the safer Wasm version. - Syncing, - /// Context used for block construction. - BlockConstruction, - /// Context used for offchain calls. - /// - /// This allows passing offchain extension and customizing available capabilities. - OffchainCall(Option<(Box, offchain::Capabilities)>), -} - -impl ExecutionContext { - /// Returns the capabilities of particular context. - pub fn capabilities(&self) -> offchain::Capabilities { - use ExecutionContext::*; - - match self { - Importing | Syncing | BlockConstruction => offchain::Capabilities::empty(), - // Enable keystore, transaction pool and Offchain DB reads by default for offchain - // calls. - OffchainCall(None) => - offchain::Capabilities::KEYSTORE | - offchain::Capabilities::OFFCHAIN_DB_READ | - offchain::Capabilities::TRANSACTION_POOL, - OffchainCall(Some((_, capabilities))) => *capabilities, - } - } -} - /// Hex-serialized shim for `Vec`. #[derive(PartialEq, Eq, Clone, RuntimeDebug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize, Hash, PartialOrd, Ord))] diff --git a/primitives/core/src/offchain/mod.rs b/primitives/core/src/offchain/mod.rs index a6cef85e6ac1b..cef495dfaacdc 100644 --- a/primitives/core/src/offchain/mod.rs +++ b/primitives/core/src/offchain/mod.rs @@ -260,26 +260,22 @@ impl Timestamp { bitflags::bitflags! { /// Execution context extra capabilities. pub struct Capabilities: u32 { - /// Access to transaction pool. - const TRANSACTION_POOL = 0b0000_0000_0001; /// External http calls. - const HTTP = 0b0000_0000_0010; + const HTTP = 1 << 0; /// Keystore access. - const KEYSTORE = 0b0000_0000_0100; + const KEYSTORE = 1 << 2; /// Randomness source. - const RANDOMNESS = 0b0000_0000_1000; + const RANDOMNESS = 1 << 3; /// Access to opaque network state. - const NETWORK_STATE = 0b0000_0001_0000; + const NETWORK_STATE = 1 << 4; /// Access to offchain worker DB (read only). - const OFFCHAIN_DB_READ = 0b0000_0010_0000; + const OFFCHAIN_DB_READ = 1 << 5; /// Access to offchain worker DB (writes). - const OFFCHAIN_DB_WRITE = 0b0000_0100_0000; + const OFFCHAIN_DB_WRITE = 1 << 6; /// Manage the authorized nodes - const NODE_AUTHORIZATION = 0b0000_1000_0000; + const NODE_AUTHORIZATION = 1 << 7; /// Access time related functionality - const TIME = 0b0001_0000_0000; - /// Access the statement store. - const STATEMENT_STORE = 0b0010_0000_0000; + const TIME = 1 << 8; } } @@ -785,8 +781,8 @@ mod tests { assert!(!none.contains(Capabilities::KEYSTORE)); assert!(all.contains(Capabilities::KEYSTORE)); assert!(some.contains(Capabilities::KEYSTORE)); - assert!(!none.contains(Capabilities::TRANSACTION_POOL)); - assert!(all.contains(Capabilities::TRANSACTION_POOL)); - assert!(!some.contains(Capabilities::TRANSACTION_POOL)); + assert!(!none.contains(Capabilities::RANDOMNESS)); + assert!(all.contains(Capabilities::RANDOMNESS)); + assert!(!some.contains(Capabilities::TIME)); } } diff --git a/primitives/core/src/offchain/storage.rs b/primitives/core/src/offchain/storage.rs index 3a114de5bfa3c..4db839f1a451a 100644 --- a/primitives/core/src/offchain/storage.rs +++ b/primitives/core/src/offchain/storage.rs @@ -17,12 +17,14 @@ //! In-memory implementation of offchain workers database. -use crate::offchain::OffchainStorage; +use crate::offchain::{DbExternalities, OffchainStorage, StorageKind, STORAGE_PREFIX}; use std::{ collections::hash_map::{Entry, HashMap}, iter::Iterator, }; +const LOG_TARGET: &str = "offchain-worker::storage"; + /// In-memory storage for offchain workers. #[derive(Debug, Clone, Default)] pub struct InMemOffchainStorage { @@ -88,3 +90,95 @@ impl OffchainStorage for InMemOffchainStorage { } } } + +fn unavailable_yet(name: &str) -> R { + tracing::error!( + target: LOG_TARGET, + "The {:?} API is not available for offchain workers yet. Follow \ + https://github.com/paritytech/substrate/issues/1458 for details", + name + ); + Default::default() +} + +const LOCAL_DB: &str = "LOCAL (fork-aware) DB"; + +/// Offchain DB that implements [`DbExternalities`] for [`OffchainStorage`]. +#[derive(Debug, Clone)] +pub struct OffchainDb { + /// Persistent storage database. + persistent: Storage, +} + +impl OffchainDb { + /// Create new instance of Offchain DB. + pub fn new(persistent: Storage) -> Self { + Self { persistent } + } +} + +impl DbExternalities for OffchainDb { + fn local_storage_set(&mut self, kind: StorageKind, key: &[u8], value: &[u8]) { + tracing::debug!( + target: LOG_TARGET, + ?kind, + key = ?array_bytes::bytes2hex("", key), + value = ?array_bytes::bytes2hex("", value), + "Write", + ); + match kind { + StorageKind::PERSISTENT => self.persistent.set(STORAGE_PREFIX, key, value), + StorageKind::LOCAL => unavailable_yet(LOCAL_DB), + } + } + + fn local_storage_clear(&mut self, kind: StorageKind, key: &[u8]) { + tracing::debug!( + target: LOG_TARGET, + ?kind, + key = ?array_bytes::bytes2hex("", key), + "Clear", + ); + match kind { + StorageKind::PERSISTENT => self.persistent.remove(STORAGE_PREFIX, key), + StorageKind::LOCAL => unavailable_yet(LOCAL_DB), + } + } + + fn local_storage_compare_and_set( + &mut self, + kind: StorageKind, + key: &[u8], + old_value: Option<&[u8]>, + new_value: &[u8], + ) -> bool { + tracing::debug!( + target: LOG_TARGET, + ?kind, + key = ?array_bytes::bytes2hex("", key), + new_value = ?array_bytes::bytes2hex("", new_value), + old_value = ?old_value.as_ref().map(|s| array_bytes::bytes2hex("", s)), + "CAS", + ); + match kind { + StorageKind::PERSISTENT => + self.persistent.compare_and_set(STORAGE_PREFIX, key, old_value, new_value), + StorageKind::LOCAL => unavailable_yet(LOCAL_DB), + } + } + + fn local_storage_get(&mut self, kind: StorageKind, key: &[u8]) -> Option> { + let result = match kind { + StorageKind::PERSISTENT => self.persistent.get(STORAGE_PREFIX, key), + StorageKind::LOCAL => unavailable_yet(LOCAL_DB), + }; + tracing::debug!( + target: LOG_TARGET, + ?kind, + key = ?array_bytes::bytes2hex("", key), + result = ?result.as_ref().map(|s| array_bytes::bytes2hex("", s)), + "Read", + ); + result + } +} diff --git a/primitives/externalities/src/extensions.rs b/primitives/externalities/src/extensions.rs index 84155227a713e..8b0bbd2c5921b 100644 --- a/primitives/externalities/src/extensions.rs +++ b/primitives/externalities/src/extensions.rs @@ -42,6 +42,12 @@ pub trait Extension: Send + Any { fn as_mut_any(&mut self) -> &mut dyn Any; } +impl Extension for Box { + fn as_mut_any(&mut self) -> &mut dyn Any { + (**self).as_mut_any() + } +} + /// Macro for declaring an extension that usable with [`Extensions`]. /// /// The extension will be an unit wrapper struct that implements [`Extension`], `Deref` and @@ -190,6 +196,14 @@ impl Extensions { pub fn iter_mut(&mut self) -> impl Iterator)> { self.extensions.iter_mut() } + + /// Merge `other` into `self`. + /// + /// If both contain the same extension, the extension instance of `other` will overwrite the + /// instance found in `self`. + pub fn merge(&mut self, other: Self) { + self.extensions.extend(other.extensions); + } } impl Extend for Extensions { diff --git a/primitives/keystore/src/lib.rs b/primitives/keystore/src/lib.rs index 1d2a27cb8726c..07583d11d527a 100644 --- a/primitives/keystore/src/lib.rs +++ b/primitives/keystore/src/lib.rs @@ -174,37 +174,36 @@ pub trait Keystore: Send + Sync { msg: &[u8; 32], ) -> Result, Error>; - #[cfg(feature = "bls-experimental")] /// Returns all bls12-381 public keys for the given key type. + #[cfg(feature = "bls-experimental")] fn bls381_public_keys(&self, id: KeyTypeId) -> Vec; - #[cfg(feature = "bls-experimental")] /// Returns all bls12-377 public keys for the given key type. + #[cfg(feature = "bls-experimental")] fn bls377_public_keys(&self, id: KeyTypeId) -> Vec; - #[cfg(feature = "bls-experimental")] /// Generate a new bls381 key pair for the given key type and an optional seed. /// /// Returns an `bls381::Public` key of the generated key pair or an `Err` if /// something failed during key generation. + #[cfg(feature = "bls-experimental")] fn bls381_generate_new( &self, key_type: KeyTypeId, seed: Option<&str>, ) -> Result; - #[cfg(feature = "bls-experimental")] /// Generate a new bls377 key pair for the given key type and an optional seed. /// /// Returns an `bls377::Public` key of the generated key pair or an `Err` if /// something failed during key generation. + #[cfg(feature = "bls-experimental")] fn bls377_generate_new( &self, key_type: KeyTypeId, seed: Option<&str>, ) -> Result; - #[cfg(feature = "bls-experimental")] /// Generate a bls381 signature for a given message. /// /// Receives [`KeyTypeId`] and a [`bls381::Public`] key to be able to map @@ -213,6 +212,7 @@ pub trait Keystore: Send + Sync { /// Returns an [`bls381::Signature`] or `None` in case the given `key_type` /// and `public` combination doesn't exist in the keystore. /// An `Err` will be returned if generating the signature itself failed. + #[cfg(feature = "bls-experimental")] fn bls381_sign( &self, key_type: KeyTypeId, @@ -220,7 +220,6 @@ pub trait Keystore: Send + Sync { msg: &[u8], ) -> Result, Error>; - #[cfg(feature = "bls-experimental")] /// Generate a bls377 signature for a given message. /// /// Receives [`KeyTypeId`] and a [`bls377::Public`] key to be able to map @@ -229,6 +228,7 @@ pub trait Keystore: Send + Sync { /// Returns an [`bls377::Signature`] or `None` in case the given `key_type` /// and `public` combination doesn't exist in the keystore. /// An `Err` will be returned if generating the signature itself failed. + #[cfg(feature = "bls-experimental")] fn bls377_sign( &self, key_type: KeyTypeId, @@ -309,6 +309,158 @@ pub trait Keystore: Send + Sync { } } +impl Keystore for Arc { + fn sr25519_public_keys(&self, key_type: KeyTypeId) -> Vec { + (**self).sr25519_public_keys(key_type) + } + + fn sr25519_generate_new( + &self, + key_type: KeyTypeId, + seed: Option<&str>, + ) -> Result { + (**self).sr25519_generate_new(key_type, seed) + } + + fn sr25519_sign( + &self, + key_type: KeyTypeId, + public: &sr25519::Public, + msg: &[u8], + ) -> Result, Error> { + (**self).sr25519_sign(key_type, public, msg) + } + + fn sr25519_vrf_sign( + &self, + key_type: KeyTypeId, + public: &sr25519::Public, + data: &sr25519::vrf::VrfSignData, + ) -> Result, Error> { + (**self).sr25519_vrf_sign(key_type, public, data) + } + + fn sr25519_vrf_output( + &self, + key_type: KeyTypeId, + public: &sr25519::Public, + input: &sr25519::vrf::VrfInput, + ) -> Result, Error> { + (**self).sr25519_vrf_output(key_type, public, input) + } + + fn ed25519_public_keys(&self, key_type: KeyTypeId) -> Vec { + (**self).ed25519_public_keys(key_type) + } + + fn ed25519_generate_new( + &self, + key_type: KeyTypeId, + seed: Option<&str>, + ) -> Result { + (**self).ed25519_generate_new(key_type, seed) + } + + fn ed25519_sign( + &self, + key_type: KeyTypeId, + public: &ed25519::Public, + msg: &[u8], + ) -> Result, Error> { + (**self).ed25519_sign(key_type, public, msg) + } + + fn ecdsa_public_keys(&self, key_type: KeyTypeId) -> Vec { + (**self).ecdsa_public_keys(key_type) + } + + fn ecdsa_generate_new( + &self, + key_type: KeyTypeId, + seed: Option<&str>, + ) -> Result { + (**self).ecdsa_generate_new(key_type, seed) + } + + fn ecdsa_sign( + &self, + key_type: KeyTypeId, + public: &ecdsa::Public, + msg: &[u8], + ) -> Result, Error> { + (**self).ecdsa_sign(key_type, public, msg) + } + + fn ecdsa_sign_prehashed( + &self, + key_type: KeyTypeId, + public: &ecdsa::Public, + msg: &[u8; 32], + ) -> Result, Error> { + (**self).ecdsa_sign_prehashed(key_type, public, msg) + } + + fn insert(&self, key_type: KeyTypeId, suri: &str, public: &[u8]) -> Result<(), ()> { + (**self).insert(key_type, suri, public) + } + + fn keys(&self, key_type: KeyTypeId) -> Result>, Error> { + (**self).keys(key_type) + } + + fn has_keys(&self, public_keys: &[(Vec, KeyTypeId)]) -> bool { + (**self).has_keys(public_keys) + } + + #[cfg(feature = "bls-experimental")] + fn bls381_public_keys(&self, id: KeyTypeId) -> Vec { + (**self).bls381_public_keys(id) + } + + #[cfg(feature = "bls-experimental")] + fn bls377_public_keys(&self, id: KeyTypeId) -> Vec { + (**self).bls377_public_keys(id) + } + + #[cfg(feature = "bls-experimental")] + fn bls381_generate_new( + &self, + key_type: KeyTypeId, + seed: Option<&str>, + ) -> Result { + (**self).bls381_generate_new(key_type, seed) + } + + #[cfg(feature = "bls-experimental")] + fn bls377_generate_new( + &self, + key_type: KeyTypeId, + seed: Option<&str>, + ) -> Result { + (**self).bls377_generate_new(key_type, seed) + } + + #[cfg(feature = "bls-experimental")] + fn bls381_sign( + &self, + key_type: KeyTypeId, + public: &bls381::Public, + msg: &[u8], + ) -> Result, Error> { + (**self).bls381_sign(key_type, public, msg) + } + + #[cfg(feature = "bls-experimental")] + fn bls377_sign( + &self, + key_type: KeyTypeId, + public: &bls377::Public, + msg: &[u8], + ) -> Result, Error> { + (**self).bls377_sign(key_type, public, msg) + } +} + /// A shared pointer to a keystore implementation. pub type KeystorePtr = Arc; @@ -319,6 +471,13 @@ sp_externalities::decl_extension! { impl KeystoreExt { /// Create a new instance of `KeystoreExt` + /// + /// This is more performant as we don't need to wrap keystore in another [`Arc`]. + pub fn from(keystore: KeystorePtr) -> Self { + Self(keystore) + } + + /// Create a new instance of `KeystoreExt` using the given `keystore`. pub fn new(keystore: T) -> Self { Self(Arc::new(keystore)) } diff --git a/primitives/runtime/src/runtime_logger.rs b/primitives/runtime/src/runtime_logger.rs index 63e96a52a527f..b7374b8b6f6c8 100644 --- a/primitives/runtime/src/runtime_logger.rs +++ b/primitives/runtime/src/runtime_logger.rs @@ -68,8 +68,7 @@ mod tests { use sp_api::ProvideRuntimeApi; use std::{env, str::FromStr}; use substrate_test_runtime_client::{ - runtime::TestAPI, DefaultTestClientBuilderExt, ExecutionStrategy, TestClientBuilder, - TestClientBuilderExt, + runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, }; #[test] @@ -78,9 +77,7 @@ mod tests { sp_tracing::try_init_simple(); log::set_max_level(log::LevelFilter::from_str(&env::var("RUST_LOG").unwrap()).unwrap()); - let client = TestClientBuilder::new() - .set_execution_strategy(ExecutionStrategy::AlwaysWasm) - .build(); + let client = TestClientBuilder::new().build(); let runtime_api = client.runtime_api(); runtime_api .do_trace_log(client.chain_info().genesis_hash) diff --git a/primitives/session/Cargo.toml b/primitives/session/Cargo.toml index f43390f0a1069..dc99c356cc197 100644 --- a/primitives/session/Cargo.toml +++ b/primitives/session/Cargo.toml @@ -20,6 +20,7 @@ sp-core = { version = "21.0.0", default-features = false, path = "../core" } sp-runtime = { version = "24.0.0", optional = true, path = "../runtime" } sp-staking = { version = "4.0.0-dev", default-features = false, path = "../staking" } sp-std = { version = "8.0.0", default-features = false, path = "../std" } +sp-keystore = { version = "0.27.0", path = "../keystore", optional = true } [features] default = [ "std" ] @@ -31,4 +32,5 @@ std = [ "sp-runtime/std", "sp-staking/std", "sp-std/std", + "sp-keystore", ] diff --git a/primitives/session/src/lib.rs b/primitives/session/src/lib.rs index 642aa2a21143e..45395e9766f55 100644 --- a/primitives/session/src/lib.rs +++ b/primitives/session/src/lib.rs @@ -112,17 +112,22 @@ pub fn generate_initial_session_keys( client: std::sync::Arc, at: Block::Hash, seeds: Vec, + keystore: sp_keystore::KeystorePtr, ) -> Result<(), sp_api::ApiError> where Block: BlockT, T: ProvideRuntimeApi, T::Api: SessionKeys, { + use sp_api::ApiExt; + if seeds.is_empty() { return Ok(()) } - let runtime_api = client.runtime_api(); + let mut runtime_api = client.runtime_api(); + + runtime_api.register_extension(sp_keystore::KeystoreExt::from(keystore)); for seed in seeds { runtime_api.generate_session_keys(at, Some(seed.as_bytes().to_vec()))?; diff --git a/primitives/state-machine/src/lib.rs b/primitives/state-machine/src/lib.rs index cc7de9080e3d0..3ef923851ffd8 100644 --- a/primitives/state-machine/src/lib.rs +++ b/primitives/state-machine/src/lib.rs @@ -168,14 +168,7 @@ mod execution { traits::{CallContext, CodeExecutor, RuntimeCode}, }; use sp_externalities::Extensions; - use std::{ - collections::{HashMap, HashSet}, - fmt, - }; - - const PROOF_CLOSE_TRANSACTION: &str = "\ - Closing a transaction that was started in this function. Client initiated transactions - are protected from being closed by the runtime. qed"; + use std::collections::{HashMap, HashSet}; pub(crate) type CallResult = Result, E>; @@ -185,21 +178,6 @@ mod execution { /// Trie backend with in-memory storage. pub type InMemoryBackend = TrieBackend, H>; - /// Strategy for executing a call into the runtime. - #[derive(Copy, Clone, Eq, PartialEq, Debug)] - pub enum ExecutionStrategy { - /// Execute with the native equivalent if it is compatible with the given wasm module; - /// otherwise fall back to the wasm. - NativeWhenPossible, - /// Use the given wasm module. - AlwaysWasm, - /// Run with both the wasm and the native variant (if compatible). Report any discrepancy - /// as an error. - Both, - /// First native, then if that fails or is not possible, wasm. - NativeElseWasm, - } - /// Storage backend trust level. #[derive(Debug, Clone)] pub enum BackendTrustLevel { @@ -211,73 +189,6 @@ mod execution { Untrusted, } - /// Like `ExecutionStrategy` only it also stores a handler in case of consensus failure. - #[derive(Clone)] - pub enum ExecutionManager { - /// Execute with the native equivalent if it is compatible with the given wasm module; - /// otherwise fall back to the wasm. - NativeWhenPossible, - /// Use the given wasm module. The backend on which code is executed code could be - /// trusted to provide all storage or not (i.e. the light client cannot be trusted to - /// provide for all storage queries since the storage entries it has come from an external - /// node). - AlwaysWasm(BackendTrustLevel), - /// Run with both the wasm and the native variant (if compatible). Call `F` in the case of - /// any discrepancy. - Both(F), - /// First native, then if that fails or is not possible, wasm. - NativeElseWasm, - } - - impl<'a, F> From<&'a ExecutionManager> for ExecutionStrategy { - fn from(s: &'a ExecutionManager) -> Self { - match *s { - ExecutionManager::NativeWhenPossible => ExecutionStrategy::NativeWhenPossible, - ExecutionManager::AlwaysWasm(_) => ExecutionStrategy::AlwaysWasm, - ExecutionManager::NativeElseWasm => ExecutionStrategy::NativeElseWasm, - ExecutionManager::Both(_) => ExecutionStrategy::Both, - } - } - } - - impl ExecutionStrategy { - /// Gets the corresponding manager for the execution strategy. - pub fn get_manager(self) -> ExecutionManager> { - match self { - ExecutionStrategy::AlwaysWasm => - ExecutionManager::AlwaysWasm(BackendTrustLevel::Trusted), - ExecutionStrategy::NativeWhenPossible => ExecutionManager::NativeWhenPossible, - ExecutionStrategy::NativeElseWasm => ExecutionManager::NativeElseWasm, - ExecutionStrategy::Both => ExecutionManager::Both(|wasm_result, native_result| { - warn!( - "Consensus error between wasm {:?} and native {:?}. Using wasm.", - wasm_result, native_result, - ); - warn!(" Native result {:?}", native_result); - warn!(" Wasm result {:?}", wasm_result); - wasm_result - }), - } - } - } - - /// Evaluate to ExecutionManager::NativeElseWasm, without having to figure out the type. - pub fn native_else_wasm() -> ExecutionManager> { - ExecutionManager::NativeElseWasm - } - - /// Evaluate to ExecutionManager::AlwaysWasm with trusted backend, without having to figure out - /// the type. - fn always_wasm() -> ExecutionManager> { - ExecutionManager::AlwaysWasm(BackendTrustLevel::Trusted) - } - - /// Evaluate ExecutionManager::AlwaysWasm with untrusted backend, without having to figure out - /// the type. - fn always_untrusted_wasm() -> ExecutionManager> { - ExecutionManager::AlwaysWasm(BackendTrustLevel::Untrusted) - } - /// The substrate state machine. pub struct StateMachine<'a, B, H, Exec> where @@ -289,7 +200,7 @@ mod execution { method: &'a str, call_data: &'a [u8], overlay: &'a mut OverlayedChanges, - extensions: Extensions, + extensions: &'a mut Extensions, storage_transaction_cache: Option<&'a mut StorageTransactionCache>, runtime_code: &'a RuntimeCode<'a>, stats: StateMachineStats, @@ -324,7 +235,7 @@ mod execution { exec: &'a Exec, method: &'a str, call_data: &'a [u8], - extensions: Extensions, + extensions: &'a mut Extensions, runtime_code: &'a RuntimeCode, context: CallContext, ) -> Self { @@ -372,13 +283,7 @@ mod execution { /// blocks (e.g. a transaction at a time), ensure a different method is used. /// /// Returns the SCALE encoded result of the executed function. - pub fn execute(&mut self, strategy: ExecutionStrategy) -> Result, Box> { - // We are not giving a native call and thus we are sure that the result can never be a - // native value. - self.execute_using_consensus_failure_handler(strategy.get_manager()) - } - - fn execute_aux(&mut self, use_native: bool) -> (CallResult, bool) { + pub fn execute(&mut self) -> Result, Box> { let mut cache = StorageTransactionCache::default(); let cache = match self.storage_transaction_cache.as_mut() { @@ -390,7 +295,7 @@ mod execution { .enter_runtime() .expect("StateMachine is never called from the runtime; qed"); - let mut ext = Ext::new(self.overlay, cache, self.backend, Some(&mut self.extensions)); + let mut ext = Ext::new(self.overlay, cache, self.backend, Some(self.extensions)); let ext_id = ext.id; @@ -403,14 +308,10 @@ mod execution { "Call", ); - let (result, was_native) = self.exec.call( - &mut ext, - self.runtime_code, - self.method, - self.call_data, - use_native, - self.context, - ); + let result = self + .exec + .call(&mut ext, self.runtime_code, self.method, self.call_data, false, self.context) + .0; self.overlay .exit_runtime() @@ -419,92 +320,11 @@ mod execution { trace!( target: "state", ext_id = %HexDisplay::from(&ext_id.to_le_bytes()), - ?was_native, ?result, "Return", ); - (result, was_native) - } - - fn execute_call_with_both_strategy( - &mut self, - on_consensus_failure: Handler, - ) -> CallResult - where - Handler: - FnOnce(CallResult, CallResult) -> CallResult, - { - self.overlay.start_transaction(); - let (result, was_native) = self.execute_aux(true); - - if was_native { - self.overlay.rollback_transaction().expect(PROOF_CLOSE_TRANSACTION); - let (wasm_result, _) = self.execute_aux(false); - - if (result.is_ok() && - wasm_result.is_ok() && result.as_ref().ok() == wasm_result.as_ref().ok()) || - result.is_err() && wasm_result.is_err() - { - result - } else { - on_consensus_failure(wasm_result, result) - } - } else { - self.overlay.commit_transaction().expect(PROOF_CLOSE_TRANSACTION); - result - } - } - - fn execute_call_with_native_else_wasm_strategy(&mut self) -> CallResult { - self.overlay.start_transaction(); - let (result, was_native) = self.execute_aux(true); - - if !was_native || result.is_ok() { - self.overlay.commit_transaction().expect(PROOF_CLOSE_TRANSACTION); - result - } else { - self.overlay.rollback_transaction().expect(PROOF_CLOSE_TRANSACTION); - self.execute_aux(false).0 - } - } - - /// Execute a call using the given state backend, overlayed changes, and call executor. - /// - /// On an error, no prospective changes are written to the overlay. - /// - /// Note: changes to code will be in place if this call is made again. For running partial - /// blocks (e.g. a transaction at a time), ensure a different method is used. - /// - /// Returns the result of the executed function either in native representation `R` or - /// in SCALE encoded representation. - pub fn execute_using_consensus_failure_handler( - &mut self, - manager: ExecutionManager, - ) -> Result, Box> - where - Handler: - FnOnce(CallResult, CallResult) -> CallResult, - { - let result = { - match manager { - ExecutionManager::Both(on_consensus_failure) => - self.execute_call_with_both_strategy(on_consensus_failure), - ExecutionManager::NativeElseWasm => - self.execute_call_with_native_else_wasm_strategy(), - ExecutionManager::AlwaysWasm(trust_level) => { - let _abort_guard = match trust_level { - BackendTrustLevel::Trusted => None, - BackendTrustLevel::Untrusted => - Some(sp_panic_handler::AbortGuard::never_abort()), - }; - self.execute_aux(false).0 - }, - ExecutionManager::NativeWhenPossible => self.execute_aux(true).0, - } - }; - - result.map_err(|e| Box::new(e) as _) + result.map_err(|e| Box::new(e) as Box<_>) } } @@ -531,7 +351,7 @@ mod execution { method, call_data, runtime_code, - Default::default(), + &mut Default::default(), ) } @@ -551,7 +371,7 @@ mod execution { method: &str, call_data: &[u8], runtime_code: &RuntimeCode, - extensions: Extensions, + extensions: &mut Extensions, ) -> Result<(Vec, StorageProof), Box> where S: trie_backend_essence::TrieBackendStorage, @@ -572,7 +392,7 @@ mod execution { runtime_code, CallContext::Offchain, ) - .execute_using_consensus_failure_handler::<_>(always_wasm())?; + .execute()?; let proof = proving_backend .extract_proof() @@ -627,11 +447,11 @@ mod execution { exec, method, call_data, - Extensions::default(), + &mut Extensions::default(), runtime_code, CallContext::Offchain, ) - .execute_using_consensus_failure_handler(always_untrusted_wasm()) + .execute() } /// Generate storage read proof. @@ -1356,6 +1176,7 @@ mod tests { let backend = trie_backend::tests::test_trie(state_version, None, None); let mut overlayed_changes = Default::default(); let wasm_code = RuntimeCode::empty(); + let mut execution_extensions = &mut Default::default(); let mut state_machine = StateMachine::new( &backend, @@ -1367,12 +1188,12 @@ mod tests { }, "test", &[], - Default::default(), + &mut execution_extensions, &wasm_code, CallContext::Offchain, ); - assert_eq!(state_machine.execute(ExecutionStrategy::NativeWhenPossible).unwrap(), vec![66]); + assert_eq!(state_machine.execute().unwrap(), vec![66]); } #[test] @@ -1384,6 +1205,7 @@ mod tests { let backend = trie_backend::tests::test_trie(state_version, None, None); let mut overlayed_changes = Default::default(); let wasm_code = RuntimeCode::empty(); + let mut execution_extensions = &mut Default::default(); let mut state_machine = StateMachine::new( &backend, @@ -1395,47 +1217,12 @@ mod tests { }, "test", &[], - Default::default(), - &wasm_code, - CallContext::Offchain, - ); - - assert_eq!(state_machine.execute(ExecutionStrategy::NativeElseWasm).unwrap(), vec![66]); - } - - #[test] - fn dual_execution_strategy_detects_consensus_failure() { - dual_execution_strategy_detects_consensus_failure_inner(StateVersion::V0); - dual_execution_strategy_detects_consensus_failure_inner(StateVersion::V1); - } - fn dual_execution_strategy_detects_consensus_failure_inner(state_version: StateVersion) { - let mut consensus_failed = false; - let backend = trie_backend::tests::test_trie(state_version, None, None); - let mut overlayed_changes = Default::default(); - let wasm_code = RuntimeCode::empty(); - - let mut state_machine = StateMachine::new( - &backend, - &mut overlayed_changes, - &DummyCodeExecutor { - native_available: true, - native_succeeds: true, - fallback_succeeds: false, - }, - "test", - &[], - Default::default(), + &mut execution_extensions, &wasm_code, CallContext::Offchain, ); - assert!(state_machine - .execute_using_consensus_failure_handler(ExecutionManager::Both(|we, _ne| { - consensus_failed = true; - we - }),) - .is_err()); - assert!(consensus_failed); + assert_eq!(state_machine.execute().unwrap(), vec![66]); } #[test] diff --git a/scripts/ci/gitlab/pipeline/test.yml b/scripts/ci/gitlab/pipeline/test.yml index 2aa67bbf44feb..0a73e0b4114bb 100644 --- a/scripts/ci/gitlab/pipeline/test.yml +++ b/scripts/ci/gitlab/pipeline/test.yml @@ -115,8 +115,8 @@ cargo-check-benches: rusty-cachier cache upload ;; 2) - cargo run --locked --release -p node-bench -- ::node::import::native::sr25519::transfer_keep_alive::paritydb::small --json - | tee ./artifacts/benches/$CI_COMMIT_REF_NAME-$CI_COMMIT_SHORT_SHA/::node::import::native::sr25519::transfer_keep_alive::paritydb::small.json + cargo run --locked --release -p node-bench -- ::node::import::sr25519::transfer_keep_alive::paritydb::small --json + | tee ./artifacts/benches/$CI_COMMIT_REF_NAME-$CI_COMMIT_SHORT_SHA/::node::import::sr25519::transfer_keep_alive::paritydb::small.json ;; esac @@ -305,7 +305,7 @@ quick-benchmarks: WASM_BUILD_RUSTFLAGS: "-C debug-assertions -D warnings" script: - rusty-cachier snapshot create - - time cargo run --locked --release --features runtime-benchmarks -- benchmark pallet --execution wasm --wasm-execution compiled --chain dev --pallet "*" --extrinsic "*" --steps 2 --repeat 1 + - time cargo run --locked --release --features runtime-benchmarks -- benchmark pallet --wasm-execution compiled --chain dev --pallet "*" --extrinsic "*" --steps 2 --repeat 1 - rusty-cachier cache upload test-frame-examples-compile-to-wasm: diff --git a/scripts/run_all_benchmarks.sh b/scripts/run_all_benchmarks.sh index 727b49e26afe5..83848100a7e51 100755 --- a/scripts/run_all_benchmarks.sh +++ b/scripts/run_all_benchmarks.sh @@ -119,7 +119,6 @@ for PALLET in "${PALLETS[@]}"; do --repeat=20 \ --pallet="$PALLET" \ --extrinsic="*" \ - --execution=wasm \ --wasm-execution=compiled \ --heap-pages=4096 \ --output="$WEIGHT_FILE" \ @@ -137,7 +136,6 @@ echo "[+] Benchmarking block and extrinsic overheads..." OUTPUT=$( $SUBSTRATE benchmark overhead \ --chain=dev \ - --execution=wasm \ --wasm-execution=compiled \ --weight-path="./frame/support/src/weights/" \ --header="./HEADER-APACHE2" \ diff --git a/test-utils/client/src/lib.rs b/test-utils/client/src/lib.rs index 94006fd9acb8e..90e15e0f8d53e 100644 --- a/test-utils/client/src/lib.rs +++ b/test-utils/client/src/lib.rs @@ -22,10 +22,7 @@ pub mod client_ext; pub use self::client_ext::{ClientBlockImportExt, ClientExt}; -pub use sc_client_api::{ - execution_extensions::{ExecutionExtensions, ExecutionStrategies}, - BadBlocks, ForkBlocks, -}; +pub use sc_client_api::{execution_extensions::ExecutionExtensions, BadBlocks, ForkBlocks}; pub use sc_client_db::{self, Backend, BlocksPruning}; pub use sc_executor::{self, NativeElseWasmExecutor, WasmExecutionMethod, WasmExecutor}; pub use sc_service::{client, RpcHandlers}; @@ -35,7 +32,6 @@ pub use sp_keyring::{ }; pub use sp_keystore::{Keystore, KeystorePtr}; pub use sp_runtime::{Storage, StorageChild}; -pub use sp_state_machine::ExecutionStrategy; use futures::{future::Future, stream::StreamExt}; use sc_client_api::BlockchainEvents; @@ -67,14 +63,12 @@ impl GenesisInit for () { /// A builder for creating a test client instance. pub struct TestClientBuilder { - execution_strategies: ExecutionStrategies, genesis_init: G, /// The key is an unprefixed storage key, this only contains /// default child trie content. child_storage_extension: HashMap, StorageChild>, backend: Arc, _executor: std::marker::PhantomData, - keystore: Option, fork_blocks: ForkBlocks, bad_blocks: BadBlocks, enable_offchain_indexing_api: bool, @@ -119,11 +113,9 @@ impl pub fn with_backend(backend: Arc) -> Self { TestClientBuilder { backend, - execution_strategies: ExecutionStrategies::default(), child_storage_extension: Default::default(), genesis_init: Default::default(), _executor: Default::default(), - keystore: None, fork_blocks: None, bad_blocks: None, enable_offchain_indexing_api: false, @@ -131,12 +123,6 @@ impl } } - /// Set the keystore that should be used by the externalities. - pub fn set_keystore(mut self, keystore: KeystorePtr) -> Self { - self.keystore = Some(keystore); - self - } - /// Alter the genesis storage parameters. pub fn genesis_init_mut(&mut self) -> &mut G { &mut self.genesis_init @@ -162,18 +148,6 @@ impl self } - /// Set the execution strategy that should be used by all contexts. - pub fn set_execution_strategy(mut self, execution_strategy: ExecutionStrategy) -> Self { - self.execution_strategies = ExecutionStrategies { - syncing: execution_strategy, - importing: execution_strategy, - block_construction: execution_strategy, - offchain_worker: execution_strategy, - other: execution_strategy, - }; - self - } - /// Sets custom block rules. pub fn set_block_rules( mut self, @@ -296,12 +270,7 @@ impl self.backend.clone(), executor.clone(), Default::default(), - ExecutionExtensions::new( - self.execution_strategies.clone(), - self.keystore.clone(), - sc_offchain::OffchainDb::factory_from_backend(&*self.backend), - Arc::new(executor), - ), + ExecutionExtensions::new(None, Arc::new(executor)), ) .expect("Creates LocalCallExecutor"); diff --git a/test-utils/runtime/src/genesismap.rs b/test-utils/runtime/src/genesismap.rs index f1289ce41a583..ed27bce0b35b3 100644 --- a/test-utils/runtime/src/genesismap.rs +++ b/test-utils/runtime/src/genesismap.rs @@ -138,10 +138,9 @@ impl GenesisStorageBuilder { .build_storage() .expect("Build storage from substrate-test-runtime GenesisConfig"); - storage.top.insert( - well_known_keys::HEAP_PAGES.into(), - self.heap_pages_override.unwrap_or(16_u64).encode(), - ); + if let Some(heap_pages) = self.heap_pages_override { + storage.top.insert(well_known_keys::HEAP_PAGES.into(), heap_pages.encode()); + } storage.top.extend(self.extra_storage.top.clone()); storage.children_default.extend(self.extra_storage.children_default.clone()); diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index d02b378e154f2..8beed61d3d3d9 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -845,8 +845,12 @@ pub mod storage_key_generator { /// Generate the hashed storage keys from the raw literals. These keys are expected to be be in /// storage with given substrate-test runtime. - pub fn generate_expected_storage_hashed_keys() -> Vec { - let literals: Vec<&[u8]> = vec![b":code", b":extrinsic_index", b":heappages"]; + pub fn generate_expected_storage_hashed_keys(custom_heap_pages: bool) -> Vec { + let mut literals: Vec<&[u8]> = vec![b":code", b":extrinsic_index"]; + + if custom_heap_pages { + literals.push(b":heappages"); + } let keys: Vec> = vec![ vec![b"Babe", b"Authorities"], @@ -906,8 +910,11 @@ pub mod storage_key_generator { /// that would be generated by `generate_expected_storage_hashed_keys`. This list is provided /// for the debugging convenience only. Value of each hex-string is documented with the literal /// origin. - pub fn get_expected_storage_hashed_keys() -> Vec { - [ + /// + /// `custom_heap_pages`: Should be set to `true` when the state contains the `:heap_pages` key + /// aka when overriding the heap pages to be used by the executor. + pub fn get_expected_storage_hashed_keys(custom_heap_pages: bool) -> Vec<&'static str> { + let mut res = vec![ //System|:__STORAGE_VERSION__: "00771836bebdd29870ff246d305c578c4e7b9012096b41c4eb3aaf947f6ea429", //SubstrateTest|Authorities @@ -977,20 +984,25 @@ pub mod storage_key_generator { "3a636f6465", // :extrinsic_index "3a65787472696e7369635f696e646578", - // :heappages - "3a686561707061676573", // Balances|:__STORAGE_VERSION__: "c2261276cc9d1f8598ea4b6a74b15c2f4e7b9012096b41c4eb3aaf947f6ea429", // Balances|TotalIssuance "c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80", - ].into_iter().map(String::from).collect::>() + ]; + + if custom_heap_pages { + // :heappages + res.push("3a686561707061676573"); + } + + res } #[test] fn expected_keys_vec_are_matching() { assert_eq!( - storage_key_generator::get_expected_storage_hashed_keys(), - storage_key_generator::generate_expected_storage_hashed_keys(), + storage_key_generator::get_expected_storage_hashed_keys(false), + storage_key_generator::generate_expected_storage_hashed_keys(false), ); } } @@ -1001,15 +1013,14 @@ mod tests { use codec::Encode; use frame_support::dispatch::DispatchInfo; use sc_block_builder::BlockBuilderProvider; - use sp_api::ProvideRuntimeApi; + use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_consensus::BlockOrigin; - use sp_core::{storage::well_known_keys::HEAP_PAGES, ExecutionContext}; + use sp_core::{storage::well_known_keys::HEAP_PAGES, traits::CallContext}; use sp_keyring::AccountKeyring; use sp_runtime::{ traits::{Hash as _, SignedExtension}, transaction_validity::{InvalidTransaction, ValidTransaction}, }; - use sp_state_machine::ExecutionStrategy; use substrate_test_runtime_client::{ prelude::*, runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, }; @@ -1019,20 +1030,15 @@ mod tests { // This tests that the on-chain `HEAP_PAGES` parameter is respected. // Create a client devoting only 8 pages of wasm memory. This gives us ~512k of heap memory. - let mut client = TestClientBuilder::new() - .set_execution_strategy(ExecutionStrategy::AlwaysWasm) - .set_heap_pages(8) - .build(); + let mut client = TestClientBuilder::new().set_heap_pages(8).build(); let best_hash = client.chain_info().best_hash; // Try to allocate 1024k of memory on heap. This is going to fail since it is twice larger // than the heap. - let ret = client.runtime_api().vec_with_capacity_with_context( - best_hash, - // Use `BlockImport` to ensure we use the on chain heap pages as configured above. - ExecutionContext::Importing, - 1048576, - ); + let mut runtime_api = client.runtime_api(); + // This is currently required to allocate the 1024k of memory as configured above. + runtime_api.set_call_context(CallContext::Onchain); + let ret = runtime_api.vec_with_capacity(best_hash, 1048576); assert!(ret.is_err()); // Create a block that sets the `:heap_pages` to 32 pages of memory which corresponds to @@ -1054,8 +1060,7 @@ mod tests { #[test] fn test_storage() { - let client = - TestClientBuilder::new().set_execution_strategy(ExecutionStrategy::Both).build(); + let client = TestClientBuilder::new().build(); let runtime_api = client.runtime_api(); let best_hash = client.chain_info().best_hash; @@ -1080,8 +1085,7 @@ mod tests { let backend = sp_state_machine::TrieBackendBuilder::<_, crate::Hashing>::new(db, root).build(); let proof = sp_state_machine::prove_read(backend, vec![b"value3"]).unwrap(); - let client = - TestClientBuilder::new().set_execution_strategy(ExecutionStrategy::Both).build(); + let client = TestClientBuilder::new().build(); let runtime_api = client.runtime_api(); let best_hash = client.chain_info().best_hash; @@ -1108,7 +1112,7 @@ mod tests { .cloned() .map(storage_key_generator::hex) .collect::>(), - storage_key_generator::get_expected_storage_hashed_keys() + storage_key_generator::get_expected_storage_hashed_keys(false) ); } diff --git a/test-utils/runtime/src/substrate_test_pallet.rs b/test-utils/runtime/src/substrate_test_pallet.rs index 0864c952b70c4..d080caa0898dd 100644 --- a/test-utils/runtime/src/substrate_test_pallet.rs +++ b/test-utils/runtime/src/substrate_test_pallet.rs @@ -24,7 +24,7 @@ use frame_support::{pallet_prelude::*, storage}; use sp_core::sr25519::Public; use sp_runtime::{ - traits::{BlakeTwo256, Hash}, + traits::Hash, transaction_validity::{ InvalidTransaction, TransactionSource, TransactionValidity, ValidTransaction, }, @@ -41,7 +41,7 @@ pub mod pallet { use crate::TransferData; use frame_system::pallet_prelude::*; use sp_core::storage::well_known_keys; - use sp_runtime::{transaction_validity::TransactionPriority, Perbill}; + use sp_runtime::{traits::BlakeTwo256, transaction_validity::TransactionPriority, Perbill}; #[pallet::pallet] #[pallet::without_storage_info] diff --git a/utils/frame/benchmarking-cli/src/block/cmd.rs b/utils/frame/benchmarking-cli/src/block/cmd.rs index 0192372fa33a7..90b71cd78c2a4 100644 --- a/utils/frame/benchmarking-cli/src/block/cmd.rs +++ b/utils/frame/benchmarking-cli/src/block/cmd.rs @@ -39,12 +39,12 @@ use super::bench::{Benchmark, BenchmarkParams}; /// did not use more weight than declared which would otherwise be an issue. /// To test this with a dev node, first create one with a temp directory: /// -/// $ substrate --dev -d /tmp/my-dev --execution wasm --wasm-execution compiled +/// $ substrate --dev -d /tmp/my-dev --wasm-execution compiled /// /// And wait some time to let it produce 3 blocks. Then benchmark them with: /// /// $ substrate benchmark-block --from 1 --to 3 --dev -d /tmp/my-dev -/// --execution wasm --wasm-execution compiled --pruning archive +/// --wasm-execution compiled --pruning archive /// /// The output will be similar to this: /// diff --git a/utils/frame/benchmarking-cli/src/overhead/README.md b/utils/frame/benchmarking-cli/src/overhead/README.md index 85bcc7fa36f2d..390bc09e41701 100644 --- a/utils/frame/benchmarking-cli/src/overhead/README.md +++ b/utils/frame/benchmarking-cli/src/overhead/README.md @@ -103,12 +103,12 @@ Writing weights to "extrinsic_weights.rs" The complete command for Polkadot looks like this: ```sh -cargo run --profile=production -- benchmark overhead --chain=polkadot-dev --execution=wasm --wasm-execution=compiled --weight-path=runtime/polkadot/constants/src/weights/ +cargo run --profile=production -- benchmark overhead --chain=polkadot-dev --wasm-execution=compiled --weight-path=runtime/polkadot/constants/src/weights/ ``` This will overwrite the the [block_weights.rs](https://github.com/paritytech/polkadot/blob/c254e5975711a6497af256f6831e9a6c752d28f5/runtime/polkadot/constants/src/weights/block_weights.rs) and [extrinsic_weights.rs](https://github.com/paritytech/polkadot/blob/c254e5975711a6497af256f6831e9a6c752d28f5/runtime/polkadot/constants/src/weights/extrinsic_weights.rs) files in the Polkadot runtime directory. You can try the same for *Rococo* and to see that the results slightly differ. -👉 It is paramount to use `--profile=production`, `--execution=wasm` and `--wasm-execution=compiled` as the results are otherwise useless. +👉 It is paramount to use `--profile=production` and `--wasm-execution=compiled` as the results are otherwise useless. ## Output Interpretation @@ -122,7 +122,6 @@ Minimizing this is important to have a large transaction throughput. - `--weight-path` Set the output directory or file to write the weights to. - `--repeat` Set the repetitions of both benchmarks. - `--warmup` Set the rounds of warmup before measuring. -- `--execution` Should be set to `wasm` for correct results. - `--wasm-execution` Should be set to `compiled` for correct results. - [`--mul`](../shared/README.md#arguments) - [`--add`](../shared/README.md#arguments) diff --git a/utils/frame/benchmarking-cli/src/pallet/command.rs b/utils/frame/benchmarking-cli/src/pallet/command.rs index 7f587d9c7fa6a..1d2d81e357724 100644 --- a/utils/frame/benchmarking-cli/src/pallet/command.rs +++ b/utils/frame/benchmarking-cli/src/pallet/command.rs @@ -23,9 +23,7 @@ use frame_benchmarking::{ }; use frame_support::traits::StorageInfo; use linked_hash_map::LinkedHashMap; -use sc_cli::{ - execution_method_from_cli, CliConfiguration, ExecutionStrategy, Result, SharedParams, -}; +use sc_cli::{execution_method_from_cli, CliConfiguration, Result, SharedParams}; use sc_client_db::BenchmarkingState; use sc_executor::WasmExecutor; use sc_service::Configuration; @@ -182,7 +180,6 @@ impl PalletCmd { } let spec = config.chain_spec; - let strategy = self.execution.unwrap_or(ExecutionStrategy::Wasm); let pallet = self.pallet.clone().unwrap_or_default(); let pallet = pallet.as_bytes(); let extrinsic = self.extrinsic.clone().unwrap_or_default(); @@ -243,11 +240,11 @@ impl PalletCmd { &executor, "Benchmark_benchmark_metadata", &(self.extra).encode(), - extensions(), + &mut extensions(), &sp_state_machine::backend::BackendRuntimeCode::new(state).runtime_code()?, CallContext::Offchain, ) - .execute(strategy.into()) + .execute() .map_err(|e| format!("{}: {}", ERROR_METADATA_NOT_FOUND, e))?; let (list, storage_info) = @@ -379,12 +376,12 @@ impl PalletCmd { 1, // no need to do internal repeats ) .encode(), - extensions(), + &mut extensions(), &sp_state_machine::backend::BackendRuntimeCode::new(state) .runtime_code()?, CallContext::Offchain, ) - .execute(strategy.into()) + .execute() .map_err(|e| { format!("Error executing and verifying runtime benchmark: {}", e) })?; @@ -419,12 +416,12 @@ impl PalletCmd { self.repeat, ) .encode(), - extensions(), + &mut extensions(), &sp_state_machine::backend::BackendRuntimeCode::new(state) .runtime_code()?, CallContext::Offchain, ) - .execute(strategy.into()) + .execute() .map_err(|e| format!("Error executing runtime benchmark: {}", e))?; let batch = @@ -451,12 +448,12 @@ impl PalletCmd { self.repeat, ) .encode(), - extensions(), + &mut extensions(), &sp_state_machine::backend::BackendRuntimeCode::new(state) .runtime_code()?, CallContext::Offchain, ) - .execute(strategy.into()) + .execute() .map_err(|e| format!("Error executing runtime benchmark: {}", e))?; let batch = diff --git a/utils/frame/benchmarking-cli/src/pallet/mod.rs b/utils/frame/benchmarking-cli/src/pallet/mod.rs index ca87ddebb32be..5090a601f0c9a 100644 --- a/utils/frame/benchmarking-cli/src/pallet/mod.rs +++ b/utils/frame/benchmarking-cli/src/pallet/mod.rs @@ -20,8 +20,8 @@ mod writer; use crate::shared::HostInfoParams; use sc_cli::{ - ExecutionStrategy, WasmExecutionMethod, WasmtimeInstantiationStrategy, - DEFAULT_WASMTIME_INSTANTIATION_STRATEGY, DEFAULT_WASM_EXECUTION_METHOD, + WasmExecutionMethod, WasmtimeInstantiationStrategy, DEFAULT_WASMTIME_INSTANTIATION_STRATEGY, + DEFAULT_WASM_EXECUTION_METHOD, }; use std::{fmt::Debug, path::PathBuf}; @@ -129,10 +129,6 @@ pub struct PalletCmd { #[clap(flatten)] pub shared_params: sc_cli::SharedParams, - /// The execution strategy that should be used for benchmarks. - #[arg(long, value_name = "STRATEGY", value_enum, ignore_case = true)] - pub execution: Option, - /// Method for executing Wasm runtime code. #[arg( long = "wasm-execution", diff --git a/utils/frame/benchmarking-cli/src/pallet/writer.rs b/utils/frame/benchmarking-cli/src/pallet/writer.rs index fd1b92b90c181..69c95d13c0985 100644 --- a/utils/frame/benchmarking-cli/src/pallet/writer.rs +++ b/utils/frame/benchmarking-cli/src/pallet/writer.rs @@ -90,7 +90,6 @@ struct CmdData { repeat: u32, lowest_range_values: Vec, highest_range_values: Vec, - execution: String, wasm_execution: String, chain: String, db_cache: u32, @@ -425,7 +424,6 @@ pub(crate) fn write_results( repeat: cmd.repeat, lowest_range_values: cmd.lowest_range_values.clone(), highest_range_values: cmd.highest_range_values.clone(), - execution: format!("{:?}", cmd.execution), wasm_execution: cmd.wasm_method.to_string(), chain: format!("{:?}", cmd.shared_params.chain), db_cache: cmd.database_cache_size, diff --git a/utils/frame/try-runtime/cli/src/lib.rs b/utils/frame/try-runtime/cli/src/lib.rs index fb4a644e2004c..fbc55ad1dce6f 100644 --- a/utils/frame/try-runtime/cli/src/lib.rs +++ b/utils/frame/try-runtime/cli/src/lib.rs @@ -858,7 +858,7 @@ pub(crate) fn state_machine_call( executor: &WasmExecutor, method: &'static str, data: &[u8], - extensions: Extensions, + mut extensions: Extensions, ) -> sc_cli::Result<(OverlayedChanges, Vec)> { let mut changes = Default::default(); let encoded_results = StateMachine::new( @@ -867,11 +867,11 @@ pub(crate) fn state_machine_call( executor, method, data, - extensions, + &mut extensions, &sp_state_machine::backend::BackendRuntimeCode::new(&ext.backend).runtime_code()?, CallContext::Offchain, ) - .execute(sp_state_machine::ExecutionStrategy::AlwaysWasm) + .execute() .map_err(|e| format!("failed to execute '{}': {}", method, e)) .map_err::(Into::into)?; @@ -887,7 +887,7 @@ pub(crate) fn state_machine_call_with_proof, method: &'static str, data: &[u8], - extensions: Extensions, + mut extensions: Extensions, maybe_export_proof: Option, ) -> sc_cli::Result<(OverlayedChanges, Vec)> { use parity_scale_codec::Encode; @@ -906,11 +906,11 @@ pub(crate) fn state_machine_call_with_proof(Into::into)?; From edf58dceaf3e1f1710e7ac83ac1cc0831e2ef9b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Tue, 11 Jul 2023 20:55:38 +0200 Subject: [PATCH 14/39] node-template: Remove accidentally added dependency (#14553) `sc-statement-store` isn't used by the template and thus, should not appear in the `Cargo.toml`. --- Cargo.lock | 1 - bin/node-template/node/Cargo.toml | 1 - 2 files changed, 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0fb4223f5390e..0dd90f3c01848 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5581,7 +5581,6 @@ dependencies = [ "sc-offchain", "sc-rpc-api", "sc-service", - "sc-statement-store", "sc-telemetry", "sc-transaction-pool", "sc-transaction-pool-api", diff --git a/bin/node-template/node/Cargo.toml b/bin/node-template/node/Cargo.toml index 39f60f52c8344..ea7989be454fd 100644 --- a/bin/node-template/node/Cargo.toml +++ b/bin/node-template/node/Cargo.toml @@ -29,7 +29,6 @@ sc-telemetry = { version = "4.0.0-dev", path = "../../../client/telemetry" } sc-transaction-pool = { version = "4.0.0-dev", path = "../../../client/transaction-pool" } sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../../client/transaction-pool/api" } sc-offchain = { version = "4.0.0-dev", path = "../../../client/offchain" } -sc-statement-store = { version = "4.0.0-dev", path = "../../../client/statement-store" } sc-consensus-aura = { version = "0.10.0-dev", path = "../../../client/consensus/aura" } sp-consensus-aura = { version = "0.10.0-dev", path = "../../../primitives/consensus/aura" } sc-consensus = { version = "0.10.0-dev", path = "../../../client/consensus/common" } From b9cbb0f4281ba20bd50eab5256230c1586f50c5f Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Wed, 12 Jul 2023 10:33:22 +0200 Subject: [PATCH 15/39] Contracts rename v9 to v09 (#14533) --- frame/contracts/src/benchmarking/mod.rs | 6 +++--- frame/contracts/src/lib.rs | 8 ++++---- frame/contracts/src/migration.rs | 10 +++++----- frame/contracts/src/migration/{v9.rs => v09.rs} | 0 4 files changed, 12 insertions(+), 12 deletions(-) rename frame/contracts/src/migration/{v9.rs => v09.rs} (100%) diff --git a/frame/contracts/src/benchmarking/mod.rs b/frame/contracts/src/benchmarking/mod.rs index 11683456f0a14..0e853b6cde357 100644 --- a/frame/contracts/src/benchmarking/mod.rs +++ b/frame/contracts/src/benchmarking/mod.rs @@ -30,7 +30,7 @@ use self::{ }; use crate::{ exec::{AccountIdOf, Key}, - migration::{v10, v11, v12, v9, MigrationStep}, + migration::{v09, v10, v11, v12, MigrationStep}, wasm::CallFlags, Pallet as Contracts, *, }; @@ -216,8 +216,8 @@ benchmarks! { #[pov_mode = Measured] v9_migration_step { let c in 0 .. T::MaxCodeLen::get(); - v9::store_old_dummy_code::(c as usize); - let mut m = v9::Migration::::default(); + v09::store_old_dummy_code::(c as usize); + let mut m = v09::Migration::::default(); }: { m.step(); } diff --git a/frame/contracts/src/lib.rs b/frame/contracts/src/lib.rs index d36a0f93f339b..f555c46859fcb 100644 --- a/frame/contracts/src/lib.rs +++ b/frame/contracts/src/lib.rs @@ -325,16 +325,16 @@ pub mod pallet { /// /// # Examples /// ``` - /// use pallet_contracts::migration::{v9, v10, v11}; + /// use pallet_contracts::migration::{v10, v11}; /// # struct Runtime {}; - /// type Migrations = (v9::Migration, v10::Migration, v11::Migration); + /// type Migrations = (v10::Migration, v11::Migration); /// ``` /// /// If you have a single migration step, you can use a tuple with a single element: /// ``` - /// use pallet_contracts::migration::v9; + /// use pallet_contracts::migration::v10; /// # struct Runtime {}; - /// type Migrations = (v9::Migration,); + /// type Migrations = (v10::Migration,); /// ``` type Migrations: MigrateSequence; } diff --git a/frame/contracts/src/migration.rs b/frame/contracts/src/migration.rs index 827135e081223..36dc8e60cdcdc 100644 --- a/frame/contracts/src/migration.rs +++ b/frame/contracts/src/migration.rs @@ -27,13 +27,13 @@ //! //! ## Example: //! -//! To configure a migration to `v11` for a runtime using `v8` of pallet-contracts on the chain, you -//! would set the `Migrations` type as follows: +//! To configure a migration to `v11` for a runtime using `v10` of pallet-contracts on the chain, +//! you would set the `Migrations` type as follows: //! //! ``` -//! use pallet_contracts::migration::{v9, v10, v11}; +//! use pallet_contracts::migration::{v10, v11}; //! # pub enum Runtime {}; -//! type Migrations = (v9::Migration, v10::Migration, v11::Migration); +//! type Migrations = (v10::Migration, v11::Migration); //! ``` //! //! ## Notes: @@ -56,10 +56,10 @@ //! While the migration is in progress, all dispatchables except `migrate`, are blocked, and returns //! a `MigrationInProgress` error. +pub mod v09; pub mod v10; pub mod v11; pub mod v12; -pub mod v9; use crate::{weights::WeightInfo, Config, Error, MigrationInProgress, Pallet, Weight, LOG_TARGET}; use codec::{Codec, Decode}; diff --git a/frame/contracts/src/migration/v9.rs b/frame/contracts/src/migration/v09.rs similarity index 100% rename from frame/contracts/src/migration/v9.rs rename to frame/contracts/src/migration/v09.rs From ebe8dcd3be6583faea1ca0b38441a39e2e02ce23 Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Wed, 12 Jul 2023 10:59:01 +0200 Subject: [PATCH 16/39] quick updates (#14557) --- frame/balances/src/lib.rs | 24 ++++++++++----------- frame/support/src/traits/tokens/currency.rs | 3 +-- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 33a336e7c94e5..4d24f5914f017 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -541,11 +541,11 @@ pub mod pallet { origin: OriginFor, dest: AccountIdLookupOf, #[pallet::compact] value: T::Balance, - ) -> DispatchResultWithPostInfo { + ) -> DispatchResult { let source = ensure_signed(origin)?; let dest = T::Lookup::lookup(dest)?; >::transfer(&source, &dest, value, Expendable)?; - Ok(().into()) + Ok(()) } /// Set the regular balance of a given account; it also takes a reserved balance but this @@ -564,7 +564,7 @@ pub mod pallet { who: AccountIdLookupOf, #[pallet::compact] new_free: T::Balance, #[pallet::compact] old_reserved: T::Balance, - ) -> DispatchResultWithPostInfo { + ) -> DispatchResult { ensure_root(origin)?; let who = T::Lookup::lookup(who)?; let existential_deposit = Self::ed(); @@ -592,7 +592,7 @@ pub mod pallet { } Self::deposit_event(Event::BalanceSet { who, free: new_free }); - Ok(().into()) + Ok(()) } /// Exactly as `transfer_allow_death`, except the origin must be root and the source account @@ -603,12 +603,12 @@ pub mod pallet { source: AccountIdLookupOf, dest: AccountIdLookupOf, #[pallet::compact] value: T::Balance, - ) -> DispatchResultWithPostInfo { + ) -> DispatchResult { ensure_root(origin)?; let source = T::Lookup::lookup(source)?; let dest = T::Lookup::lookup(dest)?; >::transfer(&source, &dest, value, Expendable)?; - Ok(().into()) + Ok(()) } /// Same as the [`transfer_allow_death`] call, but with a check that the transfer will not @@ -622,11 +622,11 @@ pub mod pallet { origin: OriginFor, dest: AccountIdLookupOf, #[pallet::compact] value: T::Balance, - ) -> DispatchResultWithPostInfo { + ) -> DispatchResult { let source = ensure_signed(origin)?; let dest = T::Lookup::lookup(dest)?; >::transfer(&source, &dest, value, Preserve)?; - Ok(().into()) + Ok(()) } /// Transfer the entire transferable balance from the caller account. @@ -724,11 +724,11 @@ pub mod pallet { origin: OriginFor, dest: AccountIdLookupOf, #[pallet::compact] value: T::Balance, - ) -> DispatchResultWithPostInfo { + ) -> DispatchResult { let source = ensure_signed(origin)?; let dest = T::Lookup::lookup(dest)?; >::transfer(&source, &dest, value, Expendable)?; - Ok(().into()) + Ok(()) } /// Set the regular balance of a given account. @@ -743,7 +743,7 @@ pub mod pallet { origin: OriginFor, who: AccountIdLookupOf, #[pallet::compact] new_free: T::Balance, - ) -> DispatchResultWithPostInfo { + ) -> DispatchResult { ensure_root(origin)?; let who = T::Lookup::lookup(who)?; let existential_deposit = Self::ed(); @@ -767,7 +767,7 @@ pub mod pallet { } Self::deposit_event(Event::BalanceSet { who, free: new_free }); - Ok(().into()) + Ok(()) } } diff --git a/frame/support/src/traits/tokens/currency.rs b/frame/support/src/traits/tokens/currency.rs index 3f6f6b8e7384b..1bc91b6ae5f9a 100644 --- a/frame/support/src/traits/tokens/currency.rs +++ b/frame/support/src/traits/tokens/currency.rs @@ -124,8 +124,7 @@ pub trait Currency { /// Transfer some liquid free balance to another staker. /// - /// This is a very high-level function. It will ensure all appropriate fees are paid - /// and no imbalance in the system remains. + /// This is a very high-level function. It will ensure no imbalance in the system remains. fn transfer( source: &AccountId, dest: &AccountId, From 47a1a0382c4431e8f238214cde84745f4a337957 Mon Sep 17 00:00:00 2001 From: Michal Kucharczyk <1728078+michalkucharczyk@users.noreply.github.com> Date: Wed, 12 Jul 2023 12:22:12 +0200 Subject: [PATCH 17/39] `GenesisBuild` deprecated. `BuildGenesisConfig` added. (#14306) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * frame::support: GenesisConfig types for Runtime enabled * frame::support: macro generating GenesisBuild::build for RuntimeGenesisConfig * frame: ambiguity BuildStorage vs GenesisBuild fixed * fix * RuntimeGenesisBuild added * Revert "frame: ambiguity BuildStorage vs GenesisBuild fixed" This reverts commit 6017dad47e011d118262a4198ccffea0b0ccbcff. * Revert "fix" This reverts commit 477d7ad8cd66d53f533a1b8f49c611a14a18c49d. * Revert "RuntimeGenesisBuild added" This reverts commit 3c131b618138ced29c01ab8d15d8c6410c9e128b. * Revert "Revert "frame: ambiguity BuildStorage vs GenesisBuild fixed"" This reverts commit 2b1ecd467231eddec69f8d328039ba48a380da3d. * Revert "Revert "fix"" This reverts commit fd7fa629adf579d83e30e6ae9fd162637fc45e30. * Code review suggestions * frame: BuildGenesisConfig added, BuildGenesis deprecated * frame: some pallets updated with BuildGenesisConfig * constuct_runtime: support for BuildGenesisConfig * frame::support: genesis_build macro supports BuildGenesisConfig * frame: BuildGenesisConfig added, BuildGenesis deprecated * Cargo.lock update * test-runtime: fixes * Revert "fix" This reverts commit 477d7ad8cd66d53f533a1b8f49c611a14a18c49d. * Revert "frame: ambiguity BuildStorage vs GenesisBuild fixed" This reverts commit 6017dad47e011d118262a4198ccffea0b0ccbcff. * self review * doc fixed * ui tests fixed * fmt * tests fixed * genesis_build macrto fixed for non-generic GenesisConfig * BuildGenesisConfig constraints added * warning fixed * some duplication removed * fmt * fix * doc tests fix * doc fix * cleanup: remove BuildModuleGenesisStorage * self review comments * fix * Update frame/treasury/src/tests.rs Co-authored-by: Sebastian Kunert * Update frame/support/src/traits/hooks.rs Co-authored-by: Sebastian Kunert * doc fix: GenesisBuild exposed * ".git/.scripts/commands/fmt/fmt.sh" * frame: more serde(skip) + cleanup * Update frame/support/src/traits/hooks.rs Co-authored-by: Davide Galassi * frame: phantom fields moved to the end of structs * chain-spec: Default::default cleanup * test-runtime: phantom at the end * merge master fixes * fix * fix * fix * fix * fix (facepalm) * Update frame/support/procedural/src/pallet/expand/genesis_build.rs Co-authored-by: Bastian Köcher * fmt * fix * fix --------- Co-authored-by: parity-processbot <> Co-authored-by: Sebastian Kunert Co-authored-by: Davide Galassi Co-authored-by: Bastian Köcher --- Cargo.lock | 1 + bin/node-template/node/src/chain_spec.rs | 2 + .../pallets/template/src/mock.rs | 3 +- bin/node/cli/src/chain_spec.rs | 23 +++++------ bin/node/runtime/src/impls.rs | 6 +-- bin/node/testing/src/genesis.rs | 10 ++++- frame/alliance/src/lib.rs | 3 +- frame/alliance/src/mock.rs | 18 ++++----- frame/asset-conversion/src/mock.rs | 4 +- frame/asset-rate/src/mock.rs | 3 +- frame/assets/src/lib.rs | 2 +- frame/assets/src/mock.rs | 7 ++-- frame/atomic-swap/src/tests.rs | 5 ++- frame/aura/src/lib.rs | 2 +- frame/aura/src/mock.rs | 7 ++-- frame/authority-discovery/src/lib.rs | 26 ++++++------- frame/authorship/src/lib.rs | 5 ++- frame/babe/src/lib.rs | 8 ++-- frame/babe/src/mock.rs | 6 +-- frame/bags-list/src/mock.rs | 5 ++- frame/balances/src/lib.rs | 21 +--------- frame/balances/src/tests/currency_tests.rs | 4 +- frame/balances/src/tests/mod.rs | 6 +-- frame/beefy-mmr/src/mock.rs | 7 ++-- frame/beefy/src/lib.rs | 2 +- frame/beefy/src/mock.rs | 8 ++-- frame/benchmarking/pov/src/benchmarking.rs | 6 +-- frame/benchmarking/pov/src/tests.rs | 2 +- frame/benchmarking/src/baseline.rs | 6 +-- frame/benchmarking/src/tests.rs | 2 +- frame/benchmarking/src/tests_instance.rs | 2 +- frame/bounties/src/tests.rs | 18 ++++----- frame/child-bounties/src/tests.rs | 16 ++++---- frame/collective/src/lib.rs | 3 +- frame/collective/src/tests.rs | 2 +- frame/contracts/src/tests.rs | 6 +-- frame/conviction-voting/src/tests.rs | 5 ++- frame/core-fellowship/src/tests.rs | 6 +-- frame/democracy/src/lib.rs | 5 ++- frame/democracy/src/tests.rs | 10 ++--- .../election-provider-multi-phase/src/mock.rs | 6 +-- .../test-staking-e2e/src/mock.rs | 10 ++--- frame/elections-phragmen/src/lib.rs | 2 +- frame/examples/basic/src/lib.rs | 2 +- frame/examples/basic/src/tests.rs | 2 +- frame/examples/dev-mode/src/tests.rs | 2 +- frame/examples/kitchensink/src/lib.rs | 2 +- frame/examples/kitchensink/src/tests.rs | 2 +- frame/examples/offchain-worker/src/tests.rs | 2 +- frame/examples/split/src/mock.rs | 4 +- frame/executive/src/lib.rs | 10 ++--- frame/fast-unstake/src/mock.rs | 7 +++- frame/glutton/src/lib.rs | 6 ++- frame/glutton/src/mock.rs | 5 ++- frame/grandpa/src/lib.rs | 8 ++-- frame/grandpa/src/mock.rs | 8 ++-- frame/identity/src/tests.rs | 5 ++- frame/im-online/src/lib.rs | 2 +- frame/im-online/src/mock.rs | 6 +-- frame/indices/src/lib.rs | 2 +- frame/indices/src/mock.rs | 6 +-- .../src/lib.rs | 5 ++- frame/lottery/src/mock.rs | 6 +-- frame/membership/src/lib.rs | 12 +++--- frame/merkle-mountain-range/src/mock.rs | 2 +- frame/merkle-mountain-range/src/tests.rs | 3 +- frame/message-queue/src/integration_test.rs | 2 +- frame/message-queue/src/mock.rs | 5 ++- frame/multisig/src/tests.rs | 6 +-- frame/nft-fractionalization/src/mock.rs | 4 +- frame/nfts/src/mock.rs | 6 +-- frame/nicks/src/lib.rs | 3 +- frame/nis/src/mock.rs | 5 ++- frame/node-authorization/src/lib.rs | 2 +- frame/node-authorization/src/mock.rs | 7 ++-- .../nomination-pools/benchmarking/src/mock.rs | 4 +- frame/nomination-pools/src/lib.rs | 2 +- frame/nomination-pools/src/mock.rs | 6 +-- .../nomination-pools/test-staking/src/mock.rs | 4 +- frame/offences/benchmarking/src/mock.rs | 3 +- frame/offences/src/mock.rs | 6 +-- frame/preimage/src/mock.rs | 3 +- frame/proxy/src/tests.rs | 5 ++- frame/ranked-collective/src/tests.rs | 5 ++- frame/recovery/src/mock.rs | 5 ++- frame/referenda/src/mock.rs | 4 +- frame/remark/src/mock.rs | 2 +- frame/root-offences/src/mock.rs | 7 ++-- frame/salary/src/tests.rs | 6 +-- frame/scheduler/src/mock.rs | 6 +-- frame/scored-pool/src/lib.rs | 2 +- frame/scored-pool/src/mock.rs | 7 ++-- frame/session/benchmarking/src/mock.rs | 6 +-- frame/session/src/historical/mod.rs | 6 +-- frame/session/src/historical/offchain.rs | 8 ++-- frame/session/src/lib.rs | 2 +- frame/session/src/mock.rs | 9 +++-- frame/society/src/benchmarking.rs | 5 ++- frame/society/src/lib.rs | 2 +- frame/society/src/mock.rs | 5 ++- frame/staking/src/mock.rs | 7 ++-- frame/staking/src/pallet/mod.rs | 2 +- frame/state-trie-migration/src/lib.rs | 8 ++-- frame/statement/src/mock.rs | 4 +- frame/sudo/src/lib.rs | 2 +- frame/sudo/src/mock.rs | 9 +++-- .../src/construct_runtime/expand/config.rs | 38 +++++++------------ frame/support/procedural/src/lib.rs | 3 +- .../src/pallet/expand/genesis_build.rs | 34 ++++++----------- .../src/pallet/parse/genesis_build.rs | 5 ++- .../procedural/src/pallet/parse/helper.rs | 33 +++++++++------- .../procedural/src/pallet/parse/mod.rs | 2 +- frame/support/src/lib.rs | 32 ++++++++++------ frame/support/src/traits.rs | 4 +- frame/support/src/traits/hooks.rs | 11 ++++++ frame/support/test/pallet/Cargo.toml | 1 + frame/support/test/pallet/src/lib.rs | 9 +++-- .../support/test/tests/common/outer_enums.rs | 6 +-- frame/support/test/tests/construct_runtime.rs | 22 +++++++---- .../feature_gated_system_pallet.rs | 2 +- .../feature_gated_system_pallet.stderr | 2 +- .../number_of_pallets_exceeds_tuple_size.rs | 2 +- .../pallet_error_too_large.rs | 2 +- .../undefined_call_part.rs | 2 +- .../undefined_event_part.rs | 2 +- .../undefined_genesis_config_part.rs | 2 +- .../undefined_inherent_part.rs | 2 +- .../undefined_origin_part.rs | 2 +- .../undefined_validate_unsigned_part.rs | 2 +- .../undefined_validate_unsigned_part.stderr | 2 +- frame/support/test/tests/final_keys.rs | 4 +- frame/support/test/tests/genesisconfig.rs | 2 +- frame/support/test/tests/instance.rs | 4 +- frame/support/test/tests/issue2219.rs | 14 +++++-- frame/support/test/tests/origin.rs | 18 ++++++--- frame/support/test/tests/pallet.rs | 13 +++++-- frame/support/test/tests/pallet_instance.rs | 10 +++-- .../test/tests/pallet_outer_enums_explicit.rs | 2 +- .../genesis_default_not_satisfied.rs | 4 +- .../genesis_default_not_satisfied.stderr | 12 +++--- .../pallet_ui/pass/no_std_genesis_config.rs | 4 +- .../test/tests/versioned_runtime_upgrade.rs | 16 +++++--- frame/system/benches/bench.rs | 9 ++--- frame/system/benchmarking/src/mock.rs | 6 +-- frame/system/src/lib.rs | 32 ++++------------ frame/system/src/mock.rs | 2 +- frame/timestamp/src/mock.rs | 5 ++- frame/tips/src/tests.rs | 16 ++++---- .../asset-conversion-tx-payment/src/tests.rs | 4 +- .../asset-tx-payment/src/tests.rs | 4 +- frame/transaction-payment/src/lib.rs | 10 +++-- frame/transaction-payment/src/mock.rs | 2 +- frame/transaction-payment/src/tests.rs | 13 ++++--- frame/transaction-storage/src/lib.rs | 2 +- frame/transaction-storage/src/mock.rs | 2 +- frame/treasury/src/lib.rs | 20 +++------- frame/treasury/src/tests.rs | 19 +++++----- frame/uniques/src/mock.rs | 5 ++- frame/utility/src/tests.rs | 8 ++-- frame/vesting/src/lib.rs | 2 +- frame/vesting/src/mock.rs | 7 ++-- primitives/runtime/src/lib.rs | 3 ++ test-utils/runtime/src/genesismap.rs | 3 ++ .../runtime/src/substrate_test_pallet.rs | 8 ++-- utils/frame/rpc/support/src/lib.rs | 2 +- 165 files changed, 578 insertions(+), 533 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0dd90f3c01848..0b3258defb2a1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2921,6 +2921,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", + "sp-runtime", ] [[package]] diff --git a/bin/node-template/node/src/chain_spec.rs b/bin/node-template/node/src/chain_spec.rs index b28e8140fabc6..2cd2d07293026 100644 --- a/bin/node-template/node/src/chain_spec.rs +++ b/bin/node-template/node/src/chain_spec.rs @@ -136,6 +136,7 @@ fn testnet_genesis( system: SystemConfig { // Add Wasm runtime to storage. code: wasm_binary.to_vec(), + ..Default::default() }, balances: BalancesConfig { // Configure endowed accounts with initial balance of 1 << 60. @@ -146,6 +147,7 @@ fn testnet_genesis( }, grandpa: GrandpaConfig { authorities: initial_authorities.iter().map(|x| (x.1.clone(), 1)).collect(), + ..Default::default() }, sudo: SudoConfig { // Assign network admin rights. diff --git a/bin/node-template/pallets/template/src/mock.rs b/bin/node-template/pallets/template/src/mock.rs index b4d6905378a5d..487e076feef95 100644 --- a/bin/node-template/pallets/template/src/mock.rs +++ b/bin/node-template/pallets/template/src/mock.rs @@ -4,6 +4,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -55,5 +56,5 @@ impl pallet_template::Config for Test { // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::::default().build_storage().unwrap().into() } diff --git a/bin/node/cli/src/chain_spec.rs b/bin/node/cli/src/chain_spec.rs index ebbda8baabd8b..a56c4e7b4016e 100644 --- a/bin/node/cli/src/chain_spec.rs +++ b/bin/node/cli/src/chain_spec.rs @@ -20,11 +20,10 @@ use grandpa_primitives::AuthorityId as GrandpaId; use kitchensink_runtime::{ - constants::currency::*, wasm_binary_unwrap, AuthorityDiscoveryConfig, BabeConfig, - BalancesConfig, Block, CouncilConfig, DemocracyConfig, ElectionsConfig, GluttonConfig, - GrandpaConfig, ImOnlineConfig, IndicesConfig, MaxNominations, NominationPoolsConfig, - SessionConfig, SessionKeys, SocietyConfig, StakerStatus, StakingConfig, SudoConfig, - SystemConfig, TechnicalCommitteeConfig, + constants::currency::*, wasm_binary_unwrap, BabeConfig, BalancesConfig, Block, CouncilConfig, + DemocracyConfig, ElectionsConfig, ImOnlineConfig, IndicesConfig, MaxNominations, + NominationPoolsConfig, SessionConfig, SessionKeys, SocietyConfig, StakerStatus, StakingConfig, + SudoConfig, SystemConfig, TechnicalCommitteeConfig, }; use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use sc_chain_spec::ChainSpecExtension; @@ -295,7 +294,7 @@ pub fn testnet_genesis( const STASH: Balance = ENDOWMENT / 1000; RuntimeGenesisConfig { - system: SystemConfig { code: wasm_binary_unwrap().to_vec() }, + system: SystemConfig { code: wasm_binary_unwrap().to_vec(), ..Default::default() }, balances: BalancesConfig { balances: endowed_accounts.iter().cloned().map(|x| (x, ENDOWMENT)).collect(), }, @@ -340,12 +339,12 @@ pub fn testnet_genesis( }, sudo: SudoConfig { key: Some(root_key) }, babe: BabeConfig { - authorities: vec![], epoch_config: Some(kitchensink_runtime::BABE_GENESIS_EPOCH_CONFIG), + ..Default::default() }, im_online: ImOnlineConfig { keys: vec![] }, - authority_discovery: AuthorityDiscoveryConfig { keys: vec![] }, - grandpa: GrandpaConfig { authorities: vec![] }, + authority_discovery: Default::default(), + grandpa: Default::default(), technical_membership: Default::default(), treasury: Default::default(), society: SocietyConfig { pot: 0 }, @@ -365,11 +364,7 @@ pub fn testnet_genesis( min_join_bond: 1 * DOLLARS, ..Default::default() }, - glutton: GluttonConfig { - compute: Default::default(), - storage: Default::default(), - trash_data_count: Default::default(), - }, + glutton: Default::default(), } } diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index 8c4a1ed4bbda2..430a1ac2824b8 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -120,7 +120,7 @@ mod multiplier_tests { use sp_runtime::{ assert_eq_error_rate, traits::{Convert, One, Zero}, - FixedPointNumber, + BuildStorage, FixedPointNumber, }; use crate::{ @@ -197,8 +197,8 @@ mod multiplier_tests { where F: Fn() -> (), { - let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::default() - .build_storage::() + let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::::default() + .build_storage() .unwrap() .into(); t.execute_with(|| { diff --git a/bin/node/testing/src/genesis.rs b/bin/node/testing/src/genesis.rs index 0514899dfbab8..8063b8ef45708 100644 --- a/bin/node/testing/src/genesis.rs +++ b/bin/node/testing/src/genesis.rs @@ -50,6 +50,7 @@ pub fn config_endowed(code: Option<&[u8]>, extra_endowed: Vec) -> Run RuntimeGenesisConfig { system: SystemConfig { code: code.map(|x| x.to_vec()).unwrap_or_else(|| wasm_binary_unwrap().to_vec()), + ..Default::default() }, indices: IndicesConfig { indices: vec![] }, balances: BalancesConfig { balances: endowed }, @@ -76,8 +77,12 @@ pub fn config_endowed(code: Option<&[u8]>, extra_endowed: Vec) -> Run invulnerables: vec![alice(), bob(), charlie()], ..Default::default() }, - babe: BabeConfig { authorities: vec![], epoch_config: Some(BABE_GENESIS_EPOCH_CONFIG) }, - grandpa: GrandpaConfig { authorities: vec![] }, + babe: BabeConfig { + authorities: vec![], + epoch_config: Some(BABE_GENESIS_EPOCH_CONFIG), + ..Default::default() + }, + grandpa: GrandpaConfig { authorities: vec![], _config: Default::default() }, im_online: Default::default(), authority_discovery: Default::default(), democracy: Default::default(), @@ -100,6 +105,7 @@ pub fn config_endowed(code: Option<&[u8]>, extra_endowed: Vec) -> Run compute: Default::default(), storage: Default::default(), trash_data_count: Default::default(), + ..Default::default() }, } } diff --git a/frame/alliance/src/lib.rs b/frame/alliance/src/lib.rs index 6c034454cf7c0..6dec6543babd1 100644 --- a/frame/alliance/src/lib.rs +++ b/frame/alliance/src/lib.rs @@ -405,11 +405,12 @@ pub mod pallet { pub struct GenesisConfig, I: 'static = ()> { pub fellows: Vec, pub allies: Vec, + #[serde(skip)] pub phantom: PhantomData<(T, I)>, } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { for m in self.fellows.iter().chain(self.allies.iter()) { assert!(Pallet::::has_identity(m).is_ok(), "Member does not set identity!"); diff --git a/frame/alliance/src/mock.rs b/frame/alliance/src/mock.rs index e1da028f44576..ea6f4e58b1536 100644 --- a/frame/alliance/src/mock.rs +++ b/frame/alliance/src/mock.rs @@ -28,7 +28,7 @@ use sp_std::convert::{TryFrom, TryInto}; pub use frame_support::{ assert_noop, assert_ok, ord_parameter_types, parameter_types, - traits::{EitherOfDiverse, GenesisBuild, SortedMembers}, + traits::{EitherOfDiverse, SortedMembers}, BoundedVec, }; use frame_system::{EnsureRoot, EnsureSignedBy}; @@ -256,7 +256,7 @@ frame_support::construct_runtime!( ); pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![ @@ -274,14 +274,12 @@ pub fn new_test_ext() -> sp_io::TestExternalities { .assimilate_storage(&mut t) .unwrap(); - GenesisBuild::::assimilate_storage( - &pallet_alliance::GenesisConfig { - fellows: vec![], - allies: vec![], - phantom: Default::default(), - }, - &mut t, - ) + pallet_alliance::GenesisConfig:: { + fellows: vec![], + allies: vec![], + phantom: Default::default(), + } + .assimilate_storage(&mut t) .unwrap(); let mut ext = sp_io::TestExternalities::new(t); diff --git a/frame/asset-conversion/src/mock.rs b/frame/asset-conversion/src/mock.rs index 34d2eeb273ca8..35c10a22cf454 100644 --- a/frame/asset-conversion/src/mock.rs +++ b/frame/asset-conversion/src/mock.rs @@ -33,8 +33,8 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{AccountIdConversion, BlakeTwo256, IdentityLookup}, + BuildStorage, }; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; @@ -183,7 +183,7 @@ impl Config for Test { } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10000), (2, 20000), (3, 30000), (4, 40000)], diff --git a/frame/asset-rate/src/mock.rs b/frame/asset-rate/src/mock.rs index 2d90fcfecd79e..56d52d708d57f 100644 --- a/frame/asset-rate/src/mock.rs +++ b/frame/asset-rate/src/mock.rs @@ -23,6 +23,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -96,5 +97,5 @@ impl pallet_asset_rate::Config for Test { // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::::default().build_storage().unwrap().into() } diff --git a/frame/assets/src/lib.rs b/frame/assets/src/lib.rs index 4b91f5184299d..363a99701b56a 100644 --- a/frame/assets/src/lib.rs +++ b/frame/assets/src/lib.rs @@ -380,7 +380,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { for (id, owner, is_sufficient, min_balance) in &self.assets { assert!(!Asset::::contains_key(id), "Asset id already in use"); diff --git a/frame/assets/src/mock.rs b/frame/assets/src/mock.rs index 09d2bd2296088..7c93e5210015a 100644 --- a/frame/assets/src/mock.rs +++ b/frame/assets/src/mock.rs @@ -23,13 +23,14 @@ use crate as pallet_assets; use codec::Encode; use frame_support::{ construct_runtime, parameter_types, - traits::{AsEnsureOriginWithArg, ConstU32, ConstU64, GenesisBuild}, + traits::{AsEnsureOriginWithArg, ConstU32, ConstU64}, }; use sp_core::H256; use sp_io::storage; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -41,7 +42,7 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Assets: pallet_assets::{Pallet, Call, Storage, Event}, } @@ -205,7 +206,7 @@ pub(crate) fn take_hooks() -> Vec { } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); let config: pallet_assets::GenesisConfig = pallet_assets::GenesisConfig { assets: vec![ diff --git a/frame/atomic-swap/src/tests.rs b/frame/atomic-swap/src/tests.rs index 53ccd64bb2731..7e4d8e97319e7 100644 --- a/frame/atomic-swap/src/tests.rs +++ b/frame/atomic-swap/src/tests.rs @@ -8,6 +8,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -19,7 +20,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, AtomicSwap: pallet_atomic_swap::{Pallet, Call, Event}, } @@ -78,7 +79,7 @@ const A: u64 = 1; const B: u64 = 2; pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let genesis = pallet_balances::GenesisConfig:: { balances: vec![(A, 100), (B, 200)] }; genesis.assimilate_storage(&mut t).unwrap(); t.into() diff --git a/frame/aura/src/lib.rs b/frame/aura/src/lib.rs index e02d24d7c237e..58c85166476f0 100644 --- a/frame/aura/src/lib.rs +++ b/frame/aura/src/lib.rs @@ -159,7 +159,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { Pallet::::initialize_authorities(&self.authorities); } diff --git a/frame/aura/src/mock.rs b/frame/aura/src/mock.rs index 5ae443b4f7685..3fa3bec669593 100644 --- a/frame/aura/src/mock.rs +++ b/frame/aura/src/mock.rs @@ -22,13 +22,14 @@ use crate as pallet_aura; use frame_support::{ parameter_types, - traits::{ConstU32, ConstU64, DisabledValidators, GenesisBuild}, + traits::{ConstU32, ConstU64, DisabledValidators}, }; use sp_consensus_aura::{ed25519::AuthorityId, AuthorityIndex}; use sp_core::H256; use sp_runtime::{ testing::{Header, UintAuthorityId}, traits::IdentityLookup, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -40,7 +41,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, Aura: pallet_aura::{Pallet, Storage, Config}, } @@ -111,7 +112,7 @@ impl pallet_aura::Config for Test { } fn build_ext(authorities: Vec) -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_aura::GenesisConfig:: { authorities: authorities.into_iter().map(|a| UintAuthorityId(a).to_public_key()).collect(), } diff --git a/frame/authority-discovery/src/lib.rs b/frame/authority-discovery/src/lib.rs index 6365c95359472..2b0c27740c3e6 100644 --- a/frame/authority-discovery/src/lib.rs +++ b/frame/authority-discovery/src/lib.rs @@ -59,14 +59,16 @@ pub mod pallet { pub(super) type NextKeys = StorageValue<_, WeakBoundedVec, ValueQuery>; - #[derive(Default)] + #[derive(frame_support::DefaultNoBound)] #[pallet::genesis_config] - pub struct GenesisConfig { + pub struct GenesisConfig { pub keys: Vec, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { Pallet::::initialize_keys(&self.keys) } @@ -168,7 +170,7 @@ mod tests { use crate as pallet_authority_discovery; use frame_support::{ parameter_types, - traits::{ConstU32, ConstU64, GenesisBuild}, + traits::{ConstU32, ConstU64}, }; use sp_application_crypto::Pair; use sp_authority_discovery::AuthorityPair; @@ -177,7 +179,7 @@ mod tests { use sp_runtime::{ testing::{Header, UintAuthorityId}, traits::{ConvertInto, IdentityLookup, OpaqueKeys}, - KeyTypeId, Perbill, + BuildStorage, KeyTypeId, Perbill, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -189,9 +191,9 @@ mod tests { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, - AuthorityDiscovery: pallet_authority_discovery::{Pallet, Config}, + AuthorityDiscovery: pallet_authority_discovery::{Pallet, Config}, } ); @@ -308,13 +310,11 @@ mod tests { .collect::>(); // Build genesis. - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); - GenesisBuild::::assimilate_storage( - &pallet_authority_discovery::GenesisConfig { keys: vec![] }, - &mut t, - ) - .unwrap(); + pallet_authority_discovery::GenesisConfig:: { keys: vec![], ..Default::default() } + .assimilate_storage(&mut t) + .unwrap(); // Create externalities. let mut externalities = TestExternalities::new(t); diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index 4bb8ba587ac8b..73c631c36f96e 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -106,6 +106,7 @@ mod tests { generic::DigestItem, testing::Header, traits::{BlakeTwo256, Header as HeaderT, IdentityLookup}, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -117,7 +118,7 @@ mod tests { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Authorship: pallet_authorship::{Pallet, Storage}, } ); @@ -188,7 +189,7 @@ mod tests { } fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); t.into() } diff --git a/frame/babe/src/lib.rs b/frame/babe/src/lib.rs index 8001450b43583..de9fca3b75dd7 100644 --- a/frame/babe/src/lib.rs +++ b/frame/babe/src/lib.rs @@ -314,15 +314,17 @@ pub mod pallet { pub(super) type SkippedEpochs = StorageValue<_, BoundedVec<(u64, SessionIndex), ConstU32<100>>, ValueQuery>; - #[derive(Default)] + #[derive(frame_support::DefaultNoBound)] #[pallet::genesis_config] - pub struct GenesisConfig { + pub struct GenesisConfig { pub authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, pub epoch_config: Option, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { SegmentIndex::::put(0); Pallet::::initialize_genesis_authorities(&self.authorities); diff --git a/frame/babe/src/mock.rs b/frame/babe/src/mock.rs index ccc24050d53ba..96f9ce4ff8e8d 100644 --- a/frame/babe/src/mock.rs +++ b/frame/babe/src/mock.rs @@ -22,7 +22,7 @@ use codec::Encode; use frame_election_provider_support::{onchain, SequentialPhragmen}; use frame_support::{ parameter_types, - traits::{ConstU128, ConstU32, ConstU64, GenesisBuild, KeyOwnerProofSystem, OnInitialize}, + traits::{ConstU128, ConstU32, ConstU64, KeyOwnerProofSystem, OnInitialize}, }; use pallet_session::historical as pallet_session_historical; use sp_consensus_babe::{AuthorityId, AuthorityPair, Randomness, Slot, VrfSignature}; @@ -36,7 +36,7 @@ use sp_runtime::{ impl_opaque_keys, testing::{Digest, DigestItem, Header, TestXt}, traits::{Header as _, IdentityLookup, OpaqueKeys}, - Perbill, + BuildStorage, Perbill, }; use sp_staking::{EraIndex, SessionIndex}; @@ -345,7 +345,7 @@ pub fn new_test_ext_with_pairs( } pub fn new_test_ext_raw_authorities(authorities: Vec) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let balances: Vec<_> = (0..authorities.len()).map(|i| (i as u64, 10_000_000)).collect(); diff --git a/frame/bags-list/src/mock.rs b/frame/bags-list/src/mock.rs index efbb2ed94c49f..f4f29ec35912d 100644 --- a/frame/bags-list/src/mock.rs +++ b/frame/bags-list/src/mock.rs @@ -21,6 +21,7 @@ use super::*; use crate::{self as bags_list}; use frame_election_provider_support::VoteWeight; use frame_support::parameter_types; +use sp_runtime::BuildStorage; use std::collections::HashMap; pub type AccountId = u32; @@ -94,7 +95,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Storage, Event, Config}, + System: frame_system::{Pallet, Call, Storage, Event, Config}, BagsList: bags_list::{Pallet, Call, Storage, Event}, } ); @@ -127,7 +128,7 @@ impl ExtBuilder { pub(crate) fn build(self) -> sp_io::TestExternalities { sp_tracing::try_init_simple(); - let storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); let ids_with_weight: Vec<_> = if self.skip_genesis_ids { self.ids.iter().collect() diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 4d24f5914f017..206ee371e0737 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -166,8 +166,6 @@ mod types; pub mod weights; use codec::{Codec, MaxEncodedLen}; -#[cfg(feature = "std")] -use frame_support::traits::GenesisBuild; use frame_support::{ ensure, pallet_prelude::DispatchResult, @@ -465,7 +463,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { let total = self.balances.iter().fold(Zero::zero(), |acc: T::Balance, &(_, n)| acc + n); @@ -499,23 +497,6 @@ pub mod pallet { } } - #[cfg(feature = "std")] - impl, I: 'static> GenesisConfig { - /// Direct implementation of `GenesisBuild::build_storage`. - /// - /// Kept in order not to break dependency. - pub fn build_storage(&self) -> Result { - >::build_storage(self) - } - - /// Direct implementation of `GenesisBuild::assimilate_storage`. - /// - /// Kept in order not to break dependency. - pub fn assimilate_storage(&self, storage: &mut sp_runtime::Storage) -> Result<(), String> { - >::assimilate_storage(self, storage) - } - } - #[pallet::hooks] impl, I: 'static> Hooks for Pallet { #[cfg(not(feature = "insecure_zero_ed"))] diff --git a/frame/balances/src/tests/currency_tests.rs b/frame/balances/src/tests/currency_tests.rs index 0c6ab0dbbaad5..c9ad19f79e36d 100644 --- a/frame/balances/src/tests/currency_tests.rs +++ b/frame/balances/src/tests/currency_tests.rs @@ -666,7 +666,7 @@ fn burn_must_work() { #[should_panic = "the balance of any account should always be at least the existential deposit."] fn cannot_set_genesis_value_below_ed() { EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = 11); - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let _ = crate::GenesisConfig:: { balances: vec![(1, 10)] } .assimilate_storage(&mut t) .unwrap(); @@ -675,7 +675,7 @@ fn cannot_set_genesis_value_below_ed() { #[test] #[should_panic = "duplicate balances in genesis."] fn cannot_set_genesis_value_twice() { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let _ = crate::GenesisConfig:: { balances: vec![(1, 10), (2, 20), (1, 15)] } .assimilate_storage(&mut t) .unwrap(); diff --git a/frame/balances/src/tests/mod.rs b/frame/balances/src/tests/mod.rs index 6deb9885b79e5..6d9b9217ba0b0 100644 --- a/frame/balances/src/tests/mod.rs +++ b/frame/balances/src/tests/mod.rs @@ -40,7 +40,7 @@ use sp_io; use sp_runtime::{ testing::Header, traits::{BadOrigin, IdentityLookup, SignedExtension, Zero}, - ArithmeticError, DispatchError, DispatchResult, FixedPointNumber, TokenError, + ArithmeticError, BuildStorage, DispatchError, DispatchResult, FixedPointNumber, TokenError, }; use std::collections::BTreeSet; @@ -78,7 +78,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event}, } @@ -176,7 +176,7 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { self.set_associated_consts(); - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: if self.monied { vec![ diff --git a/frame/beefy-mmr/src/mock.rs b/frame/beefy-mmr/src/mock.rs index 31484aaa6be70..8cb20703c63e9 100644 --- a/frame/beefy-mmr/src/mock.rs +++ b/frame/beefy-mmr/src/mock.rs @@ -21,7 +21,7 @@ use codec::Encode; use frame_support::{ construct_runtime, parameter_types, sp_io::TestExternalities, - traits::{ConstU16, ConstU32, ConstU64, GenesisBuild}, + traits::{ConstU16, ConstU32, ConstU64}, BasicExternalities, }; use sp_consensus_beefy::mmr::MmrLeafVersion; @@ -31,6 +31,7 @@ use sp_runtime::{ impl_opaque_keys, testing::Header, traits::{BlakeTwo256, ConvertInto, IdentityLookup, Keccak256, OpaqueKeys}, + BuildStorage, }; use crate as pallet_beefy_mmr; @@ -54,7 +55,7 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, Mmr: pallet_mmr::{Pallet, Storage}, Beefy: pallet_beefy::{Pallet, Config, Storage}, @@ -193,7 +194,7 @@ pub fn new_test_ext(ids: Vec) -> TestExternalities { } pub fn new_test_ext_raw_authorities(authorities: Vec<(u64, BeefyId)>) -> TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let session_keys: Vec<_> = authorities .iter() diff --git a/frame/beefy/src/lib.rs b/frame/beefy/src/lib.rs index d56d5b32f8f36..da469c5b9ca02 100644 --- a/frame/beefy/src/lib.rs +++ b/frame/beefy/src/lib.rs @@ -176,7 +176,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { Pallet::::initialize(&self.authorities) // we panic here as runtime maintainers can simply reconfigure genesis and restart diff --git a/frame/beefy/src/mock.rs b/frame/beefy/src/mock.rs index 270097e346c8f..5ec3bdb7e5593 100644 --- a/frame/beefy/src/mock.rs +++ b/frame/beefy/src/mock.rs @@ -21,9 +21,7 @@ use frame_election_provider_support::{onchain, SequentialPhragmen}; use frame_support::{ construct_runtime, parameter_types, sp_io::TestExternalities, - traits::{ - ConstU16, ConstU32, ConstU64, GenesisBuild, KeyOwnerProofSystem, OnFinalize, OnInitialize, - }, + traits::{ConstU16, ConstU32, ConstU64, KeyOwnerProofSystem, OnFinalize, OnInitialize}, BasicExternalities, }; use pallet_session::historical as pallet_session_historical; @@ -34,7 +32,7 @@ use sp_runtime::{ impl_opaque_keys, testing::{Header, TestXt}, traits::{BlakeTwo256, IdentityLookup, OpaqueKeys}, - Perbill, + BuildStorage, Perbill, }; use sp_staking::{EraIndex, SessionIndex}; @@ -260,7 +258,7 @@ pub fn new_test_ext(ids: Vec) -> TestExternalities { } pub fn new_test_ext_raw_authorities(authorities: Vec) -> TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let balances: Vec<_> = (0..authorities.len()).map(|i| (i as u64, 10_000_000)).collect(); diff --git a/frame/benchmarking/pov/src/benchmarking.rs b/frame/benchmarking/pov/src/benchmarking.rs index 27191e37219fd..1112045d9cacc 100644 --- a/frame/benchmarking/pov/src/benchmarking.rs +++ b/frame/benchmarking/pov/src/benchmarking.rs @@ -339,7 +339,7 @@ frame_benchmarking::benchmarks! { #[cfg(test)] mod mock { - use sp_runtime::testing::H256; + use sp_runtime::{testing::H256, BuildStorage}; type AccountId = u64; type AccountIndex = u32; @@ -354,7 +354,7 @@ mod mock { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Baseline: crate::{Pallet, Call, Storage, Event}, } ); @@ -391,6 +391,6 @@ mod mock { } pub fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::::default().build_storage().unwrap().into() } } diff --git a/frame/benchmarking/pov/src/tests.rs b/frame/benchmarking/pov/src/tests.rs index b908925cccd8e..2136dc50b9e6f 100644 --- a/frame/benchmarking/pov/src/tests.rs +++ b/frame/benchmarking/pov/src/tests.rs @@ -173,7 +173,7 @@ mod mock { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Baseline: crate::{Pallet, Call, Storage, Event}, } ); diff --git a/frame/benchmarking/src/baseline.rs b/frame/benchmarking/src/baseline.rs index 25336b6974d9f..a6a9fada9b2aa 100644 --- a/frame/benchmarking/src/baseline.rs +++ b/frame/benchmarking/src/baseline.rs @@ -111,7 +111,7 @@ benchmarks! { #[cfg(test)] pub mod mock { use super::*; - use sp_runtime::testing::H256; + use sp_runtime::{testing::H256, BuildStorage}; type AccountId = u64; type AccountIndex = u32; @@ -126,7 +126,7 @@ pub mod mock { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, } ); @@ -162,7 +162,7 @@ pub mod mock { pub fn new_test_ext() -> sp_io::TestExternalities { use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.register_extension(KeystoreExt::new(MemoryKeystore::new())); diff --git a/frame/benchmarking/src/tests.rs b/frame/benchmarking/src/tests.rs index c3f51aeb53d5a..0f22360a9431e 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -75,7 +75,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, TestPallet: pallet_test::{Pallet, Call, Storage}, } ); diff --git a/frame/benchmarking/src/tests_instance.rs b/frame/benchmarking/src/tests_instance.rs index 7e02cbf834d08..1741142b17b63 100644 --- a/frame/benchmarking/src/tests_instance.rs +++ b/frame/benchmarking/src/tests_instance.rs @@ -85,7 +85,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, TestPallet: pallet_test::{Pallet, Call, Storage, Event}, } ); diff --git a/frame/bounties/src/tests.rs b/frame/bounties/src/tests.rs index 9fe34b16029cb..5d47b285f647b 100644 --- a/frame/bounties/src/tests.rs +++ b/frame/bounties/src/tests.rs @@ -23,9 +23,7 @@ use super::*; use crate as pallet_bounties; use frame_support::{ - assert_noop, assert_ok, - pallet_prelude::GenesisBuild, - parameter_types, + assert_noop, assert_ok, parameter_types, traits::{ConstU32, ConstU64, OnInitialize}, PalletId, }; @@ -48,12 +46,12 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Bounties: pallet_bounties::{Pallet, Call, Storage, Event}, Bounties1: pallet_bounties::::{Pallet, Call, Storage, Event}, - Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event}, - Treasury1: pallet_treasury::::{Pallet, Call, Storage, Config, Event}, + Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event}, + Treasury1: pallet_treasury::::{Pallet, Call, Storage, Config, Event}, } ); @@ -412,7 +410,7 @@ fn treasury_account_doesnt_get_deleted() { // This is useful for chain that will just update runtime. #[test] fn inexistent_account_works() { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(0, 100), (1, 99), (2, 1)] } .assimilate_storage(&mut t) .unwrap(); @@ -1073,7 +1071,7 @@ fn test_migration_v4() { #[test] fn genesis_funding_works() { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let initial_funding = 100; pallet_balances::GenesisConfig:: { // Total issuance will be 200 with treasury account initialized with 100. @@ -1081,7 +1079,9 @@ fn genesis_funding_works() { } .assimilate_storage(&mut t) .unwrap(); - GenesisBuild::::assimilate_storage(&pallet_treasury::GenesisConfig, &mut t).unwrap(); + pallet_treasury::GenesisConfig::::default() + .assimilate_storage(&mut t) + .unwrap(); let mut t: sp_io::TestExternalities = t.into(); t.execute_with(|| { diff --git a/frame/child-bounties/src/tests.rs b/frame/child-bounties/src/tests.rs index a8f0e16ea2136..2a430b30163de 100644 --- a/frame/child-bounties/src/tests.rs +++ b/frame/child-bounties/src/tests.rs @@ -23,9 +23,7 @@ use super::*; use crate as pallet_child_bounties; use frame_support::{ - assert_noop, assert_ok, - pallet_prelude::GenesisBuild, - parameter_types, + assert_noop, assert_ok, parameter_types, traits::{ConstU32, ConstU64, OnInitialize}, weights::Weight, PalletId, @@ -35,7 +33,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BadOrigin, BlakeTwo256, IdentityLookup}, - Perbill, Permill, TokenError, + BuildStorage, Perbill, Permill, TokenError, }; use super::Event as ChildBountiesEvent; @@ -50,10 +48,10 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Bounties: pallet_bounties::{Pallet, Call, Storage, Event}, - Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event}, + Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event}, ChildBounties: pallet_child_bounties::{Pallet, Call, Storage, Event}, } ); @@ -162,14 +160,16 @@ impl pallet_child_bounties::Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { // Total issuance will be 200 with treasury account initialized at ED. balances: vec![(0, 100), (1, 98), (2, 1)], } .assimilate_storage(&mut t) .unwrap(); - GenesisBuild::::assimilate_storage(&pallet_treasury::GenesisConfig, &mut t).unwrap(); + pallet_treasury::GenesisConfig::::default() + .assimilate_storage(&mut t) + .unwrap(); t.into() } diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index fc4ab0c4f1bbd..30c4ad09291ff 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -230,12 +230,13 @@ pub mod pallet { #[pallet::genesis_config] #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig, I: 'static = ()> { + #[serde(skip)] pub phantom: PhantomData, pub members: Vec, } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { use sp_std::collections::btree_set::BTreeSet; let members_set: BTreeSet<_> = self.members.iter().collect(); diff --git a/frame/collective/src/tests.rs b/frame/collective/src/tests.rs index 8d4e0a4a82cd7..a4ec55856e49c 100644 --- a/frame/collective/src/tests.rs +++ b/frame/collective/src/tests.rs @@ -21,7 +21,7 @@ use frame_support::{ assert_noop, assert_ok, dispatch::Pays, parameter_types, - traits::{ConstU32, ConstU64, GenesisBuild, StorageVersion}, + traits::{ConstU32, ConstU64, StorageVersion}, Hashable, }; use frame_system::{EnsureRoot, EventRecord, Phase}; diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index f67be602695d6..f11b26bc21689 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -52,7 +52,7 @@ use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; use sp_runtime::{ testing::{Header, H256}, traits::{BlakeTwo256, Convert, Hash, IdentityLookup}, - AccountId32, TokenError, + AccountId32, BuildStorage, TokenError, }; use std::ops::Deref; @@ -65,7 +65,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, Randomness: pallet_insecure_randomness_collective_flip::{Pallet, Storage}, @@ -486,7 +486,7 @@ impl ExtBuilder { let env = Env::new().default_filter_or("runtime=debug"); let _ = Builder::from_env(env).is_test(true).try_init(); self.set_associated_consts(); - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![] } .assimilate_storage(&mut t) .unwrap(); diff --git a/frame/conviction-voting/src/tests.rs b/frame/conviction-voting/src/tests.rs index 1ea3a56adacb7..8f3451e28b87f 100644 --- a/frame/conviction-voting/src/tests.rs +++ b/frame/conviction-voting/src/tests.rs @@ -27,6 +27,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use super::*; @@ -41,7 +42,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Voting: pallet_conviction_voting::{Pallet, Call, Storage, Event}, } @@ -196,7 +197,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)], } diff --git a/frame/core-fellowship/src/tests.rs b/frame/core-fellowship/src/tests.rs index 87c0de112ac33..ded343d997bdf 100644 --- a/frame/core-fellowship/src/tests.rs +++ b/frame/core-fellowship/src/tests.rs @@ -30,7 +30,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup, TryMorphInto}, - DispatchError, DispatchResult, + BuildStorage, DispatchError, DispatchResult, }; use sp_std::cell::RefCell; @@ -46,7 +46,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, CoreFellowship: pallet_core_fellowship::{Pallet, Call, Storage, Event}, } ); @@ -149,7 +149,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| { let params = ParamsType { diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index 7ce3bb5611915..690224cc87217 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -441,11 +441,12 @@ pub mod pallet { #[pallet::genesis_config] #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { - _phantom: sp_std::marker::PhantomData, + #[serde(skip)] + _config: sp_std::marker::PhantomData, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { PublicPropCount::::put(0 as PropIndex); ReferendumCount::::put(0 as ReferendumIndex); diff --git a/frame/democracy/src/tests.rs b/frame/democracy/src/tests.rs index dd726004648ef..dedd13dd33227 100644 --- a/frame/democracy/src/tests.rs +++ b/frame/democracy/src/tests.rs @@ -22,8 +22,8 @@ use crate as pallet_democracy; use frame_support::{ assert_noop, assert_ok, ord_parameter_types, parameter_types, traits::{ - ConstU32, ConstU64, Contains, EqualPrivilegeOnly, GenesisBuild, OnInitialize, - SortedMembers, StorePreimage, + ConstU32, ConstU64, Contains, EqualPrivilegeOnly, OnInitialize, SortedMembers, + StorePreimage, }, weights::Weight, }; @@ -33,7 +33,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BadOrigin, BlakeTwo256, Hash, IdentityLookup}, - Perbill, + BuildStorage, Perbill, }; mod cancellation; mod decoders; @@ -60,7 +60,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Preimage: pallet_preimage, Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event}, @@ -203,7 +203,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)], } diff --git a/frame/election-provider-multi-phase/src/mock.rs b/frame/election-provider-multi-phase/src/mock.rs index cf797aea845f4..6a02e26b27ab3 100644 --- a/frame/election-provider-multi-phase/src/mock.rs +++ b/frame/election-provider-multi-phase/src/mock.rs @@ -45,7 +45,7 @@ use sp_npos_elections::{ use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, - PerU16, + BuildStorage, PerU16, }; use std::sync::Arc; @@ -59,7 +59,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system::{Pallet, Call, Event, Config}, + System: frame_system::{Pallet, Call, Event, Config}, Balances: pallet_balances::{Pallet, Call, Event, Config}, MultiPhase: multi_phase::{Pallet, Call, Event}, } @@ -574,7 +574,7 @@ impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { sp_tracing::try_init_simple(); let mut storage = - frame_system::GenesisConfig::default().build_storage::().unwrap(); + frame_system::GenesisConfig::::default().build_storage().unwrap(); let _ = pallet_balances::GenesisConfig:: { balances: vec![ diff --git a/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs b/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs index 8c641d6137c53..f41f8babd607c 100644 --- a/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs +++ b/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs @@ -18,18 +18,14 @@ #![allow(dead_code)] use _feps::ExtendedBalance; -use frame_support::{ - parameter_types, traits, - traits::{GenesisBuild, Hooks}, - weights::constants, -}; +use frame_support::{parameter_types, traits, traits::Hooks, weights::constants}; use frame_system::EnsureRoot; use sp_core::{ConstU32, Get, H256}; use sp_npos_elections::{ElectionScore, VoteWeight}; use sp_runtime::{ testing, traits::{IdentityLookup, Zero}, - transaction_validity, PerU16, Perbill, + transaction_validity, BuildStorage, PerU16, Perbill, }; use sp_staking::{ offence::{DisableStrategy, OffenceDetails, OnOffenceHandler}, @@ -490,7 +486,7 @@ impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { sp_tracing::try_init_simple(); let mut storage = - frame_system::GenesisConfig::default().build_storage::().unwrap(); + frame_system::GenesisConfig::::default().build_storage().unwrap(); let _ = pallet_balances::GenesisConfig:: { balances: self.balances_builder.balances } diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 7a4fb61970215..501e50c6a7acc 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -721,7 +721,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { assert!( self.members.len() as u32 <= T::DesiredMembers::get(), diff --git a/frame/examples/basic/src/lib.rs b/frame/examples/basic/src/lib.rs index af159c0f4bc98..adb8e99c6d6a8 100644 --- a/frame/examples/basic/src/lib.rs +++ b/frame/examples/basic/src/lib.rs @@ -627,7 +627,7 @@ pub mod pallet { // The build of genesis for the pallet. #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { >::put(&self.dummy); for (a, b) in &self.bar { diff --git a/frame/examples/basic/src/tests.rs b/frame/examples/basic/src/tests.rs index 621d93b97cd01..ae985151e6665 100644 --- a/frame/examples/basic/src/tests.rs +++ b/frame/examples/basic/src/tests.rs @@ -44,7 +44,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Example: pallet_example_basic::{Pallet, Call, Storage, Config, Event}, } diff --git a/frame/examples/dev-mode/src/tests.rs b/frame/examples/dev-mode/src/tests.rs index 8a1ca6628b91c..95e02134eecc5 100644 --- a/frame/examples/dev-mode/src/tests.rs +++ b/frame/examples/dev-mode/src/tests.rs @@ -38,7 +38,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Example: pallet_dev_mode::{Pallet, Call, Storage, Event}, } diff --git a/frame/examples/kitchensink/src/lib.rs b/frame/examples/kitchensink/src/lib.rs index c60e126181a95..c42c7b2ec62e8 100644 --- a/frame/examples/kitchensink/src/lib.rs +++ b/frame/examples/kitchensink/src/lib.rs @@ -194,7 +194,7 @@ pub mod pallet { /// Allows you to define how `genesis_configuration is built. #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { Foo::::put(self.foo); } diff --git a/frame/examples/kitchensink/src/tests.rs b/frame/examples/kitchensink/src/tests.rs index 9f1cdda9ea228..a1af5bc6c5f1a 100644 --- a/frame/examples/kitchensink/src/tests.rs +++ b/frame/examples/kitchensink/src/tests.rs @@ -33,7 +33,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Kitchensink: pallet_example_kitchensink::{Pallet, Call, Storage, Config, Event}, } diff --git a/frame/examples/offchain-worker/src/tests.rs b/frame/examples/offchain-worker/src/tests.rs index 3df7f4a8d5439..c0ff46bafcdcc 100644 --- a/frame/examples/offchain-worker/src/tests.rs +++ b/frame/examples/offchain-worker/src/tests.rs @@ -45,7 +45,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Example: example_offchain_worker::{Pallet, Call, Storage, Event, ValidateUnsigned}, } ); diff --git a/frame/examples/split/src/mock.rs b/frame/examples/split/src/mock.rs index e479e821f4262..2e117977c1418 100644 --- a/frame/examples/split/src/mock.rs +++ b/frame/examples/split/src/mock.rs @@ -16,7 +16,7 @@ // limitations under the License. use crate as pallet_template; -use frame_support::derive_impl; +use frame_support::{derive_impl, sp_runtime::BuildStorage}; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; @@ -52,5 +52,5 @@ impl pallet_template::Config for Test { // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::::default().build_storage().unwrap().into() } diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index 2aed177578a01..61daed626b040 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -689,7 +689,7 @@ mod tests { transaction_validity::{ InvalidTransaction, TransactionValidityError, UnknownTransaction, ValidTransaction, }, - DispatchError, + BuildStorage, DispatchError, }; use frame_support::{ @@ -833,7 +833,7 @@ mod tests { NodeBlock = TestBlock, UncheckedExtrinsic = TestUncheckedExtrinsic { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event}, Custom: custom::{Pallet, Call, ValidateUnsigned, Inherent}, @@ -972,7 +972,7 @@ mod tests { #[test] fn balance_transfer_dispatch_works() { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 211)] } .assimilate_storage(&mut t) .unwrap(); @@ -1000,7 +1000,7 @@ mod tests { } fn new_test_ext(balance_factor: Balance) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 111 * balance_factor)] } .assimilate_storage(&mut t) .unwrap(); @@ -1008,7 +1008,7 @@ mod tests { } fn new_test_ext_v0(balance_factor: Balance) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 111 * balance_factor)] } .assimilate_storage(&mut t) .unwrap(); diff --git a/frame/fast-unstake/src/mock.rs b/frame/fast-unstake/src/mock.rs index ecdbad9ff7745..881f3f0645571 100644 --- a/frame/fast-unstake/src/mock.rs +++ b/frame/fast-unstake/src/mock.rs @@ -23,7 +23,10 @@ use frame_support::{ traits::{ConstU64, Currency}, weights::constants::WEIGHT_REF_TIME_PER_SECOND, }; -use sp_runtime::traits::{Convert, IdentityLookup}; +use sp_runtime::{ + traits::{Convert, IdentityLookup}, + BuildStorage, +}; use pallet_staking::{Exposure, IndividualExposure, StakerStatus}; use sp_std::prelude::*; @@ -278,7 +281,7 @@ impl ExtBuilder { pub(crate) fn build(self) -> sp_io::TestExternalities { sp_tracing::try_init_simple(); let mut storage = - frame_system::GenesisConfig::default().build_storage::().unwrap(); + frame_system::GenesisConfig::::default().build_storage().unwrap(); let validators_range = VALIDATOR_PREFIX..VALIDATOR_PREFIX + VALIDATORS_PER_ERA; let nominators_range = diff --git a/frame/glutton/src/lib.rs b/frame/glutton/src/lib.rs index c02a14810d0b2..ae3e4f87f0e80 100644 --- a/frame/glutton/src/lib.rs +++ b/frame/glutton/src/lib.rs @@ -130,14 +130,16 @@ pub mod pallet { #[pallet::genesis_config] #[derive(DefaultNoBound)] - pub struct GenesisConfig { + pub struct GenesisConfig { pub compute: FixedU64, pub storage: FixedU64, pub trash_data_count: u32, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { assert!( self.trash_data_count <= MAX_TRASH_DATA_ENTRIES, diff --git a/frame/glutton/src/mock.rs b/frame/glutton/src/mock.rs index f2ce53b206fa8..01fdc1e46a252 100644 --- a/frame/glutton/src/mock.rs +++ b/frame/glutton/src/mock.rs @@ -26,6 +26,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -37,7 +38,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Glutton: pallet_glutton::{Pallet, Event}, } ); @@ -76,7 +77,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); diff --git a/frame/grandpa/src/lib.rs b/frame/grandpa/src/lib.rs index 8311131e97347..3348fcce2ca80 100644 --- a/frame/grandpa/src/lib.rs +++ b/frame/grandpa/src/lib.rs @@ -333,14 +333,16 @@ pub mod pallet { #[pallet::getter(fn session_for_set)] pub(super) type SetIdSession = StorageMap<_, Twox64Concat, SetId, SessionIndex>; - #[derive(Default)] + #[derive(frame_support::DefaultNoBound)] #[pallet::genesis_config] - pub struct GenesisConfig { + pub struct GenesisConfig { pub authorities: AuthorityList, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { CurrentSetId::::put(SetId::default()); Pallet::::initialize(&self.authorities) diff --git a/frame/grandpa/src/mock.rs b/frame/grandpa/src/mock.rs index 3a13385d35320..d5a54a9fcfd51 100644 --- a/frame/grandpa/src/mock.rs +++ b/frame/grandpa/src/mock.rs @@ -25,9 +25,7 @@ use codec::Encode; use frame_election_provider_support::{onchain, SequentialPhragmen}; use frame_support::{ parameter_types, - traits::{ - ConstU128, ConstU32, ConstU64, GenesisBuild, KeyOwnerProofSystem, OnFinalize, OnInitialize, - }, + traits::{ConstU128, ConstU32, ConstU64, KeyOwnerProofSystem, OnFinalize, OnInitialize}, }; use pallet_session::historical as pallet_session_historical; use sp_consensus_grandpa::{RoundNumber, SetId, GRANDPA_ENGINE_ID}; @@ -38,7 +36,7 @@ use sp_runtime::{ impl_opaque_keys, testing::{Header, TestXt, UintAuthorityId}, traits::{IdentityLookup, OpaqueKeys}, - DigestItem, Perbill, + BuildStorage, DigestItem, Perbill, }; use sp_staking::{EraIndex, SessionIndex}; @@ -257,7 +255,7 @@ pub fn new_test_ext(vec: Vec<(u64, u64)>) -> sp_io::TestExternalities { } pub fn new_test_ext_raw_authorities(authorities: AuthorityList) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let balances: Vec<_> = (0..authorities.len()).map(|i| (i as u64, 10_000_000)).collect(); diff --git a/frame/identity/src/tests.rs b/frame/identity/src/tests.rs index 83035c402a7dc..2c0352ac1cea5 100644 --- a/frame/identity/src/tests.rs +++ b/frame/identity/src/tests.rs @@ -31,6 +31,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BadOrigin, BlakeTwo256, IdentityLookup}, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -42,7 +43,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Identity: pallet_identity::{Pallet, Call, Storage, Event}, } @@ -118,7 +119,7 @@ impl pallet_identity::Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 10), (3, 10), (10, 100), (20, 100), (30, 100)], } diff --git a/frame/im-online/src/lib.rs b/frame/im-online/src/lib.rs index e1adbc062424f..23785c7b540c6 100644 --- a/frame/im-online/src/lib.rs +++ b/frame/im-online/src/lib.rs @@ -374,7 +374,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { Pallet::::initialize_keys(&self.keys); } diff --git a/frame/im-online/src/mock.rs b/frame/im-online/src/mock.rs index 78a86edf54598..141df6569b2ec 100644 --- a/frame/im-online/src/mock.rs +++ b/frame/im-online/src/mock.rs @@ -29,7 +29,7 @@ use sp_core::H256; use sp_runtime::{ testing::{Header, TestXt, UintAuthorityId}, traits::{BlakeTwo256, ConvertInto, IdentityLookup}, - Permill, + BuildStorage, Permill, }; use sp_staking::{ offence::{OffenceError, ReportOffence}, @@ -48,7 +48,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, ImOnline: imonline::{Pallet, Call, Storage, Config, Event}, Historical: pallet_session_historical::{Pallet}, @@ -105,7 +105,7 @@ impl ReportOffence for OffenceHandler { } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut result: sp_io::TestExternalities = t.into(); // Set the default keys, otherwise session will discard the validator. result.execute_with(|| { diff --git a/frame/indices/src/lib.rs b/frame/indices/src/lib.rs index bcc47c0089bb8..3c0b49304131f 100644 --- a/frame/indices/src/lib.rs +++ b/frame/indices/src/lib.rs @@ -269,7 +269,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { for (a, b) in &self.indices { >::insert(a, (b, >::zero(), false)) diff --git a/frame/indices/src/mock.rs b/frame/indices/src/mock.rs index f54e4dfa088dc..c7784092cae4a 100644 --- a/frame/indices/src/mock.rs +++ b/frame/indices/src/mock.rs @@ -22,7 +22,7 @@ use crate::{self as pallet_indices, Config}; use frame_support::traits::{ConstU32, ConstU64}; use sp_core::H256; -use sp_runtime::testing::Header; +use sp_runtime::{testing::Header, BuildStorage}; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; @@ -33,7 +33,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Indices: pallet_indices::{Pallet, Call, Storage, Config, Event}, } @@ -91,7 +91,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)], } diff --git a/frame/insecure-randomness-collective-flip/src/lib.rs b/frame/insecure-randomness-collective-flip/src/lib.rs index ad39c4c4fd885..883c546f441c2 100644 --- a/frame/insecure-randomness-collective-flip/src/lib.rs +++ b/frame/insecure-randomness-collective-flip/src/lib.rs @@ -166,6 +166,7 @@ mod tests { use sp_runtime::{ testing::Header, traits::{BlakeTwo256, Header as _, IdentityLookup}, + BuildStorage, }; use frame_support::{ @@ -183,7 +184,7 @@ mod tests { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, CollectiveFlip: pallet_insecure_randomness_collective_flip::{Pallet, Storage}, } ); @@ -223,7 +224,7 @@ mod tests { impl pallet_insecure_randomness_collective_flip::Config for Test {} fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); t.into() } diff --git a/frame/lottery/src/mock.rs b/frame/lottery/src/mock.rs index d89c9d6890ee2..b0a0d9b916512 100644 --- a/frame/lottery/src/mock.rs +++ b/frame/lottery/src/mock.rs @@ -30,7 +30,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, - Perbill, + BuildStorage, Perbill, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -42,7 +42,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Lottery: pallet_lottery::{Pallet, Call, Storage, Event}, } @@ -116,7 +116,7 @@ pub type SystemCall = frame_system::Call; pub type BalancesCall = pallet_balances::Call; pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)], } diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index 74891186a4e22..fd1fe7424f974 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -108,11 +108,12 @@ pub mod pallet { #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig, I: 'static = ()> { pub members: BoundedVec, + #[serde(skip)] pub phantom: PhantomData, } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { use sp_std::collections::btree_set::BTreeSet; let members_set: BTreeSet<_> = self.members.iter().collect(); @@ -526,11 +527,12 @@ mod tests { use sp_runtime::{ testing::Header, traits::{BadOrigin, BlakeTwo256, IdentityLookup}, + BuildStorage, }; use frame_support::{ assert_noop, assert_ok, bounded_vec, ord_parameter_types, parameter_types, - traits::{ConstU32, ConstU64, GenesisBuild, StorageVersion}, + traits::{ConstU32, ConstU64, StorageVersion}, }; use frame_system::EnsureSignedBy; @@ -543,7 +545,7 @@ mod tests { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Membership: pallet_membership::{Pallet, Call, Storage, Config, Event}, } ); @@ -629,7 +631,7 @@ mod tests { } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); // We use default for brevity, but you can configure as desired if needed. pallet_membership::GenesisConfig:: { members: bounded_vec![10, 20, 30], @@ -642,7 +644,7 @@ mod tests { #[cfg(feature = "runtime-benchmarks")] pub(crate) fn new_bench_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::::default().build_storage().unwrap().into() } #[cfg(feature = "runtime-benchmarks")] diff --git a/frame/merkle-mountain-range/src/mock.rs b/frame/merkle-mountain-range/src/mock.rs index cea426368c35c..2c7b422c62ee3 100644 --- a/frame/merkle-mountain-range/src/mock.rs +++ b/frame/merkle-mountain-range/src/mock.rs @@ -39,7 +39,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, MMR: pallet_mmr::{Pallet, Storage}, } ); diff --git a/frame/merkle-mountain-range/src/tests.rs b/frame/merkle-mountain-range/src/tests.rs index b628b51d2938b..2f02fc09150f6 100644 --- a/frame/merkle-mountain-range/src/tests.rs +++ b/frame/merkle-mountain-range/src/tests.rs @@ -23,9 +23,10 @@ use sp_core::{ H256, }; use sp_mmr_primitives::{mmr_lib::helper, utils, Compact, Proof}; +use sp_runtime::BuildStorage; pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::::default().build_storage().unwrap().into() } fn register_offchain_ext(ext: &mut sp_io::TestExternalities) { diff --git a/frame/message-queue/src/integration_test.rs b/frame/message-queue/src/integration_test.rs index 9371fa7c7c291..3716597731eca 100644 --- a/frame/message-queue/src/integration_test.rs +++ b/frame/message-queue/src/integration_test.rs @@ -52,7 +52,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event}, } ); diff --git a/frame/message-queue/src/mock.rs b/frame/message-queue/src/mock.rs index f03ab8130952b..f2a0ca1b494c3 100644 --- a/frame/message-queue/src/mock.rs +++ b/frame/message-queue/src/mock.rs @@ -31,6 +31,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use sp_std::collections::btree_map::BTreeMap; @@ -43,7 +44,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event}, } ); @@ -294,7 +295,7 @@ where WeightForCall::take(); QueueChanges::take(); NumMessagesErrored::take(); - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| frame_system::Pallet::::set_block_number(1.into())); ext diff --git a/frame/multisig/src/tests.rs b/frame/multisig/src/tests.rs index cc0fbc8098936..e024da22810fc 100644 --- a/frame/multisig/src/tests.rs +++ b/frame/multisig/src/tests.rs @@ -30,7 +30,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, - TokenError, + BuildStorage, TokenError, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -42,7 +42,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Multisig: pallet_multisig::{Pallet, Call, Storage, Event}, } @@ -115,7 +115,7 @@ impl Config for Test { use pallet_balances::Call as BalancesCall; pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 10), (3, 10), (4, 10), (5, 2)], } diff --git a/frame/nft-fractionalization/src/mock.rs b/frame/nft-fractionalization/src/mock.rs index 62ff3df5b1a0f..c5142c8695b98 100644 --- a/frame/nft-fractionalization/src/mock.rs +++ b/frame/nft-fractionalization/src/mock.rs @@ -31,7 +31,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, - MultiSignature, + BuildStorage, MultiSignature, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -184,7 +184,7 @@ impl Config for Test { // Build genesis storage according to the mock runtime. pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); diff --git a/frame/nfts/src/mock.rs b/frame/nfts/src/mock.rs index 79f0b341e9fd3..8b8c7c6a0fd70 100644 --- a/frame/nfts/src/mock.rs +++ b/frame/nfts/src/mock.rs @@ -29,7 +29,7 @@ use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, - MultiSignature, + BuildStorage, MultiSignature, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -41,7 +41,7 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Nfts: pallet_nfts::{Pallet, Call, Storage, Event}, } @@ -131,7 +131,7 @@ impl Config for Test { } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.register_extension(KeystoreExt::new(MemoryKeystore::new())); diff --git a/frame/nicks/src/lib.rs b/frame/nicks/src/lib.rs index 7a7b33051b22e..9fa7595bdf3f3 100644 --- a/frame/nicks/src/lib.rs +++ b/frame/nicks/src/lib.rs @@ -241,6 +241,7 @@ mod tests { use sp_runtime::{ testing::Header, traits::{BadOrigin, BlakeTwo256, IdentityLookup}, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -315,7 +316,7 @@ mod tests { } fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 10)] } .assimilate_storage(&mut t) .unwrap(); diff --git a/frame/nis/src/mock.rs b/frame/nis/src/mock.rs index 60aa0f756e9c6..0146acabf9fde 100644 --- a/frame/nis/src/mock.rs +++ b/frame/nis/src/mock.rs @@ -33,6 +33,7 @@ use sp_core::{ConstU128, H256}; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -157,7 +158,7 @@ impl pallet_nis::Config for Test { // This function basically just builds a genesis storage key/value store according to // our desired mockup. pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 100), (2, 100), (3, 100), (4, 100)], } @@ -170,7 +171,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { // our desired mockup, but without any balances. #[cfg(feature = "runtime-benchmarks")] pub fn new_test_ext_empty() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::::default().build_storage().unwrap().into() } pub fn run_to_block(n: u64) { diff --git a/frame/node-authorization/src/lib.rs b/frame/node-authorization/src/lib.rs index 6ccc142431e61..dec05d0c37058 100644 --- a/frame/node-authorization/src/lib.rs +++ b/frame/node-authorization/src/lib.rs @@ -115,7 +115,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { Pallet::::initialize_nodes(&self.nodes); } diff --git a/frame/node-authorization/src/mock.rs b/frame/node-authorization/src/mock.rs index b7c5957e15dee..c0594f1d94424 100644 --- a/frame/node-authorization/src/mock.rs +++ b/frame/node-authorization/src/mock.rs @@ -22,13 +22,14 @@ use crate as pallet_node_authorization; use frame_support::{ ord_parameter_types, - traits::{ConstU32, ConstU64, GenesisBuild}, + traits::{ConstU32, ConstU64}, }; use frame_system::EnsureSignedBy; use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -40,7 +41,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, NodeAuthorization: pallet_node_authorization::{ Pallet, Call, Storage, Config, Event, }, @@ -97,7 +98,7 @@ pub fn test_node(id: u8) -> PeerId { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_node_authorization::GenesisConfig:: { nodes: vec![(test_node(10), 10), (test_node(20), 20), (test_node(30), 30)], } diff --git a/frame/nomination-pools/benchmarking/src/mock.rs b/frame/nomination-pools/benchmarking/src/mock.rs index 62655690a2d63..5666e7b450acb 100644 --- a/frame/nomination-pools/benchmarking/src/mock.rs +++ b/frame/nomination-pools/benchmarking/src/mock.rs @@ -20,7 +20,7 @@ use frame_election_provider_support::VoteWeight; use frame_support::{pallet_prelude::*, parameter_types, traits::ConstU64, PalletId}; use sp_runtime::{ traits::{Convert, IdentityLookup}, - FixedU128, Perbill, + BuildStorage, FixedU128, Perbill, }; type AccountId = u128; @@ -192,7 +192,7 @@ frame_support::construct_runtime!( ); pub fn new_test_ext() -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); let _ = pallet_nomination_pools::GenesisConfig:: { min_join_bond: 2, min_create_bond: 2, diff --git a/frame/nomination-pools/src/lib.rs b/frame/nomination-pools/src/lib.rs index a356ba529aa44..587fe1b9e8d2a 100644 --- a/frame/nomination-pools/src/lib.rs +++ b/frame/nomination-pools/src/lib.rs @@ -1680,7 +1680,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { MinJoinBond::::put(self.min_join_bond); MinCreateBond::::put(self.min_create_bond); diff --git a/frame/nomination-pools/src/mock.rs b/frame/nomination-pools/src/mock.rs index 0a404603496ec..ef1240b666101 100644 --- a/frame/nomination-pools/src/mock.rs +++ b/frame/nomination-pools/src/mock.rs @@ -2,7 +2,7 @@ use super::*; use crate::{self as pools}; use frame_support::{assert_ok, parameter_types, PalletId}; use frame_system::RawOrigin; -use sp_runtime::FixedU128; +use sp_runtime::{BuildStorage, FixedU128}; use sp_staking::Stake; pub type BlockNumber = u64; @@ -254,7 +254,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Storage, Event, Config}, + System: frame_system::{Pallet, Call, Storage, Event, Config}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Pools: pools::{Pallet, Call, Storage, Event}, } @@ -324,7 +324,7 @@ impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { sp_tracing::try_init_simple(); let mut storage = - frame_system::GenesisConfig::default().build_storage::().unwrap(); + frame_system::GenesisConfig::::default().build_storage().unwrap(); let _ = crate::GenesisConfig:: { min_join_bond: MinJoinBondConfig::get(), diff --git a/frame/nomination-pools/test-staking/src/mock.rs b/frame/nomination-pools/test-staking/src/mock.rs index 6d73615c8055b..f7697d534fd57 100644 --- a/frame/nomination-pools/test-staking/src/mock.rs +++ b/frame/nomination-pools/test-staking/src/mock.rs @@ -25,7 +25,7 @@ use frame_support::{ }; use sp_runtime::{ traits::{Convert, IdentityLookup}, - FixedU128, Perbill, + BuildStorage, FixedU128, Perbill, }; type AccountId = u128; @@ -206,7 +206,7 @@ frame_support::construct_runtime!( pub fn new_test_ext() -> sp_io::TestExternalities { sp_tracing::try_init_simple(); - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); let _ = pallet_nomination_pools::GenesisConfig:: { min_join_bond: 2, min_create_bond: 2, diff --git a/frame/offences/benchmarking/src/mock.rs b/frame/offences/benchmarking/src/mock.rs index d6c1f95117c61..ec64ce13632e3 100644 --- a/frame/offences/benchmarking/src/mock.rs +++ b/frame/offences/benchmarking/src/mock.rs @@ -30,6 +30,7 @@ use pallet_session::historical as pallet_session_historical; use sp_runtime::{ testing::{Header, UintAuthorityId}, traits::IdentityLookup, + BuildStorage, }; type AccountId = u64; @@ -235,6 +236,6 @@ frame_support::construct_runtime!( ); pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); sp_io::TestExternalities::new(t) } diff --git a/frame/offences/src/mock.rs b/frame/offences/src/mock.rs index 17480be76c1d8..f719fe6cdd7d2 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -31,7 +31,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, - Perbill, + BuildStorage, Perbill, }; use sp_staking::{ offence::{self, DisableStrategy, Kind, OffenceDetails}, @@ -75,7 +75,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Offences: offences::{Pallet, Storage, Event}, } ); @@ -114,7 +114,7 @@ impl Config for Runtime { } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext diff --git a/frame/preimage/src/mock.rs b/frame/preimage/src/mock.rs index 7c645da2c51d8..d3d891c1d0dc9 100644 --- a/frame/preimage/src/mock.rs +++ b/frame/preimage/src/mock.rs @@ -30,6 +30,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -104,7 +105,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let balances = pallet_balances::GenesisConfig:: { balances: vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)], }; diff --git a/frame/proxy/src/tests.rs b/frame/proxy/src/tests.rs index 54b76413bcff4..ccfeed8cd5693 100644 --- a/frame/proxy/src/tests.rs +++ b/frame/proxy/src/tests.rs @@ -33,6 +33,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -44,7 +45,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Proxy: proxy::{Pallet, Call, Storage, Event}, Utility: pallet_utility::{Pallet, Call, Event}, @@ -174,7 +175,7 @@ use pallet_utility::{Call as UtilityCall, Event as UtilityEvent}; type SystemError = frame_system::Error; pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 10), (3, 10), (4, 10), (5, 3)], } diff --git a/frame/ranked-collective/src/tests.rs b/frame/ranked-collective/src/tests.rs index 338dcaacedcf7..fb8dc00e76551 100644 --- a/frame/ranked-collective/src/tests.rs +++ b/frame/ranked-collective/src/tests.rs @@ -29,6 +29,7 @@ use sp_core::{Get, H256}; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup, ReduceBy}, + BuildStorage, }; use super::*; @@ -44,7 +45,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Club: pallet_ranked_collective::{Pallet, Call, Storage, Event}, } ); @@ -199,7 +200,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext diff --git a/frame/recovery/src/mock.rs b/frame/recovery/src/mock.rs index 523dd3aa3e8dc..75e5168f13aaa 100644 --- a/frame/recovery/src/mock.rs +++ b/frame/recovery/src/mock.rs @@ -28,6 +28,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -39,7 +40,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Recovery: recovery::{Pallet, Call, Storage, Event}, } @@ -115,7 +116,7 @@ pub type BalancesCall = pallet_balances::Call; pub type RecoveryCall = super::Call; pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)], } diff --git a/frame/referenda/src/mock.rs b/frame/referenda/src/mock.rs index 1a43257cb94e1..b6b5905709d0d 100644 --- a/frame/referenda/src/mock.rs +++ b/frame/referenda/src/mock.rs @@ -33,7 +33,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, Hash, IdentityLookup}, - DispatchResult, Perbill, + BuildStorage, DispatchResult, Perbill, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -233,7 +233,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let balances = vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100), (6, 100)]; pallet_balances::GenesisConfig:: { balances } .assimilate_storage(&mut t) diff --git a/frame/remark/src/mock.rs b/frame/remark/src/mock.rs index 569c383928189..13f20557c6ceb 100644 --- a/frame/remark/src/mock.rs +++ b/frame/remark/src/mock.rs @@ -36,7 +36,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Remark: pallet_remark::{ Pallet, Call, Event }, } ); diff --git a/frame/root-offences/src/mock.rs b/frame/root-offences/src/mock.rs index 65fd788e05f25..d8a8e597da484 100644 --- a/frame/root-offences/src/mock.rs +++ b/frame/root-offences/src/mock.rs @@ -21,7 +21,7 @@ use crate as root_offences; use frame_election_provider_support::{onchain, SequentialPhragmen}; use frame_support::{ parameter_types, - traits::{ConstU32, ConstU64, GenesisBuild, Hooks, OneSessionHandler}, + traits::{ConstU32, ConstU64, Hooks, OneSessionHandler}, }; use pallet_staking::StakerStatus; use sp_core::H256; @@ -29,6 +29,7 @@ use sp_runtime::{ curve::PiecewiseLinear, testing::{Header, UintAuthorityId}, traits::{BlakeTwo256, IdentityLookup, Zero}, + BuildStorage, }; use sp_staking::{EraIndex, SessionIndex}; use sp_std::collections::btree_map::BTreeMap; @@ -48,7 +49,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Staking: pallet_staking::{Pallet, Call, Config, Storage, Event}, @@ -244,7 +245,7 @@ impl Default for ExtBuilder { impl ExtBuilder { fn build(self) -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![ diff --git a/frame/salary/src/tests.rs b/frame/salary/src/tests.rs index 7bad2cf77ace5..7ffa819724ba1 100644 --- a/frame/salary/src/tests.rs +++ b/frame/salary/src/tests.rs @@ -29,7 +29,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, Identity, IdentityLookup}, - DispatchResult, + BuildStorage, DispatchResult, }; use sp_std::cell::RefCell; @@ -45,7 +45,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Salary: pallet_salary::{Pallet, Call, Storage, Event}, } ); @@ -187,7 +187,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext diff --git a/frame/scheduler/src/mock.rs b/frame/scheduler/src/mock.rs index 1b0fb8112469c..7a98d8e0db1c6 100644 --- a/frame/scheduler/src/mock.rs +++ b/frame/scheduler/src/mock.rs @@ -32,7 +32,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, - Perbill, + BuildStorage, Perbill, }; // Logger module to track execution. @@ -102,7 +102,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Logger: logger::{Pallet, Call, Event}, Scheduler: scheduler::{Pallet, Call, Storage, Event}, Preimage: pallet_preimage::{Pallet, Call, Storage, Event}, @@ -225,7 +225,7 @@ impl Config for Test { pub type LoggerCall = logger::Call; pub fn new_test_ext() -> sp_io::TestExternalities { - let t = system::GenesisConfig::default().build_storage::().unwrap(); + let t = system::GenesisConfig::::default().build_storage().unwrap(); t.into() } diff --git a/frame/scored-pool/src/lib.rs b/frame/scored-pool/src/lib.rs index f8fc0fecd492a..6aa64ea64abf0 100644 --- a/frame/scored-pool/src/lib.rs +++ b/frame/scored-pool/src/lib.rs @@ -256,7 +256,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { let mut pool = self.pool.clone(); diff --git a/frame/scored-pool/src/mock.rs b/frame/scored-pool/src/mock.rs index 83bc939e8230d..e6cfea1bfb281 100644 --- a/frame/scored-pool/src/mock.rs +++ b/frame/scored-pool/src/mock.rs @@ -22,13 +22,14 @@ use crate as pallet_scored_pool; use frame_support::{ bounded_vec, construct_runtime, ord_parameter_types, parameter_types, - traits::{ConstU32, ConstU64, GenesisBuild}, + traits::{ConstU32, ConstU64}, }; use frame_system::EnsureSignedBy; use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -40,7 +41,7 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, ScoredPool: pallet_scored_pool::{Pallet, Call, Storage, Config, Event}, } @@ -140,7 +141,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut balances = vec![]; for i in 1..31 { balances.push((i, 500_000)); diff --git a/frame/session/benchmarking/src/mock.rs b/frame/session/benchmarking/src/mock.rs index d4866a46079af..67c1d95f4707d 100644 --- a/frame/session/benchmarking/src/mock.rs +++ b/frame/session/benchmarking/src/mock.rs @@ -24,7 +24,7 @@ use frame_support::{ parameter_types, traits::{ConstU32, ConstU64}, }; -use sp_runtime::traits::IdentityLookup; +use sp_runtime::{traits::IdentityLookup, BuildStorage}; type AccountId = u64; type AccountIndex = u32; @@ -40,7 +40,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Staking: pallet_staking::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, @@ -192,6 +192,6 @@ impl pallet_staking::Config for Test { impl crate::Config for Test {} pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); sp_io::TestExternalities::new(t) } diff --git a/frame/session/src/historical/mod.rs b/frame/session/src/historical/mod.rs index f00a1c95e763e..04129e4eba130 100644 --- a/frame/session/src/historical/mod.rs +++ b/frame/session/src/historical/mod.rs @@ -377,17 +377,17 @@ pub(crate) mod tests { force_new_session, set_next_validators, NextValidators, Session, System, Test, }; - use sp_runtime::{key_types::DUMMY, testing::UintAuthorityId}; + use sp_runtime::{key_types::DUMMY, testing::UintAuthorityId, BuildStorage}; use frame_support::{ - traits::{GenesisBuild, KeyOwnerProofSystem, OnInitialize}, + traits::{KeyOwnerProofSystem, OnInitialize}, BasicExternalities, }; type Historical = Pallet; pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let keys: Vec<_> = NextValidators::get() .iter() .cloned() diff --git a/frame/session/src/historical/offchain.rs b/frame/session/src/historical/offchain.rs index 4185788cbbed0..c44eea2f374c0 100644 --- a/frame/session/src/historical/offchain.rs +++ b/frame/session/src/historical/offchain.rs @@ -149,18 +149,18 @@ mod tests { crypto::key_types::DUMMY, offchain::{testing::TestOffchainExt, OffchainDbExt, OffchainWorkerExt, StorageKind}, }; - use sp_runtime::testing::UintAuthorityId; + use sp_runtime::{testing::UintAuthorityId, BuildStorage}; use frame_support::{ - traits::{GenesisBuild, KeyOwnerProofSystem, OnInitialize}, + traits::{KeyOwnerProofSystem, OnInitialize}, BasicExternalities, }; type Historical = Pallet; pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default() - .build_storage::() + let mut t = frame_system::GenesisConfig::::default() + .build_storage() .expect("Failed to create test externalities."); let keys: Vec<_> = NextValidators::get() diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index 1219aaaf12a10..d1d6296e65730 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -420,7 +420,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { if T::SessionHandler::KEY_TYPE_IDS.len() != T::Keys::key_ids().len() { panic!("Number of keys in session handler and session keys does not match"); diff --git a/frame/session/src/mock.rs b/frame/session/src/mock.rs index d6b8d9e207e02..3d74c32dcdb25 100644 --- a/frame/session/src/mock.rs +++ b/frame/session/src/mock.rs @@ -29,12 +29,13 @@ use sp_runtime::{ impl_opaque_keys, testing::{Header, UintAuthorityId}, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use sp_staking::SessionIndex; use frame_support::{ parameter_types, - traits::{ConstU32, ConstU64, GenesisBuild}, + traits::{ConstU32, ConstU64}, BasicExternalities, }; @@ -85,7 +86,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, Historical: pallet_session_historical::{Pallet}, } @@ -98,7 +99,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, } ); @@ -215,7 +216,7 @@ pub fn reset_before_session_end_called() { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let keys: Vec<_> = NextValidators::get() .iter() .cloned() diff --git a/frame/society/src/benchmarking.rs b/frame/society/src/benchmarking.rs index f9cd378b97d3d..20af6e35ada52 100644 --- a/frame/society/src/benchmarking.rs +++ b/frame/society/src/benchmarking.rs @@ -370,7 +370,10 @@ benchmarks_instance_pallet! { impl_benchmark_test_suite!( Society, - sp_io::TestExternalities::from(frame_system::GenesisConfig::default().build_storage::().unwrap()), + sp_io::TestExternalities::from( + as sp_runtime::BuildStorage>::build_storage( + &frame_system::GenesisConfig::default()).unwrap() + ), crate::mock::Test ); } diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index 6f42ae00f287d..63d90a0703c4d 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -798,7 +798,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { Pot::::put(self.pot); } diff --git a/frame/society/src/mock.rs b/frame/society/src/mock.rs index ed04aa181e161..1b215febac6c0 100644 --- a/frame/society/src/mock.rs +++ b/frame/society/src/mock.rs @@ -30,6 +30,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use RuntimeOrigin as Origin; @@ -43,7 +44,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Society: pallet_society::{Pallet, Call, Storage, Event, Config}, } @@ -150,7 +151,7 @@ impl EnvBuilder { } pub fn execute R>(mut self, f: F) -> R { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); self.balances.push((Society::account_id(), self.balance.max(self.pot))); pallet_balances::GenesisConfig:: { balances: self.balances } .assimilate_storage(&mut t) diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index 19529ca08735d..2a5edd6e00e56 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -22,8 +22,8 @@ use frame_election_provider_support::{onchain, SequentialPhragmen, VoteWeight}; use frame_support::{ assert_ok, ord_parameter_types, parameter_types, traits::{ - ConstU32, ConstU64, Currency, EitherOfDiverse, FindAuthor, GenesisBuild, Get, Hooks, - Imbalance, OnUnbalanced, OneSessionHandler, + ConstU32, ConstU64, Currency, EitherOfDiverse, FindAuthor, Get, Hooks, Imbalance, + OnUnbalanced, OneSessionHandler, }, weights::constants::RocksDbWeight, }; @@ -34,6 +34,7 @@ use sp_runtime::{ curve::PiecewiseLinear, testing::{Header, UintAuthorityId}, traits::{IdentityLookup, Zero}, + BuildStorage, }; use sp_staking::offence::{DisableStrategy, OffenceDetails, OnOffenceHandler}; @@ -429,7 +430,7 @@ impl ExtBuilder { } fn build(self) -> sp_io::TestExternalities { sp_tracing::try_init_simple(); - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); let _ = pallet_balances::GenesisConfig:: { balances: vec![ diff --git a/frame/staking/src/pallet/mod.rs b/frame/staking/src/pallet/mod.rs index 0163d6543f2ab..41b8d4b415e1a 100644 --- a/frame/staking/src/pallet/mod.rs +++ b/frame/staking/src/pallet/mod.rs @@ -598,7 +598,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { ValidatorCount::::put(self.validator_count); MinimumValidatorCount::::put(self.minimum_validator_count); diff --git a/frame/state-trie-migration/src/lib.rs b/frame/state-trie-migration/src/lib.rs index 05ca21c1de752..c7d4924de1fb9 100644 --- a/frame/state-trie-migration/src/lib.rs +++ b/frame/state-trie-migration/src/lib.rs @@ -1062,7 +1062,7 @@ mod mock { }; use sp_runtime::{ traits::{BlakeTwo256, Header as _, IdentityLookup}, - StorageChild, + BuildStorage, StorageChild, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -1075,7 +1075,7 @@ mod mock { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Config, Storage, Event}, StateTrieMigration: pallet_state_trie_migration::{Pallet, Call, Storage, Event}, } @@ -1241,8 +1241,8 @@ mod mock { }; if with_pallets { - frame_system::GenesisConfig::default() - .assimilate_storage::(&mut custom_storage) + frame_system::GenesisConfig::::default() + .assimilate_storage(&mut custom_storage) .unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 1000)] } .assimilate_storage(&mut custom_storage) diff --git a/frame/statement/src/mock.rs b/frame/statement/src/mock.rs index 8b9e7a1a7d965..f2e81b7719021 100644 --- a/frame/statement/src/mock.rs +++ b/frame/statement/src/mock.rs @@ -29,7 +29,7 @@ use sp_core::{Pair, H256}; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, - AccountId32, + AccountId32, BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -111,7 +111,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let balances = pallet_balances::GenesisConfig:: { balances: vec![ (sp_core::sr25519::Pair::from_string("//Alice", None).unwrap().public().into(), 6000), diff --git a/frame/sudo/src/lib.rs b/frame/sudo/src/lib.rs index a41e479b6154d..f735469558c70 100644 --- a/frame/sudo/src/lib.rs +++ b/frame/sudo/src/lib.rs @@ -289,7 +289,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { if let Some(ref key) = self.key { Key::::put(key); diff --git a/frame/sudo/src/mock.rs b/frame/sudo/src/mock.rs index 856cb35c8718c..4854b006e19d8 100644 --- a/frame/sudo/src/mock.rs +++ b/frame/sudo/src/mock.rs @@ -19,12 +19,13 @@ use super::*; use crate as sudo; -use frame_support::traits::{ConstU32, ConstU64, Contains, GenesisBuild}; +use frame_support::traits::{ConstU32, ConstU64, Contains}; use sp_core::H256; use sp_io; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; // Logger module to track execution. @@ -99,7 +100,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Sudo: sudo::{Pallet, Call, Config, Storage, Event}, Logger: logger::{Pallet, Call, Storage, Event}, } @@ -157,7 +158,7 @@ pub type LoggerCall = logger::Call; // Build test environment by setting the root `key` for the Genesis. pub fn new_test_ext(root_key: u64) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); sudo::GenesisConfig:: { key: Some(root_key) } .assimilate_storage(&mut t) .unwrap(); @@ -166,5 +167,5 @@ pub fn new_test_ext(root_key: u64) -> sp_io::TestExternalities { #[cfg(feature = "runtime-benchmarks")] pub fn new_bench_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::::default().build_storage().unwrap().into() } diff --git a/frame/support/procedural/src/construct_runtime/expand/config.rs b/frame/support/procedural/src/construct_runtime/expand/config.rs index 32b8a32a4fe6a..440e856221a36 100644 --- a/frame/support/procedural/src/construct_runtime/expand/config.rs +++ b/frame/support/procedural/src/construct_runtime/expand/config.rs @@ -29,7 +29,7 @@ pub fn expand_outer_config( ) -> TokenStream { let mut types = TokenStream::new(); let mut fields = TokenStream::new(); - let mut build_storage_calls = TokenStream::new(); + let mut genesis_build_calls = TokenStream::new(); let mut query_genesis_config_part_macros = Vec::new(); for decl in pallet_decls { @@ -52,8 +52,8 @@ pub fn expand_outer_config( types.extend(expand_config_types(attr, runtime, decl, &config, part_is_generic)); fields.extend(quote!(#attr pub #field_name: #config,)); - build_storage_calls - .extend(expand_config_build_storage_call(scrate, attr, runtime, decl, field_name)); + genesis_build_calls + .extend(expand_config_build_storage_call(scrate, &config, attr, field_name)); query_genesis_config_part_macros.push(quote! { #path::__substrate_genesis_config_check::is_genesis_config_defined!(#pallet_name); #[cfg(feature = "std")] @@ -67,9 +67,7 @@ pub fn expand_outer_config( #types - #[cfg(any(feature = "std", test))] use #scrate::serde as __genesis_config_serde_import__; - #[cfg(any(feature = "std", test))] #[derive(#scrate::serde::Serialize, #scrate::serde::Deserialize, Default)] #[serde(rename_all = "camelCase")] #[serde(deny_unknown_fields)] @@ -88,13 +86,17 @@ pub fn expand_outer_config( &self, storage: &mut #scrate::sp_runtime::Storage, ) -> std::result::Result<(), String> { - #build_storage_calls - #scrate::BasicExternalities::execute_with_storage(storage, || { - ::on_genesis(); - }); + ::build(&self); + Ok(()) + }) + } + } - Ok(()) + impl #scrate::traits::BuildGenesisConfig for RuntimeGenesisConfig { + fn build(&self) { + #genesis_build_calls + ::on_genesis(); } } } @@ -112,17 +114,14 @@ fn expand_config_types( match (decl.instance.as_ref(), part_is_generic) { (Some(inst), true) => quote! { #attr - #[cfg(any(feature = "std", test))] pub type #config = #path::GenesisConfig<#runtime, #path::#inst>; }, (None, true) => quote! { #attr - #[cfg(any(feature = "std", test))] pub type #config = #path::GenesisConfig<#runtime>; }, (_, false) => quote! { #attr - #[cfg(any(feature = "std", test))] pub type #config = #path::GenesisConfig; }, } @@ -130,21 +129,12 @@ fn expand_config_types( fn expand_config_build_storage_call( scrate: &TokenStream, + pallet_genesis_config: &Ident, attr: &TokenStream, - runtime: &Ident, - decl: &Pallet, field_name: &Ident, ) -> TokenStream { - let path = &decl.path; - let instance = if let Some(inst) = decl.instance.as_ref() { - quote!(#path::#inst) - } else { - quote!(#path::__InherentHiddenInstance) - }; - quote! { #attr - #scrate::sp_runtime::BuildModuleGenesisStorage:: - <#runtime, #instance>::build_module_genesis_storage(&self.#field_name, storage)?; + <#pallet_genesis_config as #scrate::traits::BuildGenesisConfig>::build(&self.#field_name); } } diff --git a/frame/support/procedural/src/lib.rs b/frame/support/procedural/src/lib.rs index 15b11a1c9698e..ca82a7971aca0 100644 --- a/frame/support/procedural/src/lib.rs +++ b/frame/support/procedural/src/lib.rs @@ -1651,8 +1651,7 @@ pub fn genesis_config(_: TokenStream, _: TokenStream) -> TokenStream { /// The macro will add the following attribute: /// * `#[cfg(feature = "std")]` /// -/// The macro will implement `sp_runtime::BuildModuleGenesisStorage` using `()` as a second -/// generic for non-instantiable pallets. +/// The macro will implement `sp_runtime::BuildStorage`. #[proc_macro_attribute] pub fn genesis_build(_: TokenStream, _: TokenStream) -> TokenStream { pallet_macro_stub() diff --git a/frame/support/procedural/src/pallet/expand/genesis_build.rs b/frame/support/procedural/src/pallet/expand/genesis_build.rs index 1c8fb40f1f96e..f54d308fce304 100644 --- a/frame/support/procedural/src/pallet/expand/genesis_build.rs +++ b/frame/support/procedural/src/pallet/expand/genesis_build.rs @@ -18,7 +18,7 @@ use crate::pallet::Def; /// -/// * implement the trait `sp_runtime::BuildModuleGenesisStorage` +/// * implement the trait `sp_runtime::BuildStorage` pub fn expand_genesis_build(def: &mut Def) -> proc_macro2::TokenStream { let genesis_config = if let Some(genesis_config) = &def.genesis_config { genesis_config @@ -28,34 +28,22 @@ pub fn expand_genesis_build(def: &mut Def) -> proc_macro2::TokenStream { let genesis_build = def.genesis_build.as_ref().expect("Checked by def parser"); let frame_support = &def.frame_support; - let type_impl_gen = &def.type_impl_generics(genesis_build.attr_span); - let type_use_gen = &def.type_use_generics(genesis_build.attr_span); - let trait_use_gen = if def.config.has_instance { - quote::quote_spanned!(genesis_build.attr_span => T, I) - } else { - // `__InherentHiddenInstance` used by construct_runtime here is alias for `()` - quote::quote_spanned!(genesis_build.attr_span => T, ()) - }; + let type_impl_gen = &genesis_config.gen_kind.type_impl_gen(genesis_build.attr_span); let gen_cfg_ident = &genesis_config.genesis_config; - - let gen_cfg_use_gen = genesis_config.gen_kind.type_use_gen(genesis_build.attr_span); + let gen_cfg_use_gen = &genesis_config.gen_kind.type_use_gen(genesis_build.attr_span); let where_clause = &genesis_build.where_clause; quote::quote_spanned!(genesis_build.attr_span => #[cfg(feature = "std")] - impl<#type_impl_gen> #frame_support::sp_runtime::BuildModuleGenesisStorage<#trait_use_gen> - for #gen_cfg_ident<#gen_cfg_use_gen> #where_clause - { - fn build_module_genesis_storage( - &self, - storage: &mut #frame_support::sp_runtime::Storage, - ) -> std::result::Result<(), std::string::String> { - #frame_support::BasicExternalities::execute_with_storage(storage, || { - >::build(self); - Ok(()) - }) + impl<#type_impl_gen> #frame_support::sp_runtime::BuildStorage for #gen_cfg_ident<#gen_cfg_use_gen> #where_clause + { + fn assimilate_storage(&self, storage: &mut sp_runtime::Storage) -> std::result::Result<(), std::string::String> { + #frame_support::BasicExternalities::execute_with_storage(storage, || { + self.build(); + Ok(()) + }) + } } - } ) } diff --git a/frame/support/procedural/src/pallet/parse/genesis_build.rs b/frame/support/procedural/src/pallet/parse/genesis_build.rs index 6d356b2ee3844..d0e1d9ec998ec 100644 --- a/frame/support/procedural/src/pallet/parse/genesis_build.rs +++ b/frame/support/procedural/src/pallet/parse/genesis_build.rs @@ -23,7 +23,7 @@ pub struct GenesisBuildDef { /// The index of item in pallet module. pub index: usize, /// A set of usage of instance, must be check for consistency with trait. - pub instances: Vec, + pub instances: Option>, /// The where_clause used. pub where_clause: Option, /// The span of the pallet::genesis_build attribute. @@ -53,7 +53,8 @@ impl GenesisBuildDef { })? .1; - let instances = vec![helper::check_genesis_builder_usage(item_trait)?]; + let instances = + helper::check_genesis_builder_usage(item_trait)?.map(|instances| vec![instances]); Ok(Self { attr_span, index, instances, where_clause: item.generics.where_clause.clone() }) } diff --git a/frame/support/procedural/src/pallet/parse/helper.rs b/frame/support/procedural/src/pallet/parse/helper.rs index 9319248771642..1e6e83d7eeba7 100644 --- a/frame/support/procedural/src/pallet/parse/helper.rs +++ b/frame/support/procedural/src/pallet/parse/helper.rs @@ -23,6 +23,7 @@ mod keyword { syn::custom_keyword!(I); syn::custom_keyword!(compact); syn::custom_keyword!(GenesisBuild); + syn::custom_keyword!(BuildGenesisConfig); syn::custom_keyword!(Config); syn::custom_keyword!(T); syn::custom_keyword!(Pallet); @@ -488,26 +489,32 @@ pub fn check_type_def_gen( /// Check the syntax: /// * either `GenesisBuild` /// * or `GenesisBuild` +/// * or `BuildGenesisConfig` /// -/// return the instance if found. -pub fn check_genesis_builder_usage(type_: &syn::Path) -> syn::Result { +/// return the instance if found for `GenesisBuild` +/// return None for BuildGenesisConfig +pub fn check_genesis_builder_usage(type_: &syn::Path) -> syn::Result> { let expected = "expected `GenesisBuild` or `GenesisBuild`"; - pub struct Checker(InstanceUsage); + pub struct Checker(Option); impl syn::parse::Parse for Checker { fn parse(input: syn::parse::ParseStream) -> syn::Result { let mut instance_usage = InstanceUsage { span: input.span(), has_instance: false }; - input.parse::()?; - input.parse::()?; - input.parse::()?; - if input.peek(syn::Token![,]) { - instance_usage.has_instance = true; - input.parse::()?; - input.parse::()?; + if input.peek(keyword::GenesisBuild) { + input.parse::()?; + input.parse::()?; + input.parse::()?; + if input.peek(syn::Token![,]) { + instance_usage.has_instance = true; + input.parse::()?; + input.parse::()?; + } + input.parse::]>()?; + return Ok(Self(Some(instance_usage))) + } else { + input.parse::()?; + return Ok(Self(None)) } - input.parse::]>()?; - - Ok(Self(instance_usage)) } } diff --git a/frame/support/procedural/src/pallet/parse/mod.rs b/frame/support/procedural/src/pallet/parse/mod.rs index 4a4602964a996..0f5e5f1136610 100644 --- a/frame/support/procedural/src/pallet/parse/mod.rs +++ b/frame/support/procedural/src/pallet/parse/mod.rs @@ -268,7 +268,7 @@ impl Def { instances.extend_from_slice(&genesis_config.instances[..]); } if let Some(genesis_build) = &self.genesis_build { - instances.extend_from_slice(&genesis_build.instances[..]); + genesis_build.instances.as_ref().map(|i| instances.extend_from_slice(&i)); } if let Some(extra_constants) = &self.extra_constants { instances.extend_from_slice(&extra_constants.instances[..]); diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 2a183b00ee14a..250f15bb36461 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -925,19 +925,25 @@ pub mod tests { >; #[pallet::genesis_config] - pub struct GenesisConfig { + pub struct GenesisConfig { pub data: Vec<(u32, u64)>, pub test_config: Vec<(u32, u32, u64)>, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } - impl Default for GenesisConfig { + impl Default for GenesisConfig { fn default() -> Self { - Self { data: vec![(15u32, 42u64)], test_config: vec![(15u32, 16u32, 42u64)] } + Self { + _config: Default::default(), + data: vec![(15u32, 42u64)], + test_config: vec![(15u32, 16u32, 42u64)], + } } } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { for (k, v) in &self.data { >::insert(k, v); @@ -1556,7 +1562,7 @@ pub mod pallet_prelude { }, }, traits::{ - ConstU32, EnsureOrigin, GenesisBuild, Get, GetDefault, GetStorageVersion, Hooks, + BuildGenesisConfig, ConstU32, EnsureOrigin, Get, GetDefault, GetStorageVersion, Hooks, IsType, PalletInfoAccess, StorageInfoTrait, StorageVersion, TypedGet, }, Blake2_128, Blake2_128Concat, Blake2_256, CloneNoBound, DebugNoBound, EqNoBound, Identity, @@ -2231,7 +2237,7 @@ pub mod pallet_prelude { /// for the pallet. /// /// Item is defined as either an enum or a struct. It needs to be public and implement the -/// trait [`GenesisBuild`](`traits::GenesisBuild`) with +/// trait [`BuildGenesisConfig`](`traits::BuildGenesisConfig`) with /// [`#[pallet::genesis_build]`](#genesis-build-palletgenesis_build-optional). The type /// generics are constrained to be either none, or `T` or `T: Config`. /// @@ -2513,14 +2519,15 @@ pub mod pallet_prelude { /// // /// // Type must implement the `Default` trait. /// #[pallet::genesis_config] -/// #[derive(Default)] -/// pub struct GenesisConfig { +/// #[derive(frame_support::DefaultNoBound)] +/// pub struct GenesisConfig { +/// _config: sp_std::marker::PhantomData, /// _myfield: u32, /// } /// /// // Declare genesis builder. (This is need only if GenesisConfig is declared) /// #[pallet::genesis_build] -/// impl GenesisBuild for GenesisConfig { +/// impl BuildGenesisConfig for GenesisConfig { /// fn build(&self) {} /// } /// @@ -2650,13 +2657,14 @@ pub mod pallet_prelude { /// StorageMap; /// /// #[pallet::genesis_config] -/// #[derive(Default)] -/// pub struct GenesisConfig { +/// #[derive(frame_support::DefaultNoBound)] +/// pub struct GenesisConfig, I: 'static = ()> { +/// _config: sp_std::marker::PhantomData<(T,I)>, /// _myfield: u32, /// } /// /// #[pallet::genesis_build] -/// impl, I: 'static> GenesisBuild for GenesisConfig { +/// impl, I: 'static> BuildGenesisConfig for GenesisConfig { /// fn build(&self) {} /// } /// diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index f34a0b5d87bcf..27396d93487bd 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -80,8 +80,10 @@ pub use metadata::{ }; mod hooks; +#[allow(deprecated)] +pub use hooks::GenesisBuild; pub use hooks::{ - GenesisBuild, Hooks, IntegrityTest, OnFinalize, OnGenesis, OnIdle, OnInitialize, + BuildGenesisConfig, Hooks, IntegrityTest, OnFinalize, OnGenesis, OnIdle, OnInitialize, OnRuntimeUpgrade, OnTimestampSet, }; diff --git a/frame/support/src/traits/hooks.rs b/frame/support/src/traits/hooks.rs index 7dda6624ffe65..58da1ad569929 100644 --- a/frame/support/src/traits/hooks.rs +++ b/frame/support/src/traits/hooks.rs @@ -359,8 +359,19 @@ pub trait Hooks { fn integrity_test() {} } +/// A trait to define the build function of a genesis config for both runtime and pallets. +/// +/// Replaces deprecated [`GenesisBuild`]. +pub trait BuildGenesisConfig: Default + sp_runtime::traits::MaybeSerializeDeserialize { + /// The build function puts initial `GenesisConfig` keys/values pairs into the storage. + fn build(&self); +} + /// A trait to define the build function of a genesis config, T and I are placeholder for pallet /// trait and pallet instance. +#[deprecated( + note = "GenesisBuild is planned to be removed in December 2023. Use BuildGenesisConfig instead of it." +)] pub trait GenesisBuild: Default + sp_runtime::traits::MaybeSerializeDeserialize { /// The build function is called within an externalities allowing storage APIs. /// Thus one can write to storage using regular pallet storages. diff --git a/frame/support/test/pallet/Cargo.toml b/frame/support/test/pallet/Cargo.toml index f2ff334a0438c..bc171c354e6ab 100644 --- a/frame/support/test/pallet/Cargo.toml +++ b/frame/support/test/pallet/Cargo.toml @@ -17,6 +17,7 @@ scale-info = { version = "2.0.0", default-features = false, features = ["derive" serde = { version = "1.0.163", default-features = false, features = ["derive"] } frame-support = { version = "4.0.0-dev", default-features = false, path = "../../" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../../../system" } +sp-runtime = { version = "24.0.0", default-features = false, path = "../../../../primitives/runtime" } [features] default = ["std"] diff --git a/frame/support/test/pallet/src/lib.rs b/frame/support/test/pallet/src/lib.rs index f2d0fd7b80d8d..49450659285d7 100644 --- a/frame/support/test/pallet/src/lib.rs +++ b/frame/support/test/pallet/src/lib.rs @@ -37,11 +37,14 @@ pub mod pallet { pub type Value = StorageValue<_, u32>; #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig {} + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { + #[serde(skip)] + _config: core::marker::PhantomData, + } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) {} } diff --git a/frame/support/test/tests/common/outer_enums.rs b/frame/support/test/tests/common/outer_enums.rs index 98139b0f0d1a8..92dc7ac522079 100644 --- a/frame/support/test/tests/common/outer_enums.rs +++ b/frame/support/test/tests/common/outer_enums.rs @@ -52,7 +52,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) {} } @@ -96,7 +96,7 @@ pub mod pallet2 { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) {} } @@ -140,7 +140,7 @@ pub mod pallet3 { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) {} } } diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index f91ea6cdf4127..acdaef190b330 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -165,11 +165,14 @@ mod nested { } #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig {} + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, + } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) {} } } @@ -234,11 +237,14 @@ pub mod module3 { } #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig {} + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, + } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) {} } } @@ -262,8 +268,8 @@ frame_support::construct_runtime!( Module1_1: module1::::{Pallet, Call, Storage, Event, Origin}, Module2: module2::{Pallet, Call, Storage, Event, Origin}, Module1_2: module1::::{Pallet, Call, Storage, Event, Origin}, - NestedModule3: nested::module3::{Pallet, Call, Config, Storage, Event, Origin}, - Module3: self::module3::{Pallet, Call, Config, Storage, Event, Origin}, + NestedModule3: nested::module3::{Pallet, Call, Config, Storage, Event, Origin}, + Module3: self::module3::{Pallet, Call, Config, Storage, Event, Origin}, Module1_3: module1::::{Pallet, Storage, Event } = 6, Module1_4: module1::::{Pallet, Call, Event } = 3, Module1_5: module1::::{Pallet, Event}, diff --git a/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.rs b/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.rs index 7ab4329110d8b..e566f7d458233 100644 --- a/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.rs +++ b/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.rs @@ -7,7 +7,7 @@ construct_runtime! { UncheckedExtrinsic = UncheckedExtrinsic { #[cfg(test)] - System: frame_system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.stderr b/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.stderr index a86a839615aa0..31ae4c987bbe3 100644 --- a/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.stderr +++ b/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.stderr @@ -1,5 +1,5 @@ error: `System` pallet declaration is feature gated, please remove any `#[cfg]` attributes --> tests/construct_runtime_ui/feature_gated_system_pallet.rs:10:3 | -10 | System: frame_system::{Pallet, Call, Storage, Config, Event}, +10 | System: frame_system::{Pallet, Call, Storage, Config, Event}, | ^^^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs b/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs index 5dfc67c83836a..577dbf4091048 100644 --- a/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs +++ b/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs @@ -52,7 +52,7 @@ construct_runtime! { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet1: pallet::{Pallet}, Pallet2: pallet::{Pallet}, Pallet3: pallet::{Pallet}, diff --git a/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs b/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs index 866c3f0de6c3c..3b5773f2c9386 100644 --- a/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs +++ b/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs @@ -77,7 +77,7 @@ construct_runtime! { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet::{Pallet}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs index 0010f5277bb40..a65acf43584c7 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs @@ -52,7 +52,7 @@ construct_runtime! { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet::{Pallet, Call}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs index 28622eb08e443..fdc8a44930666 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs @@ -52,7 +52,7 @@ construct_runtime! { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, + System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, Pallet: pallet expanded::{}::{Pallet, Event}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs index f6365ceb1a9cd..c245f65119776 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs @@ -52,7 +52,7 @@ construct_runtime! { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, + System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, Pallet: pallet expanded::{}::{Pallet, Config}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs index 83179a51abc8f..966d2d119baab 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs @@ -52,7 +52,7 @@ construct_runtime! { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, + System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, Pallet: pallet expanded::{}::{Pallet, Inherent}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs index b15a2d3349043..fb712dbf05acc 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs @@ -52,7 +52,7 @@ construct_runtime! { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, + System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, Pallet: pallet expanded::{}::{Pallet, Origin}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs index b5573d816eff2..3fb42f9a1ee04 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs @@ -52,7 +52,7 @@ construct_runtime! { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet::{Pallet, ValidateUnsigned}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.stderr index 211df67b70056..c2205c5286084 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.stderr @@ -23,7 +23,7 @@ error[E0599]: no variant or associated item named `Pallet` found for enum `Runti 51 | || Block = Block, 52 | || NodeBlock = Block, ... || -55 | || System: frame_system::{Pallet, Call, Storage, Config, Event}, +55 | || System: frame_system::{Pallet, Call, Storage, Config, Event}, 56 | || Pallet: pallet::{Pallet, ValidateUnsigned}, | || -^^^^^^ variant or associated item not found in `RuntimeCall` | ||________| diff --git a/frame/support/test/tests/final_keys.rs b/frame/support/test/tests/final_keys.rs index f56a6c9fcaaa1..164da3ff444a5 100644 --- a/frame/support/test/tests/final_keys.rs +++ b/frame/support/test/tests/final_keys.rs @@ -90,7 +90,7 @@ mod no_instance { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { >::put(self.value); >::put(&self.test_generic_value); @@ -169,7 +169,7 @@ mod instance { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { >::put(self.value); >::put(&self.test_generic_value); diff --git a/frame/support/test/tests/genesisconfig.rs b/frame/support/test/tests/genesisconfig.rs index 291b250c146b2..8ac7bc37e2e72 100644 --- a/frame/support/test/tests/genesisconfig.rs +++ b/frame/support/test/tests/genesisconfig.rs @@ -53,7 +53,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { for (k1, k2, v) in &self.t { >::insert(k1, k2, v); diff --git a/frame/support/test/tests/instance.rs b/frame/support/test/tests/instance.rs index 28611ddbf599c..8d5d49927721f 100644 --- a/frame/support/test/tests/instance.rs +++ b/frame/support/test/tests/instance.rs @@ -87,7 +87,7 @@ mod module1 { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig + impl, I: 'static> BuildGenesisConfig for GenesisConfig where T::BlockNumber: std::fmt::Display, { @@ -196,7 +196,7 @@ mod module2 { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig + impl, I: 'static> BuildGenesisConfig for GenesisConfig where T::BlockNumber: std::fmt::Display, { diff --git a/frame/support/test/tests/issue2219.rs b/frame/support/test/tests/issue2219.rs index 3822fea030d15..e6230dfc71018 100644 --- a/frame/support/test/tests/issue2219.rs +++ b/frame/support/test/tests/issue2219.rs @@ -134,14 +134,16 @@ mod module { pub type RequestLifeTime = StorageValue<_, u64, ValueQuery, ConstU64<0>>; #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig { + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { pub enable_storage_role: bool, pub request_life_time: u64, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { if self.enable_storage_role { >::insert(Role::Storage, >::default()); @@ -187,7 +189,11 @@ frame_support::construct_runtime!( #[test] fn create_genesis_config() { let config = RuntimeGenesisConfig { - module: module::GenesisConfig { request_life_time: 0, enable_storage_role: true }, + module: module::GenesisConfig { + request_life_time: 0, + enable_storage_role: true, + ..Default::default() + }, }; assert_eq!(config.module.request_life_time, 0); assert!(config.module.enable_storage_role); diff --git a/frame/support/test/tests/origin.rs b/frame/support/test/tests/origin.rs index 47451157b352c..0d9a13c1bd8bc 100644 --- a/frame/support/test/tests/origin.rs +++ b/frame/support/test/tests/origin.rs @@ -60,11 +60,14 @@ mod nested { } #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig {} + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, + } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) {} } } @@ -128,11 +131,14 @@ pub mod module { } #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig {} + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, + } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) {} } } diff --git a/frame/support/test/tests/pallet.rs b/frame/support/test/tests/pallet.rs index 5129346acea55..e382176431b21 100644 --- a/frame/support/test/tests/pallet.rs +++ b/frame/support/test/tests/pallet.rs @@ -402,13 +402,18 @@ pub mod pallet { pub type Unbounded = StorageValue>; #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig { + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig + where + T::AccountId: From + SomeAssociation1 + From, + { + #[serde(skip)] + _config: sp_std::marker::PhantomData, _myfield: u32, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig + impl BuildGenesisConfig for GenesisConfig where T::AccountId: From + SomeAssociation1 + From, { @@ -586,7 +591,7 @@ pub mod pallet2 { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig + impl BuildGenesisConfig for GenesisConfig where T::AccountId: From + SomeAssociation1, { diff --git a/frame/support/test/tests/pallet_instance.rs b/frame/support/test/tests/pallet_instance.rs index 03dcc455096e9..ed9ba048cf63c 100644 --- a/frame/support/test/tests/pallet_instance.rs +++ b/frame/support/test/tests/pallet_instance.rs @@ -185,13 +185,15 @@ pub mod pallet { >; #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig { + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig, I: 'static = ()> { + #[serde(skip)] + _config: sp_std::marker::PhantomData<(T, I)>, _myfield: u32, } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) {} } @@ -281,7 +283,7 @@ pub mod pallet2 { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) {} } } diff --git a/frame/support/test/tests/pallet_outer_enums_explicit.rs b/frame/support/test/tests/pallet_outer_enums_explicit.rs index dc98ec43fd933..8c03f7ecf27aa 100644 --- a/frame/support/test/tests/pallet_outer_enums_explicit.rs +++ b/frame/support/test/tests/pallet_outer_enums_explicit.rs @@ -78,7 +78,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic { // Exclude part `Storage` in order not to check its metadata in tests. - System: frame_system::{Pallet, Config, Call, Event }, + System: frame_system::{Pallet, Config, Call, Event }, // This pallet exposes the Error type explicitly. Example: common::outer_enums::pallet::{Pallet, Config, Event, Error}, diff --git a/frame/support/test/tests/pallet_ui/genesis_default_not_satisfied.rs b/frame/support/test/tests/pallet_ui/genesis_default_not_satisfied.rs index da5e8d0c4da52..a4a0eb832c9c0 100644 --- a/frame/support/test/tests/pallet_ui/genesis_default_not_satisfied.rs +++ b/frame/support/test/tests/pallet_ui/genesis_default_not_satisfied.rs @@ -1,6 +1,6 @@ #[frame_support::pallet] mod pallet { - use frame_support::pallet_prelude::{Hooks, GenesisBuild}; + use frame_support::pallet_prelude::{BuildGenesisConfig, Hooks}; use frame_system::pallet_prelude::BlockNumberFor; #[pallet::config] @@ -19,7 +19,7 @@ mod pallet { pub struct GenesisConfig; #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig {} + impl BuildGenesisConfig for GenesisConfig {} } fn main() { diff --git a/frame/support/test/tests/pallet_ui/genesis_default_not_satisfied.stderr b/frame/support/test/tests/pallet_ui/genesis_default_not_satisfied.stderr index 04d5b99d0dea5..7245333c9842e 100644 --- a/frame/support/test/tests/pallet_ui/genesis_default_not_satisfied.stderr +++ b/frame/support/test/tests/pallet_ui/genesis_default_not_satisfied.stderr @@ -1,14 +1,14 @@ error[E0277]: the trait bound `pallet::GenesisConfig: std::default::Default` is not satisfied - --> tests/pallet_ui/genesis_default_not_satisfied.rs:22:38 + --> tests/pallet_ui/genesis_default_not_satisfied.rs:22:30 | -22 | impl GenesisBuild for GenesisConfig {} - | ^^^^^^^^^^^^^ the trait `std::default::Default` is not implemented for `pallet::GenesisConfig` +22 | impl BuildGenesisConfig for GenesisConfig {} + | ^^^^^^^^^^^^^ the trait `std::default::Default` is not implemented for `pallet::GenesisConfig` | -note: required by a bound in `GenesisBuild` +note: required by a bound in `BuildGenesisConfig` --> $WORKSPACE/frame/support/src/traits/hooks.rs | - | pub trait GenesisBuild: Default + sp_runtime::traits::MaybeSerializeDeserialize { - | ^^^^^^^ required by this bound in `GenesisBuild` + | pub trait BuildGenesisConfig: Default + sp_runtime::traits::MaybeSerializeDeserialize { + | ^^^^^^^ required by this bound in `BuildGenesisConfig` help: consider annotating `pallet::GenesisConfig` with `#[derive(Default)]` | 19 + #[derive(Default)] diff --git a/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs b/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs index 9c9c49c4b2740..7682caf6bf1ce 100644 --- a/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs +++ b/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs @@ -43,8 +43,8 @@ construct_runtime! { NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system::{Pallet, Call, Storage, Config, Event}, - Pallet: test_pallet::{Pallet, Config}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Pallet: test_pallet::{Pallet, Config}, } } diff --git a/frame/support/test/tests/versioned_runtime_upgrade.rs b/frame/support/test/tests/versioned_runtime_upgrade.rs index f74521f3101da..338d0776974ad 100644 --- a/frame/support/test/tests/versioned_runtime_upgrade.rs +++ b/frame/support/test/tests/versioned_runtime_upgrade.rs @@ -27,6 +27,7 @@ use frame_support::{ weights::constants::RocksDbWeight, }; use frame_system::Config; +use sp_runtime::BuildStorage; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; @@ -48,11 +49,14 @@ mod dummy_pallet { pub type SomeStorage = StorageValue<_, u32, ValueQuery>; #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig {} + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { + #[serde(skip)] + _config: sp_std::marker::PhantomData, + } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) {} } } @@ -65,8 +69,8 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, - DummyPallet: dummy_pallet::{Pallet, Config, Storage} = 1, + System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, + DummyPallet: dummy_pallet::{Pallet, Config, Storage} = 1, } ); @@ -81,7 +85,7 @@ impl frame_system::Config for Test { } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext: sp_io::TestExternalities = sp_io::TestExternalities::from(storage); ext.execute_with(|| System::set_block_number(1)); ext diff --git a/frame/system/benches/bench.rs b/frame/system/benches/bench.rs index e2fed3e51855d..f344e041a0d49 100644 --- a/frame/system/benches/bench.rs +++ b/frame/system/benches/bench.rs @@ -21,9 +21,8 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, - Perbill, + BuildStorage, Perbill, }; - #[frame_support::pallet] mod module { use frame_support::pallet_prelude::*; @@ -52,7 +51,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Module: module::{Pallet, Event}, } ); @@ -95,8 +94,8 @@ impl module::Config for Runtime { } fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default() - .build_storage::() + frame_system::GenesisConfig::::default() + .build_storage() .unwrap() .into() } diff --git a/frame/system/benchmarking/src/mock.rs b/frame/system/benchmarking/src/mock.rs index 8b05c5a8ba82a..98f8ea6e07ebf 100644 --- a/frame/system/benchmarking/src/mock.rs +++ b/frame/system/benchmarking/src/mock.rs @@ -20,7 +20,7 @@ #![cfg(test)] use codec::Encode; -use sp_runtime::traits::IdentityLookup; +use sp_runtime::{traits::IdentityLookup, BuildStorage}; type AccountId = u64; type AccountIndex = u32; @@ -35,7 +35,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, } ); @@ -81,7 +81,7 @@ impl sp_core::traits::ReadRuntimeVersion for MockedReadRuntimeVersion { } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let version = sp_version::RuntimeVersion { spec_name: "spec_name".into(), diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index cbda3d55cc68c..9fcd7c12fec4e 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -84,6 +84,8 @@ use sp_std::{fmt::Debug, marker::PhantomData, prelude::*}; use sp_version::RuntimeVersion; use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen}; +#[cfg(feature = "std")] +use frame_support::traits::BuildGenesisConfig; use frame_support::{ dispatch::{ extract_actual_pays_fee, extract_actual_weight, DispatchClass, DispatchInfo, @@ -101,8 +103,6 @@ use scale_info::TypeInfo; use sp_core::storage::well_known_keys; use sp_weights::{RuntimeDbWeight, Weight}; -#[cfg(feature = "std")] -use frame_support::traits::GenesisBuild; #[cfg(any(feature = "std", test))] use sp_io::TestExternalities; @@ -670,15 +670,17 @@ pub mod pallet { #[pallet::whitelist_storage] pub(super) type ExecutionPhase = StorageValue<_, Phase>; - #[derive(Default)] + #[derive(frame_support::DefaultNoBound)] #[pallet::genesis_config] - pub struct GenesisConfig { + pub struct GenesisConfig { #[serde(with = "sp_core::bytes")] pub code: Vec, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { >::insert::<_, T::Hash>(T::BlockNumber::zero(), hash69()); >::put::(hash69()); @@ -692,26 +694,6 @@ pub mod pallet { } } -#[cfg(feature = "std")] -impl GenesisConfig { - /// Direct implementation of `GenesisBuild::build_storage`. - /// - /// Kept in order not to break dependency. - pub fn build_storage(&self) -> Result { - >::build_storage(self) - } - - /// Direct implementation of `GenesisBuild::assimilate_storage`. - /// - /// Kept in order not to break dependency. - pub fn assimilate_storage( - &self, - storage: &mut sp_runtime::Storage, - ) -> Result<(), String> { - >::assimilate_storage(self, storage) - } -} - pub type Key = Vec; pub type KeyValue = (Vec, Vec); diff --git a/frame/system/src/mock.rs b/frame/system/src/mock.rs index b484c22ad4fe4..0325c970b8616 100644 --- a/frame/system/src/mock.rs +++ b/frame/system/src/mock.rs @@ -36,7 +36,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, } ); diff --git a/frame/timestamp/src/mock.rs b/frame/timestamp/src/mock.rs index 6f681788236c3..2144322e62128 100644 --- a/frame/timestamp/src/mock.rs +++ b/frame/timestamp/src/mock.rs @@ -29,6 +29,7 @@ use sp_io::TestExternalities; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -41,7 +42,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, } ); @@ -100,7 +101,7 @@ pub(crate) fn get_captured_moment() -> Option { } pub(crate) fn new_test_ext() -> TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); clear_captured_moment(); TestExternalities::new(t) } diff --git a/frame/tips/src/tests.rs b/frame/tips/src/tests.rs index 25043b413db07..4026e54863a32 100644 --- a/frame/tips/src/tests.rs +++ b/frame/tips/src/tests.rs @@ -28,9 +28,7 @@ use sp_runtime::{ use sp_storage::Storage; use frame_support::{ - assert_noop, assert_ok, - pallet_prelude::GenesisBuild, - parameter_types, + assert_noop, assert_ok, parameter_types, storage::StoragePrefixedMap, traits::{ConstU32, ConstU64, SortedMembers, StorageVersion}, PalletId, @@ -48,10 +46,10 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event}, - Treasury1: pallet_treasury::::{Pallet, Call, Storage, Config, Event}, + Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event}, + Treasury1: pallet_treasury::::{Pallet, Call, Storage, Config, Event}, Tips: pallet_tips::{Pallet, Call, Storage, Event}, Tips1: pallet_tips::::{Pallet, Call, Storage, Event}, } @@ -570,7 +568,7 @@ fn test_migration_v4() { #[test] fn genesis_funding_works() { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let initial_funding = 100; pallet_balances::GenesisConfig:: { // Total issuance will be 200 with treasury account initialized with 100. @@ -578,7 +576,9 @@ fn genesis_funding_works() { } .assimilate_storage(&mut t) .unwrap(); - GenesisBuild::::assimilate_storage(&pallet_treasury::GenesisConfig, &mut t).unwrap(); + pallet_treasury::GenesisConfig::::default() + .assimilate_storage(&mut t) + .unwrap(); let mut t: sp_io::TestExternalities = t.into(); t.execute_with(|| { diff --git a/frame/transaction-payment/asset-conversion-tx-payment/src/tests.rs b/frame/transaction-payment/asset-conversion-tx-payment/src/tests.rs index 7cd22e305831b..9e9b74a0ddb2e 100644 --- a/frame/transaction-payment/asset-conversion-tx-payment/src/tests.rs +++ b/frame/transaction-payment/asset-conversion-tx-payment/src/tests.rs @@ -26,7 +26,7 @@ use frame_system as system; use mock::{ExtrinsicBaseWeight, *}; use pallet_asset_conversion::NativeOrAssetId; use pallet_balances::Call as BalancesCall; -use sp_runtime::traits::StaticLookup; +use sp_runtime::{traits::StaticLookup, BuildStorage}; const CALL: &::RuntimeCall = &RuntimeCall::Balances(BalancesCall::transfer_allow_death { dest: 2, value: 69 }); @@ -65,7 +65,7 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { self.set_constants(); - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: if self.balance_factor > 0 { vec![ diff --git a/frame/transaction-payment/asset-tx-payment/src/tests.rs b/frame/transaction-payment/asset-tx-payment/src/tests.rs index 2fee9c849f4b4..8df98ceda9971 100644 --- a/frame/transaction-payment/asset-tx-payment/src/tests.rs +++ b/frame/transaction-payment/asset-tx-payment/src/tests.rs @@ -25,7 +25,7 @@ use frame_support::{ use frame_system as system; use mock::{ExtrinsicBaseWeight, *}; use pallet_balances::Call as BalancesCall; -use sp_runtime::traits::StaticLookup; +use sp_runtime::{traits::StaticLookup, BuildStorage}; const CALL: &::RuntimeCall = &RuntimeCall::Balances(BalancesCall::transfer_allow_death { dest: 2, value: 69 }); @@ -64,7 +64,7 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { self.set_constants(); - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: if self.balance_factor > 0 { vec![ diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index 1ea2dc9f33ebb..bff32456cba4a 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -380,18 +380,20 @@ pub mod pallet { pub(super) type StorageVersion = StorageValue<_, Releases, ValueQuery>; #[pallet::genesis_config] - pub struct GenesisConfig { + pub struct GenesisConfig { pub multiplier: Multiplier, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } - impl Default for GenesisConfig { + impl Default for GenesisConfig { fn default() -> Self { - Self { multiplier: MULTIPLIER_DEFAULT_VALUE } + Self { multiplier: MULTIPLIER_DEFAULT_VALUE, _config: Default::default() } } } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { StorageVersion::::put(Releases::V2); NextFeeMultiplier::::put(self.multiplier); diff --git a/frame/transaction-payment/src/mock.rs b/frame/transaction-payment/src/mock.rs index 28d57065eca18..448079000cab8 100644 --- a/frame/transaction-payment/src/mock.rs +++ b/frame/transaction-payment/src/mock.rs @@ -42,7 +42,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: system::{Pallet, Call, Config, Storage, Event}, + System: system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event}, } diff --git a/frame/transaction-payment/src/tests.rs b/frame/transaction-payment/src/tests.rs index d5109609e2975..d3a1721ccb990 100644 --- a/frame/transaction-payment/src/tests.rs +++ b/frame/transaction-payment/src/tests.rs @@ -20,12 +20,14 @@ use crate as pallet_transaction_payment; use codec::Encode; -use sp_runtime::{testing::TestXt, traits::One, transaction_validity::InvalidTransaction}; +use sp_runtime::{ + testing::TestXt, traits::One, transaction_validity::InvalidTransaction, BuildStorage, +}; use frame_support::{ assert_noop, assert_ok, dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo, PostDispatchInfo}, - traits::{Currency, GenesisBuild}, + traits::Currency, weights::Weight, }; use frame_system as system; @@ -80,7 +82,7 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { self.set_constants(); - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: if self.balance_factor > 0 { vec![ @@ -99,8 +101,9 @@ impl ExtBuilder { .unwrap(); if let Some(multiplier) = self.initial_multiplier { - let genesis = pallet::GenesisConfig { multiplier }; - GenesisBuild::::assimilate_storage(&genesis, &mut t).unwrap(); + pallet::GenesisConfig:: { multiplier, ..Default::default() } + .assimilate_storage(&mut t) + .unwrap(); } t.into() diff --git a/frame/transaction-storage/src/lib.rs b/frame/transaction-storage/src/lib.rs index b99bc49fc5b6f..4004dbd0a435b 100644 --- a/frame/transaction-storage/src/lib.rs +++ b/frame/transaction-storage/src/lib.rs @@ -394,7 +394,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { >::put(&self.byte_fee); >::put(&self.entry_fee); diff --git a/frame/transaction-storage/src/mock.rs b/frame/transaction-storage/src/mock.rs index 1f8a4e2d09ba8..efabcb97f081d 100644 --- a/frame/transaction-storage/src/mock.rs +++ b/frame/transaction-storage/src/mock.rs @@ -39,7 +39,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Config, Storage, Event}, TransactionStorage: pallet_transaction_storage::{ Pallet, Call, Storage, Config, Inherent, Event diff --git a/frame/treasury/src/lib.rs b/frame/treasury/src/lib.rs index 509ab933430bb..01cda66edbb25 100644 --- a/frame/treasury/src/lib.rs +++ b/frame/treasury/src/lib.rs @@ -234,24 +234,14 @@ pub mod pallet { StorageValue<_, BoundedVec, ValueQuery>; #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig; - - #[cfg(feature = "std")] - impl GenesisConfig { - /// Direct implementation of `GenesisBuild::assimilate_storage`. - #[deprecated(note = "Will be removed after July 2023; use \ - ` as GenesisBuild>::assimilate_storage` instead")] - pub fn assimilate_storage, I: 'static>( - &self, - storage: &mut sp_runtime::Storage, - ) -> Result<(), String> { - >::assimilate_storage(self, storage) - } + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig, I: 'static = ()> { + #[serde(skip)] + _config: sp_std::marker::PhantomData<(T, I)>, } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { // Create Treasury account let account_id = >::account_id(); diff --git a/frame/treasury/src/tests.rs b/frame/treasury/src/tests.rs index 0659c2f5941b1..e1cbffc2f2a31 100644 --- a/frame/treasury/src/tests.rs +++ b/frame/treasury/src/tests.rs @@ -23,12 +23,11 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BadOrigin, BlakeTwo256, Dispatchable, IdentityLookup}, + BuildStorage, }; use frame_support::{ - assert_err_ignore_postinfo, assert_noop, assert_ok, - pallet_prelude::GenesisBuild, - parameter_types, + assert_err_ignore_postinfo, assert_noop, assert_ok, parameter_types, traits::{ConstU32, ConstU64, OnInitialize}, PalletId, }; @@ -47,9 +46,9 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Treasury: treasury::{Pallet, Call, Storage, Config, Event}, + Treasury: treasury::{Pallet, Call, Storage, Config, Event}, Utility: pallet_utility, } ); @@ -147,14 +146,14 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { // Total issuance will be 200 with treasury account initialized at ED. balances: vec![(0, 100), (1, 98), (2, 1)], } .assimilate_storage(&mut t) .unwrap(); - GenesisBuild::::assimilate_storage(&crate::GenesisConfig, &mut t).unwrap(); + crate::GenesisConfig::::default().assimilate_storage(&mut t).unwrap(); t.into() } @@ -399,7 +398,7 @@ fn treasury_account_doesnt_get_deleted() { // This is useful for chain that will just update runtime. #[test] fn inexistent_account_works() { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(0, 100), (1, 99), (2, 1)] } .assimilate_storage(&mut t) .unwrap(); @@ -431,7 +430,7 @@ fn inexistent_account_works() { #[test] fn genesis_funding_works() { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let initial_funding = 100; pallet_balances::GenesisConfig:: { // Total issuance will be 200 with treasury account initialized with 100. @@ -439,7 +438,7 @@ fn genesis_funding_works() { } .assimilate_storage(&mut t) .unwrap(); - GenesisBuild::::assimilate_storage(&crate::GenesisConfig, &mut t).unwrap(); + crate::GenesisConfig::::default().assimilate_storage(&mut t).unwrap(); let mut t: sp_io::TestExternalities = t.into(); t.execute_with(|| { diff --git a/frame/uniques/src/mock.rs b/frame/uniques/src/mock.rs index e783f0b7cf4d9..b975f6bac6a55 100644 --- a/frame/uniques/src/mock.rs +++ b/frame/uniques/src/mock.rs @@ -28,6 +28,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -39,7 +40,7 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Uniques: pallet_uniques::{Pallet, Call, Storage, Event}, } @@ -110,7 +111,7 @@ impl Config for Test { } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); diff --git a/frame/utility/src/tests.rs b/frame/utility/src/tests.rs index ced50f828d564..e39820ae251dd 100644 --- a/frame/utility/src/tests.rs +++ b/frame/utility/src/tests.rs @@ -27,7 +27,7 @@ use frame_support::{ dispatch::{DispatchError, DispatchErrorWithPostInfo, Dispatchable, Pays}, error::BadOrigin, parameter_types, storage, - traits::{ConstU32, ConstU64, Contains, GenesisBuild}, + traits::{ConstU32, ConstU64, Contains}, weights::Weight, }; use pallet_collective::{EnsureProportionAtLeast, Instance1}; @@ -35,7 +35,7 @@ use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, Hash, IdentityLookup}, - TokenError, + BuildStorage, TokenError, }; type BlockNumber = u64; @@ -134,7 +134,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Timestamp: pallet_timestamp::{Call, Inherent}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, RootTesting: pallet_root_testing::{Pallet, Call, Storage}, @@ -265,7 +265,7 @@ use pallet_root_testing::Call as RootTestingCall; use pallet_timestamp::Call as TimestampCall; pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 10), (3, 10), (4, 10), (5, 2)], } diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index 8f98295dd385a..f19e38d311914 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -220,7 +220,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { use sp_runtime::traits::Saturating; diff --git a/frame/vesting/src/mock.rs b/frame/vesting/src/mock.rs index 31f35bbdab604..d0c25221cd5e9 100644 --- a/frame/vesting/src/mock.rs +++ b/frame/vesting/src/mock.rs @@ -17,12 +17,13 @@ use frame_support::{ parameter_types, - traits::{ConstU32, ConstU64, GenesisBuild, WithdrawReasons}, + traits::{ConstU32, ConstU64, WithdrawReasons}, }; use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, Identity, IdentityLookup}, + BuildStorage, }; use super::*; @@ -37,7 +38,7 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Vesting: pallet_vesting::{Pallet, Call, Storage, Event, Config}, } @@ -125,7 +126,7 @@ impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit); - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![ (1, 10 * self.existential_deposit), diff --git a/primitives/runtime/src/lib.rs b/primitives/runtime/src/lib.rs index d29938d0a8610..e2f890a46b3db 100644 --- a/primitives/runtime/src/lib.rs +++ b/primitives/runtime/src/lib.rs @@ -199,6 +199,9 @@ pub trait BuildStorage { /// Something that can build the genesis storage of a module. #[cfg(feature = "std")] +#[deprecated( + note = "`BuildModuleGenesisStorage` is planned to be removed in December 2023. Use `BuildStorage` instead of it." +)] pub trait BuildModuleGenesisStorage: Sized { /// Create the module genesis storage into the given `storage` and `child_storage`. fn build_module_genesis_storage( diff --git a/test-utils/runtime/src/genesismap.rs b/test-utils/runtime/src/genesismap.rs index ed27bce0b35b3..97504c232aef5 100644 --- a/test-utils/runtime/src/genesismap.rs +++ b/test-utils/runtime/src/genesismap.rs @@ -119,6 +119,7 @@ impl GenesisStorageBuilder { let genesis_config = RuntimeGenesisConfig { system: frame_system::GenesisConfig { code: self.wasm_code.clone().unwrap_or(wasm_binary_unwrap().to_vec()), + ..Default::default() }, babe: pallet_babe::GenesisConfig { authorities: authorities_sr25519 @@ -127,9 +128,11 @@ impl GenesisStorageBuilder { .map(|x| (x.into(), 1)) .collect(), epoch_config: Some(crate::TEST_RUNTIME_BABE_EPOCH_CONFIGURATION), + ..Default::default() }, substrate_test: substrate_test_pallet::GenesisConfig { authorities: authorities_sr25519.clone(), + ..Default::default() }, balances: pallet_balances::GenesisConfig { balances: self.balances.clone() }, }; diff --git a/test-utils/runtime/src/substrate_test_pallet.rs b/test-utils/runtime/src/substrate_test_pallet.rs index d080caa0898dd..ed1ad990472ba 100644 --- a/test-utils/runtime/src/substrate_test_pallet.rs +++ b/test-utils/runtime/src/substrate_test_pallet.rs @@ -55,13 +55,15 @@ pub mod pallet { pub type Authorities = StorageValue<_, Vec, ValueQuery>; #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig { + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { pub authorities: Vec, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { >::put(self.authorities.clone()); } diff --git a/utils/frame/rpc/support/src/lib.rs b/utils/frame/rpc/support/src/lib.rs index 431bcdab03288..424d16bd14c68 100644 --- a/utils/frame/rpc/support/src/lib.rs +++ b/utils/frame/rpc/support/src/lib.rs @@ -45,7 +45,7 @@ use sp_storage::{StorageData, StorageKey}; /// # NodeBlock = frame_system::mocking::MockBlock, /// # UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic, /// # { -/// # System: frame_system::{Pallet, Call, Config, Storage, Event}, +/// # System: frame_system::{Pallet, Call, Config, Storage, Event}, /// # Test: pallet_test::{Pallet, Storage}, /// # } /// # ); From d6e9c579ca8608a002de31771962f080581fa098 Mon Sep 17 00:00:00 2001 From: Nuke Date: Wed, 12 Jul 2023 04:48:21 -0700 Subject: [PATCH 18/39] Update `subkey` README.md (#14552) * Update `subkey` README.md getsubstrate.io is not maintained. Perhaps other things should be updated here in this PR too - open to suggestions! * Update README.md --- bin/utils/subkey/README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/bin/utils/subkey/README.md b/bin/utils/subkey/README.md index ddef20f61e134..d19ccefb59aae 100644 --- a/bin/utils/subkey/README.md +++ b/bin/utils/subkey/README.md @@ -25,10 +25,9 @@ You will need to have the Substrate build dependencies to install Subkey. Use th Command: ```bash -# Use the `--fast` flag to get the dependencies without needing to install the Substrate and Subkey binary -curl https://getsubstrate.io -sSf | bash -s -- --fast # Install only `subkey`, at a specific version of the subkey crate cargo install --force subkey --git https://github.com/paritytech/substrate --version --locked +# If you run into issues building, you likely are missing deps defined in https://docs.substrate.io/install/ ``` ### Run in a container @@ -69,7 +68,7 @@ The output above also show the **public key** and the **Account ID**. Those are The **SS58 address** (or **Public Address**) of a new account is a reprensentation of the public keys of an account for a given network (for instance Kusama or Polkadot). -You can read more about the SS58 format in the [Substrate Docs](https://docs.substrate.io/v3/advanced/ss58/) and see the list of reserved prefixes in the [SS58 Registry](https://github.com/paritytech/ss58-registry). +You can read more about the [SS58 format in the Substrate Docs](https://docs.substrate.io/reference/address-formats/) and see the list of reserved prefixes in the [SS58 Registry](https://github.com/paritytech/ss58-registry). For instance, considering the previous seed `0xa05c75731970cc7868a2fb7cb577353cd5b31f62dccced92c441acd8fee0c92d` the SS58 addresses are: From 7b5a4d227b7e5aedefc8b2f9d0373b15116c32a4 Mon Sep 17 00:00:00 2001 From: Branislav Kontur Date: Wed, 12 Jul 2023 15:41:46 +0200 Subject: [PATCH 19/39] Fix refund benchmark for pallet_assets (#14561) * Fix refund benchmark for pallet_assets * Update frame/assets/src/benchmarking.rs Co-authored-by: joe petrowski <25483142+joepetrowski@users.noreply.github.com> * Re-added docs * Another "fix" --------- Co-authored-by: joe petrowski <25483142+joepetrowski@users.noreply.github.com> Co-authored-by: parity-processbot <> --- frame/assets/src/benchmarking.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/frame/assets/src/benchmarking.rs b/frame/assets/src/benchmarking.rs index 982edf33514cf..376f19139ab9b 100644 --- a/frame/assets/src/benchmarking.rs +++ b/frame/assets/src/benchmarking.rs @@ -514,8 +514,8 @@ benchmarks_instance_pallet! { SystemOrigin::Signed(new_account.clone()).into(), asset_id ).is_ok()); - // `touch` should reserve some balance of the caller... - assert!(!T::Currency::reserved_balance(&new_account).is_zero()); + // `touch` should reserve balance of the caller according to the `AssetAccountDeposit` amount... + assert_eq!(T::Currency::reserved_balance(&new_account), T::AssetAccountDeposit::get()); // ...and also create an `Account` entry. assert!(Account::::contains_key(asset_id.into(), &new_account)); }: _(SystemOrigin::Signed(new_account.clone()), asset_id, true) @@ -535,8 +535,8 @@ benchmarks_instance_pallet! { asset_id, new_account_lookup.clone() ).is_ok()); - // `touch_other` should reserve balance of the freezer - assert!(!T::Currency::reserved_balance(&asset_owner).is_zero()); + // `touch` should reserve balance of the caller according to the `AssetAccountDeposit` amount... + assert_eq!(T::Currency::reserved_balance(&asset_owner), T::AssetAccountDeposit::get()); assert!(Account::::contains_key(asset_id.into(), &new_account)); }: _(SystemOrigin::Signed(asset_owner.clone()), asset_id, new_account_lookup.clone()) verify { From da65b99f5edba5064355b755c2f511c619a4fd10 Mon Sep 17 00:00:00 2001 From: Toufeeq Pasha <47236805+ToufeeqP@users.noreply.github.com> Date: Wed, 12 Jul 2023 21:31:08 +0530 Subject: [PATCH 20/39] [pallet_collective] Enforce prime is a valid member of collective in set_members extrinsic (#14354) * Updated set_members extrinsic to enforce prime is valid member of collective * Added additional tests for set_members extrinsic * applied the code review suggestions --- frame/collective/src/lib.rs | 5 +++++ frame/collective/src/tests.rs | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 30c4ad09291ff..6d6958666664e 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -346,6 +346,8 @@ pub mod pallet { WrongProposalWeight, /// The given length bound for the proposal was too low. WrongProposalLength, + /// Prime account is not a member + PrimeAccountNotMember, } #[pallet::hooks] @@ -417,6 +419,9 @@ pub mod pallet { old.len(), ); } + if let Some(p) = &prime { + ensure!(new_members.contains(p), Error::::PrimeAccountNotMember); + } let mut new_members = new_members; new_members.sort(); >::set_members_sorted(&new_members, &old); diff --git a/frame/collective/src/tests.rs b/frame/collective/src/tests.rs index a4ec55856e49c..bf169316491b0 100644 --- a/frame/collective/src/tests.rs +++ b/frame/collective/src/tests.rs @@ -236,6 +236,25 @@ fn initialize_members_sorts_members() { }); } +#[test] +fn set_members_with_prime_works() { + ExtBuilder::default().build_and_execute(|| { + let members = vec![1, 2, 3]; + assert_ok!(Collective::set_members( + RuntimeOrigin::root(), + members.clone(), + Some(3), + MaxMembers::get() + )); + assert_eq!(Collective::members(), members.clone()); + assert_eq!(Collective::prime(), Some(3)); + assert_noop!( + Collective::set_members(RuntimeOrigin::root(), members, Some(4), MaxMembers::get()), + Error::::PrimeAccountNotMember + ); + }); +} + #[test] fn proposal_weight_limit_works() { ExtBuilder::default().build_and_execute(|| { From e97e17445c8d354412de080c7ed3570dc0549799 Mon Sep 17 00:00:00 2001 From: Sam Johnson Date: Thu, 13 Jul 2023 05:05:04 -0400 Subject: [PATCH 21/39] update to docify 0.2.0 / crate-relative embed paths (#14570) --- Cargo.lock | 11 +++++------ frame/fast-unstake/Cargo.toml | 2 +- frame/fast-unstake/src/lib.rs | 4 ++-- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0b3258defb2a1..b975b4c32b034 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2133,23 +2133,22 @@ checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10" [[package]] name = "docify" -version = "0.1.14" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15aa210b350ff62db3149ac5d0b2a0287c01ee91354e16290de344082b2b3ff6" +checksum = "f6491709f76fb7ceb951244daf624d480198b427556084391d6e3c33d3ae74b9" dependencies = [ "docify_macros", ] [[package]] name = "docify_macros" -version = "0.1.14" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bf3504ed030133996c59a9954669a7a4f869f93a7e74389e16149843db16f57" +checksum = "ffc5338a9f72ce29a81377d9039798fcc926fb471b2004666caf48e446dffbbf" dependencies = [ "common-path", "derive-syn-parse", - "lazy_static", - "prettyplease 0.2.6", + "once_cell", "proc-macro2", "quote", "regex", diff --git a/frame/fast-unstake/Cargo.toml b/frame/fast-unstake/Cargo.toml index bac64925ea35c..c628da7123f2e 100644 --- a/frame/fast-unstake/Cargo.toml +++ b/frame/fast-unstake/Cargo.toml @@ -27,7 +27,7 @@ frame-election-provider-support = { default-features = false, path = "../electio frame-benchmarking = { version = "4.0.0-dev", default-features = false, optional = true, path = "../benchmarking" } -docify = "0.1.13" +docify = "0.2.0" [dev-dependencies] pallet-staking-reward-curve = { version = "4.0.0-dev", path = "../staking/reward-curve" } diff --git a/frame/fast-unstake/src/lib.rs b/frame/fast-unstake/src/lib.rs index 9be5878f2e199..99742dbb75ae5 100644 --- a/frame/fast-unstake/src/lib.rs +++ b/frame/fast-unstake/src/lib.rs @@ -71,10 +71,10 @@ //! ### Example //! //! 1. Fast-unstake with multiple participants in the queue. -#![doc = docify::embed!("frame/fast-unstake/src/tests.rs", successful_multi_queue)] +#![doc = docify::embed!("src/tests.rs", successful_multi_queue)] //! //! 2. Fast unstake failing because a nominator is exposed. -#![doc = docify::embed!("frame/fast-unstake/src/tests.rs", exposed_nominator_cannot_unstake)] +#![doc = docify::embed!("src/tests.rs", exposed_nominator_cannot_unstake)] //! //! ## Pallet API //! From 3bc1671e77b751c97beedfe542a33c17dbfaeacc Mon Sep 17 00:00:00 2001 From: Liam Aharon Date: Thu, 13 Jul 2023 20:08:45 +1000 Subject: [PATCH 22/39] Fix Society v2 migration (#14421) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix society v2 migration * Update frame/society/src/migrations.rs * Update frame/society/src/migrations.rs Co-authored-by: Bastian Köcher * Update frame/society/src/migrations.rs Co-authored-by: Bastian Köcher * update for versioned upgrade * fix society v2 migration * remove references to members being sorted from commnets * fix type * fix can_migrate check * add sanity log * fix sanity check * kick ci * kick ci * run tests with --experimental flag * versioned migration cleanup * revert pipeline change * use defensive! * semicolons * defensive and doc comment * address pr comment * feature gate the versioned migration * defensive_unwrap_or * fix test * fix doc comment * change defensive to a log warning * remove can_migrate anti-pattern * Update frame/society/Cargo.toml Co-authored-by: Bastian Köcher * add experimental feature warning to doc comment * update doc comment * bump ci * kick ci * kick ci * kick ci --------- Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> Co-authored-by: Bastian Köcher --- frame/society/Cargo.toml | 4 ++ frame/society/src/lib.rs | 14 +++--- frame/society/src/migrations.rs | 79 ++++++++++++++++++++++----------- frame/society/src/tests.rs | 2 +- frame/support/src/migrations.rs | 36 ++++++++------- 5 files changed, 85 insertions(+), 50 deletions(-) diff --git a/frame/society/Cargo.toml b/frame/society/Cargo.toml index 2ef5dfad78c6e..7f3e55e339fe0 100644 --- a/frame/society/Cargo.toml +++ b/frame/society/Cargo.toml @@ -35,6 +35,10 @@ sp-io = { version = "23.0.0", path = "../../primitives/io" } [features] default = ["std"] +# Enable `VersionedRuntimeUpgrade` for the migrations that is currently still experimental. +experimental = [ + "frame-support/experimental" +] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index 63d90a0703c4d..3d4b9323246d8 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -466,12 +466,12 @@ pub struct GroupParams { pub type GroupParamsFor = GroupParams>; +pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(2); + #[frame_support::pallet] pub mod pallet { use super::*; - const STORAGE_VERSION: StorageVersion = StorageVersion::new(2); - #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] #[pallet::without_storage_info] @@ -1681,8 +1681,8 @@ impl, I: 'static> Pallet { bids.iter().any(|bid| bid.who == *who) } - /// Add a member to the sorted members list. If the user is already a member, do nothing. - /// Can fail when `MaxMember` limit is reached, but in that case it has no side-effects. + /// Add a member to the members list. If the user is already a member, do nothing. Can fail when + /// `MaxMember` limit is reached, but in that case it has no side-effects. /// /// Set the `payouts` for the member. NOTE: This *WILL NOT RESERVE THE FUNDS TO MAKE THE /// PAYOUT*. Only set this to be non-empty if you already have the funds reserved in the Payouts @@ -1703,7 +1703,7 @@ impl, I: 'static> Pallet { Ok(()) } - /// Add a member back to the sorted members list, setting their `rank` and `payouts`. + /// Add a member back to the members list, setting their `rank` and `payouts`. /// /// Can fail when `MaxMember` limit is reached, but in that case it has no side-effects. /// @@ -1713,8 +1713,8 @@ impl, I: 'static> Pallet { Self::insert_member(who, rank) } - /// Add a member to the sorted members list. If the user is already a member, do nothing. - /// Can fail when `MaxMember` limit is reached, but in that case it has no side-effects. + /// Add a member to the members list. If the user is already a member, do nothing. Can fail when + /// `MaxMember` limit is reached, but in that case it has no side-effects. fn add_new_member(who: &T::AccountId, rank: Rank) -> DispatchResult { Self::insert_member(who, rank) } diff --git a/frame/society/src/migrations.rs b/frame/society/src/migrations.rs index bd590f9b18770..404b1e5fd2cb9 100644 --- a/frame/society/src/migrations.rs +++ b/frame/society/src/migrations.rs @@ -19,7 +19,7 @@ use super::*; use codec::{Decode, Encode}; -use frame_support::traits::{Instance, OnRuntimeUpgrade}; +use frame_support::traits::{Defensive, DefensiveOption, Instance, OnRuntimeUpgrade}; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; @@ -28,7 +28,7 @@ use sp_runtime::TryRuntimeError; const TARGET: &'static str = "runtime::society::migration"; /// This migration moves all the state to v2 of Society. -pub struct MigrateToV2, I: 'static, PastPayouts>( +pub struct VersionUncheckedMigrateToV2, I: 'static, PastPayouts>( sp_std::marker::PhantomData<(T, I, PastPayouts)>, ); @@ -36,12 +36,10 @@ impl< T: Config, I: Instance + 'static, PastPayouts: Get::AccountId, BalanceOf)>>, - > OnRuntimeUpgrade for MigrateToV2 + > OnRuntimeUpgrade for VersionUncheckedMigrateToV2 { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, TryRuntimeError> { - ensure!(can_migrate::(), "pallet_society: already upgraded"); - let current = Pallet::::current_storage_version(); let onchain = Pallet::::on_chain_storage_version(); ensure!(onchain == 0 && current == 2, "pallet_society: invalid version"); @@ -50,16 +48,16 @@ impl< } fn on_runtime_upgrade() -> Weight { - let current = Pallet::::current_storage_version(); let onchain = Pallet::::on_chain_storage_version(); - if current == 2 && onchain == 0 { - from_original::(&mut PastPayouts::get()) - } else { + if onchain < 2 { log::info!( - "Running migration with current storage version {:?} / onchain {:?}", - current, + target: TARGET, + "Running migration against onchain version {:?}", onchain ); + from_original::(&mut PastPayouts::get()).defensive_unwrap_or(Weight::MAX) + } else { + log::warn!("Unexpected onchain version: {:?} (expected 0)", onchain); T::DbWeight::get().reads(1) } } @@ -95,6 +93,19 @@ impl< } } +/// [`VersionUncheckedMigrateToV2`] wrapped in a +/// [`frame_support::migrations::VersionedRuntimeUpgrade`], ensuring the migration is only performed +/// when on-chain version is 0. +#[cfg(feature = "experimental")] +pub type VersionCheckedMigrateToV2 = + frame_support::migrations::VersionedRuntimeUpgrade< + 0, + 2, + VersionUncheckedMigrateToV2, + crate::pallet::Pallet, + ::DbWeight, + >; + pub(crate) mod old { use super::*; use frame_support::storage_alias; @@ -180,10 +191,6 @@ pub(crate) mod old { StorageMap, Twox64Concat, ::AccountId, Vote>; } -pub fn can_migrate, I: Instance + 'static>() -> bool { - old::Members::::exists() -} - /// Will panic if there are any inconsistencies in the pallet's state or old keys remaining. pub fn assert_internal_consistency, I: Instance + 'static>() { // Check all members are valid data. @@ -235,15 +242,7 @@ pub fn assert_internal_consistency, I: Instance + 'static>() { pub fn from_original, I: Instance + 'static>( past_payouts: &mut [(::AccountId, BalanceOf)], -) -> Weight { - // First check that this is the original state layout. This is easy since the original layout - // contained the Members value, and this value no longer exists in the new layout. - if !old::Members::::exists() { - log::warn!(target: TARGET, "Skipping MigrateToV2 migration since it appears unapplicable"); - // Already migrated or no data to migrate: Bail. - return T::DbWeight::get().reads(1) - } - +) -> Result { // Migrate Bids from old::Bids (just a trunctation). Bids::::put(BoundedVec::<_, T::MaxBids>::truncate_from(old::Bids::::take())); @@ -281,6 +280,36 @@ pub fn from_original, I: Instance + 'static>( let record = MemberRecord { index: member_count, rank: 0, strikes, vouching }; Members::::insert(&member, record); MemberByIndex::::insert(member_count, &member); + + // The founder must be the first member in Society V2. If we find the founder not in index + // zero, we swap it with the first member. + if member == Founder::::get().defensive_ok_or("founder must always be set")? && + member_count > 0 + { + let member_to_swap = MemberByIndex::::get(0) + .defensive_ok_or("member_count > 0, we must have at least 1 member")?; + // Swap the founder with the first member in MemberByIndex. + MemberByIndex::::swap(0, member_count); + // Update the indicies of the swapped member MemberRecords. + Members::::mutate(&member, |m| { + if let Some(member) = m { + member.index = 0; + } else { + frame_support::defensive!( + "Member somehow disapeared from storage after it was inserted" + ); + } + }); + Members::::mutate(&member_to_swap, |m| { + if let Some(member) = m { + member.index = member_count; + } else { + frame_support::defensive!( + "Member somehow disapeared from storage after it was queried" + ); + } + }); + } member_count.saturating_inc(); } MemberCount::::put(member_count); @@ -317,7 +346,7 @@ pub fn from_original, I: Instance + 'static>( old::Defender::::kill(); let _ = old::DefenderVotes::::clear(u32::MAX, None); - T::BlockWeights::get().max_block + Ok(T::BlockWeights::get().max_block) } pub fn from_raw_past_payouts, I: Instance + 'static>( diff --git a/frame/society/src/tests.rs b/frame/society/src/tests.rs index 4a90ad52112d8..ea2afef3b32b5 100644 --- a/frame/society/src/tests.rs +++ b/frame/society/src/tests.rs @@ -77,7 +77,7 @@ fn migration_works() { .collect::>(); old::Bids::::put(bids); - migrations::from_original::(&mut [][..]); + migrations::from_original::(&mut [][..]).expect("migration failed"); migrations::assert_internal_consistency::(); assert_eq!( diff --git a/frame/support/src/migrations.rs b/frame/support/src/migrations.rs index 889439907efd2..9ba22d3e15404 100644 --- a/frame/support/src/migrations.rs +++ b/frame/support/src/migrations.rs @@ -24,12 +24,8 @@ use sp_core::Get; use sp_io::{hashing::twox_128, storage::clear_prefix, KillStorageResult}; use sp_std::marker::PhantomData; -#[cfg(feature = "try-runtime")] -use sp_std::vec::Vec; - -#[cfg(feature = "experimental")] -use crate::traits::OnRuntimeUpgrade; - +/// EXPERIMENTAL: The API of this feature may change. +/// /// Make it easier to write versioned runtime upgrades. /// /// [`VersionedRuntimeUpgrade`] allows developers to write migrations without worrying about @@ -57,13 +53,19 @@ use crate::traits::OnRuntimeUpgrade; /// // OnRuntimeUpgrade implementation... /// } /// -/// pub type VersionCheckedMigrateV5ToV6 = -/// VersionedRuntimeUpgrade<5, 6, VersionUncheckedMigrateV5ToV6, Pallet, DbWeight>; +/// pub type VersionCheckedMigrateV5ToV6 = +/// VersionedRuntimeUpgrade< +/// 5, +/// 6, +/// VersionUncheckedMigrateV5ToV6, +/// crate::pallet::Pallet, +/// ::DbWeight +/// >; /// /// // Migrations tuple to pass to the Executive pallet: /// pub type Migrations = ( /// // other migrations... -/// VersionCheckedMigrateV5ToV6, +/// VersionCheckedMigrateV5ToV6, /// // other migrations... /// ); /// ``` @@ -78,7 +80,7 @@ pub struct VersionedRuntimeUpgrade), + MigrationExecuted(sp_std::vec::Vec), /// This migration is a noop, do not run post_upgrade checks. Noop, } @@ -93,16 +95,16 @@ pub enum VersionedPostUpgradeData { impl< const FROM: u16, const TO: u16, - Inner: OnRuntimeUpgrade, + Inner: crate::traits::OnRuntimeUpgrade, Pallet: GetStorageVersion + PalletInfoAccess, DbWeight: Get, - > OnRuntimeUpgrade for VersionedRuntimeUpgrade + > crate::traits::OnRuntimeUpgrade for VersionedRuntimeUpgrade { /// Executes pre_upgrade if the migration will run, and wraps the pre_upgrade bytes in /// [`VersionedPostUpgradeData`] before passing them to post_upgrade, so it knows whether the /// migration ran or not. #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { + fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { use codec::Encode; let on_chain_version = Pallet::on_chain_storage_version(); if on_chain_version == FROM { @@ -152,7 +154,7 @@ impl< /// the migration ran, and [`VersionedPostUpgradeData::Noop`] otherwise. #[cfg(feature = "try-runtime")] fn post_upgrade( - versioned_post_upgrade_data_bytes: Vec, + versioned_post_upgrade_data_bytes: sp_std::vec::Vec, ) -> Result<(), sp_runtime::TryRuntimeError> { use codec::DecodeAll; match ::decode_all(&mut &versioned_post_upgrade_data_bytes[..]) @@ -321,7 +323,7 @@ impl, DbWeight: Get> frame_support::traits } #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { + fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { use crate::storage::unhashed::contains_prefixed_key; let hashed_prefix = twox_128(P::get().as_bytes()); @@ -332,11 +334,11 @@ impl, DbWeight: Get> frame_support::traits P::get() ), }; - Ok(Vec::new()) + Ok(sp_std::vec::Vec::new()) } #[cfg(feature = "try-runtime")] - fn post_upgrade(_state: Vec) -> Result<(), sp_runtime::TryRuntimeError> { + fn post_upgrade(_state: sp_std::vec::Vec) -> Result<(), sp_runtime::TryRuntimeError> { use crate::storage::unhashed::contains_prefixed_key; let hashed_prefix = twox_128(P::get().as_bytes()); From ec3bedd5c8cd0caa77a312b53a3cf3306149276c Mon Sep 17 00:00:00 2001 From: gupnik <17176722+gupnik@users.noreply.github.com> Date: Thu, 13 Jul 2023 17:31:34 +0530 Subject: [PATCH 23/39] Moves `Block` to `frame_system` instead of `construct_runtime` and removes `Header` and `BlockNumber` (#14437) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Initial setup * Adds node block * Uses UncheckedExtrinsic and removes Where section * Updates frame_system to use Block * Adds deprecation warning * Fixes pallet-timestamp * Removes Header and BlockNumber * Addresses review comments * Addresses review comments * Adds comment about compiler bug * Removes where clause * Refactors code * Fixes errors in cargo check * Fixes errors in cargo check * Fixes warnings in cargo check * Formatting * Fixes construct_runtime tests * Uses import instead of full path for BlockNumber * Uses import instead of full path for Header * Formatting * Fixes construct_runtime tests * Fixes imports in benchmarks * Formatting * Fixes construct_runtime tests * Formatting * Minor updates * Fixes construct_runtime ui tests * Fixes construct_runtime ui tests with 1.70 * Fixes docs * Fixes docs * Adds u128 mock block type * Fixes split example * fixes for cumulus * ".git/.scripts/commands/fmt/fmt.sh" * Updates new tests * Fixes fully-qualified path in few places * Formatting * Update frame/examples/default-config/src/lib.rs Co-authored-by: Juan * Update frame/support/procedural/src/construct_runtime/mod.rs Co-authored-by: Juan * ".git/.scripts/commands/fmt/fmt.sh" * Addresses some review comments * Fixes build * ".git/.scripts/commands/fmt/fmt.sh" * Update frame/democracy/src/lib.rs Co-authored-by: Oliver Tale-Yazdi * Update frame/democracy/src/lib.rs Co-authored-by: Oliver Tale-Yazdi * Update frame/support/procedural/src/construct_runtime/mod.rs Co-authored-by: Oliver Tale-Yazdi * Update frame/support/procedural/src/construct_runtime/mod.rs Co-authored-by: Oliver Tale-Yazdi * Addresses review comments * Updates trait bounds * Minor fix * ".git/.scripts/commands/fmt/fmt.sh" * Removes unnecessary bound * ".git/.scripts/commands/fmt/fmt.sh" * Updates test * Fixes build * Adds a bound for header * ".git/.scripts/commands/fmt/fmt.sh" * Removes where block * Minor fix * Minor fix * Fixes tests * ".git/.scripts/commands/update-ui/update-ui.sh" 1.70 * Updates test * Update primitives/runtime/src/traits.rs Co-authored-by: Bastian Köcher * Update primitives/runtime/src/traits.rs Co-authored-by: Bastian Köcher * Updates doc * Updates doc --------- Co-authored-by: command-bot <> Co-authored-by: Juan Co-authored-by: Oliver Tale-Yazdi Co-authored-by: Bastian Köcher --- .../pallets/template/src/mock.rs | 10 +- bin/node-template/runtime/src/lib.rs | 13 +- bin/node/runtime/src/lib.rs | 8 +- frame/alliance/src/benchmarking.rs | 6 +- frame/alliance/src/lib.rs | 4 +- frame/alliance/src/mock.rs | 10 +- frame/asset-conversion/src/lib.rs | 7 +- frame/asset-conversion/src/mock.rs | 10 +- frame/asset-rate/src/mock.rs | 10 +- frame/assets/src/mock.rs | 10 +- frame/atomic-swap/src/lib.rs | 5 +- frame/atomic-swap/src/tests.rs | 10 +- frame/aura/src/lib.rs | 4 +- frame/aura/src/mock.rs | 15 +- frame/authority-discovery/src/lib.rs | 11 +- frame/authorship/src/lib.rs | 15 +- frame/babe/src/equivocation.rs | 9 +- frame/babe/src/lib.rs | 49 +- frame/babe/src/mock.rs | 9 +- frame/babe/src/randomness.rs | 17 +- frame/bags-list/src/mock.rs | 9 +- frame/balances/README.md | 2 +- frame/balances/src/impl_currency.rs | 3 +- frame/balances/src/lib.rs | 4 +- frame/balances/src/tests/mod.rs | 10 +- frame/beefy-mmr/src/lib.rs | 3 +- frame/beefy-mmr/src/mock.rs | 12 +- frame/beefy/src/equivocation.rs | 5 +- frame/beefy/src/mock.rs | 11 +- frame/benchmarking/pov/src/benchmarking.rs | 10 +- frame/benchmarking/pov/src/tests.rs | 9 +- frame/benchmarking/src/baseline.rs | 10 +- frame/benchmarking/src/tests.rs | 11 +- frame/benchmarking/src/tests_instance.rs | 11 +- frame/bounties/src/benchmarking.rs | 18 +- frame/bounties/src/lib.rs | 6 +- frame/bounties/src/tests.rs | 10 +- frame/child-bounties/src/benchmarking.rs | 8 +- frame/child-bounties/src/lib.rs | 4 +- frame/child-bounties/src/tests.rs | 10 +- frame/collective/src/benchmarking.rs | 10 +- frame/collective/src/lib.rs | 4 +- frame/collective/src/tests.rs | 8 +- frame/contracts/src/exec.rs | 13 +- frame/contracts/src/lib.rs | 4 +- frame/contracts/src/tests.rs | 11 +- frame/contracts/src/wasm/mod.rs | 5 +- frame/contracts/src/wasm/runtime.rs | 2 +- frame/conviction-voting/src/lib.rs | 16 +- frame/conviction-voting/src/tests.rs | 10 +- frame/core-fellowship/src/benchmarking.rs | 6 +- frame/core-fellowship/src/lib.rs | 5 +- frame/core-fellowship/src/tests.rs | 10 +- frame/democracy/src/benchmarking.rs | 10 +- frame/democracy/src/lib.rs | 73 +-- frame/democracy/src/migrations/v1.rs | 9 +- frame/democracy/src/tests.rs | 10 +- .../src/benchmarking.rs | 2 +- .../election-provider-multi-phase/src/lib.rs | 34 +- .../election-provider-multi-phase/src/mock.rs | 12 +- .../src/signed.rs | 9 +- .../src/unsigned.rs | 6 +- .../test-staking-e2e/src/mock.rs | 10 +- .../election-provider-support/src/onchain.rs | 12 +- frame/elections-phragmen/src/lib.rs | 16 +- frame/examples/basic/src/lib.rs | 6 +- frame/examples/basic/src/tests.rs | 10 +- frame/examples/default-config/src/lib.rs | 13 +- frame/examples/dev-mode/src/tests.rs | 10 +- frame/examples/kitchensink/src/lib.rs | 14 +- frame/examples/kitchensink/src/tests.rs | 8 +- frame/examples/offchain-worker/src/lib.rs | 52 ++- frame/examples/offchain-worker/src/tests.rs | 15 +- frame/examples/split/src/mock.rs | 9 +- frame/executive/src/lib.rs | 100 ++-- frame/fast-unstake/src/lib.rs | 6 +- frame/fast-unstake/src/mock.rs | 12 +- frame/glutton/src/mock.rs | 10 +- frame/grandpa/src/equivocation.rs | 9 +- frame/grandpa/src/lib.rs | 37 +- frame/grandpa/src/mock.rs | 11 +- frame/identity/src/tests.rs | 10 +- frame/im-online/src/benchmarking.rs | 7 +- frame/im-online/src/lib.rs | 18 +- frame/im-online/src/mock.rs | 11 +- frame/indices/src/mock.rs | 11 +- .../src/lib.rs | 20 +- frame/lottery/src/lib.rs | 10 +- frame/lottery/src/mock.rs | 10 +- frame/membership/src/lib.rs | 10 +- frame/merkle-mountain-range/src/lib.rs | 24 +- frame/merkle-mountain-range/src/mock.rs | 14 +- frame/merkle-mountain-range/src/tests.rs | 2 +- frame/message-queue/src/integration_test.rs | 14 +- frame/message-queue/src/mock.rs | 12 +- frame/multisig/src/lib.rs | 20 +- frame/multisig/src/tests.rs | 10 +- .../nft-fractionalization/src/benchmarking.rs | 13 +- frame/nft-fractionalization/src/mock.rs | 10 +- frame/nfts/src/benchmarking.rs | 8 +- frame/nfts/src/features/approvals.rs | 2 +- frame/nfts/src/features/atomic_swap.rs | 2 +- frame/nfts/src/features/settings.rs | 2 +- frame/nfts/src/lib.rs | 22 +- frame/nfts/src/mock.rs | 10 +- frame/nfts/src/types.rs | 14 +- frame/nicks/src/lib.rs | 10 +- frame/nis/src/lib.rs | 23 +- frame/nis/src/mock.rs | 10 +- frame/node-authorization/src/lib.rs | 2 +- frame/node-authorization/src/mock.rs | 10 +- .../nomination-pools/benchmarking/src/mock.rs | 10 +- frame/nomination-pools/src/lib.rs | 13 +- frame/nomination-pools/src/mock.rs | 9 +- .../nomination-pools/test-staking/src/mock.rs | 9 +- frame/offences/benchmarking/src/mock.rs | 9 +- frame/offences/src/mock.rs | 10 +- frame/preimage/src/mock.rs | 10 +- frame/proxy/src/benchmarking.rs | 14 +- frame/proxy/src/lib.rs | 35 +- frame/proxy/src/tests.rs | 10 +- frame/ranked-collective/src/lib.rs | 2 +- frame/ranked-collective/src/tests.rs | 10 +- frame/recovery/src/lib.rs | 6 +- frame/recovery/src/mock.rs | 10 +- frame/referenda/src/benchmarking.rs | 4 +- frame/referenda/src/lib.rs | 51 +- frame/referenda/src/migration.rs | 2 +- frame/referenda/src/mock.rs | 10 +- frame/referenda/src/types.rs | 17 +- frame/remark/src/mock.rs | 10 +- frame/root-offences/src/mock.rs | 11 +- frame/salary/src/lib.rs | 11 +- frame/salary/src/tests.rs | 10 +- frame/scheduler/src/benchmarking.rs | 13 +- frame/scheduler/src/lib.rs | 149 +++--- frame/scheduler/src/migration.rs | 37 +- frame/scheduler/src/mock.rs | 10 +- frame/scored-pool/src/lib.rs | 4 +- frame/scored-pool/src/mock.rs | 10 +- frame/session/benchmarking/src/lib.rs | 8 +- frame/session/benchmarking/src/mock.rs | 10 +- frame/session/src/lib.rs | 13 +- frame/session/src/mock.rs | 16 +- frame/society/src/lib.rs | 31 +- frame/society/src/migrations.rs | 2 +- frame/society/src/mock.rs | 10 +- frame/staking/src/mock.rs | 11 +- frame/staking/src/pallet/impls.rs | 6 +- frame/staking/src/pallet/mod.rs | 8 +- frame/state-trie-migration/src/lib.rs | 17 +- frame/statement/src/mock.rs | 10 +- frame/sudo/src/mock.rs | 10 +- .../src/construct_runtime/expand/inherent.rs | 6 +- .../src/construct_runtime/expand/metadata.rs | 4 +- .../procedural/src/construct_runtime/mod.rs | 35 +- .../procedural/src/construct_runtime/parse.rs | 10 +- frame/support/procedural/src/lib.rs | 6 +- .../procedural/src/pallet/expand/hooks.rs | 40 +- frame/support/src/dispatch.rs | 266 +---------- frame/support/src/error.rs | 45 -- frame/support/src/lib.rs | 49 +- frame/support/src/migrations.rs | 7 +- frame/support/src/storage/generator/mod.rs | 13 +- frame/support/test/compile_pass/src/lib.rs | 10 +- frame/support/test/src/lib.rs | 7 +- frame/support/test/tests/construct_runtime.rs | 129 +++-- .../both_use_and_excluded_parts.rs | 7 +- .../both_use_and_excluded_parts.stderr | 4 +- .../conflicting_module_name.rs | 5 +- .../conflicting_module_name.stderr | 16 +- .../deprecated_where_block.rs | 13 + .../deprecated_where_block.stderr | 442 ++++++++++++++++++ .../double_module_parts.rs | 5 +- .../double_module_parts.stderr | 8 +- .../construct_runtime_ui/empty_pallet_path.rs | 5 +- .../empty_pallet_path.stderr | 4 +- .../exclude_undefined_part.rs | 7 +- .../exclude_undefined_part.stderr | 4 +- .../feature_gated_system_pallet.rs | 5 +- .../feature_gated_system_pallet.stderr | 8 +- .../generics_in_invalid_module.rs | 5 +- .../generics_in_invalid_module.stderr | 8 +- .../invalid_meta_literal.rs | 5 +- .../invalid_meta_literal.stderr | 8 +- .../invalid_module_details.rs | 5 +- .../invalid_module_details.stderr | 4 +- .../invalid_module_details_keyword.rs | 5 +- .../invalid_module_details_keyword.stderr | 4 +- .../invalid_module_entry.rs | 5 +- .../invalid_module_entry.stderr | 8 +- .../invalid_token_after_module.rs | 5 +- .../invalid_token_after_module.stderr | 4 +- .../invalid_token_after_name.rs | 5 +- .../invalid_token_after_name.stderr | 4 +- ...g_event_generic_on_module_with_instance.rs | 5 +- ...ent_generic_on_module_with_instance.stderr | 8 +- .../missing_module_instance.rs | 5 +- .../missing_module_instance.stderr | 4 +- ..._origin_generic_on_module_with_instance.rs | 5 +- ...gin_generic_on_module_with_instance.stderr | 8 +- .../missing_system_module.rs | 5 +- .../missing_system_module.stderr | 8 +- .../missing_where_block.rs | 7 - .../missing_where_block.stderr | 5 - .../number_of_pallets_exceeds_tuple_size.rs | 8 +- ...umber_of_pallets_exceeds_tuple_size.stderr | 18 +- .../pallet_error_too_large.rs | 8 +- .../pallet_error_too_large.stderr | 18 +- .../undefined_call_part.rs | 8 +- .../undefined_call_part.stderr | 14 +- .../undefined_event_part.rs | 8 +- .../undefined_event_part.stderr | 30 +- .../undefined_genesis_config_part.rs | 8 +- .../undefined_genesis_config_part.stderr | 30 +- .../undefined_inherent_part.rs | 8 +- .../undefined_inherent_part.stderr | 94 ++-- .../undefined_origin_part.rs | 8 +- .../undefined_origin_part.stderr | 30 +- .../undefined_validate_unsigned_part.rs | 8 +- .../undefined_validate_unsigned_part.stderr | 60 ++- .../unsupported_meta_structure.rs | 5 +- .../unsupported_meta_structure.stderr | 8 +- .../unsupported_pallet_attr.rs | 5 +- .../unsupported_pallet_attr.stderr | 8 +- .../use_undefined_part.rs | 7 +- .../use_undefined_part.stderr | 4 +- frame/support/test/tests/final_keys.rs | 40 +- frame/support/test/tests/genesisconfig.rs | 25 +- frame/support/test/tests/instance.rs | 31 +- frame/support/test/tests/issue2219.rs | 47 +- frame/support/test/tests/origin.rs | 28 +- frame/support/test/tests/pallet.rs | 8 +- frame/support/test/tests/pallet_instance.rs | 8 +- .../test/tests/pallet_outer_enums_explicit.rs | 28 +- .../test/tests/pallet_outer_enums_implicit.rs | 28 +- .../tests/pallet_ui/pass/dev_mode_valid.rs | 8 +- .../pallet_ui/pass/no_std_genesis_config.rs | 8 +- frame/support/test/tests/runtime_metadata.rs | 8 +- frame/support/test/tests/storage_layers.rs | 10 +- .../support/test/tests/storage_transaction.rs | 23 +- .../test/tests/versioned_runtime_upgrade.rs | 9 +- frame/system/benches/bench.rs | 10 +- frame/system/benchmarking/src/mock.rs | 10 +- frame/system/src/extensions/check_genesis.rs | 4 +- .../system/src/extensions/check_mortality.rs | 4 +- frame/system/src/lib.rs | 70 ++- frame/system/src/mock.rs | 10 +- frame/system/src/mocking.rs | 15 +- frame/timestamp/src/lib.rs | 2 +- frame/timestamp/src/mock.rs | 10 +- frame/tips/src/benchmarking.rs | 2 +- frame/tips/src/lib.rs | 11 +- frame/tips/src/tests.rs | 10 +- .../asset-conversion-tx-payment/src/mock.rs | 10 +- .../asset-tx-payment/src/mock.rs | 16 +- frame/transaction-payment/src/lib.rs | 2 +- frame/transaction-payment/src/mock.rs | 14 +- frame/transaction-storage/src/benchmarking.rs | 8 +- frame/transaction-storage/src/lib.rs | 14 +- frame/transaction-storage/src/mock.rs | 10 +- frame/treasury/src/benchmarking.rs | 2 +- frame/treasury/src/lib.rs | 4 +- frame/treasury/src/tests.rs | 10 +- frame/uniques/src/mock.rs | 10 +- frame/utility/src/tests.rs | 10 +- frame/vesting/src/benchmarking.rs | 10 +- frame/vesting/src/lib.rs | 43 +- frame/vesting/src/migrations.rs | 4 +- frame/vesting/src/mock.rs | 10 +- frame/whitelist/src/mock.rs | 10 +- primitives/runtime/src/generic/block.rs | 16 +- primitives/runtime/src/generic/header.rs | 9 +- primitives/runtime/src/testing.rs | 6 +- primitives/runtime/src/traits.rs | 50 +- test-utils/runtime/src/lib.rs | 8 +- utils/frame/rpc/support/src/lib.rs | 8 +- 277 files changed, 2017 insertions(+), 2450 deletions(-) create mode 100644 frame/support/test/tests/construct_runtime_ui/deprecated_where_block.rs create mode 100644 frame/support/test/tests/construct_runtime_ui/deprecated_where_block.stderr delete mode 100644 frame/support/test/tests/construct_runtime_ui/missing_where_block.rs delete mode 100644 frame/support/test/tests/construct_runtime_ui/missing_where_block.stderr diff --git a/bin/node-template/pallets/template/src/mock.rs b/bin/node-template/pallets/template/src/mock.rs index 487e076feef95..65fe3fa94327b 100644 --- a/bin/node-template/pallets/template/src/mock.rs +++ b/bin/node-template/pallets/template/src/mock.rs @@ -2,20 +2,15 @@ use crate as pallet_template; use frame_support::traits::{ConstU16, ConstU64}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, TemplateModule: pallet_template, @@ -30,12 +25,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/bin/node-template/runtime/src/lib.rs b/bin/node-template/runtime/src/lib.rs index 22fb01b62d0f0..90de167e41ea7 100644 --- a/bin/node-template/runtime/src/lib.rs +++ b/bin/node-template/runtime/src/lib.rs @@ -155,6 +155,8 @@ parameter_types! { impl frame_system::Config for Runtime { /// The basic call filter to use in dispatchable. type BaseCallFilter = frame_support::traits::Everything; + /// The block type for the runtime. + type Block = Block; /// Block & extrinsics weights: base values and limits. type BlockWeights = BlockWeights; /// The maximum length of a block (in bytes). @@ -167,14 +169,10 @@ impl frame_system::Config for Runtime { type Lookup = AccountIdLookup; /// The index type for storing how many extrinsics an account has signed. type Index = Index; - /// The index type for blocks. - type BlockNumber = BlockNumber; /// The type for hashing blocks and tries. type Hash = Hash; /// The hashing algorithm used. type Hashing = BlakeTwo256; - /// The header type. - type Header = generic::Header; /// The ubiquitous event type. type RuntimeEvent = RuntimeEvent; /// The ubiquitous origin type. @@ -278,12 +276,7 @@ impl pallet_template::Config for Runtime { // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( - pub struct Runtime - where - Block = Block, - NodeBlock = opaque::Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub struct Runtime { System: frame_system, Timestamp: pallet_timestamp, Aura: pallet_aura, diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 058f43dad00b1..6f75fff1348ff 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -227,12 +227,11 @@ impl frame_system::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = Index; - type BlockNumber = BlockNumber; type Hash = Hash; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = Indices; - type Header = generic::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type Version = Version; @@ -1868,10 +1867,7 @@ impl pallet_statement::Config for Runtime { } construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = node_primitives::Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system, Utility: pallet_utility, diff --git a/frame/alliance/src/benchmarking.rs b/frame/alliance/src/benchmarking.rs index 92bf1ae4468df..eb32c6c466c91 100644 --- a/frame/alliance/src/benchmarking.rs +++ b/frame/alliance/src/benchmarking.rs @@ -27,7 +27,7 @@ use sp_std::{ use frame_benchmarking::v1::{account, benchmarks_instance_pallet, BenchmarkError}; use frame_support::traits::{EnsureOrigin, Get, UnfilteredDispatchable}; -use frame_system::{Pallet as System, RawOrigin as SystemOrigin}; +use frame_system::{pallet_prelude::BlockNumberFor, Pallet as System, RawOrigin as SystemOrigin}; use super::{Call as AllianceCall, Pallet as Alliance, *}; @@ -432,7 +432,7 @@ benchmarks_instance_pallet! { false, )?; - System::::set_block_number(T::BlockNumber::max_value()); + System::::set_block_number(BlockNumberFor::::max_value()); }: close(SystemOrigin::Signed(voter), last_hash.clone(), index, Weight::MAX, bytes_in_storage) verify { @@ -504,7 +504,7 @@ benchmarks_instance_pallet! { } // caller is prime, prime already votes aye by creating the proposal - System::::set_block_number(T::BlockNumber::max_value()); + System::::set_block_number(BlockNumberFor::::max_value()); }: close(SystemOrigin::Signed(voter), last_hash.clone(), index, Weight::MAX, bytes_in_storage) verify { diff --git a/frame/alliance/src/lib.rs b/frame/alliance/src/lib.rs index 6dec6543babd1..c103f975f23be 100644 --- a/frame/alliance/src/lib.rs +++ b/frame/alliance/src/lib.rs @@ -309,7 +309,7 @@ pub mod pallet { /// The number of blocks a member must wait between giving a retirement notice and retiring. /// Supposed to be greater than time required to `kick_member`. - type RetirementPeriod: Get; + type RetirementPeriod: Get>; } #[pallet::error] @@ -477,7 +477,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn retiring_members)] pub type RetiringMembers, I: 'static = ()> = - StorageMap<_, Blake2_128Concat, T::AccountId, T::BlockNumber, OptionQuery>; + StorageMap<_, Blake2_128Concat, T::AccountId, BlockNumberFor, OptionQuery>; /// The current list of accounts deemed unscrupulous. These accounts non grata cannot submit /// candidacy. diff --git a/frame/alliance/src/mock.rs b/frame/alliance/src/mock.rs index ea6f4e58b1536..f141ead43ca8b 100644 --- a/frame/alliance/src/mock.rs +++ b/frame/alliance/src/mock.rs @@ -20,7 +20,6 @@ pub use sp_core::H256; use sp_runtime::traits::Hash; pub use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; @@ -53,12 +52,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = BlockNumber; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type DbWeight = (); @@ -238,14 +236,10 @@ impl Config for Test { type RetirementPeriod = RetirementPeriod; } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Balances: pallet_balances, diff --git a/frame/asset-conversion/src/lib.rs b/frame/asset-conversion/src/lib.rs index 68a0210b40058..5887295f973c3 100644 --- a/frame/asset-conversion/src/lib.rs +++ b/frame/asset-conversion/src/lib.rs @@ -72,7 +72,10 @@ use frame_support::{ ensure, traits::tokens::{AssetId, Balance}, }; -use frame_system::{ensure_signed, pallet_prelude::OriginFor}; +use frame_system::{ + ensure_signed, + pallet_prelude::{BlockNumberFor, OriginFor}, +}; pub use pallet::*; use sp_arithmetic::traits::Unsigned; use sp_runtime::{ @@ -357,7 +360,7 @@ pub mod pallet { } #[pallet::hooks] - impl Hooks for Pallet { + impl Hooks> for Pallet { fn integrity_test() { assert!( T::MaxSwapPathLength::get() > 1, diff --git a/frame/asset-conversion/src/mock.rs b/frame/asset-conversion/src/mock.rs index 35c10a22cf454..022f9d6337580 100644 --- a/frame/asset-conversion/src/mock.rs +++ b/frame/asset-conversion/src/mock.rs @@ -31,18 +31,13 @@ use frame_system::{EnsureSigned, EnsureSignedBy}; use sp_arithmetic::Permill; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{AccountIdConversion, BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Balances: pallet_balances, @@ -59,12 +54,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u128; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); diff --git a/frame/asset-rate/src/mock.rs b/frame/asset-rate/src/mock.rs index 56d52d708d57f..966eb7fad8ae5 100644 --- a/frame/asset-rate/src/mock.rs +++ b/frame/asset-rate/src/mock.rs @@ -21,19 +21,14 @@ use crate as pallet_asset_rate; use frame_support::traits::{ConstU16, ConstU64}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, AssetRate: pallet_asset_rate, @@ -49,12 +44,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/assets/src/mock.rs b/frame/assets/src/mock.rs index 7c93e5210015a..5a7b244754c8a 100644 --- a/frame/assets/src/mock.rs +++ b/frame/assets/src/mock.rs @@ -28,19 +28,14 @@ use frame_support::{ use sp_core::H256; use sp_io::storage; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -58,12 +53,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); diff --git a/frame/atomic-swap/src/lib.rs b/frame/atomic-swap/src/lib.rs index 2d93887b82596..8094c06030120 100644 --- a/frame/atomic-swap/src/lib.rs +++ b/frame/atomic-swap/src/lib.rs @@ -50,6 +50,7 @@ use frame_support::{ weights::Weight, RuntimeDebugNoBound, }; +use frame_system::pallet_prelude::BlockNumberFor; use scale_info::TypeInfo; use sp_io::hashing::blake2_256; use sp_runtime::RuntimeDebug; @@ -69,7 +70,7 @@ pub struct PendingSwap { /// Action of this swap. pub action: T::SwapAction, /// End block of the lock. - pub end_block: T::BlockNumber, + pub end_block: BlockNumberFor, } /// Hashed proof type. @@ -249,7 +250,7 @@ pub mod pallet { target: T::AccountId, hashed_proof: HashedProof, action: T::SwapAction, - duration: T::BlockNumber, + duration: BlockNumberFor, ) -> DispatchResult { let source = ensure_signed(origin)?; ensure!( diff --git a/frame/atomic-swap/src/tests.rs b/frame/atomic-swap/src/tests.rs index 7e4d8e97319e7..eaba60c41bbc0 100644 --- a/frame/atomic-swap/src/tests.rs +++ b/frame/atomic-swap/src/tests.rs @@ -6,19 +6,14 @@ use crate as pallet_atomic_swap; use frame_support::traits::{ConstU32, ConstU64}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -33,13 +28,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/aura/src/lib.rs b/frame/aura/src/lib.rs index 58c85166476f0..7a1969d905fcc 100644 --- a/frame/aura/src/lib.rs +++ b/frame/aura/src/lib.rs @@ -102,7 +102,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(_: T::BlockNumber) -> Weight { + fn on_initialize(_: BlockNumberFor) -> Weight { if let Some(new_slot) = Self::current_slot_from_digests() { let current_slot = CurrentSlot::::get(); @@ -134,7 +134,7 @@ pub mod pallet { } #[cfg(feature = "try-runtime")] - fn try_state(_: T::BlockNumber) -> Result<(), sp_runtime::TryRuntimeError> { + fn try_state(_: BlockNumberFor) -> Result<(), sp_runtime::TryRuntimeError> { Self::do_try_state() } } diff --git a/frame/aura/src/mock.rs b/frame/aura/src/mock.rs index 3fa3bec669593..eb6c08d17566a 100644 --- a/frame/aura/src/mock.rs +++ b/frame/aura/src/mock.rs @@ -26,20 +26,12 @@ use frame_support::{ }; use sp_consensus_aura::{ed25519::AuthorityId, AuthorityIndex}; use sp_core::H256; -use sp_runtime::{ - testing::{Header, UintAuthorityId}, - traits::IdentityLookup, - BuildStorage, -}; +use sp_runtime::{testing::UintAuthorityId, traits::IdentityLookup, BuildStorage}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, @@ -54,13 +46,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/authority-discovery/src/lib.rs b/frame/authority-discovery/src/lib.rs index 2b0c27740c3e6..80a35071d1e35 100644 --- a/frame/authority-discovery/src/lib.rs +++ b/frame/authority-discovery/src/lib.rs @@ -177,19 +177,15 @@ mod tests { use sp_core::{crypto::key_types, H256}; use sp_io::TestExternalities; use sp_runtime::{ - testing::{Header, UintAuthorityId}, + testing::UintAuthorityId, traits::{ConvertInto, IdentityLookup, OpaqueKeys}, BuildStorage, KeyTypeId, Perbill, }; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, @@ -236,13 +232,12 @@ mod tests { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = AuthorityId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index 73c631c36f96e..2065439439b7b 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -45,7 +45,7 @@ pub mod pallet { /// Find the author of a block. type FindAuthor: FindAuthor; /// An event handler for authored blocks. - type EventHandler: EventHandler; + type EventHandler: EventHandler>; } #[pallet::pallet] @@ -53,7 +53,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(_: T::BlockNumber) -> Weight { + fn on_initialize(_: BlockNumberFor) -> Weight { if let Some(author) = Self::author() { T::EventHandler::note_author(author); } @@ -61,7 +61,7 @@ pub mod pallet { Weight::zero() } - fn on_finalize(_: T::BlockNumber) { + fn on_finalize(_: BlockNumberFor) { // ensure we never go to trie with these values. >::kill(); } @@ -109,14 +109,10 @@ mod tests { BuildStorage, }; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Authorship: pallet_authorship::{Pallet, Storage}, @@ -130,13 +126,12 @@ mod tests { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/babe/src/equivocation.rs b/frame/babe/src/equivocation.rs index be38beb6e1682..ed1df640583b2 100644 --- a/frame/babe/src/equivocation.rs +++ b/frame/babe/src/equivocation.rs @@ -34,6 +34,7 @@ //! definition. use frame_support::traits::{Get, KeyOwnerProofSystem}; +use frame_system::pallet_prelude::HeaderFor; use log::{error, info}; use sp_consensus_babe::{AuthorityId, EquivocationProof, Slot, KEY_TYPE}; @@ -106,7 +107,7 @@ impl Offence for EquivocationOffence { pub struct EquivocationReportSystem(sp_std::marker::PhantomData<(T, R, P, L)>); impl - OffenceReportSystem, (EquivocationProof, T::KeyOwnerProof)> + OffenceReportSystem, (EquivocationProof>, T::KeyOwnerProof)> for EquivocationReportSystem where T: Config + pallet_authorship::Config + frame_system::offchain::SendTransactionTypes>, @@ -122,7 +123,7 @@ where type Longevity = L; fn publish_evidence( - evidence: (EquivocationProof, T::KeyOwnerProof), + evidence: (EquivocationProof>, T::KeyOwnerProof), ) -> Result<(), ()> { use frame_system::offchain::SubmitTransaction; let (equivocation_proof, key_owner_proof) = evidence; @@ -140,7 +141,7 @@ where } fn check_evidence( - evidence: (EquivocationProof, T::KeyOwnerProof), + evidence: (EquivocationProof>, T::KeyOwnerProof), ) -> Result<(), TransactionValidityError> { let (equivocation_proof, key_owner_proof) = evidence; @@ -159,7 +160,7 @@ where fn process_evidence( reporter: Option, - evidence: (EquivocationProof, T::KeyOwnerProof), + evidence: (EquivocationProof>, T::KeyOwnerProof), ) -> Result<(), DispatchError> { let (equivocation_proof, key_owner_proof) = evidence; let reporter = reporter.or_else(|| >::author()); diff --git a/frame/babe/src/lib.rs b/frame/babe/src/lib.rs index de9fca3b75dd7..eff56515a38d0 100644 --- a/frame/babe/src/lib.rs +++ b/frame/babe/src/lib.rs @@ -29,6 +29,7 @@ use frame_support::{ weights::Weight, BoundedVec, WeakBoundedVec, }; +use frame_system::pallet_prelude::{BlockNumberFor, HeaderFor}; use sp_consensus_babe::{ digests::{NextConfigDescriptor, NextEpochDescriptor, PreDigest}, AllowedSlots, BabeAuthorityWeight, BabeEpochConfiguration, ConsensusLog, Epoch, @@ -78,7 +79,7 @@ pub trait WeightInfo { pub trait EpochChangeTrigger { /// Trigger an epoch change, if any should take place. This should be called /// during every block, after initialization is done. - fn trigger(now: T::BlockNumber); + fn trigger(now: BlockNumberFor); } /// A type signifying to BABE that an external trigger @@ -86,7 +87,7 @@ pub trait EpochChangeTrigger { pub struct ExternalTrigger; impl EpochChangeTrigger for ExternalTrigger { - fn trigger(_: T::BlockNumber) {} // nothing - trigger is external. + fn trigger(_: BlockNumberFor) {} // nothing - trigger is external. } /// A type signifying to BABE that it should perform epoch changes @@ -94,7 +95,7 @@ impl EpochChangeTrigger for ExternalTrigger { pub struct SameAuthoritiesForever; impl EpochChangeTrigger for SameAuthoritiesForever { - fn trigger(now: T::BlockNumber) { + fn trigger(now: BlockNumberFor) { if >::should_epoch_change(now) { let authorities = >::authorities(); let next_authorities = authorities.clone(); @@ -162,7 +163,7 @@ pub mod pallet { /// (from an offchain context). type EquivocationReportSystem: OffenceReportSystem< Option, - (EquivocationProof, Self::KeyOwnerProof), + (EquivocationProof>, Self::KeyOwnerProof), >; } @@ -279,7 +280,7 @@ pub mod pallet { /// slots, which may be skipped, the block numbers may not line up with the slot numbers. #[pallet::storage] pub(super) type EpochStart = - StorageValue<_, (T::BlockNumber, T::BlockNumber), ValueQuery>; + StorageValue<_, (BlockNumberFor, BlockNumberFor), ValueQuery>; /// How late the current block is compared to its parent. /// @@ -288,7 +289,7 @@ pub mod pallet { /// execution context should always yield zero. #[pallet::storage] #[pallet::getter(fn lateness)] - pub(super) type Lateness = StorageValue<_, T::BlockNumber, ValueQuery>; + pub(super) type Lateness = StorageValue<_, BlockNumberFor, ValueQuery>; /// The configuration for the current epoch. Should never be `None` as it is initialized in /// genesis. @@ -409,7 +410,7 @@ pub mod pallet { ))] pub fn report_equivocation( origin: OriginFor, - equivocation_proof: Box>, + equivocation_proof: Box>>, key_owner_proof: T::KeyOwnerProof, ) -> DispatchResultWithPostInfo { let reporter = ensure_signed(origin)?; @@ -435,7 +436,7 @@ pub mod pallet { ))] pub fn report_equivocation_unsigned( origin: OriginFor, - equivocation_proof: Box>, + equivocation_proof: Box>>, key_owner_proof: T::KeyOwnerProof, ) -> DispatchResultWithPostInfo { ensure_none(origin)?; @@ -505,8 +506,8 @@ impl IsMember for Pallet { } } -impl pallet_session::ShouldEndSession for Pallet { - fn should_end_session(now: T::BlockNumber) -> bool { +impl pallet_session::ShouldEndSession> for Pallet { + fn should_end_session(now: BlockNumberFor) -> bool { // it might be (and it is in current implementation) that session module is calling // `should_end_session` from it's own `on_initialize` handler, in which case it's // possible that babe's own `on_initialize` has not run yet, so let's ensure that we @@ -526,7 +527,7 @@ impl Pallet { /// Determine whether an epoch change should take place at this block. /// Assumes that initialization has already taken place. - pub fn should_epoch_change(now: T::BlockNumber) -> bool { + pub fn should_epoch_change(now: BlockNumberFor) -> bool { // The epoch has technically ended during the passage of time // between this block and the last, but we have to "end" the epoch now, // since there is no earlier possible block we could have done it. @@ -556,11 +557,11 @@ impl Pallet { // // WEIGHT NOTE: This function is tied to the weight of `EstimateNextSessionRotation`. If you // update this function, you must also update the corresponding weight. - pub fn next_expected_epoch_change(now: T::BlockNumber) -> Option { + pub fn next_expected_epoch_change(now: BlockNumberFor) -> Option> { let next_slot = Self::current_epoch_start().saturating_add(T::EpochDuration::get()); next_slot.checked_sub(*CurrentSlot::::get()).map(|slots_remaining| { // This is a best effort guess. Drifts in the slot/block ratio will cause errors here. - let blocks_remaining: T::BlockNumber = slots_remaining.saturated_into(); + let blocks_remaining: BlockNumberFor = slots_remaining.saturated_into(); now.saturating_add(blocks_remaining) }) } @@ -778,7 +779,7 @@ impl Pallet { Self::deposit_consensus(ConsensusLog::NextEpochData(next)); } - fn initialize(now: T::BlockNumber) { + fn initialize(now: BlockNumberFor) { // since `initialize` can be called twice (e.g. if session module is present) // let's ensure that we only do the initialization once per block let initialized = Self::initialized().is_some(); @@ -813,7 +814,7 @@ impl Pallet { // how many slots were skipped between current and last block let lateness = current_slot.saturating_sub(CurrentSlot::::get() + 1); - let lateness = T::BlockNumber::from(*lateness as u32); + let lateness = BlockNumberFor::::from(*lateness as u32); Lateness::::put(lateness); CurrentSlot::::put(current_slot); @@ -879,7 +880,7 @@ impl Pallet { /// will push the transaction to the pool. Only useful in an offchain /// context. pub fn submit_unsigned_equivocation_report( - equivocation_proof: EquivocationProof, + equivocation_proof: EquivocationProof>, key_owner_proof: T::KeyOwnerProof, ) -> Option<()> { T::EquivocationReportSystem::publish_evidence((equivocation_proof, key_owner_proof)).ok() @@ -901,12 +902,14 @@ impl OnTimestampSet for Pallet { } } -impl frame_support::traits::EstimateNextSessionRotation for Pallet { - fn average_session_length() -> T::BlockNumber { +impl frame_support::traits::EstimateNextSessionRotation> + for Pallet +{ + fn average_session_length() -> BlockNumberFor { T::EpochDuration::get().saturated_into() } - fn estimate_current_session_progress(_now: T::BlockNumber) -> (Option, Weight) { + fn estimate_current_session_progress(_now: BlockNumberFor) -> (Option, Weight) { let elapsed = CurrentSlot::::get().saturating_sub(Self::current_epoch_start()) + 1; ( @@ -916,7 +919,9 @@ impl frame_support::traits::EstimateNextSessionRotation (Option, Weight) { + fn estimate_next_session_rotation( + now: BlockNumberFor, + ) -> (Option>, Weight) { ( Self::next_expected_epoch_change(now), // Read: Current Slot, Epoch Index, Genesis Slot @@ -925,8 +930,8 @@ impl frame_support::traits::EstimateNextSessionRotation frame_support::traits::Lateness for Pallet { - fn lateness(&self) -> T::BlockNumber { +impl frame_support::traits::Lateness> for Pallet { + fn lateness(&self) -> BlockNumberFor { Self::lateness() } } diff --git a/frame/babe/src/mock.rs b/frame/babe/src/mock.rs index 96f9ce4ff8e8d..2b1c62d20622a 100644 --- a/frame/babe/src/mock.rs +++ b/frame/babe/src/mock.rs @@ -42,14 +42,10 @@ use sp_staking::{EraIndex, SessionIndex}; type DummyValidatorId = u64; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Authorship: pallet_authorship, @@ -70,14 +66,13 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Version = (); type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = DummyValidatorId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type PalletInfo = PalletInfo; diff --git a/frame/babe/src/randomness.rs b/frame/babe/src/randomness.rs index b9b24786b7a74..d3d1bea2292da 100644 --- a/frame/babe/src/randomness.rs +++ b/frame/babe/src/randomness.rs @@ -22,6 +22,7 @@ use super::{ AuthorVrfRandomness, Config, EpochStart, NextRandomness, Randomness, RANDOMNESS_LENGTH, }; use frame_support::traits::Randomness as RandomnessT; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::traits::{Hash, One, Saturating}; /// Randomness usable by consensus protocols that **depend** upon finality and take action @@ -129,8 +130,8 @@ pub struct ParentBlockRandomness(sp_std::marker::PhantomData); Please use `ParentBlockRandomness` instead.")] pub struct CurrentBlockRandomness(sp_std::marker::PhantomData); -impl RandomnessT for RandomnessFromTwoEpochsAgo { - fn random(subject: &[u8]) -> (T::Hash, T::BlockNumber) { +impl RandomnessT> for RandomnessFromTwoEpochsAgo { + fn random(subject: &[u8]) -> (T::Hash, BlockNumberFor) { let mut subject = subject.to_vec(); subject.reserve(RANDOMNESS_LENGTH); subject.extend_from_slice(&Randomness::::get()[..]); @@ -139,8 +140,8 @@ impl RandomnessT for RandomnessFromTwoEpochs } } -impl RandomnessT for RandomnessFromOneEpochAgo { - fn random(subject: &[u8]) -> (T::Hash, T::BlockNumber) { +impl RandomnessT> for RandomnessFromOneEpochAgo { + fn random(subject: &[u8]) -> (T::Hash, BlockNumberFor) { let mut subject = subject.to_vec(); subject.reserve(RANDOMNESS_LENGTH); subject.extend_from_slice(&NextRandomness::::get()[..]); @@ -149,8 +150,8 @@ impl RandomnessT for RandomnessFromOneEpochA } } -impl RandomnessT, T::BlockNumber> for ParentBlockRandomness { - fn random(subject: &[u8]) -> (Option, T::BlockNumber) { +impl RandomnessT, BlockNumberFor> for ParentBlockRandomness { + fn random(subject: &[u8]) -> (Option, BlockNumberFor) { let random = AuthorVrfRandomness::::get().map(|random| { let mut subject = subject.to_vec(); subject.reserve(RANDOMNESS_LENGTH); @@ -164,8 +165,8 @@ impl RandomnessT, T::BlockNumber> for ParentBlockRand } #[allow(deprecated)] -impl RandomnessT, T::BlockNumber> for CurrentBlockRandomness { - fn random(subject: &[u8]) -> (Option, T::BlockNumber) { +impl RandomnessT, BlockNumberFor> for CurrentBlockRandomness { + fn random(subject: &[u8]) -> (Option, BlockNumberFor) { let (random, _) = ParentBlockRandomness::::random(subject); (random, >::block_number()) } diff --git a/frame/bags-list/src/mock.rs b/frame/bags-list/src/mock.rs index f4f29ec35912d..860a07eb7f05c 100644 --- a/frame/bags-list/src/mock.rs +++ b/frame/bags-list/src/mock.rs @@ -53,13 +53,12 @@ impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type DbWeight = (); @@ -87,13 +86,9 @@ impl bags_list::Config for Runtime { type Score = VoteWeight; } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub struct Runtime { System: frame_system::{Pallet, Call, Storage, Event, Config}, BagsList: bags_list::{Pallet, Call, Storage, Event}, diff --git a/frame/balances/README.md b/frame/balances/README.md index dd56ab3fadfb5..fa1ee622d48ce 100644 --- a/frame/balances/README.md +++ b/frame/balances/README.md @@ -94,7 +94,7 @@ The Staking module uses the `LockableCurrency` trait to lock a stash account's f use frame_support::traits::{WithdrawReasons, LockableCurrency}; use sp_runtime::traits::Bounded; pub trait Config: frame_system::Config { - type Currency: LockableCurrency; + type Currency: LockableCurrency>; } fn update_ledger( diff --git a/frame/balances/src/impl_currency.rs b/frame/balances/src/impl_currency.rs index baa153c119b20..2cbe776c51297 100644 --- a/frame/balances/src/impl_currency.rs +++ b/frame/balances/src/impl_currency.rs @@ -32,6 +32,7 @@ use frame_support::{ ReservableCurrency, SignedImbalance, TryDrop, WithdrawReasons, }, }; +use frame_system::pallet_prelude::BlockNumberFor; pub use imbalances::{NegativeImbalance, PositiveImbalance}; // wrapping these imbalances in a private module is necessary to ensure absolute privacy @@ -842,7 +843,7 @@ impl, I: 'static> LockableCurrency for Pallet where T::Balance: MaybeSerializeDeserialize + Debug, { - type Moment = T::BlockNumber; + type Moment = BlockNumberFor; type MaxLocks = T::MaxLocks; diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 206ee371e0737..e77b0f5e5d956 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -120,7 +120,7 @@ //! use frame_support::traits::{WithdrawReasons, LockableCurrency}; //! use sp_runtime::traits::Bounded; //! pub trait Config: frame_system::Config { -//! type Currency: LockableCurrency; +//! type Currency: LockableCurrency>; //! } //! # struct StakingLedger { //! # stash: ::AccountId, @@ -498,7 +498,7 @@ pub mod pallet { } #[pallet::hooks] - impl, I: 'static> Hooks for Pallet { + impl, I: 'static> Hooks> for Pallet { #[cfg(not(feature = "insecure_zero_ed"))] fn integrity_test() { assert!( diff --git a/frame/balances/src/tests/mod.rs b/frame/balances/src/tests/mod.rs index 6d9b9217ba0b0..60ea7b9eeefc5 100644 --- a/frame/balances/src/tests/mod.rs +++ b/frame/balances/src/tests/mod.rs @@ -38,7 +38,6 @@ use scale_info::TypeInfo; use sp_core::{hexdisplay::HexDisplay, H256}; use sp_io; use sp_runtime::{ - testing::Header, traits::{BadOrigin, IdentityLookup, SignedExtension, Zero}, ArithmeticError, BuildStorage, DispatchError, DispatchResult, FixedPointNumber, TokenError, }; @@ -50,7 +49,6 @@ mod fungible_conformance_tests; mod fungible_tests; mod reentrancy_tests; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; #[derive( @@ -73,10 +71,7 @@ pub enum TestId { } frame_support::construct_runtime!( - pub struct Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub struct Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -98,13 +93,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/beefy-mmr/src/lib.rs b/frame/beefy-mmr/src/lib.rs index ba416922e2563..ec1519ac41bd3 100644 --- a/frame/beefy-mmr/src/lib.rs +++ b/frame/beefy-mmr/src/lib.rs @@ -43,6 +43,7 @@ use sp_consensus_beefy::{ }; use frame_support::{crypto::ecdsa::ECDSAExt, traits::Get}; +use frame_system::pallet_prelude::BlockNumberFor; pub use pallet::*; @@ -139,7 +140,7 @@ pub mod pallet { impl LeafDataProvider for Pallet { type LeafData = MmrLeaf< - ::BlockNumber, + BlockNumberFor, ::Hash, MerkleRootOf, T::LeafExtra, diff --git a/frame/beefy-mmr/src/mock.rs b/frame/beefy-mmr/src/mock.rs index 8cb20703c63e9..af73c6a9a4966 100644 --- a/frame/beefy-mmr/src/mock.rs +++ b/frame/beefy-mmr/src/mock.rs @@ -29,7 +29,6 @@ use sp_core::H256; use sp_runtime::{ app_crypto::ecdsa::Public, impl_opaque_keys, - testing::Header, traits::{BlakeTwo256, ConvertInto, IdentityLookup, Keccak256, OpaqueKeys}, BuildStorage, }; @@ -46,14 +45,10 @@ impl_opaque_keys! { } } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, @@ -70,13 +65,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -103,7 +97,7 @@ impl pallet_session::Config for Test { } pub type MmrLeaf = sp_consensus_beefy::mmr::MmrLeaf< - ::BlockNumber, + frame_system::pallet_prelude::BlockNumberFor, ::Hash, crate::MerkleRootOf, Vec, diff --git a/frame/beefy/src/equivocation.rs b/frame/beefy/src/equivocation.rs index 96446cf1b8277..acbd3a2532d78 100644 --- a/frame/beefy/src/equivocation.rs +++ b/frame/beefy/src/equivocation.rs @@ -39,6 +39,7 @@ use frame_support::{ log, traits::{Get, KeyOwnerProofSystem}, }; +use frame_system::pallet_prelude::BlockNumberFor; use log::{error, info}; use sp_consensus_beefy::{EquivocationProof, ValidatorSetId, KEY_TYPE}; use sp_runtime::{ @@ -126,7 +127,7 @@ pub struct EquivocationReportSystem(sp_std::marker::PhantomData<(T, /// Equivocation evidence convenience alias. pub type EquivocationEvidenceFor = ( EquivocationProof< - ::BlockNumber, + BlockNumberFor, ::BeefyId, <::BeefyId as RuntimeAppPublic>::Signature, >, @@ -140,7 +141,7 @@ where R: ReportOffence< T::AccountId, P::IdentificationTuple, - EquivocationOffence, + EquivocationOffence>, >, P: KeyOwnerProofSystem<(KeyTypeId, T::BeefyId), Proof = T::KeyOwnerProof>, P::IdentificationTuple: Clone, diff --git a/frame/beefy/src/mock.rs b/frame/beefy/src/mock.rs index 5ec3bdb7e5593..1d7052a62d2c9 100644 --- a/frame/beefy/src/mock.rs +++ b/frame/beefy/src/mock.rs @@ -30,7 +30,7 @@ use sp_runtime::{ app_crypto::ecdsa::Public, curve::PiecewiseLinear, impl_opaque_keys, - testing::{Header, TestXt}, + testing::TestXt, traits::{BlakeTwo256, IdentityLookup, OpaqueKeys}, BuildStorage, Perbill, }; @@ -49,14 +49,10 @@ impl_opaque_keys! { } } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Authorship: pallet_authorship, @@ -77,13 +73,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/benchmarking/pov/src/benchmarking.rs b/frame/benchmarking/pov/src/benchmarking.rs index 1112045d9cacc..1ed446d972136 100644 --- a/frame/benchmarking/pov/src/benchmarking.rs +++ b/frame/benchmarking/pov/src/benchmarking.rs @@ -343,16 +343,11 @@ mod mock { type AccountId = u64; type AccountIndex = u32; - type BlockNumber = u64; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Baseline: crate::{Pallet, Call, Storage, Event}, @@ -366,13 +361,12 @@ mod mock { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; - type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); diff --git a/frame/benchmarking/pov/src/tests.rs b/frame/benchmarking/pov/src/tests.rs index 2136dc50b9e6f..a6101a72e9c98 100644 --- a/frame/benchmarking/pov/src/tests.rs +++ b/frame/benchmarking/pov/src/tests.rs @@ -164,14 +164,10 @@ fn noop_is_free() { mod mock { use sp_runtime::testing::H256; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Baseline: crate::{Pallet, Call, Storage, Event}, @@ -185,13 +181,12 @@ mod mock { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u32; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = u32; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); diff --git a/frame/benchmarking/src/baseline.rs b/frame/benchmarking/src/baseline.rs index a6a9fada9b2aa..6940947471e20 100644 --- a/frame/benchmarking/src/baseline.rs +++ b/frame/benchmarking/src/baseline.rs @@ -115,16 +115,11 @@ pub mod mock { type AccountId = u64; type AccountIndex = u32; - type BlockNumber = u64; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, } @@ -137,13 +132,12 @@ pub mod mock { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; - type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); diff --git a/frame/benchmarking/src/tests.rs b/frame/benchmarking/src/tests.rs index 0f22360a9431e..d4abb437a360c 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -22,7 +22,7 @@ use super::*; use frame_support::{parameter_types, traits::ConstU32}; use sp_runtime::{ - testing::{Header, H256}, + testing::H256, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; @@ -66,14 +66,10 @@ mod pallet_test { } } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, TestPallet: pallet_test::{Pallet, Call, Storage}, @@ -87,13 +83,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); diff --git a/frame/benchmarking/src/tests_instance.rs b/frame/benchmarking/src/tests_instance.rs index 1741142b17b63..2ccad38a8b746 100644 --- a/frame/benchmarking/src/tests_instance.rs +++ b/frame/benchmarking/src/tests_instance.rs @@ -22,7 +22,7 @@ use super::*; use frame_support::traits::ConstU32; use sp_runtime::{ - testing::{Header, H256}, + testing::H256, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; @@ -76,14 +76,10 @@ mod pallet_test { } } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, TestPallet: pallet_test::{Pallet, Call, Storage, Event}, @@ -97,12 +93,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type DbWeight = (); diff --git a/frame/bounties/src/benchmarking.rs b/frame/bounties/src/benchmarking.rs index 0675328c3d3c2..6fff337cba450 100644 --- a/frame/bounties/src/benchmarking.rs +++ b/frame/bounties/src/benchmarking.rs @@ -24,7 +24,7 @@ use super::*; use frame_benchmarking::v1::{ account, benchmarks_instance_pallet, whitelisted_caller, BenchmarkError, }; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use sp_runtime::traits::Bounded; use crate::Pallet as Bounties; @@ -77,7 +77,7 @@ fn create_bounty, I: 'static>( let approve_origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; Bounties::::approve_bounty(approve_origin.clone(), bounty_id)?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); Bounties::::propose_curator(approve_origin, bounty_id, curator_lookup.clone(), fee)?; Bounties::::accept_curator(RawOrigin::Signed(curator).into(), bounty_id)?; Ok((curator_lookup, bounty_id)) @@ -115,14 +115,14 @@ benchmarks_instance_pallet! { let bounty_id = BountyCount::::get() - 1; let approve_origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; Bounties::::approve_bounty(approve_origin.clone(), bounty_id)?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); }: _(approve_origin, bounty_id, curator_lookup, fee) // Worst case when curator is inactive and any sender unassigns the curator. unassign_curator { setup_pot_account::(); let (curator_lookup, bounty_id) = create_bounty::()?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); let bounty_id = BountyCount::::get() - 1; frame_system::Pallet::::set_block_number(T::BountyUpdatePeriod::get() + 2u32.into()); let caller = whitelisted_caller(); @@ -136,14 +136,14 @@ benchmarks_instance_pallet! { let bounty_id = BountyCount::::get() - 1; let approve_origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; Bounties::::approve_bounty(approve_origin.clone(), bounty_id)?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); Bounties::::propose_curator(approve_origin, bounty_id, curator_lookup, fee)?; }: _(RawOrigin::Signed(curator), bounty_id) award_bounty { setup_pot_account::(); let (curator_lookup, bounty_id) = create_bounty::()?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); let bounty_id = BountyCount::::get() - 1; let curator = T::Lookup::lookup(curator_lookup).map_err(<&str>::from)?; @@ -154,7 +154,7 @@ benchmarks_instance_pallet! { claim_bounty { setup_pot_account::(); let (curator_lookup, bounty_id) = create_bounty::()?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); let bounty_id = BountyCount::::get() - 1; let curator = T::Lookup::lookup(curator_lookup).map_err(<&str>::from)?; @@ -183,7 +183,7 @@ benchmarks_instance_pallet! { close_bounty_active { setup_pot_account::(); let (curator_lookup, bounty_id) = create_bounty::()?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); let bounty_id = BountyCount::::get() - 1; let approve_origin = T::ApproveOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; @@ -195,7 +195,7 @@ benchmarks_instance_pallet! { extend_bounty_expiry { setup_pot_account::(); let (curator_lookup, bounty_id) = create_bounty::()?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); let bounty_id = BountyCount::::get() - 1; let curator = T::Lookup::lookup(curator_lookup).map_err(<&str>::from)?; diff --git a/frame/bounties/src/lib.rs b/frame/bounties/src/lib.rs index 07ac23a9d8010..c64a35672c7f7 100644 --- a/frame/bounties/src/lib.rs +++ b/frame/bounties/src/lib.rs @@ -201,11 +201,11 @@ pub mod pallet { /// The delay period for which a bounty beneficiary need to wait before claim the payout. #[pallet::constant] - type BountyDepositPayoutDelay: Get; + type BountyDepositPayoutDelay: Get>; /// Bounty duration in blocks. #[pallet::constant] - type BountyUpdatePeriod: Get; + type BountyUpdatePeriod: Get>; /// The curator deposit is calculated as a percentage of the curator fee. /// @@ -305,7 +305,7 @@ pub mod pallet { _, Twox64Concat, BountyIndex, - Bounty, T::BlockNumber>, + Bounty, BlockNumberFor>, >; /// The description of each bounty. diff --git a/frame/bounties/src/tests.rs b/frame/bounties/src/tests.rs index 5d47b285f647b..f02c9cbffdbff 100644 --- a/frame/bounties/src/tests.rs +++ b/frame/bounties/src/tests.rs @@ -30,21 +30,16 @@ use frame_support::{ use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BadOrigin, BlakeTwo256, IdentityLookup}, BuildStorage, Perbill, Storage, }; use super::Event as BountiesEvent; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -68,13 +63,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u128; // u64 is not enough to hold bytes used to generate bounty account type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/child-bounties/src/benchmarking.rs b/frame/child-bounties/src/benchmarking.rs index e49d9c836125d..1973564d0dc1d 100644 --- a/frame/child-bounties/src/benchmarking.rs +++ b/frame/child-bounties/src/benchmarking.rs @@ -22,7 +22,7 @@ use super::*; use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller, BenchmarkError}; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use crate::Pallet as ChildBounties; use pallet_bounties::Pallet as Bounties; @@ -114,7 +114,7 @@ fn activate_bounty( let approve_origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; Bounties::::approve_bounty(approve_origin, child_bounty_setup.bounty_id)?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); Bounties::::propose_curator( RawOrigin::Root.into(), child_bounty_setup.bounty_id, @@ -229,7 +229,7 @@ benchmarks! { unassign_curator { setup_pot_account::(); let bounty_setup = activate_child_bounty::(0, T::MaximumReasonLength::get())?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); frame_system::Pallet::::set_block_number(T::BountyUpdatePeriod::get() + 1u32.into()); let caller = whitelisted_caller(); }: _(RawOrigin::Signed(caller), bounty_setup.bounty_id, @@ -303,7 +303,7 @@ benchmarks! { close_child_bounty_active { setup_pot_account::(); let bounty_setup = activate_child_bounty::(0, T::MaximumReasonLength::get())?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); }: close_child_bounty(RawOrigin::Root, bounty_setup.bounty_id, bounty_setup.child_bounty_id) verify { assert_last_event::(Event::Canceled { diff --git a/frame/child-bounties/src/lib.rs b/frame/child-bounties/src/lib.rs index 14c1907af2c46..1eedeaa5a1ae3 100644 --- a/frame/child-bounties/src/lib.rs +++ b/frame/child-bounties/src/lib.rs @@ -200,7 +200,7 @@ pub mod pallet { BountyIndex, Twox64Concat, BountyIndex, - ChildBounty, T::BlockNumber>, + ChildBounty, BlockNumberFor>, >; /// The description of each child-bounty. @@ -816,7 +816,7 @@ impl Pallet { fn ensure_bounty_active( bounty_id: BountyIndex, - ) -> Result<(T::AccountId, T::BlockNumber), DispatchError> { + ) -> Result<(T::AccountId, BlockNumberFor), DispatchError> { let parent_bounty = pallet_bounties::Pallet::::bounties(bounty_id) .ok_or(BountiesError::::InvalidIndex)?; if let BountyStatus::Active { curator, update_due } = parent_bounty.get_status() { diff --git a/frame/child-bounties/src/tests.rs b/frame/child-bounties/src/tests.rs index 2a430b30163de..60161c88f510a 100644 --- a/frame/child-bounties/src/tests.rs +++ b/frame/child-bounties/src/tests.rs @@ -31,22 +31,17 @@ use frame_support::{ use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BadOrigin, BlakeTwo256, IdentityLookup}, BuildStorage, Perbill, Permill, TokenError, }; use super::Event as ChildBountiesEvent; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; type BountiesError = pallet_bounties::Error; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -71,13 +66,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u128; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/collective/src/benchmarking.rs b/frame/collective/src/benchmarking.rs index 8a4495ef4095b..503d725105309 100644 --- a/frame/collective/src/benchmarking.rs +++ b/frame/collective/src/benchmarking.rs @@ -24,7 +24,9 @@ use sp_runtime::traits::Bounded; use sp_std::mem::size_of; use frame_benchmarking::v1::{account, benchmarks_instance_pallet, whitelisted_caller}; -use frame_system::{Call as SystemCall, Pallet as System, RawOrigin as SystemOrigin}; +use frame_system::{ + pallet_prelude::BlockNumberFor, Call as SystemCall, Pallet as System, RawOrigin as SystemOrigin, +}; const SEED: u32 = 0; @@ -516,7 +518,7 @@ benchmarks_instance_pallet! { false, )?; - System::::set_block_number(T::BlockNumber::max_value()); + System::::set_block_number(BlockNumberFor::::max_value()); assert_eq!(Collective::::proposals().len(), p as usize); // Prime nay will close it as disapproved @@ -588,7 +590,7 @@ benchmarks_instance_pallet! { } // caller is prime, prime already votes aye by creating the proposal - System::::set_block_number(T::BlockNumber::max_value()); + System::::set_block_number(BlockNumberFor::::max_value()); assert_eq!(Collective::::proposals().len(), p as usize); // Prime aye will close it as approved @@ -637,7 +639,7 @@ benchmarks_instance_pallet! { last_hash = T::Hashing::hash_of(&proposal); } - System::::set_block_number(T::BlockNumber::max_value()); + System::::set_block_number(BlockNumberFor::::max_value()); assert_eq!(Collective::::proposals().len(), p as usize); }: _(SystemOrigin::Root, last_hash) diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 6d6958666664e..1084091173934 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -201,7 +201,7 @@ pub mod pallet { + IsType<::RuntimeEvent>; /// The time-out for council motions. - type MotionDuration: Get; + type MotionDuration: Get>; /// Maximum number of proposals allowed to be active in parallel. type MaxProposals: Get; @@ -274,7 +274,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn voting)] pub type Voting, I: 'static = ()> = - StorageMap<_, Identity, T::Hash, Votes, OptionQuery>; + StorageMap<_, Identity, T::Hash, Votes>, OptionQuery>; /// Proposals so far. #[pallet::storage] diff --git a/frame/collective/src/tests.rs b/frame/collective/src/tests.rs index bf169316491b0..d67747a2b78f5 100644 --- a/frame/collective/src/tests.rs +++ b/frame/collective/src/tests.rs @@ -36,10 +36,7 @@ pub type Block = sp_runtime::generic::Block; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub enum Test { System: frame_system::{Pallet, Call, Event}, Collective: pallet_collective::::{Pallet, Call, Event, Origin, Config}, @@ -100,13 +97,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/contracts/src/exec.rs b/frame/contracts/src/exec.rs index 2c38f68b3ce08..cf37b132ddc27 100644 --- a/frame/contracts/src/exec.rs +++ b/frame/contracts/src/exec.rs @@ -34,7 +34,7 @@ use frame_support::{ weights::Weight, Blake2_128Concat, BoundedVec, StorageHasher, }; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use pallet_contracts_primitives::ExecReturnValue; use smallvec::{Array, SmallVec}; use sp_core::{ @@ -48,7 +48,6 @@ use sp_std::{marker::PhantomData, mem, prelude::*, vec::Vec}; pub type AccountIdOf = ::AccountId; pub type MomentOf = <::Time as Time>::Moment; pub type SeedOf = ::Hash; -pub type BlockNumberOf = ::BlockNumber; pub type ExecResult = Result; /// A type that represents a topic of an event. At the moment a hash is used. @@ -244,7 +243,7 @@ pub trait Ext: sealing::Sealed { fn minimum_balance(&self) -> BalanceOf; /// Returns a random number for the current block with the given subject. - fn random(&self, subject: &[u8]) -> (SeedOf, BlockNumberOf); + fn random(&self, subject: &[u8]) -> (SeedOf, BlockNumberFor); /// Deposit an event with the given topics. /// @@ -252,7 +251,7 @@ pub trait Ext: sealing::Sealed { fn deposit_event(&mut self, topics: Vec>, data: Vec); /// Returns the current block number. - fn block_number(&self) -> BlockNumberOf; + fn block_number(&self) -> BlockNumberFor; /// Returns the maximum allowed size of a storage item. fn max_value_size(&self) -> u32; @@ -400,7 +399,7 @@ pub struct Stack<'a, T: Config, E> { /// The timestamp at the point of call stack instantiation. timestamp: MomentOf, /// The block number at the time of call stack instantiation. - block_number: T::BlockNumber, + block_number: BlockNumberFor, /// The nonce is cached here when accessed. It is written back when the call stack /// finishes executing. Please refer to [`Nonce`] to a description of /// the nonce itself. @@ -1341,7 +1340,7 @@ where self.top_frame().value_transferred } - fn random(&self, subject: &[u8]) -> (SeedOf, BlockNumberOf) { + fn random(&self, subject: &[u8]) -> (SeedOf, BlockNumberFor) { T::Randomness::random(subject) } @@ -1360,7 +1359,7 @@ where ); } - fn block_number(&self) -> T::BlockNumber { + fn block_number(&self) -> BlockNumberFor { self.block_number } diff --git a/frame/contracts/src/lib.rs b/frame/contracts/src/lib.rs index f555c46859fcb..da4bd3bad230e 100644 --- a/frame/contracts/src/lib.rs +++ b/frame/contracts/src/lib.rs @@ -209,7 +209,7 @@ pub mod pallet { /// be instantiated from existing codes that use this deprecated functionality. It will /// be removed eventually. Hence for new `pallet-contracts` deployments it is okay /// to supply a dummy implementation for this type (because it is never used). - type Randomness: Randomness; + type Randomness: Randomness>; /// The currency in which fees are paid and contract balances are held. type Currency: ReservableCurrency // TODO: Move to fungible traits @@ -341,7 +341,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_idle(_block: T::BlockNumber, mut remaining_weight: Weight) -> Weight { + fn on_idle(_block: BlockNumberFor, mut remaining_weight: Weight) -> Weight { use migration::MigrateResult::*; loop { diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index f11b26bc21689..a07390329cd4d 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -50,20 +50,16 @@ use sp_core::ByteArray; use sp_io::hashing::blake2_256; use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; use sp_runtime::{ - testing::{Header, H256}, + testing::H256, traits::{BlakeTwo256, Convert, Hash, IdentityLookup}, AccountId32, BuildStorage, TokenError, }; use std::ops::Deref; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -314,13 +310,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = AccountId32; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/contracts/src/wasm/mod.rs b/frame/contracts/src/wasm/mod.rs index fa05de3f33ac0..aa37b6fea2c73 100644 --- a/frame/contracts/src/wasm/mod.rs +++ b/frame/contracts/src/wasm/mod.rs @@ -417,7 +417,7 @@ impl Executable for WasmBlob { mod tests { use super::*; use crate::{ - exec::{AccountIdOf, BlockNumberOf, ErrorOrigin, ExecError, Executable, Ext, Key, SeedOf}, + exec::{AccountIdOf, ErrorOrigin, ExecError, Executable, Ext, Key, SeedOf}, gas::GasMeter, storage::WriteOutcome, tests::{RuntimeCall, Test, ALICE, BOB}, @@ -427,6 +427,7 @@ mod tests { use frame_support::{ assert_err, assert_ok, dispatch::DispatchResultWithPostInfo, weights::Weight, }; + use frame_system::pallet_prelude::BlockNumberFor; use pallet_contracts_primitives::{ExecReturnValue, ReturnFlags}; use pretty_assertions::assert_eq; use sp_core::H256; @@ -632,7 +633,7 @@ mod tests { fn minimum_balance(&self) -> u64 { 666 } - fn random(&self, subject: &[u8]) -> (SeedOf, BlockNumberOf) { + fn random(&self, subject: &[u8]) -> (SeedOf, BlockNumberFor) { (H256::from_slice(subject), 42) } fn deposit_event(&mut self, topics: Vec, data: Vec) { diff --git a/frame/contracts/src/wasm/runtime.rs b/frame/contracts/src/wasm/runtime.rs index b2e2ed0e5401e..4c5b98d8786d0 100644 --- a/frame/contracts/src/wasm/runtime.rs +++ b/frame/contracts/src/wasm/runtime.rs @@ -2091,7 +2091,7 @@ pub mod env { /// `out_ptr`. This call overwrites it with the size of the value. If the available /// space at `out_ptr` is less than the size of the value a trap is triggered. /// - /// The data is encoded as (T::Hash, T::BlockNumber). + /// The data is encoded as (T::Hash, frame_system::pallet_prelude::BlockNumberFor::). /// /// # Changes from v0 /// diff --git a/frame/conviction-voting/src/lib.rs b/frame/conviction-voting/src/lib.rs index 3ad81486ed26d..9c2993fc5cae1 100644 --- a/frame/conviction-voting/src/lib.rs +++ b/frame/conviction-voting/src/lib.rs @@ -35,6 +35,7 @@ use frame_support::{ ReservableCurrency, WithdrawReasons, }, }; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::{ traits::{AtLeast32BitUnsigned, Saturating, StaticLookup, Zero}, ArithmeticError, Perbill, @@ -68,16 +69,13 @@ type BalanceOf = type VotingOf = Voting< BalanceOf, ::AccountId, - ::BlockNumber, + BlockNumberFor, PollIndexOf, >::MaxVotes, >; #[allow(dead_code)] -type DelegatingOf = Delegating< - BalanceOf, - ::AccountId, - ::BlockNumber, ->; +type DelegatingOf = + Delegating, ::AccountId, BlockNumberFor>; pub type TallyOf = Tally, >::MaxTurnout>; pub type VotesOf = BalanceOf; type PollIndexOf = <>::Polls as Polling>>::Index; @@ -103,14 +101,14 @@ pub mod pallet { type WeightInfo: WeightInfo; /// Currency type with which voting happens. type Currency: ReservableCurrency - + LockableCurrency + + LockableCurrency> + fungible::Inspect; /// The implementation of the logic which conducts polls. type Polls: Polling< TallyOf, Votes = BalanceOf, - Moment = Self::BlockNumber, + Moment = BlockNumberFor, >; /// The maximum amount of tokens which may be used for voting. May just be @@ -130,7 +128,7 @@ pub mod pallet { /// It should be no shorter than enactment period to ensure that in the case of an approval, /// those successful voters are locked into the consequences that their votes entail. #[pallet::constant] - type VoteLockingPeriod: Get; + type VoteLockingPeriod: Get>; } /// All voting for a particular voter in a particular voting class. We store the balance for the diff --git a/frame/conviction-voting/src/tests.rs b/frame/conviction-voting/src/tests.rs index 8f3451e28b87f..b0b692446d5d2 100644 --- a/frame/conviction-voting/src/tests.rs +++ b/frame/conviction-voting/src/tests.rs @@ -25,7 +25,6 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; @@ -33,14 +32,10 @@ use sp_runtime::{ use super::*; use crate as pallet_conviction_voting; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -63,13 +58,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/core-fellowship/src/benchmarking.rs b/frame/core-fellowship/src/benchmarking.rs index c49f50d4cc115..ea0b5c6d4495f 100644 --- a/frame/core-fellowship/src/benchmarking.rs +++ b/frame/core-fellowship/src/benchmarking.rs @@ -23,7 +23,7 @@ use super::*; use crate::Pallet as CoreFellowship; use frame_benchmarking::v2::*; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use sp_arithmetic::traits::Bounded; const SEED: u32 = 0; @@ -75,7 +75,7 @@ mod benchmarks { let member = make_member::(0)?; // Set it to the max value to ensure that any possible auto-demotion period has passed. - frame_system::Pallet::::set_block_number(T::BlockNumber::max_value()); + frame_system::Pallet::::set_block_number(BlockNumberFor::::max_value()); ensure_evidence::(&member)?; assert!(Member::::contains_key(&member)); @@ -92,7 +92,7 @@ mod benchmarks { let member = make_member::(2)?; // Set it to the max value to ensure that any possible auto-demotion period has passed. - frame_system::Pallet::::set_block_number(T::BlockNumber::max_value()); + frame_system::Pallet::::set_block_number(BlockNumberFor::::max_value()); ensure_evidence::(&member)?; assert!(Member::::contains_key(&member)); assert_eq!(T::Members::rank_of(&member), Some(2)); diff --git a/frame/core-fellowship/src/lib.rs b/frame/core-fellowship/src/lib.rs index ba02627ec11b9..8f3d9633fcf22 100644 --- a/frame/core-fellowship/src/lib.rs +++ b/frame/core-fellowship/src/lib.rs @@ -193,9 +193,8 @@ pub mod pallet { type EvidenceSize: Get; } - pub type ParamsOf = - ParamsType<>::Balance, ::BlockNumber, RANK_COUNT>; - pub type MemberStatusOf = MemberStatus<::BlockNumber>; + pub type ParamsOf = ParamsType<>::Balance, BlockNumberFor, RANK_COUNT>; + pub type MemberStatusOf = MemberStatus>; pub type RankOf = <>::Members as RankedMembers>::Rank; /// The overall status of the system. diff --git a/frame/core-fellowship/src/tests.rs b/frame/core-fellowship/src/tests.rs index ded343d997bdf..7e984c1efed34 100644 --- a/frame/core-fellowship/src/tests.rs +++ b/frame/core-fellowship/src/tests.rs @@ -28,7 +28,6 @@ use frame_support::{ use frame_system::EnsureSignedBy; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup, TryMorphInto}, BuildStorage, DispatchError, DispatchResult, }; @@ -37,14 +36,10 @@ use sp_std::cell::RefCell; use super::*; use crate as pallet_core_fellowship; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, CoreFellowship: pallet_core_fellowship::{Pallet, Call, Storage, Event}, @@ -62,13 +57,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/democracy/src/benchmarking.rs b/frame/democracy/src/benchmarking.rs index 9a67ba698a662..e4a21a4e1d9b8 100644 --- a/frame/democracy/src/benchmarking.rs +++ b/frame/democracy/src/benchmarking.rs @@ -24,7 +24,7 @@ use frame_support::{ assert_noop, assert_ok, traits::{Currency, EnsureOrigin, Get, OnInitialize, UnfilteredDispatchable}, }; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use sp_core::H256; use sp_runtime::{traits::Bounded, BoundedVec}; @@ -258,7 +258,7 @@ benchmarks! { .collect::>() .try_into() .unwrap(); - Blacklist::::insert(proposal.hash(), (T::BlockNumber::zero(), addresses)); + Blacklist::::insert(proposal.hash(), (BlockNumberFor::::zero(), addresses)); }: _(origin, proposal) verify { // External proposal created @@ -332,7 +332,7 @@ benchmarks! { vetoers.try_push(account::("vetoer", i, SEED)).unwrap(); } vetoers.sort(); - Blacklist::::insert(proposal_hash, (T::BlockNumber::zero(), vetoers)); + Blacklist::::insert(proposal_hash, (BlockNumberFor::::zero(), vetoers)); let origin = T::VetoOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; ensure!(NextExternal::::get().is_some(), "no external proposal"); @@ -816,7 +816,7 @@ benchmarks! { // create not ongoing referendum. ReferendumInfoOf::::insert( 0, - ReferendumInfo::Finished { end: T::BlockNumber::zero(), approved: true }, + ReferendumInfo::Finished { end: BlockNumberFor::::zero(), approved: true }, ); let owner = MetadataOwner::Referendum(0); let caller = funded_account::("caller", 0); @@ -833,7 +833,7 @@ benchmarks! { // create not ongoing referendum. ReferendumInfoOf::::insert( 0, - ReferendumInfo::Finished { end: T::BlockNumber::zero(), approved: true }, + ReferendumInfo::Finished { end: BlockNumberFor::::zero(), approved: true }, ); let owner = MetadataOwner::Referendum(0); let hash = note_preimage::(); diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index 690224cc87217..e538d31c6ad03 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -165,7 +165,7 @@ use frame_support::{ }, weights::Weight, }; -use frame_system::pallet_prelude::OriginFor; +use frame_system::pallet_prelude::{BlockNumberFor, OriginFor}; use sp_runtime::{ traits::{Bounded as ArithBounded, One, Saturating, StaticLookup, Zero}, ArithmeticError, DispatchError, DispatchResult, @@ -226,14 +226,14 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// The Scheduler. - type Scheduler: ScheduleNamed, Self::PalletsOrigin>; + type Scheduler: ScheduleNamed, CallOf, Self::PalletsOrigin>; /// The Preimage provider. type Preimages: QueryPreimage + StorePreimage; /// Currency type for this pallet. type Currency: ReservableCurrency - + LockableCurrency; + + LockableCurrency>; /// The period between a proposal being approved and enacted. /// @@ -241,22 +241,22 @@ pub mod pallet { /// voting stakers have an opportunity to remove themselves from the system in the case /// where they are on the losing side of a vote. #[pallet::constant] - type EnactmentPeriod: Get; + type EnactmentPeriod: Get>; /// How often (in blocks) new public referenda are launched. #[pallet::constant] - type LaunchPeriod: Get; + type LaunchPeriod: Get>; /// How often (in blocks) to check for new votes. #[pallet::constant] - type VotingPeriod: Get; + type VotingPeriod: Get>; /// The minimum period of vote locking. /// /// It should be no shorter than enactment period to ensure that in the case of an approval, /// those successful voters are locked into the consequences that their votes entail. #[pallet::constant] - type VoteLockingPeriod: Get; + type VoteLockingPeriod: Get>; /// The minimum amount to be used as a deposit for a public referendum proposal. #[pallet::constant] @@ -270,11 +270,11 @@ pub mod pallet { /// Minimum voting period allowed for a fast-track referendum. #[pallet::constant] - type FastTrackVotingPeriod: Get; + type FastTrackVotingPeriod: Get>; /// Period in blocks where an external proposal may not be re-submitted after being vetoed. #[pallet::constant] - type CooloffPeriod: Get; + type CooloffPeriod: Get>; /// The maximum number of votes for an account. /// @@ -387,7 +387,7 @@ pub mod pallet { _, Twox64Concat, ReferendumIndex, - ReferendumInfo, BalanceOf>, + ReferendumInfo, BoundedCallOf, BalanceOf>, >; /// All votes for a particular voter. We store the balance for the number of votes that we @@ -399,7 +399,7 @@ pub mod pallet { _, Twox64Concat, T::AccountId, - Voting, T::AccountId, T::BlockNumber, T::MaxVotes>, + Voting, T::AccountId, BlockNumberFor, T::MaxVotes>, ValueQuery, >; @@ -422,7 +422,7 @@ pub mod pallet { _, Identity, H256, - (T::BlockNumber, BoundedVec), + (BlockNumberFor, BoundedVec), >; /// Record of all proposals that have been subject to emergency cancellation. @@ -476,7 +476,7 @@ pub mod pallet { /// An account has cancelled a previous delegation operation. Undelegated { account: T::AccountId }, /// An external proposal has been vetoed. - Vetoed { who: T::AccountId, proposal_hash: H256, until: T::BlockNumber }, + Vetoed { who: T::AccountId, proposal_hash: H256, until: BlockNumberFor }, /// A proposal_hash has been blacklisted permanently. Blacklisted { proposal_hash: H256 }, /// An account has voted in a referendum @@ -566,7 +566,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { /// Weight: see `begin_block` - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: BlockNumberFor) -> Weight { Self::begin_block(n) } } @@ -776,8 +776,8 @@ pub mod pallet { pub fn fast_track( origin: OriginFor, proposal_hash: H256, - voting_period: T::BlockNumber, - delay: T::BlockNumber, + voting_period: BlockNumberFor, + delay: BlockNumberFor, ) -> DispatchResult { // Rather complicated bit of code to ensure that either: // - `voting_period` is at least `FastTrackVotingPeriod` and `origin` is @@ -795,7 +795,7 @@ pub mod pallet { ensure!(T::InstantAllowed::get(), Error::::InstantNotAllowed); } - ensure!(voting_period > T::BlockNumber::zero(), Error::::VotingPeriodLow); + ensure!(voting_period > Zero::zero(), Error::::VotingPeriodLow); let (ext_proposal, threshold) = >::get().ok_or(Error::::ProposalMissing)?; ensure!( @@ -1048,7 +1048,8 @@ pub mod pallet { T::BlacklistOrigin::ensure_origin(origin)?; // Insert the proposal into the blacklist. - let permanent = (T::BlockNumber::max_value(), BoundedVec::::default()); + let permanent = + (BlockNumberFor::::max_value(), BoundedVec::::default()); Blacklist::::insert(&proposal_hash, permanent); // Remove the queued proposal, if it's there. @@ -1201,17 +1202,19 @@ impl Pallet { /// Get all referenda ready for tally at block `n`. pub fn maturing_referenda_at( - n: T::BlockNumber, - ) -> Vec<(ReferendumIndex, ReferendumStatus, BalanceOf>)> { + n: BlockNumberFor, + ) -> Vec<(ReferendumIndex, ReferendumStatus, BoundedCallOf, BalanceOf>)> + { let next = Self::lowest_unbaked(); let last = Self::referendum_count(); Self::maturing_referenda_at_inner(n, next..last) } fn maturing_referenda_at_inner( - n: T::BlockNumber, + n: BlockNumberFor, range: core::ops::Range, - ) -> Vec<(ReferendumIndex, ReferendumStatus, BalanceOf>)> { + ) -> Vec<(ReferendumIndex, ReferendumStatus, BoundedCallOf, BalanceOf>)> + { range .into_iter() .map(|i| (i, Self::referendum_info(i))) @@ -1229,7 +1232,7 @@ impl Pallet { pub fn internal_start_referendum( proposal: BoundedCallOf, threshold: VoteThreshold, - delay: T::BlockNumber, + delay: BlockNumberFor, ) -> ReferendumIndex { >::inject_referendum( >::block_number().saturating_add(T::VotingPeriod::get()), @@ -1250,8 +1253,9 @@ impl Pallet { /// Ok if the given referendum is active, Err otherwise fn ensure_ongoing( - r: ReferendumInfo, BalanceOf>, - ) -> Result, BalanceOf>, DispatchError> { + r: ReferendumInfo, BoundedCallOf, BalanceOf>, + ) -> Result, BoundedCallOf, BalanceOf>, DispatchError> + { match r { ReferendumInfo::Ongoing(s) => Ok(s), _ => Err(Error::::ReferendumInvalid.into()), @@ -1260,7 +1264,8 @@ impl Pallet { fn referendum_status( ref_index: ReferendumIndex, - ) -> Result, BalanceOf>, DispatchError> { + ) -> Result, BoundedCallOf, BalanceOf>, DispatchError> + { let info = ReferendumInfoOf::::get(ref_index).ok_or(Error::::ReferendumInvalid)?; Self::ensure_ongoing(info) } @@ -1515,10 +1520,10 @@ impl Pallet { /// Start a referendum fn inject_referendum( - end: T::BlockNumber, + end: BlockNumberFor, proposal: BoundedCallOf, threshold: VoteThreshold, - delay: T::BlockNumber, + delay: BlockNumberFor, ) -> ReferendumIndex { let ref_index = Self::referendum_count(); ReferendumCount::::put(ref_index + 1); @@ -1531,7 +1536,7 @@ impl Pallet { } /// Table the next waiting proposal for a vote. - fn launch_next(now: T::BlockNumber) -> DispatchResult { + fn launch_next(now: BlockNumberFor) -> DispatchResult { if LastTabledWasExternal::::take() { Self::launch_public(now).or_else(|_| Self::launch_external(now)) } else { @@ -1541,7 +1546,7 @@ impl Pallet { } /// Table the waiting external proposal for a vote, if there is one. - fn launch_external(now: T::BlockNumber) -> DispatchResult { + fn launch_external(now: BlockNumberFor) -> DispatchResult { if let Some((proposal, threshold)) = >::take() { LastTabledWasExternal::::put(true); Self::deposit_event(Event::::ExternalTabled); @@ -1559,7 +1564,7 @@ impl Pallet { } /// Table the waiting public proposal with the highest backing for a vote. - fn launch_public(now: T::BlockNumber) -> DispatchResult { + fn launch_public(now: BlockNumberFor) -> DispatchResult { let mut public_props = Self::public_props(); if let Some((winner_index, _)) = public_props.iter().enumerate().max_by_key( // defensive only: All current public proposals have an amount locked @@ -1592,9 +1597,9 @@ impl Pallet { } fn bake_referendum( - now: T::BlockNumber, + now: BlockNumberFor, index: ReferendumIndex, - status: ReferendumStatus, BalanceOf>, + status: ReferendumStatus, BoundedCallOf, BalanceOf>, ) -> bool { let total_issuance = T::Currency::total_issuance(); let approved = status.threshold.approved(status.tally, total_issuance); @@ -1629,7 +1634,7 @@ impl Pallet { /// ## Complexity: /// If a referendum is launched or maturing, this will take full block weight if queue is not /// empty. Otherwise, `O(R)` where `R` is the number of unbaked referenda. - fn begin_block(now: T::BlockNumber) -> Weight { + fn begin_block(now: BlockNumberFor) -> Weight { let max_block_weight = T::BlockWeights::get().max_block; let mut weight = Weight::zero(); diff --git a/frame/democracy/src/migrations/v1.rs b/frame/democracy/src/migrations/v1.rs index f3d29511ff659..27a500a615cff 100644 --- a/frame/democracy/src/migrations/v1.rs +++ b/frame/democracy/src/migrations/v1.rs @@ -19,6 +19,7 @@ use crate::*; use frame_support::{pallet_prelude::*, storage_alias, traits::OnRuntimeUpgrade, BoundedVec}; +use frame_system::pallet_prelude::BlockNumberFor; use sp_core::H256; /// The log target. @@ -45,11 +46,7 @@ mod v0 { Pallet, frame_support::Twox64Concat, ReferendumIndex, - ReferendumInfo< - ::BlockNumber, - ::Hash, - BalanceOf, - >, + ReferendumInfo, ::Hash, BalanceOf>, >; } @@ -87,7 +84,7 @@ pub mod v1 { } ReferendumInfoOf::::translate( - |index, old: ReferendumInfo>| { + |index, old: ReferendumInfo, T::Hash, BalanceOf>| { weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1)); log::info!(target: TARGET, "migrating referendum #{:?}", &index); Some(match old { diff --git a/frame/democracy/src/tests.rs b/frame/democracy/src/tests.rs index dedd13dd33227..0339b46d03a9f 100644 --- a/frame/democracy/src/tests.rs +++ b/frame/democracy/src/tests.rs @@ -31,7 +31,6 @@ use frame_system::{EnsureRoot, EnsureSigned, EnsureSignedBy}; use pallet_balances::{BalanceLock, Error as BalancesError}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BadOrigin, BlakeTwo256, Hash, IdentityLookup}, BuildStorage, Perbill, }; @@ -51,14 +50,10 @@ const NAY: Vote = Vote { aye: false, conviction: Conviction::None }; const BIG_AYE: Vote = Vote { aye: true, conviction: Conviction::Locked1x }; const BIG_NAY: Vote = Vote { aye: false, conviction: Conviction::Locked1x }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -89,13 +84,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/election-provider-multi-phase/src/benchmarking.rs b/frame/election-provider-multi-phase/src/benchmarking.rs index a5946c6a1d3c1..1284d0b873ea6 100644 --- a/frame/election-provider-multi-phase/src/benchmarking.rs +++ b/frame/election-provider-multi-phase/src/benchmarking.rs @@ -313,7 +313,7 @@ frame_benchmarking::benchmarks! { assert!(>::get().is_none()); assert!(>::get().is_none()); assert!(>::get().is_none()); - assert_eq!(>::get(), >::Off); + assert_eq!(>::get(), >>::Off); } submit { diff --git a/frame/election-provider-multi-phase/src/lib.rs b/frame/election-provider-multi-phase/src/lib.rs index 1960c458b983e..03ab5574a2180 100644 --- a/frame/election-provider-multi-phase/src/lib.rs +++ b/frame/election-provider-multi-phase/src/lib.rs @@ -241,7 +241,7 @@ use frame_support::{ weights::Weight, DefaultNoBound, EqNoBound, PartialEqNoBound, }; -use frame_system::{ensure_none, offchain::SendTransactionTypes}; +use frame_system::{ensure_none, offchain::SendTransactionTypes, pallet_prelude::BlockNumberFor}; use scale_info::TypeInfo; use sp_arithmetic::{ traits::{CheckedAdd, Zero}, @@ -585,10 +585,10 @@ pub mod pallet { /// Duration of the unsigned phase. #[pallet::constant] - type UnsignedPhase: Get; + type UnsignedPhase: Get>; /// Duration of the signed phase. #[pallet::constant] - type SignedPhase: Get; + type SignedPhase: Get>; /// The minimum amount of improvement to the solution score that defines a solution as /// "better" in the Signed phase. @@ -605,7 +605,7 @@ pub mod pallet { /// For example, if it is 5, that means that at least 5 blocks will elapse between attempts /// to submit the worker's solution. #[pallet::constant] - type OffchainRepeat: Get; + type OffchainRepeat: Get>; /// The priority of the unsigned transaction submitted in the unsigned-phase #[pallet::constant] @@ -685,13 +685,13 @@ pub mod pallet { /// Something that will provide the election data. type DataProvider: ElectionDataProvider< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, >; /// Configuration for the fallback. type Fallback: InstantElectionProvider< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, DataProvider = Self::DataProvider, MaxWinners = Self::MaxWinners, >; @@ -702,7 +702,7 @@ pub mod pallet { /// BoundedExecution<_>` if the test-net is not expected to have thousands of nominators. type GovernanceFallback: InstantElectionProvider< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, DataProvider = Self::DataProvider, MaxWinners = Self::MaxWinners, >; @@ -747,7 +747,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(now: T::BlockNumber) -> Weight { + fn on_initialize(now: BlockNumberFor) -> Weight { let next_election = T::DataProvider::next_election_prediction(now).max(now); let signed_deadline = T::SignedPhase::get() + T::UnsignedPhase::get(); @@ -824,7 +824,7 @@ pub mod pallet { } } - fn offchain_worker(now: T::BlockNumber) { + fn offchain_worker(now: BlockNumberFor) { use sp_runtime::offchain::storage_lock::{BlockAndTime, StorageLock}; // Create a lock with the maximum deadline of number of blocks in the unsigned phase. @@ -886,7 +886,7 @@ pub mod pallet { } #[cfg(feature = "try-runtime")] - fn try_state(_n: T::BlockNumber) -> Result<(), TryRuntimeError> { + fn try_state(_n: BlockNumberFor) -> Result<(), TryRuntimeError> { Self::do_try_state() } } @@ -1155,7 +1155,11 @@ pub mod pallet { /// An account has been slashed for submitting an invalid signed submission. Slashed { account: ::AccountId, value: BalanceOf }, /// There was a phase transition in a given round. - PhaseTransitioned { from: Phase, to: Phase, round: u32 }, + PhaseTransitioned { + from: Phase>, + to: Phase>, + round: u32, + }, } /// Error of the pallet that can be returned in response to dispatches. @@ -1257,7 +1261,7 @@ pub mod pallet { /// Current phase. #[pallet::storage] #[pallet::getter(fn current_phase)] - pub type CurrentPhase = StorageValue<_, Phase, ValueQuery>; + pub type CurrentPhase = StorageValue<_, Phase>, ValueQuery>; /// Current best solution, signed or unsigned, queued to be returned upon `elect`. /// @@ -1349,7 +1353,7 @@ pub mod pallet { impl Pallet { /// Internal logic of the offchain worker, to be executed only when the offchain lock is /// acquired with success. - fn do_synchronized_offchain_worker(now: T::BlockNumber) { + fn do_synchronized_offchain_worker(now: BlockNumberFor) { let current_phase = Self::current_phase(); log!(trace, "lock for offchain worker acquired. Phase = {:?}", current_phase); match current_phase { @@ -1375,7 +1379,7 @@ impl Pallet { } /// Phase transition helper. - pub(crate) fn phase_transition(to: Phase) { + pub(crate) fn phase_transition(to: Phase>) { log!(info, "Starting phase {:?}, round {}.", to, Self::round()); Self::deposit_event(Event::PhaseTransitioned { from: >::get(), @@ -1672,7 +1676,7 @@ impl Pallet { impl ElectionProviderBase for Pallet { type AccountId = T::AccountId; - type BlockNumber = T::BlockNumber; + type BlockNumber = BlockNumberFor; type Error = ElectionError; type MaxWinners = T::MaxWinners; type DataProvider = T::DataProvider; diff --git a/frame/election-provider-multi-phase/src/mock.rs b/frame/election-provider-multi-phase/src/mock.rs index 6a02e26b27ab3..5dfb7f7744f4f 100644 --- a/frame/election-provider-multi-phase/src/mock.rs +++ b/frame/election-provider-multi-phase/src/mock.rs @@ -54,10 +54,7 @@ pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system::{Pallet, Call, Event, Config}, Balances: pallet_balances::{Pallet, Call, Event, Config}, @@ -212,13 +209,12 @@ impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type DbWeight = (); @@ -322,8 +318,8 @@ impl onchain::Config for OnChainSeqPhragmen { pub struct MockFallback; impl ElectionProviderBase for MockFallback { + type BlockNumber = BlockNumber; type AccountId = AccountId; - type BlockNumber = u64; type Error = &'static str; type DataProvider = StakingMock; type MaxWinners = MaxWinners; @@ -436,8 +432,8 @@ pub struct ExtBuilder {} pub struct StakingMock; impl ElectionDataProvider for StakingMock { + type BlockNumber = BlockNumber; type AccountId = AccountId; - type BlockNumber = u64; type MaxVotesPerVoter = MaxNominations; fn electable_targets(maybe_max_len: Option) -> data_provider::Result> { diff --git a/frame/election-provider-multi-phase/src/signed.rs b/frame/election-provider-multi-phase/src/signed.rs index bde985518d53e..226404e4afc1a 100644 --- a/frame/election-provider-multi-phase/src/signed.rs +++ b/frame/election-provider-multi-phase/src/signed.rs @@ -27,6 +27,7 @@ use frame_election_provider_support::NposSolution; use frame_support::traits::{ defensive_prelude::*, Currency, Get, OnUnbalanced, ReservableCurrency, }; +use frame_system::pallet_prelude::BlockNumberFor; use sp_arithmetic::traits::SaturatedConversion; use sp_core::bounded::BoundedVec; use sp_npos_elections::ElectionScore; @@ -100,10 +101,8 @@ pub type SignedSubmissionOf = SignedSubmission< /// Always sorted vector of a score, submitted at the given block number, which can be found at the /// given index (`u32`) of the `SignedSubmissionsMap`. -pub type SubmissionIndicesOf = BoundedVec< - (ElectionScore, ::BlockNumber, u32), - ::SignedMaxSubmissions, ->; +pub type SubmissionIndicesOf = + BoundedVec<(ElectionScore, BlockNumberFor, u32), ::SignedMaxSubmissions>; /// Outcome of [`SignedSubmissions::insert`]. pub enum InsertResult { @@ -216,7 +215,7 @@ impl SignedSubmissions { fn swap_out_submission( &mut self, remove_pos: usize, - insert: Option<(ElectionScore, T::BlockNumber, u32)>, + insert: Option<(ElectionScore, BlockNumberFor, u32)>, ) -> Option> { if remove_pos >= self.indices.len() { return None diff --git a/frame/election-provider-multi-phase/src/unsigned.rs b/frame/election-provider-multi-phase/src/unsigned.rs index 9c09cb48c7c05..e21e6c5e6d229 100644 --- a/frame/election-provider-multi-phase/src/unsigned.rs +++ b/frame/election-provider-multi-phase/src/unsigned.rs @@ -29,7 +29,7 @@ use frame_support::{ traits::{DefensiveResult, Get}, BoundedVec, }; -use frame_system::offchain::SubmitTransaction; +use frame_system::{offchain::SubmitTransaction, pallet_prelude::BlockNumberFor}; use scale_info::TypeInfo; use sp_npos_elections::{ assignment_ratio_to_staked_normalized, assignment_staked_to_ratio_normalized, ElectionResult, @@ -298,12 +298,12 @@ impl Pallet { /// /// Returns `Ok(())` if offchain worker limit is respected, `Err(reason)` otherwise. If `Ok()` /// is returned, `now` is written in storage and will be used in further calls as the baseline. - pub fn ensure_offchain_repeat_frequency(now: T::BlockNumber) -> Result<(), MinerError> { + pub fn ensure_offchain_repeat_frequency(now: BlockNumberFor) -> Result<(), MinerError> { let threshold = T::OffchainRepeat::get(); let last_block = StorageValueRef::persistent(OFFCHAIN_LAST_BLOCK); let mutate_stat = last_block.mutate::<_, &'static str, _>( - |maybe_head: Result, _>| { + |maybe_head: Result>, _>| { match maybe_head { Ok(Some(head)) if now < head => Err("fork."), Ok(Some(head)) if now >= head && now <= head + threshold => diff --git a/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs b/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs index f41f8babd607c..85fafa25c4c8b 100644 --- a/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs +++ b/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs @@ -46,14 +46,11 @@ pub const INIT_TIMESTAMP: u64 = 30_000; pub const BLOCK_TIME: u64 = 1000; type Block = frame_system::mocking::MockBlock; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; + type Extrinsic = testing::TestXt; frame_support::construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub enum Runtime { System: frame_system, ElectionProviderMultiPhase: pallet_election_provider_multi_phase, @@ -81,13 +78,12 @@ impl frame_system::Config for Runtime { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; - type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); diff --git a/frame/election-provider-support/src/onchain.rs b/frame/election-provider-support/src/onchain.rs index a312562d4944c..4adcf99b3345a 100644 --- a/frame/election-provider-support/src/onchain.rs +++ b/frame/election-provider-support/src/onchain.rs @@ -73,7 +73,7 @@ pub trait Config { /// Something that provides the data for election. type DataProvider: ElectionDataProvider< AccountId = ::AccountId, - BlockNumber = ::BlockNumber, + BlockNumber = frame_system::pallet_prelude::BlockNumberFor, >; /// Weight information for extrinsics in this pallet. @@ -151,7 +151,7 @@ fn elect_with_input_bounds( impl ElectionProviderBase for OnChainExecution { type AccountId = ::AccountId; - type BlockNumber = ::BlockNumber; + type BlockNumber = frame_system::pallet_prelude::BlockNumberFor; type Error = Error; type MaxWinners = T::MaxWinners; type DataProvider = T::DataProvider; @@ -197,10 +197,7 @@ mod tests { pub type Block = sp_runtime::generic::Block; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system::{Pallet, Call, Event}, } @@ -211,13 +208,12 @@ mod tests { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = AccountId; - type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = (); type BlockHashCount = (); type DbWeight = (); diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 501e50c6a7acc..55c16dfda995d 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -204,7 +204,7 @@ pub mod pallet { type PalletId: Get; /// The currency that people are electing with. - type Currency: LockableCurrency + type Currency: LockableCurrency> + ReservableCurrency; /// What to do when the members change. @@ -250,7 +250,7 @@ pub mod pallet { /// round will happen. If set to zero, no elections are ever triggered and the module will /// be in passive mode. #[pallet::constant] - type TermDuration: Get; + type TermDuration: Get>; /// The maximum number of candidates in a phragmen election. /// @@ -286,7 +286,7 @@ pub mod pallet { /// What to do at the end of each block. /// /// Checks if an election needs to happen or not. - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: BlockNumberFor) -> Weight { let term_duration = T::TermDuration::get(); if !term_duration.is_zero() && (n % term_duration).is_zero() { Self::do_phragmen() @@ -331,7 +331,7 @@ pub mod pallet { } #[cfg(feature = "try-runtime")] - fn try_state(_n: T::BlockNumber) -> Result<(), TryRuntimeError> { + fn try_state(_n: BlockNumberFor) -> Result<(), TryRuntimeError> { Self::do_try_state() } } @@ -1324,13 +1324,12 @@ mod tests { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -1447,10 +1446,7 @@ mod tests { sp_runtime::generic::UncheckedExtrinsic; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub enum Test { System: frame_system::{Pallet, Call, Event}, Balances: pallet_balances::{Pallet, Call, Event, Config}, diff --git a/frame/examples/basic/src/lib.rs b/frame/examples/basic/src/lib.rs index adb8e99c6d6a8..426e9b7ec648c 100644 --- a/frame/examples/basic/src/lib.rs +++ b/frame/examples/basic/src/lib.rs @@ -388,21 +388,21 @@ pub mod pallet { // dispatched. // // This function must return the weight consumed by `on_initialize` and `on_finalize`. - fn on_initialize(_n: T::BlockNumber) -> Weight { + fn on_initialize(_n: BlockNumberFor) -> Weight { // Anything that needs to be done at the start of the block. // We don't do anything here. Weight::zero() } // `on_finalize` is executed at the end of block after all extrinsic are dispatched. - fn on_finalize(_n: T::BlockNumber) { + fn on_finalize(_n: BlockNumberFor) { // Perform necessary data/state clean up here. } // A runtime code run after every block and have access to extended set of APIs. // // For instance you can generate extrinsics for the upcoming produced block. - fn offchain_worker(_n: T::BlockNumber) { + fn offchain_worker(_n: BlockNumberFor) { // We don't do anything here. // but we could dispatch extrinsic (transaction/unsigned/inherent) using // sp_io::submit_extrinsic. diff --git a/frame/examples/basic/src/tests.rs b/frame/examples/basic/src/tests.rs index ae985151e6665..14f4d64d5c68c 100644 --- a/frame/examples/basic/src/tests.rs +++ b/frame/examples/basic/src/tests.rs @@ -27,22 +27,17 @@ use sp_core::H256; // The testing primitives are very useful for avoiding having to work with signatures // or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; // Reexport crate as its pallet name for construct_runtime. use crate as pallet_example_basic; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; // For testing the pallet, we construct a mock runtime. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -57,13 +52,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/examples/default-config/src/lib.rs b/frame/examples/default-config/src/lib.rs index 5112f3d72d59e..a2c11e168fe27 100644 --- a/frame/examples/default-config/src/lib.rs +++ b/frame/examples/default-config/src/lib.rs @@ -107,17 +107,14 @@ pub mod pallet { pub mod tests { use super::*; use frame_support::derive_impl; + use sp_runtime::traits::ConstU64; use super::pallet as pallet_default_config_example; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, DefaultPallet: pallet_default_config_example, @@ -129,6 +126,8 @@ pub mod tests { // these items are defined by frame-system as `no_default`, so we must specify them here. // Note that these are types that actually rely on the outer runtime, and can't sensibly // have an _independent_ default. + type Block = Block; + type BlockHashCount = ConstU64<10>; type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; @@ -140,7 +139,9 @@ pub mod tests { // type Index = u32; // type BlockNumber = u32; - // type Header = sp_runtime::generic::Header; + // type Header = + // sp_runtime::generic::Header, + // Self::Hashing>; // type Hash = sp_core::hash::H256; // type Hashing = sp_runtime::traits::BlakeTwo256; // type AccountId = u64; diff --git a/frame/examples/dev-mode/src/tests.rs b/frame/examples/dev-mode/src/tests.rs index 95e02134eecc5..83f66f0031b83 100644 --- a/frame/examples/dev-mode/src/tests.rs +++ b/frame/examples/dev-mode/src/tests.rs @@ -21,22 +21,17 @@ use crate::*; use frame_support::{assert_ok, traits::ConstU64}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; // Reexport crate as its pallet name for construct_runtime. use crate as pallet_dev_mode; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; // For testing the pallet, we construct a mock runtime. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -51,13 +46,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/examples/kitchensink/src/lib.rs b/frame/examples/kitchensink/src/lib.rs index c42c7b2ec62e8..0fbffc971da62 100644 --- a/frame/examples/kitchensink/src/lib.rs +++ b/frame/examples/kitchensink/src/lib.rs @@ -183,7 +183,7 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig { pub foo: u32, - pub bar: T::BlockNumber, + pub bar: BlockNumberFor, } impl Default for GenesisConfig { @@ -249,22 +249,22 @@ pub mod pallet { /// All the possible hooks that a pallet can have. See [`frame_support::traits::Hooks`] for more /// info. #[pallet::hooks] - impl Hooks for Pallet { + impl Hooks> for Pallet { fn integrity_test() {} - fn offchain_worker(_n: T::BlockNumber) { + fn offchain_worker(_n: BlockNumberFor) { unimplemented!() } - fn on_initialize(_n: T::BlockNumber) -> Weight { + fn on_initialize(_n: BlockNumberFor) -> Weight { unimplemented!() } - fn on_finalize(_n: T::BlockNumber) { + fn on_finalize(_n: BlockNumberFor) { unimplemented!() } - fn on_idle(_n: T::BlockNumber, _remaining_weight: Weight) -> Weight { + fn on_idle(_n: BlockNumberFor, _remaining_weight: Weight) -> Weight { unimplemented!() } @@ -283,7 +283,7 @@ pub mod pallet { } #[cfg(feature = "try-runtime")] - fn try_state(_n: T::BlockNumber) -> Result<(), TryRuntimeError> { + fn try_state(_n: BlockNumberFor) -> Result<(), TryRuntimeError> { unimplemented!() } } diff --git a/frame/examples/kitchensink/src/tests.rs b/frame/examples/kitchensink/src/tests.rs index a1af5bc6c5f1a..b2af7c8983f56 100644 --- a/frame/examples/kitchensink/src/tests.rs +++ b/frame/examples/kitchensink/src/tests.rs @@ -23,15 +23,11 @@ use sp_runtime::BuildStorage; // Reexport crate as its pallet name for construct_runtime. use crate as pallet_example_kitchensink; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; // For testing the pallet, we construct a mock runtime. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -44,6 +40,8 @@ frame_support::construct_runtime!( #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU64<10>; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; diff --git a/frame/examples/offchain-worker/src/lib.rs b/frame/examples/offchain-worker/src/lib.rs index 6ce8524174200..6c1fa6ea8ec42 100644 --- a/frame/examples/offchain-worker/src/lib.rs +++ b/frame/examples/offchain-worker/src/lib.rs @@ -53,6 +53,7 @@ use frame_system::{ AppCrypto, CreateSignedTransaction, SendSignedTransaction, SendUnsignedTransaction, SignedPayload, Signer, SigningTypes, SubmitTransaction, }, + pallet_prelude::BlockNumberFor, }; use lite_json::json::JsonValue; use sp_core::crypto::KeyTypeId; @@ -136,14 +137,14 @@ pub mod pallet { /// every `GRACE_PERIOD` blocks. We use Local Storage to coordinate /// sending between distinct runs of this offchain worker. #[pallet::constant] - type GracePeriod: Get; + type GracePeriod: Get>; /// Number of blocks of cooldown after unsigned transaction is included. /// /// This ensures that we only accept unsigned transactions once, every `UnsignedInterval` /// blocks. #[pallet::constant] - type UnsignedInterval: Get; + type UnsignedInterval: Get>; /// A configuration for base priority of unsigned transactions. /// @@ -171,7 +172,7 @@ pub mod pallet { /// be cases where some blocks are skipped, or for some the worker runs twice (re-orgs), /// so the code should be able to handle that. /// You can use `Local Storage` API to coordinate runs of the worker. - fn offchain_worker(block_number: T::BlockNumber) { + fn offchain_worker(block_number: BlockNumberFor) { // Note that having logs compiled to WASM may cause the size of the blob to increase // significantly. You can use `RuntimeDebug` custom derive to hide details of the types // in WASM. The `sp-api` crate also provides a feature `disable-logging` to disable @@ -258,7 +259,7 @@ pub mod pallet { #[pallet::weight({0})] pub fn submit_price_unsigned( origin: OriginFor, - _block_number: T::BlockNumber, + _block_number: BlockNumberFor, price: u32, ) -> DispatchResultWithPostInfo { // This ensures that the function can only be called via unsigned transaction. @@ -275,7 +276,7 @@ pub mod pallet { #[pallet::weight({0})] pub fn submit_price_unsigned_with_signed_payload( origin: OriginFor, - price_payload: PricePayload, + price_payload: PricePayload>, _signature: T::Signature, ) -> DispatchResultWithPostInfo { // This ensures that the function can only be called via unsigned transaction. @@ -341,7 +342,7 @@ pub mod pallet { /// This storage entry defines when new transaction is going to be accepted. #[pallet::storage] #[pallet::getter(fn next_unsigned_at)] - pub(super) type NextUnsignedAt = StorageValue<_, T::BlockNumber, ValueQuery>; + pub(super) type NextUnsignedAt = StorageValue<_, BlockNumberFor, ValueQuery>; } /// Payload used by this example crate to hold price @@ -353,7 +354,7 @@ pub struct PricePayload { public: Public, } -impl SignedPayload for PricePayload { +impl SignedPayload for PricePayload> { fn public(&self) -> T::Public { self.public.clone() } @@ -374,7 +375,7 @@ impl Pallet { /// and local storage usage. /// /// Returns a type of transaction that should be produced in current run. - fn choose_transaction_type(block_number: T::BlockNumber) -> TransactionType { + fn choose_transaction_type(block_number: BlockNumberFor) -> TransactionType { /// A friendlier name for the error that is going to be returned in case we are in the grace /// period. const RECENTLY_SENT: () = (); @@ -389,16 +390,17 @@ impl Pallet { // low-level method of local storage API, which means that only one worker // will be able to "acquire a lock" and send a transaction if multiple workers // happen to be executed concurrently. - let res = val.mutate(|last_send: Result, StorageRetrievalError>| { - match last_send { - // If we already have a value in storage and the block number is recent enough - // we avoid sending another transaction at this time. - Ok(Some(block)) if block_number < block + T::GracePeriod::get() => - Err(RECENTLY_SENT), - // In every other case we attempt to acquire the lock and send a transaction. - _ => Ok(block_number), - } - }); + let res = + val.mutate(|last_send: Result>, StorageRetrievalError>| { + match last_send { + // If we already have a value in storage and the block number is recent enough + // we avoid sending another transaction at this time. + Ok(Some(block)) if block_number < block + T::GracePeriod::get() => + Err(RECENTLY_SENT), + // In every other case we attempt to acquire the lock and send a transaction. + _ => Ok(block_number), + } + }); // The result of `mutate` call will give us a nested `Result` type. // The first one matches the return of the closure passed to `mutate`, i.e. @@ -419,9 +421,9 @@ impl Pallet { let transaction_type = block_number % 4u32.into(); if transaction_type == Zero::zero() { TransactionType::Signed - } else if transaction_type == T::BlockNumber::from(1u32) { + } else if transaction_type == BlockNumberFor::::from(1u32) { TransactionType::UnsignedForAny - } else if transaction_type == T::BlockNumber::from(2u32) { + } else if transaction_type == BlockNumberFor::::from(2u32) { TransactionType::UnsignedForAll } else { TransactionType::Raw @@ -472,7 +474,9 @@ impl Pallet { } /// A helper function to fetch the price and send a raw unsigned transaction. - fn fetch_price_and_send_raw_unsigned(block_number: T::BlockNumber) -> Result<(), &'static str> { + fn fetch_price_and_send_raw_unsigned( + block_number: BlockNumberFor, + ) -> Result<(), &'static str> { // Make sure we don't fetch the price if unsigned transaction is going to be rejected // anyway. let next_unsigned_at = >::get(); @@ -505,7 +509,7 @@ impl Pallet { /// A helper function to fetch the price, sign payload and send an unsigned transaction fn fetch_price_and_send_unsigned_for_any_account( - block_number: T::BlockNumber, + block_number: BlockNumberFor, ) -> Result<(), &'static str> { // Make sure we don't fetch the price if unsigned transaction is going to be rejected // anyway. @@ -535,7 +539,7 @@ impl Pallet { /// A helper function to fetch the price, sign payload and send an unsigned transaction fn fetch_price_and_send_unsigned_for_all_accounts( - block_number: T::BlockNumber, + block_number: BlockNumberFor, ) -> Result<(), &'static str> { // Make sure we don't fetch the price if unsigned transaction is going to be rejected // anyway. @@ -669,7 +673,7 @@ impl Pallet { } fn validate_transaction_parameters( - block_number: &T::BlockNumber, + block_number: &BlockNumberFor, new_price: &u32, ) -> TransactionValidity { // Now let's check if the transaction has any chance to succeed. diff --git a/frame/examples/offchain-worker/src/tests.rs b/frame/examples/offchain-worker/src/tests.rs index c0ff46bafcdcc..84d9c3f972891 100644 --- a/frame/examples/offchain-worker/src/tests.rs +++ b/frame/examples/offchain-worker/src/tests.rs @@ -30,20 +30,16 @@ use sp_core::{ use sp_keystore::{testing::MemoryKeystore, Keystore, KeystoreExt}; use sp_runtime::{ - testing::{Header, TestXt}, + testing::TestXt, traits::{BlakeTwo256, Extrinsic as ExtrinsicT, IdentifyAccount, IdentityLookup, Verify}, RuntimeAppPublic, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; // For testing the module, we construct a mock runtime. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Example: example_offchain_worker::{Pallet, Call, Storage, Event, ValidateUnsigned}, @@ -58,12 +54,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = sp_core::sr25519::Public; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -274,7 +269,7 @@ fn should_submit_unsigned_transaction_on_chain_for_any_account() { let signature_valid = ::Public, - ::BlockNumber, + frame_system::pallet_prelude::BlockNumberFor, > as SignedPayload>::verify::(&price_payload, signature); assert!(signature_valid); @@ -328,7 +323,7 @@ fn should_submit_unsigned_transaction_on_chain_for_all_accounts() { let signature_valid = ::Public, - ::BlockNumber, + frame_system::pallet_prelude::BlockNumberFor, > as SignedPayload>::verify::(&price_payload, signature); assert!(signature_valid); diff --git a/frame/examples/split/src/mock.rs b/frame/examples/split/src/mock.rs index 2e117977c1418..bee3633ef68f2 100644 --- a/frame/examples/split/src/mock.rs +++ b/frame/examples/split/src/mock.rs @@ -17,16 +17,13 @@ use crate as pallet_template; use frame_support::{derive_impl, sp_runtime::BuildStorage}; +use sp_core::ConstU64; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, TemplatePallet: pallet_template, @@ -37,6 +34,8 @@ frame_support::construct_runtime!( /// details. #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { + type Block = Block; + type BlockHashCount = ConstU64<10>; type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index 61daed626b040..f758cfc841d61 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -126,6 +126,7 @@ use frame_support::{ }, weights::Weight, }; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::{ generic::Digest, traits::{ @@ -178,14 +179,17 @@ pub struct Executive< impl< System: frame_system::Config + EnsureInherentsAreFirst, - Block: traits::Block
, + Block: traits::Block< + Header = frame_system::pallet_prelude::HeaderFor, + Hash = System::Hash, + >, Context: Default, UnsignedValidator, AllPalletsWithSystem: OnRuntimeUpgrade - + OnInitialize - + OnIdle - + OnFinalize - + OffchainWorker, + + OnInitialize> + + OnIdle> + + OnFinalize> + + OffchainWorker>, COnRuntimeUpgrade: OnRuntimeUpgrade, > ExecuteBlock for Executive @@ -212,15 +216,18 @@ where #[cfg(feature = "try-runtime")] impl< System: frame_system::Config + EnsureInherentsAreFirst, - Block: traits::Block
, + Block: traits::Block< + Header = frame_system::pallet_prelude::HeaderFor, + Hash = System::Hash, + >, Context: Default, UnsignedValidator, AllPalletsWithSystem: OnRuntimeUpgrade - + OnInitialize - + OnIdle - + OnFinalize - + OffchainWorker - + frame_support::traits::TryState, + + OnInitialize> + + OnIdle> + + OnFinalize> + + OffchainWorker> + + frame_support::traits::TryState>, COnRuntimeUpgrade: OnRuntimeUpgrade, > Executive where @@ -297,10 +304,9 @@ where // run the try-state checks of all pallets, ensuring they don't alter any state. let _guard = frame_support::StorageNoopGuard::default(); - >::try_state( - *header.number(), - select, - ) + , + >>::try_state(*header.number(), select) .map_err(|e| { frame_support::log::error!(target: LOG_TARGET, "failure: {:?}", e); e @@ -350,7 +356,9 @@ where ) -> Result { if checks.try_state() { let _guard = frame_support::StorageNoopGuard::default(); - >::try_state( + , + >>::try_state( frame_system::Pallet::::block_number(), frame_try_runtime::TryStateSelect::All, )?; @@ -363,7 +371,9 @@ where if checks.try_state() { let _guard = frame_support::StorageNoopGuard::default(); - >::try_state( + , + >>::try_state( frame_system::Pallet::::block_number(), frame_try_runtime::TryStateSelect::All, )?; @@ -375,14 +385,17 @@ where impl< System: frame_system::Config + EnsureInherentsAreFirst, - Block: traits::Block
, + Block: traits::Block< + Header = frame_system::pallet_prelude::HeaderFor, + Hash = System::Hash, + >, Context: Default, UnsignedValidator, AllPalletsWithSystem: OnRuntimeUpgrade - + OnInitialize - + OnIdle - + OnFinalize - + OffchainWorker, + + OnInitialize> + + OnIdle> + + OnFinalize> + + OffchainWorker>, COnRuntimeUpgrade: OnRuntimeUpgrade, > Executive where @@ -399,14 +412,14 @@ where } /// Start the execution of a particular block. - pub fn initialize_block(header: &System::Header) { + pub fn initialize_block(header: &frame_system::pallet_prelude::HeaderFor) { sp_io::init_tracing(); sp_tracing::enter_span!(sp_tracing::Level::TRACE, "init_block"); let digests = Self::extract_pre_digest(header); Self::initialize_block_impl(header.number(), header.parent_hash(), &digests); } - fn extract_pre_digest(header: &System::Header) -> Digest { + fn extract_pre_digest(header: &frame_system::pallet_prelude::HeaderFor) -> Digest { let mut digest = ::default(); header.digest().logs().iter().for_each(|d| { if d.as_pre_runtime().is_some() { @@ -417,7 +430,7 @@ where } fn initialize_block_impl( - block_number: &System::BlockNumber, + block_number: &BlockNumberFor, parent_hash: &System::Hash, digest: &Digest, ) { @@ -432,7 +445,7 @@ where } >::initialize(block_number, parent_hash, digest); weight = weight.saturating_add(, >>::on_initialize(*block_number)); weight = weight.saturating_add( >::get().base_block, @@ -467,8 +480,8 @@ where // Check that `parent_hash` is correct. let n = *header.number(); assert!( - n > System::BlockNumber::zero() && - >::block_hash(n - System::BlockNumber::one()) == + n > BlockNumberFor::::zero() && + >::block_hash(n - BlockNumberFor::::one()) == *header.parent_hash(), "Parent hash should be valid.", ); @@ -518,7 +531,7 @@ where /// Finalize the block - it is up the caller to ensure that all header fields are valid /// except state-root. - pub fn finalize_block() -> System::Header { + pub fn finalize_block() -> frame_system::pallet_prelude::HeaderFor { sp_io::init_tracing(); sp_tracing::enter_span!(sp_tracing::Level::TRACE, "finalize_block"); >::note_finished_extrinsics(); @@ -535,7 +548,7 @@ where let remaining_weight = max_weight.saturating_sub(weight.total()); if remaining_weight.all_gt(Weight::zero()) { - let used_weight = >::on_idle( + let used_weight = >>::on_idle( block_number, remaining_weight, ); @@ -545,7 +558,7 @@ where ); } - >::on_finalize(block_number); + >>::on_finalize(block_number); } /// Apply extrinsic outside of the block execution function. @@ -585,7 +598,7 @@ where Ok(r.map(|_| ()).map_err(|e| e.error)) } - fn final_checks(header: &System::Header) { + fn final_checks(header: &frame_system::pallet_prelude::HeaderFor) { sp_tracing::enter_span!(sp_tracing::Level::TRACE, "final_checks"); // remove temporaries let new_header = >::finalize(); @@ -657,7 +670,7 @@ where } /// Start an offchain worker and generate extrinsics. - pub fn offchain_worker(header: &System::Header) { + pub fn offchain_worker(header: &frame_system::pallet_prelude::HeaderFor) { sp_io::init_tracing(); // We need to keep events available for offchain workers, // hence we initialize the block manually. @@ -671,7 +684,7 @@ where // as well. frame_system::BlockHash::::insert(header.number(), header.hash()); - >::offchain_worker( + >>::offchain_worker( *header.number(), ) } @@ -718,17 +731,17 @@ mod tests { impl Hooks> for Pallet { // module hooks. // one with block number arg and one without - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: BlockNumberFor) -> Weight { println!("on_initialize({})", n); Weight::from_parts(175, 0) } - fn on_idle(n: T::BlockNumber, remaining_weight: Weight) -> Weight { + fn on_idle(n: BlockNumberFor, remaining_weight: Weight) -> Weight { println!("on_idle{}, {})", n, remaining_weight); Weight::from_parts(175, 0) } - fn on_finalize(n: T::BlockNumber) { + fn on_finalize(n: BlockNumberFor) { println!("on_finalize({})", n); } @@ -737,8 +750,8 @@ mod tests { Weight::from_parts(200, 0) } - fn offchain_worker(n: T::BlockNumber) { - assert_eq!(T::BlockNumber::from(1u32), n); + fn offchain_worker(n: BlockNumberFor) { + assert_eq!(BlockNumberFor::::from(1u32), n); } } @@ -828,10 +841,7 @@ mod tests { } frame_support::construct_runtime!( - pub struct Runtime where - Block = TestBlock, - NodeBlock = TestBlock, - UncheckedExtrinsic = TestUncheckedExtrinsic + pub struct Runtime { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -860,12 +870,11 @@ mod tests { type RuntimeOrigin = RuntimeOrigin; type Index = u64; type RuntimeCall = RuntimeCall; - type BlockNumber = u64; type Hash = sp_core::H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = TestBlock; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = RuntimeVersion; @@ -929,7 +938,6 @@ mod tests { ); type TestXt = sp_runtime::testing::TestXt; type TestBlock = Block; - type TestUncheckedExtrinsic = TestXt; // Will contain `true` when the custom runtime logic was called. const CUSTOM_ON_RUNTIME_KEY: &[u8] = b":custom:on_runtime"; diff --git a/frame/fast-unstake/src/lib.rs b/frame/fast-unstake/src/lib.rs index 99742dbb75ae5..7620b61111cdb 100644 --- a/frame/fast-unstake/src/lib.rs +++ b/frame/fast-unstake/src/lib.rs @@ -272,8 +272,8 @@ pub mod pallet { } #[pallet::hooks] - impl Hooks for Pallet { - fn on_idle(_: T::BlockNumber, remaining_weight: Weight) -> Weight { + impl Hooks> for Pallet { + fn on_idle(_: BlockNumberFor, remaining_weight: Weight) -> Weight { if remaining_weight.any_lt(T::DbWeight::get().reads(2)) { return Weight::from_parts(0, 0) } @@ -295,7 +295,7 @@ pub mod pallet { } #[cfg(feature = "try-runtime")] - fn try_state(_n: T::BlockNumber) -> Result<(), TryRuntimeError> { + fn try_state(_n: BlockNumberFor) -> Result<(), TryRuntimeError> { // ensure that the value of `ErasToCheckPerBlock` is less than // `T::MaxErasToCheckPerBlock`. ensure!( diff --git a/frame/fast-unstake/src/mock.rs b/frame/fast-unstake/src/mock.rs index 881f3f0645571..b78d0e84dad29 100644 --- a/frame/fast-unstake/src/mock.rs +++ b/frame/fast-unstake/src/mock.rs @@ -51,13 +51,12 @@ impl frame_system::Config for Runtime { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; - type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); @@ -198,14 +197,9 @@ impl fast_unstake::Config for Runtime { } type Block = frame_system::mocking::MockBlock; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; + frame_support::construct_runtime!( - pub struct Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub struct Runtime { System: frame_system, Timestamp: pallet_timestamp, Balances: pallet_balances, diff --git a/frame/glutton/src/mock.rs b/frame/glutton/src/mock.rs index 01fdc1e46a252..b05d25ab62a3e 100644 --- a/frame/glutton/src/mock.rs +++ b/frame/glutton/src/mock.rs @@ -24,19 +24,14 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Glutton: pallet_glutton::{Pallet, Event}, @@ -50,13 +45,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/grandpa/src/equivocation.rs b/frame/grandpa/src/equivocation.rs index 5cc5cd9bd3d70..16727f79a58d5 100644 --- a/frame/grandpa/src/equivocation.rs +++ b/frame/grandpa/src/equivocation.rs @@ -37,6 +37,7 @@ use codec::{self as codec, Decode, Encode}; use frame_support::traits::{Get, KeyOwnerProofSystem}; +use frame_system::pallet_prelude::BlockNumberFor; use log::{error, info}; use sp_consensus_grandpa::{AuthorityId, EquivocationProof, RoundNumber, SetId, KEY_TYPE}; use sp_runtime::{ @@ -118,7 +119,7 @@ pub struct EquivocationReportSystem(sp_std::marker::PhantomData<(T, impl OffenceReportSystem< Option, - (EquivocationProof, T::KeyOwnerProof), + (EquivocationProof>, T::KeyOwnerProof), > for EquivocationReportSystem where T: Config + pallet_authorship::Config + frame_system::offchain::SendTransactionTypes>, @@ -134,7 +135,7 @@ where type Longevity = L; fn publish_evidence( - evidence: (EquivocationProof, T::KeyOwnerProof), + evidence: (EquivocationProof>, T::KeyOwnerProof), ) -> Result<(), ()> { use frame_system::offchain::SubmitTransaction; let (equivocation_proof, key_owner_proof) = evidence; @@ -152,7 +153,7 @@ where } fn check_evidence( - evidence: (EquivocationProof, T::KeyOwnerProof), + evidence: (EquivocationProof>, T::KeyOwnerProof), ) -> Result<(), TransactionValidityError> { let (equivocation_proof, key_owner_proof) = evidence; @@ -172,7 +173,7 @@ where fn process_evidence( reporter: Option, - evidence: (EquivocationProof, T::KeyOwnerProof), + evidence: (EquivocationProof>, T::KeyOwnerProof), ) -> Result<(), DispatchError> { let (equivocation_proof, key_owner_proof) = evidence; let reporter = reporter.or_else(|| >::author()); diff --git a/frame/grandpa/src/lib.rs b/frame/grandpa/src/lib.rs index 3348fcce2ca80..204bcfa826b77 100644 --- a/frame/grandpa/src/lib.rs +++ b/frame/grandpa/src/lib.rs @@ -42,6 +42,7 @@ use frame_support::{ weights::Weight, WeakBoundedVec, }; +use frame_system::pallet_prelude::BlockNumberFor; use scale_info::TypeInfo; use sp_consensus_grandpa::{ ConsensusLog, EquivocationProof, ScheduledChange, SetId, GRANDPA_AUTHORITIES_KEY, @@ -113,13 +114,13 @@ pub mod pallet { /// (from an offchain context). type EquivocationReportSystem: OffenceReportSystem< Option, - (EquivocationProof, Self::KeyOwnerProof), + (EquivocationProof>, Self::KeyOwnerProof), >; } #[pallet::hooks] impl Hooks> for Pallet { - fn on_finalize(block_number: T::BlockNumber) { + fn on_finalize(block_number: BlockNumberFor) { // check for scheduled pending authority set changes if let Some(pending_change) = >::get() { // emit signal if we're at the block that scheduled the change @@ -191,7 +192,7 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::report_equivocation(key_owner_proof.validator_count()))] pub fn report_equivocation( origin: OriginFor, - equivocation_proof: Box>, + equivocation_proof: Box>>, key_owner_proof: T::KeyOwnerProof, ) -> DispatchResultWithPostInfo { let reporter = ensure_signed(origin)?; @@ -217,7 +218,7 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::report_equivocation(key_owner_proof.validator_count()))] pub fn report_equivocation_unsigned( origin: OriginFor, - equivocation_proof: Box>, + equivocation_proof: Box>>, key_owner_proof: T::KeyOwnerProof, ) -> DispatchResultWithPostInfo { ensure_none(origin)?; @@ -245,8 +246,8 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::note_stalled())] pub fn note_stalled( origin: OriginFor, - delay: T::BlockNumber, - best_finalized_block_number: T::BlockNumber, + delay: BlockNumberFor, + best_finalized_block_number: BlockNumberFor, ) -> DispatchResult { ensure_root(origin)?; @@ -287,7 +288,7 @@ pub mod pallet { } #[pallet::type_value] - pub(super) fn DefaultForState() -> StoredState { + pub(super) fn DefaultForState() -> StoredState> { StoredState::Live } @@ -295,23 +296,23 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn state)] pub(super) type State = - StorageValue<_, StoredState, ValueQuery, DefaultForState>; + StorageValue<_, StoredState>, ValueQuery, DefaultForState>; /// Pending change: (signaled at, scheduled change). #[pallet::storage] #[pallet::getter(fn pending_change)] pub(super) type PendingChange = - StorageValue<_, StoredPendingChange>; + StorageValue<_, StoredPendingChange, T::MaxAuthorities>>; /// next block number where we can force a change. #[pallet::storage] #[pallet::getter(fn next_forced)] - pub(super) type NextForced = StorageValue<_, T::BlockNumber>; + pub(super) type NextForced = StorageValue<_, BlockNumberFor>; /// `true` if we are currently stalled. #[pallet::storage] #[pallet::getter(fn stalled)] - pub(super) type Stalled = StorageValue<_, (T::BlockNumber, T::BlockNumber)>; + pub(super) type Stalled = StorageValue<_, (BlockNumberFor, BlockNumberFor)>; /// The number of changes (both in terms of keys and underlying economic responsibilities) /// in the "set" of Grandpa validators from genesis. @@ -429,7 +430,7 @@ impl Pallet { /// Schedule GRANDPA to pause starting in the given number of blocks. /// Cannot be done when already paused. - pub fn schedule_pause(in_blocks: T::BlockNumber) -> DispatchResult { + pub fn schedule_pause(in_blocks: BlockNumberFor) -> DispatchResult { if let StoredState::Live = >::get() { let scheduled_at = >::block_number(); >::put(StoredState::PendingPause { delay: in_blocks, scheduled_at }); @@ -441,7 +442,7 @@ impl Pallet { } /// Schedule a resume of GRANDPA after pausing. - pub fn schedule_resume(in_blocks: T::BlockNumber) -> DispatchResult { + pub fn schedule_resume(in_blocks: BlockNumberFor) -> DispatchResult { if let StoredState::Paused = >::get() { let scheduled_at = >::block_number(); >::put(StoredState::PendingResume { delay: in_blocks, scheduled_at }); @@ -468,8 +469,8 @@ impl Pallet { /// an error if a change is already pending. pub fn schedule_change( next_authorities: AuthorityList, - in_blocks: T::BlockNumber, - forced: Option, + in_blocks: BlockNumberFor, + forced: Option>, ) -> DispatchResult { if !>::exists() { let scheduled_at = >::block_number(); @@ -506,7 +507,7 @@ impl Pallet { } /// Deposit one of this module's logs. - fn deposit_log(log: ConsensusLog) { + fn deposit_log(log: ConsensusLog>) { let log = DigestItem::Consensus(GRANDPA_ENGINE_ID, log.encode()); >::deposit_log(log); } @@ -530,13 +531,13 @@ impl Pallet { /// will push the transaction to the pool. Only useful in an offchain /// context. pub fn submit_unsigned_equivocation_report( - equivocation_proof: EquivocationProof, + equivocation_proof: EquivocationProof>, key_owner_proof: T::KeyOwnerProof, ) -> Option<()> { T::EquivocationReportSystem::publish_evidence((equivocation_proof, key_owner_proof)).ok() } - fn on_stalled(further_wait: T::BlockNumber, median: T::BlockNumber) { + fn on_stalled(further_wait: BlockNumberFor, median: BlockNumberFor) { // when we record old authority sets we could try to figure out _who_ // failed. until then, we can't meaningfully guard against // `next == last` the way that normal session changes do. diff --git a/frame/grandpa/src/mock.rs b/frame/grandpa/src/mock.rs index d5a54a9fcfd51..47d07c73904b8 100644 --- a/frame/grandpa/src/mock.rs +++ b/frame/grandpa/src/mock.rs @@ -34,20 +34,16 @@ use sp_keyring::Ed25519Keyring; use sp_runtime::{ curve::PiecewiseLinear, impl_opaque_keys, - testing::{Header, TestXt, UintAuthorityId}, + testing::{TestXt, UintAuthorityId}, traits::{IdentityLookup, OpaqueKeys}, BuildStorage, DigestItem, Perbill, }; use sp_staking::{EraIndex, SessionIndex}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Authorship: pallet_authorship, @@ -74,13 +70,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/identity/src/tests.rs b/frame/identity/src/tests.rs index 2c0352ac1cea5..57b372ef57912 100644 --- a/frame/identity/src/tests.rs +++ b/frame/identity/src/tests.rs @@ -29,19 +29,14 @@ use frame_support::{ use frame_system::{EnsureRoot, EnsureSignedBy}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BadOrigin, BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -55,13 +50,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); diff --git a/frame/im-online/src/benchmarking.rs b/frame/im-online/src/benchmarking.rs index 4766e5edaadcf..d8170d4817e3e 100644 --- a/frame/im-online/src/benchmarking.rs +++ b/frame/im-online/src/benchmarking.rs @@ -36,7 +36,10 @@ const MAX_KEYS: u32 = 1000; pub fn create_heartbeat( k: u32, ) -> Result< - (crate::Heartbeat, ::Signature), + ( + crate::Heartbeat>, + ::Signature, + ), &'static str, > { let mut keys = Vec::new(); @@ -48,7 +51,7 @@ pub fn create_heartbeat( Keys::::put(bounded_keys); let input_heartbeat = Heartbeat { - block_number: T::BlockNumber::zero(), + block_number: frame_system::pallet_prelude::BlockNumberFor::::zero(), session_index: 0, authority_index: k - 1, validators_len: keys.len() as u32, diff --git a/frame/im-online/src/lib.rs b/frame/im-online/src/lib.rs index 23785c7b540c6..1de89dd00c812 100644 --- a/frame/im-online/src/lib.rs +++ b/frame/im-online/src/lib.rs @@ -245,7 +245,7 @@ pub type IdentificationTuple = ( >>::Identification, ); -type OffchainResult = Result::BlockNumber>>; +type OffchainResult = Result>>; #[frame_support::pallet] pub mod pallet { @@ -287,7 +287,7 @@ pub mod pallet { /// rough time when we should start considering sending heartbeats, since the workers /// avoids sending them at the very beginning of the session, assuming there is a /// chance the authority will produce a block and they won't be necessary. - type NextSessionRotation: EstimateNextSessionRotation; + type NextSessionRotation: EstimateNextSessionRotation>; /// A type that gives us the ability to submit unresponsiveness offence reports. type ReportUnresponsiveness: ReportOffence< @@ -339,7 +339,7 @@ pub mod pallet { /// more accurate then the value we calculate for `HeartbeatAfter`. #[pallet::storage] #[pallet::getter(fn heartbeat_after)] - pub(super) type HeartbeatAfter = StorageValue<_, T::BlockNumber, ValueQuery>; + pub(super) type HeartbeatAfter = StorageValue<_, BlockNumberFor, ValueQuery>; /// The current set of keys that may issue a heartbeat. #[pallet::storage] @@ -393,7 +393,7 @@ pub mod pallet { ))] pub fn heartbeat( origin: OriginFor, - heartbeat: Heartbeat, + heartbeat: Heartbeat>, // since signature verification is done in `validate_unsigned` // we can skip doing it here again. _signature: ::Signature, @@ -505,7 +505,7 @@ pub mod pallet { /// Keep track of number of authored blocks per authority, uncles are counted as /// well since they're a valid proof of being online. impl - pallet_authorship::EventHandler, T::BlockNumber> for Pallet + pallet_authorship::EventHandler, BlockNumberFor> for Pallet { fn note_author(author: ValidatorId) { Self::note_authorship(author); @@ -551,7 +551,7 @@ impl Pallet { } pub(crate) fn send_heartbeats( - block_number: T::BlockNumber, + block_number: BlockNumberFor, ) -> OffchainResult>> { const START_HEARTBEAT_RANDOM_PERIOD: Permill = Permill::from_percent(10); const START_HEARTBEAT_FINAL_PERIOD: Permill = Permill::from_percent(80); @@ -614,7 +614,7 @@ impl Pallet { authority_index: u32, key: T::AuthorityId, session_index: SessionIndex, - block_number: T::BlockNumber, + block_number: BlockNumberFor, validators_len: u32, ) -> OffchainResult { // A helper function to prepare heartbeat call. @@ -677,7 +677,7 @@ impl Pallet { fn with_heartbeat_lock( authority_index: u32, session_index: SessionIndex, - now: T::BlockNumber, + now: BlockNumberFor, f: impl FnOnce() -> OffchainResult, ) -> OffchainResult { let key = { @@ -687,7 +687,7 @@ impl Pallet { }; let storage = StorageValueRef::persistent(&key); let res = storage.mutate( - |status: Result>, StorageRetrievalError>| { + |status: Result>>, StorageRetrievalError>| { // Check if there is already a lock for that particular block. // This means that the heartbeat has already been sent, and we are just waiting // for it to be included. However if it doesn't get included for INCLUDE_THRESHOLD diff --git a/frame/im-online/src/mock.rs b/frame/im-online/src/mock.rs index 141df6569b2ec..6cc134c98ac6e 100644 --- a/frame/im-online/src/mock.rs +++ b/frame/im-online/src/mock.rs @@ -27,7 +27,7 @@ use frame_support::{ use pallet_session::historical as pallet_session_historical; use sp_core::H256; use sp_runtime::{ - testing::{Header, TestXt, UintAuthorityId}, + testing::{TestXt, UintAuthorityId}, traits::{BlakeTwo256, ConvertInto, IdentityLookup}, BuildStorage, Permill, }; @@ -39,14 +39,10 @@ use sp_staking::{ use crate as imonline; use crate::Config; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub struct Runtime { System: frame_system::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, @@ -124,13 +120,12 @@ impl frame_system::Config for Runtime { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/indices/src/mock.rs b/frame/indices/src/mock.rs index c7784092cae4a..3e7d6240b1087 100644 --- a/frame/indices/src/mock.rs +++ b/frame/indices/src/mock.rs @@ -22,16 +22,12 @@ use crate::{self as pallet_indices, Config}; use frame_support::traits::{ConstU32, ConstU64}; use sp_core::H256; -use sp_runtime::{testing::Header, BuildStorage}; +use sp_runtime::BuildStorage; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -47,12 +43,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = Indices; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/insecure-randomness-collective-flip/src/lib.rs b/frame/insecure-randomness-collective-flip/src/lib.rs index 883c546f441c2..13dff14da7b9b 100644 --- a/frame/insecure-randomness-collective-flip/src/lib.rs +++ b/frame/insecure-randomness-collective-flip/src/lib.rs @@ -74,11 +74,12 @@ use safe_mix::TripletMix; use codec::Encode; use frame_support::{pallet_prelude::Weight, traits::Randomness}; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::traits::{Hash, Saturating}; const RANDOM_MATERIAL_LEN: u32 = 81; -fn block_number_to_index(block_number: T::BlockNumber) -> usize { +fn block_number_to_index(block_number: BlockNumberFor) -> usize { // on_initialize is called on the first block after genesis let index = (block_number - 1u32.into()) % RANDOM_MATERIAL_LEN.into(); index.try_into().ok().expect("Something % 81 is always smaller than usize; qed") @@ -90,7 +91,6 @@ pub use pallet::*; pub mod pallet { use super::*; use frame_support::pallet_prelude::*; - use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -100,7 +100,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(block_number: T::BlockNumber) -> Weight { + fn on_initialize(block_number: BlockNumberFor) -> Weight { let parent_hash = >::parent_hash(); >::mutate(|ref mut values| { @@ -123,7 +123,7 @@ pub mod pallet { StorageValue<_, BoundedVec>, ValueQuery>; } -impl Randomness for Pallet { +impl Randomness> for Pallet { /// This randomness uses a low-influence function, drawing upon the block hashes from the /// previous 81 blocks. Its result for any given subject will be known far in advance by anyone /// observing the chain. Any block producer has significant influence over their block hashes @@ -134,7 +134,7 @@ impl Randomness for Pallet { /// WARNING: Hashing the result of this function will remove any low-influence properties it has /// and mean that all bits of the resulting value are entirely manipulatable by the author of /// the parent block, who can determine the value of `parent_hash`. - fn random(subject: &[u8]) -> (T::Hash, T::BlockNumber) { + fn random(subject: &[u8]) -> (T::Hash, BlockNumberFor) { let block_number = >::block_number(); let index = block_number_to_index::(block_number); @@ -164,7 +164,6 @@ mod tests { use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, Header as _, IdentityLookup}, BuildStorage, }; @@ -175,14 +174,10 @@ mod tests { }; use frame_system::limits; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, CollectiveFlip: pallet_insecure_randomness_collective_flip::{Pallet, Storage}, @@ -201,13 +196,12 @@ mod tests { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/lottery/src/lib.rs b/frame/lottery/src/lib.rs index 178f221a8946f..a6a94b4ab19af 100644 --- a/frame/lottery/src/lib.rs +++ b/frame/lottery/src/lib.rs @@ -142,7 +142,7 @@ pub mod pallet { type Currency: ReservableCurrency; /// Something that provides randomness in the runtime. - type Randomness: Randomness; + type Randomness: Randomness>; /// The overarching event type. type RuntimeEvent: From> + IsType<::RuntimeEvent>; @@ -208,7 +208,7 @@ pub mod pallet { /// The configuration for the current lottery. #[pallet::storage] pub(crate) type Lottery = - StorageValue<_, LotteryConfig>>; + StorageValue<_, LotteryConfig, BalanceOf>>; /// Users who have purchased a ticket. (Lottery Index, Tickets Purchased) #[pallet::storage] @@ -239,7 +239,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: BlockNumberFor) -> Weight { Lottery::::mutate(|mut lottery| -> Weight { if let Some(config) = &mut lottery { let payout_block = @@ -350,8 +350,8 @@ pub mod pallet { pub fn start_lottery( origin: OriginFor, price: BalanceOf, - length: T::BlockNumber, - delay: T::BlockNumber, + length: BlockNumberFor, + delay: BlockNumberFor, repeat: bool, ) -> DispatchResult { T::ManagerOrigin::ensure_origin(origin)?; diff --git a/frame/lottery/src/mock.rs b/frame/lottery/src/mock.rs index b0a0d9b916512..5578c0add1d1e 100644 --- a/frame/lottery/src/mock.rs +++ b/frame/lottery/src/mock.rs @@ -28,19 +28,14 @@ use frame_support_test::TestRandomness; use frame_system::EnsureRoot; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, Perbill, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -60,12 +55,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type Index = u64; type RuntimeCall = RuntimeCall; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index fd1fe7424f974..4f4bc9fdda982 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -525,7 +525,6 @@ mod tests { use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BadOrigin, BlakeTwo256, IdentityLookup}, BuildStorage, }; @@ -536,14 +535,10 @@ mod tests { }; use frame_system::EnsureSignedBy; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Membership: pallet_membership::{Pallet, Call, Storage, Config, Event}, @@ -562,13 +557,12 @@ mod tests { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/merkle-mountain-range/src/lib.rs b/frame/merkle-mountain-range/src/lib.rs index 3adad1e955481..2edef9a35d57a 100644 --- a/frame/merkle-mountain-range/src/lib.rs +++ b/frame/merkle-mountain-range/src/lib.rs @@ -57,6 +57,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use frame_support::{log, weights::Weight}; +use frame_system::pallet_prelude::{BlockNumberFor, HeaderFor}; use sp_mmr_primitives::utils; use sp_runtime::{ traits::{self, One, Saturating}, @@ -91,7 +92,7 @@ pub struct ParentNumberAndHash { } impl LeafDataProvider for ParentNumberAndHash { - type LeafData = (::BlockNumber, ::Hash); + type LeafData = (BlockNumberFor, ::Hash); fn leaf_data() -> Self::LeafData { ( @@ -120,7 +121,6 @@ pub(crate) type HashOf = <>::Hashing as traits::Hash>::Outp pub mod pallet { use super::*; use frame_support::pallet_prelude::*; - use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(PhantomData<(T, I)>); @@ -201,7 +201,7 @@ pub mod pallet { #[pallet::hooks] impl, I: 'static> Hooks> for Pallet { - fn on_initialize(_n: T::BlockNumber) -> Weight { + fn on_initialize(_n: BlockNumberFor) -> Weight { use primitives::LeafDataProvider; let leaves = Self::mmr_leaves(); let peaks_before = sp_mmr_primitives::utils::NodesUtils::new(leaves).number_of_peaks(); @@ -266,11 +266,7 @@ impl, I: 'static> Pallet { pos: NodeIndex, parent_hash: ::Hash, ) -> sp_std::prelude::Vec { - NodesUtils::node_temp_offchain_key::<::Header>( - &T::INDEXING_PREFIX, - pos, - parent_hash, - ) + NodesUtils::node_temp_offchain_key::>(&T::INDEXING_PREFIX, pos, parent_hash) } /// Build canonical offchain key for node `pos` in MMR. @@ -286,7 +282,7 @@ impl, I: 'static> Pallet { fn leaf_index_to_parent_block_num( leaf_index: LeafIndex, leaves_count: LeafIndex, - ) -> ::BlockNumber { + ) -> BlockNumberFor { // leaves are zero-indexed and were added one per block since pallet activation, // while block numbers are one-indexed, so block number that added `leaf_idx` is: // `block_num = block_num_when_pallet_activated + leaf_idx + 1` @@ -298,16 +294,16 @@ impl, I: 'static> Pallet { } /// Convert a block number into a leaf index. - fn block_num_to_leaf_index(block_num: T::BlockNumber) -> Result + fn block_num_to_leaf_index(block_num: BlockNumberFor) -> Result where T: frame_system::Config, { - let first_mmr_block = utils::first_mmr_block_num::( + let first_mmr_block = utils::first_mmr_block_num::>( >::block_number(), Self::mmr_leaves(), )?; - utils::block_num_to_leaf_index::(block_num, first_mmr_block) + utils::block_num_to_leaf_index::>(block_num, first_mmr_block) } /// Generate an MMR proof for the given `block_numbers`. @@ -320,8 +316,8 @@ impl, I: 'static> Pallet { /// all the leaves to be present. /// It may return an error or panic if used incorrectly. pub fn generate_proof( - block_numbers: Vec, - best_known_block_number: Option, + block_numbers: Vec>, + best_known_block_number: Option>, ) -> Result<(Vec>, primitives::Proof>), primitives::Error> { // check whether best_known_block_number provided, else use current best block let best_known_block_number = diff --git a/frame/merkle-mountain-range/src/mock.rs b/frame/merkle-mountain-range/src/mock.rs index 2c7b422c62ee3..286b0b2084a6d 100644 --- a/frame/merkle-mountain-range/src/mock.rs +++ b/frame/merkle-mountain-range/src/mock.rs @@ -25,19 +25,12 @@ use frame_support::{ }; use sp_core::H256; use sp_mmr_primitives::{Compact, LeafDataProvider}; -use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, IdentityLookup, Keccak256}, -}; +use sp_runtime::traits::{BlakeTwo256, IdentityLookup, Keccak256}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, MMR: pallet_mmr::{Pallet, Storage}, @@ -49,12 +42,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = sp_core::sr25519::Public; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); diff --git a/frame/merkle-mountain-range/src/tests.rs b/frame/merkle-mountain-range/src/tests.rs index 2f02fc09150f6..429df75182eee 100644 --- a/frame/merkle-mountain-range/src/tests.rs +++ b/frame/merkle-mountain-range/src/tests.rs @@ -54,7 +54,7 @@ pub(crate) fn hex(s: &str) -> H256 { s.parse().unwrap() } -type BlockNumber = ::BlockNumber; +type BlockNumber = frame_system::pallet_prelude::BlockNumberFor; fn decode_node( v: Vec, diff --git a/frame/message-queue/src/integration_test.rs b/frame/message-queue/src/integration_test.rs index 3716597731eca..2b9e9a0a7878c 100644 --- a/frame/message-queue/src/integration_test.rs +++ b/frame/message-queue/src/integration_test.rs @@ -37,20 +37,13 @@ use frame_support::{ use rand::{rngs::StdRng, Rng, SeedableRng}; use rand_distr::Pareto; use sp_core::H256; -use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, IdentityLookup}, -}; +use sp_runtime::traits::{BlakeTwo256, IdentityLookup}; use std::collections::{BTreeMap, BTreeSet}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event}, @@ -64,13 +57,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/message-queue/src/mock.rs b/frame/message-queue/src/mock.rs index f2a0ca1b494c3..8c2ba8805aaad 100644 --- a/frame/message-queue/src/mock.rs +++ b/frame/message-queue/src/mock.rs @@ -29,20 +29,15 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; use sp_std::collections::btree_map::BTreeMap; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event}, @@ -55,13 +50,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -289,7 +283,7 @@ impl QueuePausedQuery for MockedQueuePauser { /// Is generic since it is used by the unit test, integration tests and benchmarks. pub fn new_test_ext() -> sp_io::TestExternalities where - ::BlockNumber: From, + frame_system::pallet_prelude::BlockNumberFor: From, { sp_tracing::try_init_simple(); WeightForCall::take(); diff --git a/frame/multisig/src/lib.rs b/frame/multisig/src/lib.rs index 64058be9c8fbf..ab117315f8985 100644 --- a/frame/multisig/src/lib.rs +++ b/frame/multisig/src/lib.rs @@ -59,7 +59,7 @@ use frame_support::{ weights::Weight, BoundedVec, RuntimeDebug, }; -use frame_system::{self as system, RawOrigin}; +use frame_system::{self as system, pallet_prelude::BlockNumberFor, RawOrigin}; use scale_info::TypeInfo; use sp_io::hashing::blake2_256; use sp_runtime::{ @@ -183,7 +183,7 @@ pub mod pallet { T::AccountId, Blake2_128Concat, [u8; 32], - Multisig, T::AccountId, T::MaxSignatories>, + Multisig, BalanceOf, T::AccountId, T::MaxSignatories>, >; #[pallet::error] @@ -226,14 +226,14 @@ pub mod pallet { /// A multisig operation has been approved by someone. MultisigApproval { approving: T::AccountId, - timepoint: Timepoint, + timepoint: Timepoint>, multisig: T::AccountId, call_hash: CallHash, }, /// A multisig operation has been executed. MultisigExecuted { approving: T::AccountId, - timepoint: Timepoint, + timepoint: Timepoint>, multisig: T::AccountId, call_hash: CallHash, result: DispatchResult, @@ -241,7 +241,7 @@ pub mod pallet { /// A multisig operation has been cancelled. MultisigCancelled { cancelling: T::AccountId, - timepoint: Timepoint, + timepoint: Timepoint>, multisig: T::AccountId, call_hash: CallHash, }, @@ -366,7 +366,7 @@ pub mod pallet { origin: OriginFor, threshold: u16, other_signatories: Vec, - maybe_timepoint: Option>, + maybe_timepoint: Option>>, call: Box<::RuntimeCall>, max_weight: Weight, ) -> DispatchResultWithPostInfo { @@ -423,7 +423,7 @@ pub mod pallet { origin: OriginFor, threshold: u16, other_signatories: Vec, - maybe_timepoint: Option>, + maybe_timepoint: Option>>, call_hash: [u8; 32], max_weight: Weight, ) -> DispatchResultWithPostInfo { @@ -465,7 +465,7 @@ pub mod pallet { origin: OriginFor, threshold: u16, other_signatories: Vec, - timepoint: Timepoint, + timepoint: Timepoint>, call_hash: [u8; 32], ) -> DispatchResult { let who = ensure_signed(origin)?; @@ -511,7 +511,7 @@ impl Pallet { who: T::AccountId, threshold: u16, other_signatories: Vec, - maybe_timepoint: Option>, + maybe_timepoint: Option>>, call_or_hash: CallOrHash, max_weight: Weight, ) -> DispatchResultWithPostInfo { @@ -637,7 +637,7 @@ impl Pallet { } /// The current `Timepoint`. - pub fn timepoint() -> Timepoint { + pub fn timepoint() -> Timepoint> { Timepoint { height: >::block_number(), index: >::extrinsic_index().unwrap_or_default(), diff --git a/frame/multisig/src/tests.rs b/frame/multisig/src/tests.rs index e024da22810fc..e3cdd086fb757 100644 --- a/frame/multisig/src/tests.rs +++ b/frame/multisig/src/tests.rs @@ -28,19 +28,14 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, TokenError, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -55,13 +50,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/nft-fractionalization/src/benchmarking.rs b/frame/nft-fractionalization/src/benchmarking.rs index 50bb6039eb6ec..0b54acdab49ea 100644 --- a/frame/nft-fractionalization/src/benchmarking.rs +++ b/frame/nft-fractionalization/src/benchmarking.rs @@ -29,7 +29,7 @@ use frame_support::{ Get, }, }; -use frame_system::RawOrigin as SystemOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin as SystemOrigin}; use pallet_nfts::{CollectionConfig, CollectionSettings, ItemConfig, MintSettings}; use sp_runtime::traits::StaticLookup; use sp_std::prelude::*; @@ -39,11 +39,8 @@ use crate::Pallet as NftFractionalization; type BalanceOf = <::Currency as InspectFungible<::AccountId>>::Balance; -type CollectionConfigOf = CollectionConfig< - BalanceOf, - ::BlockNumber, - ::NftCollectionId, ->; +type CollectionConfigOf = + CollectionConfig, BlockNumberFor, ::NftCollectionId>; fn default_collection_config() -> CollectionConfigOf where @@ -58,7 +55,7 @@ where fn mint_nft(nft_id: T::NftId) -> (T::AccountId, AccountIdLookupOf) where - T::Nfts: Create, T::BlockNumber, T::NftCollectionId>> + T::Nfts: Create, BlockNumberFor, T::NftCollectionId>> + Mutate, { let caller: T::AccountId = whitelisted_caller(); @@ -84,7 +81,7 @@ fn assert_last_event(generic_event: ::RuntimeEvent) { benchmarks! { where_clause { where - T::Nfts: Create, T::BlockNumber, T::NftCollectionId>> + T::Nfts: Create, frame_system::pallet_prelude::BlockNumberFor::, T::NftCollectionId>> + Mutate, } diff --git a/frame/nft-fractionalization/src/mock.rs b/frame/nft-fractionalization/src/mock.rs index c5142c8695b98..569429552d268 100644 --- a/frame/nft-fractionalization/src/mock.rs +++ b/frame/nft-fractionalization/src/mock.rs @@ -29,12 +29,10 @@ use frame_system::EnsureSigned; use pallet_nfts::PalletFeatures; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, BuildStorage, MultiSignature, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; type Signature = MultiSignature; type AccountPublic = ::Signer; @@ -42,10 +40,7 @@ type AccountId = ::AccountId; // Configure a mock runtime to test the pallet. construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, NftFractionalization: pallet_nft_fractionalization, @@ -61,12 +56,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); diff --git a/frame/nfts/src/benchmarking.rs b/frame/nfts/src/benchmarking.rs index 45390bf032bd6..67ba29266245a 100644 --- a/frame/nfts/src/benchmarking.rs +++ b/frame/nfts/src/benchmarking.rs @@ -30,7 +30,7 @@ use frame_support::{ traits::{EnsureOrigin, Get}, BoundedVec, }; -use frame_system::RawOrigin as SystemOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin as SystemOrigin}; use sp_io::crypto::{sr25519_generate, sr25519_sign}; use sp_runtime::{ traits::{Bounded, IdentifyAccount, One}, @@ -589,7 +589,7 @@ benchmarks_instance_pallet! { let (item, ..) = mint_item::(0); let delegate: T::AccountId = account("delegate", 0, SEED); let delegate_lookup = T::Lookup::unlookup(delegate.clone()); - let deadline = T::BlockNumber::max_value(); + let deadline = BlockNumberFor::::max_value(); }: _(SystemOrigin::Signed(caller.clone()), collection, item, delegate_lookup, Some(deadline)) verify { assert_last_event::(Event::TransferApproved { collection, item, owner: caller, delegate, deadline: Some(deadline) }.into()); @@ -601,7 +601,7 @@ benchmarks_instance_pallet! { let delegate: T::AccountId = account("delegate", 0, SEED); let delegate_lookup = T::Lookup::unlookup(delegate.clone()); let origin = SystemOrigin::Signed(caller.clone()).into(); - let deadline = T::BlockNumber::max_value(); + let deadline = BlockNumberFor::::max_value(); Nfts::::approve_transfer(origin, collection, item, delegate_lookup.clone(), Some(deadline))?; }: _(SystemOrigin::Signed(caller.clone()), collection, item, delegate_lookup) verify { @@ -614,7 +614,7 @@ benchmarks_instance_pallet! { let delegate: T::AccountId = account("delegate", 0, SEED); let delegate_lookup = T::Lookup::unlookup(delegate.clone()); let origin = SystemOrigin::Signed(caller.clone()).into(); - let deadline = T::BlockNumber::max_value(); + let deadline = BlockNumberFor::::max_value(); Nfts::::approve_transfer(origin, collection, item, delegate_lookup.clone(), Some(deadline))?; }: _(SystemOrigin::Signed(caller.clone()), collection, item) verify { diff --git a/frame/nfts/src/features/approvals.rs b/frame/nfts/src/features/approvals.rs index 634436a8562d8..c78dd2d96b089 100644 --- a/frame/nfts/src/features/approvals.rs +++ b/frame/nfts/src/features/approvals.rs @@ -24,7 +24,7 @@ impl, I: 'static> Pallet { collection: T::CollectionId, item: T::ItemId, delegate: T::AccountId, - maybe_deadline: Option<::BlockNumber>, + maybe_deadline: Option>, ) -> DispatchResult { ensure!( Self::is_pallet_feature_enabled(PalletFeature::Approvals), diff --git a/frame/nfts/src/features/atomic_swap.rs b/frame/nfts/src/features/atomic_swap.rs index 505056be95353..5b0096d72a3d6 100644 --- a/frame/nfts/src/features/atomic_swap.rs +++ b/frame/nfts/src/features/atomic_swap.rs @@ -29,7 +29,7 @@ impl, I: 'static> Pallet { desired_collection_id: T::CollectionId, maybe_desired_item_id: Option, maybe_price: Option>>, - duration: ::BlockNumber, + duration: frame_system::pallet_prelude::BlockNumberFor, ) -> DispatchResult { ensure!( Self::is_pallet_feature_enabled(PalletFeature::Swaps), diff --git a/frame/nfts/src/features/settings.rs b/frame/nfts/src/features/settings.rs index 080d7b97f13b1..3d96a411ae708 100644 --- a/frame/nfts/src/features/settings.rs +++ b/frame/nfts/src/features/settings.rs @@ -61,7 +61,7 @@ impl, I: 'static> Pallet { collection: T::CollectionId, mint_settings: MintSettings< BalanceOf, - ::BlockNumber, + frame_system::pallet_prelude::BlockNumberFor, T::CollectionId, >, ) -> DispatchResult { diff --git a/frame/nfts/src/lib.rs b/frame/nfts/src/lib.rs index f2812674a5408..8124c71682451 100644 --- a/frame/nfts/src/lib.rs +++ b/frame/nfts/src/lib.rs @@ -171,7 +171,7 @@ pub mod pallet { /// The max duration in blocks for deadlines. #[pallet::constant] - type MaxDeadlineDuration: Get<::BlockNumber>; + type MaxDeadlineDuration: Get>; /// The max number of attributes a user could set per call. #[pallet::constant] @@ -343,7 +343,7 @@ pub mod pallet { T::CollectionId, T::ItemId, PriceWithDirection>, - ::BlockNumber, + BlockNumberFor, >, OptionQuery, >; @@ -414,7 +414,7 @@ pub mod pallet { item: T::ItemId, owner: T::AccountId, delegate: T::AccountId, - deadline: Option<::BlockNumber>, + deadline: Option>, }, /// An approval for a `delegate` account to transfer the `item` of an item /// `collection` was cancelled by its `owner`. @@ -509,7 +509,7 @@ pub mod pallet { desired_collection: T::CollectionId, desired_item: Option, price: Option>>, - deadline: ::BlockNumber, + deadline: BlockNumberFor, }, /// The swap was cancelled. SwapCancelled { @@ -518,7 +518,7 @@ pub mod pallet { desired_collection: T::CollectionId, desired_item: Option, price: Option>>, - deadline: ::BlockNumber, + deadline: BlockNumberFor, }, /// The swap has been claimed. SwapClaimed { @@ -529,7 +529,7 @@ pub mod pallet { received_item: T::ItemId, received_item_owner: T::AccountId, price: Option>>, - deadline: ::BlockNumber, + deadline: BlockNumberFor, }, /// New attributes have been set for an `item` of the `collection`. PreSignedAttributesSet { @@ -1236,7 +1236,7 @@ pub mod pallet { collection: T::CollectionId, item: T::ItemId, delegate: AccountIdLookupOf, - maybe_deadline: Option<::BlockNumber>, + maybe_deadline: Option>, ) -> DispatchResult { let maybe_check_origin = T::ForceOrigin::try_origin(origin) .map(|_| None) @@ -1659,11 +1659,7 @@ pub mod pallet { pub fn update_mint_settings( origin: OriginFor, collection: T::CollectionId, - mint_settings: MintSettings< - BalanceOf, - ::BlockNumber, - T::CollectionId, - >, + mint_settings: MintSettings, BlockNumberFor, T::CollectionId>, ) -> DispatchResult { let maybe_check_origin = T::ForceOrigin::try_origin(origin) .map(|_| None) @@ -1759,7 +1755,7 @@ pub mod pallet { desired_collection: T::CollectionId, maybe_desired_item: Option, maybe_price: Option>>, - duration: ::BlockNumber, + duration: BlockNumberFor, ) -> DispatchResult { let origin = ensure_signed(origin)?; Self::do_create_swap( diff --git a/frame/nfts/src/mock.rs b/frame/nfts/src/mock.rs index 8b8c7c6a0fd70..e791c85b67f3f 100644 --- a/frame/nfts/src/mock.rs +++ b/frame/nfts/src/mock.rs @@ -27,19 +27,14 @@ use frame_support::{ use sp_core::H256; use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, BuildStorage, MultiSignature, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -58,12 +53,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); diff --git a/frame/nfts/src/types.rs b/frame/nfts/src/types.rs index ab966f0d73828..e4e6165774627 100644 --- a/frame/nfts/src/types.rs +++ b/frame/nfts/src/types.rs @@ -26,6 +26,7 @@ use frame_support::{ traits::Get, BoundedBTreeMap, BoundedBTreeSet, }; +use frame_system::pallet_prelude::BlockNumberFor; use scale_info::{build::Fields, meta_type, Path, Type, TypeInfo, TypeParameter}; pub(super) type DepositBalanceOf = @@ -34,7 +35,7 @@ pub(super) type CollectionDetailsFor = CollectionDetails<::AccountId, DepositBalanceOf>; pub(super) type ApprovalsOf = BoundedBTreeMap< ::AccountId, - Option<::BlockNumber>, + Option>, >::ApprovalsLimit, >; pub(super) type ItemAttributesApprovals = @@ -56,23 +57,20 @@ pub(super) type ItemTipOf = ItemTip< ::AccountId, BalanceOf, >; -pub(super) type CollectionConfigFor = CollectionConfig< - BalanceOf, - ::BlockNumber, - >::CollectionId, ->; +pub(super) type CollectionConfigFor = + CollectionConfig, BlockNumberFor, >::CollectionId>; pub(super) type PreSignedMintOf = PreSignedMint< >::CollectionId, >::ItemId, ::AccountId, - ::BlockNumber, + BlockNumberFor, BalanceOf, >; pub(super) type PreSignedAttributesOf = PreSignedAttributes< >::CollectionId, >::ItemId, ::AccountId, - ::BlockNumber, + BlockNumberFor, >; /// Information about a collection. diff --git a/frame/nicks/src/lib.rs b/frame/nicks/src/lib.rs index 9fa7595bdf3f3..a0dd3125db75d 100644 --- a/frame/nicks/src/lib.rs +++ b/frame/nicks/src/lib.rs @@ -239,19 +239,14 @@ mod tests { use frame_system::EnsureSignedBy; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BadOrigin, BlakeTwo256, IdentityLookup}, BuildStorage, }; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Balances: pallet_balances, @@ -266,13 +261,12 @@ mod tests { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/nis/src/lib.rs b/frame/nis/src/lib.rs index 48d322545a635..1bf052a39d1ed 100644 --- a/frame/nis/src/lib.rs +++ b/frame/nis/src/lib.rs @@ -186,13 +186,10 @@ pub mod pallet { <::Currency as FunInspect<::AccountId>>::Balance; type DebtOf = fungible::Debt<::AccountId, ::Currency>; - type ReceiptRecordOf = ReceiptRecord< - ::AccountId, - ::BlockNumber, - BalanceOf, - >; + type ReceiptRecordOf = + ReceiptRecord<::AccountId, BlockNumberFor, BalanceOf>; type IssuanceInfoOf = IssuanceInfo>; - type SummaryRecordOf = SummaryRecord<::BlockNumber, BalanceOf>; + type SummaryRecordOf = SummaryRecord, BalanceOf>; type BidOf = Bid, ::AccountId>; type QueueTotalsTypeOf = BoundedVec<(u32, BalanceOf), ::QueueCount>; @@ -275,7 +272,7 @@ pub mod pallet { /// The base period for the duration queues. This is the common multiple across all /// supported freezing durations that can be bid upon. #[pallet::constant] - type BasePeriod: Get; + type BasePeriod: Get>; /// The minimum amount of funds that may be placed in a bid. Note that this /// does not actually limit the amount which may be represented in a receipt since bids may @@ -296,7 +293,7 @@ pub mod pallet { /// A larger value results in fewer storage hits each block, but a slower period to get to /// the target. #[pallet::constant] - type IntakePeriod: Get; + type IntakePeriod: Get>; /// The maximum amount of bids that can consolidated into receipts in a single intake. A /// larger value here means less of the block available for transactions should there be a @@ -306,7 +303,7 @@ pub mod pallet { /// The maximum proportion which may be thawed and the period over which it is reset. #[pallet::constant] - type ThawThrottle: Get<(Perquintill, Self::BlockNumber)>; + type ThawThrottle: Get<(Perquintill, BlockNumberFor)>; } #[pallet::pallet] @@ -413,7 +410,7 @@ pub mod pallet { /// The identity of the receipt. index: ReceiptIndex, /// The block number at which the receipt may be thawed. - expiry: T::BlockNumber, + expiry: BlockNumberFor, /// The owner of the receipt. who: T::AccountId, /// The proportion of the effective total issuance which the receipt represents. @@ -508,7 +505,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: BlockNumberFor) -> Weight { let mut weight_counter = WeightCounter { used: Weight::zero(), limit: T::MaxIntakeWeight::get() }; if T::IntakePeriod::get().is_zero() || (n % T::IntakePeriod::get()).is_zero() { @@ -1062,7 +1059,7 @@ pub mod pallet { pub(crate) fn process_queue( duration: u32, - now: T::BlockNumber, + now: BlockNumberFor, our_account: &T::AccountId, issuance: &IssuanceInfo>, max_bids: u32, @@ -1106,7 +1103,7 @@ pub mod pallet { pub(crate) fn process_bid( mut bid: BidOf, - expiry: T::BlockNumber, + expiry: BlockNumberFor, _our_account: &T::AccountId, issuance: &IssuanceInfo>, remaining: &mut BalanceOf, diff --git a/frame/nis/src/mock.rs b/frame/nis/src/mock.rs index 0146acabf9fde..4fb51ed324e22 100644 --- a/frame/nis/src/mock.rs +++ b/frame/nis/src/mock.rs @@ -31,22 +31,17 @@ use frame_support::{ use pallet_balances::{Instance1, Instance2}; use sp_core::{ConstU128, H256}; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; pub type Balance = u64; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Balances: pallet_balances::, @@ -62,12 +57,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); diff --git a/frame/node-authorization/src/lib.rs b/frame/node-authorization/src/lib.rs index dec05d0c37058..8a823d29f2355 100644 --- a/frame/node-authorization/src/lib.rs +++ b/frame/node-authorization/src/lib.rs @@ -169,7 +169,7 @@ pub mod pallet { impl Hooks> for Pallet { /// Set reserved node every block. It may not be enabled depends on the offchain /// worker settings when starting the node. - fn offchain_worker(now: T::BlockNumber) { + fn offchain_worker(now: frame_system::pallet_prelude::BlockNumberFor) { let network_state = sp_io::offchain::network_state(); match network_state { Err(_) => log::error!( diff --git a/frame/node-authorization/src/mock.rs b/frame/node-authorization/src/mock.rs index c0594f1d94424..0733016b82cb9 100644 --- a/frame/node-authorization/src/mock.rs +++ b/frame/node-authorization/src/mock.rs @@ -27,19 +27,14 @@ use frame_support::{ use frame_system::EnsureSignedBy; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, NodeAuthorization: pallet_node_authorization::{ @@ -55,13 +50,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/nomination-pools/benchmarking/src/mock.rs b/frame/nomination-pools/benchmarking/src/mock.rs index 5666e7b450acb..60ca5166abb87 100644 --- a/frame/nomination-pools/benchmarking/src/mock.rs +++ b/frame/nomination-pools/benchmarking/src/mock.rs @@ -35,13 +35,12 @@ impl frame_system::Config for Runtime { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; - type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); @@ -175,12 +174,9 @@ impl pallet_nomination_pools::Config for Runtime { impl crate::Config for Runtime {} type Block = frame_system::mocking::MockBlock; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; + frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system::{Pallet, Call, Event}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, diff --git a/frame/nomination-pools/src/lib.rs b/frame/nomination-pools/src/lib.rs index 587fe1b9e8d2a..c4bebc5a1d030 100644 --- a/frame/nomination-pools/src/lib.rs +++ b/frame/nomination-pools/src/lib.rs @@ -362,6 +362,7 @@ use frame_support::{ }, DefaultNoBound, PalletError, }; +use frame_system::pallet_prelude::BlockNumberFor; use scale_info::TypeInfo; use sp_core::U256; use sp_runtime::{ @@ -672,10 +673,10 @@ pub struct Commission { pub max: Option, /// Optional configuration around how often commission can be updated, and when the last /// commission update took place. - pub change_rate: Option>, + pub change_rate: Option>>, /// The block from where throttling should be checked from. This value will be updated on all /// commission updates and when setting an initial `change_rate`. - pub throttle_from: Option, + pub throttle_from: Option>, } impl Commission { @@ -817,7 +818,7 @@ impl Commission { /// throttling can be checked from this block. fn try_update_change_rate( &mut self, - change_rate: CommissionChangeRate, + change_rate: CommissionChangeRate>, ) -> DispatchResult { ensure!(!&self.less_restrictive(&change_rate), Error::::CommissionChangeRateNotAllowed); @@ -837,7 +838,7 @@ impl Commission { /// /// No change rate will always be less restrictive than some change rate, so where no /// `change_rate` is currently set, `false` is returned. - fn less_restrictive(&self, new: &CommissionChangeRate) -> bool { + fn less_restrictive(&self, new: &CommissionChangeRate>) -> bool { self.change_rate .as_ref() .map(|c| new.max_increase > c.max_increase || new.min_delay < c.min_delay) @@ -1765,7 +1766,7 @@ pub mod pallet { /// A pool's commission `change_rate` has been changed. PoolCommissionChangeRateUpdated { pool_id: PoolId, - change_rate: CommissionChangeRate, + change_rate: CommissionChangeRate>, }, /// Pool commission has been claimed. PoolCommissionClaimed { pool_id: PoolId, commission: BalanceOf }, @@ -2603,7 +2604,7 @@ pub mod pallet { pub fn set_commission_change_rate( origin: OriginFor, pool_id: PoolId, - change_rate: CommissionChangeRate, + change_rate: CommissionChangeRate>, ) -> DispatchResult { let who = ensure_signed(origin)?; let mut bonded_pool = BondedPool::::get(pool_id).ok_or(Error::::PoolNotFound)?; diff --git a/frame/nomination-pools/src/mock.rs b/frame/nomination-pools/src/mock.rs index ef1240b666101..fd8514bfc8bfe 100644 --- a/frame/nomination-pools/src/mock.rs +++ b/frame/nomination-pools/src/mock.rs @@ -169,13 +169,12 @@ impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type DbWeight = (); @@ -246,13 +245,9 @@ impl pools::Config for Runtime { type MaxPointsToBalance = frame_support::traits::ConstU8<10>; } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub struct Runtime { System: frame_system::{Pallet, Call, Storage, Event, Config}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, diff --git a/frame/nomination-pools/test-staking/src/mock.rs b/frame/nomination-pools/test-staking/src/mock.rs index f7697d534fd57..8c8618913d518 100644 --- a/frame/nomination-pools/test-staking/src/mock.rs +++ b/frame/nomination-pools/test-staking/src/mock.rs @@ -45,13 +45,12 @@ impl frame_system::Config for Runtime { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; - type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); @@ -187,13 +186,9 @@ impl pallet_nomination_pools::Config for Runtime { } type Block = frame_system::mocking::MockBlock; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system::{Pallet, Call, Event}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, diff --git a/frame/offences/benchmarking/src/mock.rs b/frame/offences/benchmarking/src/mock.rs index ec64ce13632e3..6089025dcb2b2 100644 --- a/frame/offences/benchmarking/src/mock.rs +++ b/frame/offences/benchmarking/src/mock.rs @@ -35,7 +35,6 @@ use sp_runtime::{ type AccountId = u64; type AccountIndex = u32; -type BlockNumber = u64; type Balance = u64; impl frame_system::Config for Test { @@ -45,13 +44,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; - type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); @@ -220,10 +218,7 @@ pub type Block = sp_runtime::generic::Block; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub enum Test { System: system::{Pallet, Call, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, diff --git a/frame/offences/src/mock.rs b/frame/offences/src/mock.rs index f719fe6cdd7d2..150ab3665269d 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -29,7 +29,6 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, Perbill, }; @@ -66,14 +65,10 @@ pub fn with_on_offence_fractions) -> R>(f: F) -> OnOffencePerbill::mutate(|fractions| f(fractions)) } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub struct Runtime { System: frame_system::{Pallet, Call, Config, Storage, Event}, Offences: offences::{Pallet, Storage, Event}, @@ -87,13 +82,12 @@ impl frame_system::Config for Runtime { type DbWeight = RocksDbWeight; type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/preimage/src/mock.rs b/frame/preimage/src/mock.rs index d3d891c1d0dc9..f196a18acae36 100644 --- a/frame/preimage/src/mock.rs +++ b/frame/preimage/src/mock.rs @@ -28,19 +28,14 @@ use frame_support::{ use frame_system::EnsureSignedBy; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Balances: pallet_balances, @@ -56,12 +51,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/proxy/src/benchmarking.rs b/frame/proxy/src/benchmarking.rs index 7244dd5f17472..e0d14163d21b2 100644 --- a/frame/proxy/src/benchmarking.rs +++ b/frame/proxy/src/benchmarking.rs @@ -22,7 +22,7 @@ use super::*; use crate::Pallet as Proxy; use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller}; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use sp_runtime::traits::Bounded; const SEED: u32 = 0; @@ -41,7 +41,7 @@ fn add_proxies(n: u32, maybe_who: Option) -> Result<(), RawOrigin::Signed(caller.clone()).into(), real, T::ProxyType::default(), - T::BlockNumber::zero(), + BlockNumberFor::::zero(), )?; } Ok(()) @@ -64,7 +64,7 @@ fn add_announcements( RawOrigin::Signed(real.clone()).into(), caller_lookup, T::ProxyType::default(), - T::BlockNumber::zero(), + BlockNumberFor::::zero(), )?; real }; @@ -187,7 +187,7 @@ benchmarks! { RawOrigin::Signed(caller.clone()), real, T::ProxyType::default(), - T::BlockNumber::zero() + BlockNumberFor::::zero() ) verify { let (proxies, _) = Proxies::::get(caller); @@ -202,7 +202,7 @@ benchmarks! { RawOrigin::Signed(caller.clone()), delegate, T::ProxyType::default(), - T::BlockNumber::zero() + BlockNumberFor::::zero() ) verify { let (proxies, _) = Proxies::::get(caller); @@ -224,7 +224,7 @@ benchmarks! { }: _( RawOrigin::Signed(caller.clone()), T::ProxyType::default(), - T::BlockNumber::zero(), + BlockNumberFor::::zero(), 0 ) verify { @@ -246,7 +246,7 @@ benchmarks! { Pallet::::create_pure( RawOrigin::Signed(whitelisted_caller()).into(), T::ProxyType::default(), - T::BlockNumber::zero(), + BlockNumberFor::::zero(), 0 )?; let height = system::Pallet::::block_number(); diff --git a/frame/proxy/src/lib.rs b/frame/proxy/src/lib.rs index 76ff2662bd0f4..33e9fcfade35a 100644 --- a/frame/proxy/src/lib.rs +++ b/frame/proxy/src/lib.rs @@ -40,7 +40,7 @@ use frame_support::{ traits::{Currency, Get, InstanceFilter, IsSubType, IsType, OriginTrait, ReservableCurrency}, RuntimeDebug, }; -use frame_system::{self as system, ensure_signed}; +use frame_system::{self as system, ensure_signed, pallet_prelude::BlockNumberFor}; pub use pallet::*; use scale_info::TypeInfo; use sp_io::hashing::blake2_256; @@ -227,7 +227,7 @@ pub mod pallet { origin: OriginFor, delegate: AccountIdLookupOf, proxy_type: T::ProxyType, - delay: T::BlockNumber, + delay: BlockNumberFor, ) -> DispatchResult { let who = ensure_signed(origin)?; let delegate = T::Lookup::lookup(delegate)?; @@ -247,7 +247,7 @@ pub mod pallet { origin: OriginFor, delegate: AccountIdLookupOf, proxy_type: T::ProxyType, - delay: T::BlockNumber, + delay: BlockNumberFor, ) -> DispatchResult { let who = ensure_signed(origin)?; let delegate = T::Lookup::lookup(delegate)?; @@ -291,7 +291,7 @@ pub mod pallet { pub fn create_pure( origin: OriginFor, proxy_type: T::ProxyType, - delay: T::BlockNumber, + delay: BlockNumberFor, index: u16, ) -> DispatchResult { let who = ensure_signed(origin)?; @@ -341,7 +341,7 @@ pub mod pallet { spawner: AccountIdLookupOf, proxy_type: T::ProxyType, index: u16, - #[pallet::compact] height: T::BlockNumber, + #[pallet::compact] height: BlockNumberFor, #[pallet::compact] ext_index: u32, ) -> DispatchResult { let who = ensure_signed(origin)?; @@ -535,14 +535,14 @@ pub mod pallet { delegator: T::AccountId, delegatee: T::AccountId, proxy_type: T::ProxyType, - delay: T::BlockNumber, + delay: BlockNumberFor, }, /// A proxy was removed. ProxyRemoved { delegator: T::AccountId, delegatee: T::AccountId, proxy_type: T::ProxyType, - delay: T::BlockNumber, + delay: BlockNumberFor, }, } @@ -575,7 +575,10 @@ pub mod pallet { Twox64Concat, T::AccountId, ( - BoundedVec, T::MaxProxies>, + BoundedVec< + ProxyDefinition>, + T::MaxProxies, + >, BalanceOf, ), ValueQuery, @@ -589,7 +592,7 @@ pub mod pallet { Twox64Concat, T::AccountId, ( - BoundedVec, T::BlockNumber>, T::MaxPending>, + BoundedVec, BlockNumberFor>, T::MaxPending>, BalanceOf, ), ValueQuery, @@ -612,7 +615,7 @@ impl Pallet { who: &T::AccountId, proxy_type: &T::ProxyType, index: u16, - maybe_when: Option<(T::BlockNumber, u32)>, + maybe_when: Option<(BlockNumberFor, u32)>, ) -> T::AccountId { let (height, ext_index) = maybe_when.unwrap_or_else(|| { ( @@ -638,7 +641,7 @@ impl Pallet { delegator: &T::AccountId, delegatee: T::AccountId, proxy_type: T::ProxyType, - delay: T::BlockNumber, + delay: BlockNumberFor, ) -> DispatchResult { ensure!(delegator != &delegatee, Error::::NoSelfProxy); Proxies::::try_mutate(delegator, |(ref mut proxies, ref mut deposit)| { @@ -678,7 +681,7 @@ impl Pallet { delegator: &T::AccountId, delegatee: T::AccountId, proxy_type: T::ProxyType, - delay: T::BlockNumber, + delay: BlockNumberFor, ) -> DispatchResult { Proxies::::try_mutate_exists(delegator, |x| { let (mut proxies, old_deposit) = x.take().ok_or(Error::::NotFound)?; @@ -734,7 +737,7 @@ impl Pallet { } fn edit_announcements< - F: FnMut(&Announcement, T::BlockNumber>) -> bool, + F: FnMut(&Announcement, BlockNumberFor>) -> bool, >( delegate: &T::AccountId, f: F, @@ -760,8 +763,8 @@ impl Pallet { real: &T::AccountId, delegate: &T::AccountId, force_proxy_type: Option, - ) -> Result, DispatchError> { - let f = |x: &ProxyDefinition| -> bool { + ) -> Result>, DispatchError> { + let f = |x: &ProxyDefinition>| -> bool { &x.delegate == delegate && force_proxy_type.as_ref().map_or(true, |y| &x.proxy_type == y) }; @@ -769,7 +772,7 @@ impl Pallet { } fn do_proxy( - def: ProxyDefinition, + def: ProxyDefinition>, real: T::AccountId, call: ::RuntimeCall, ) { diff --git a/frame/proxy/src/tests.rs b/frame/proxy/src/tests.rs index ccfeed8cd5693..54466e5d5bbce 100644 --- a/frame/proxy/src/tests.rs +++ b/frame/proxy/src/tests.rs @@ -31,19 +31,14 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -59,13 +54,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/ranked-collective/src/lib.rs b/frame/ranked-collective/src/lib.rs index 6fe9fc221a7df..fe1308cd034f4 100644 --- a/frame/ranked-collective/src/lib.rs +++ b/frame/ranked-collective/src/lib.rs @@ -391,7 +391,7 @@ pub mod pallet { type DemoteOrigin: EnsureOrigin; /// The polling system used for our voting. - type Polls: Polling, Votes = Votes, Moment = Self::BlockNumber>; + type Polls: Polling, Votes = Votes, Moment = BlockNumberFor>; /// Convert the tally class into the minimum rank required to vote on the poll. If /// `Polls::Class` is the same type as `Rank`, then `Identity` can be used here to mean diff --git a/frame/ranked-collective/src/tests.rs b/frame/ranked-collective/src/tests.rs index fb8dc00e76551..7f3cd27705e97 100644 --- a/frame/ranked-collective/src/tests.rs +++ b/frame/ranked-collective/src/tests.rs @@ -27,7 +27,6 @@ use frame_support::{ }; use sp_core::{Get, H256}; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup, ReduceBy}, BuildStorage, }; @@ -35,15 +34,11 @@ use sp_runtime::{ use super::*; use crate as pallet_ranked_collective; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; type Class = Rank; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Club: pallet_ranked_collective::{Pallet, Call, Storage, Event}, @@ -57,13 +52,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/recovery/src/lib.rs b/frame/recovery/src/lib.rs index 8f70ebfe5ec67..9c01d25d4f76b 100644 --- a/frame/recovery/src/lib.rs +++ b/frame/recovery/src/lib.rs @@ -334,7 +334,7 @@ pub mod pallet { _, Twox64Concat, T::AccountId, - RecoveryConfig, FriendsOf>, + RecoveryConfig, BalanceOf, FriendsOf>, >; /// Active recovery attempts. @@ -349,7 +349,7 @@ pub mod pallet { T::AccountId, Twox64Concat, T::AccountId, - ActiveRecovery, FriendsOf>, + ActiveRecovery, BalanceOf, FriendsOf>, >; /// The list of allowed proxy accounts. @@ -440,7 +440,7 @@ pub mod pallet { origin: OriginFor, friends: Vec, threshold: u16, - delay_period: T::BlockNumber, + delay_period: BlockNumberFor, ) -> DispatchResult { let who = ensure_signed(origin)?; // Check account is not already set up for recovery diff --git a/frame/recovery/src/mock.rs b/frame/recovery/src/mock.rs index 75e5168f13aaa..16de531867c24 100644 --- a/frame/recovery/src/mock.rs +++ b/frame/recovery/src/mock.rs @@ -26,19 +26,14 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -54,12 +49,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/referenda/src/benchmarking.rs b/frame/referenda/src/benchmarking.rs index 4c332a3048d0b..d4b273c0307a3 100644 --- a/frame/referenda/src/benchmarking.rs +++ b/frame/referenda/src/benchmarking.rs @@ -172,7 +172,9 @@ fn skip_timeout_period, I: 'static>(index: ReferendumIndex) { frame_system::Pallet::::set_block_number(timeout_period_over); } -fn alarm_time, I: 'static>(index: ReferendumIndex) -> T::BlockNumber { +fn alarm_time, I: 'static>( + index: ReferendumIndex, +) -> frame_system::pallet_prelude::BlockNumberFor { let status = Referenda::::ensure_ongoing(index).unwrap(); status.alarm.unwrap().0 } diff --git a/frame/referenda/src/lib.rs b/frame/referenda/src/lib.rs index 3756257c33fe5..8ff754dc0db8e 100644 --- a/frame/referenda/src/lib.rs +++ b/frame/referenda/src/lib.rs @@ -77,6 +77,7 @@ use frame_support::{ }, BoundedVec, }; +use frame_system::pallet_prelude::BlockNumberFor; use scale_info::TypeInfo; use sp_runtime::{ traits::{AtLeast32BitUnsigned, Bounded, Dispatchable, One, Saturating, Zero}, @@ -161,8 +162,8 @@ pub mod pallet { /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; /// The Scheduler. - type Scheduler: ScheduleAnon, PalletsOriginOf> - + ScheduleNamed, PalletsOriginOf>; + type Scheduler: ScheduleAnon, CallOf, PalletsOriginOf> + + ScheduleNamed, CallOf, PalletsOriginOf>; /// Currency type for this pallet. type Currency: ReservableCurrency; // Origins and unbalances. @@ -201,25 +202,25 @@ pub mod pallet { /// The number of blocks after submission that a referendum must begin being decided by. /// Once this passes, then anyone may cancel the referendum. #[pallet::constant] - type UndecidingTimeout: Get; + type UndecidingTimeout: Get>; /// Quantization level for the referendum wakeup scheduler. A higher number will result in /// fewer storage reads/writes needed for smaller voters, but also result in delays to the /// automatic referendum status changes. Explicit servicing instructions are unaffected. #[pallet::constant] - type AlarmInterval: Get; + type AlarmInterval: Get>; // The other stuff. /// Information concerning the different referendum tracks. #[pallet::constant] type Tracks: Get< Vec<( - , Self::BlockNumber>>::Id, - TrackInfo, Self::BlockNumber>, + , BlockNumberFor>>::Id, + TrackInfo, BlockNumberFor>, )>, > + TracksInfo< BalanceOf, - Self::BlockNumber, + BlockNumberFor, RuntimeOrigin = ::PalletsOrigin, >; @@ -432,7 +433,7 @@ pub mod pallet { origin: OriginFor, proposal_origin: Box>, proposal: BoundedCallOf, - enactment_moment: DispatchTime, + enactment_moment: DispatchTime>, ) -> DispatchResult { let proposal_origin = *proposal_origin; let who = T::SubmitOrigin::ensure_origin(origin, &proposal_origin)?; @@ -704,7 +705,7 @@ pub mod pallet { impl, I: 'static> Polling for Pallet { type Index = ReferendumIndex; type Votes = VotesOf; - type Moment = T::BlockNumber; + type Moment = BlockNumberFor; type Class = TrackIdOf; fn classes() -> Vec { @@ -713,7 +714,7 @@ impl, I: 'static> Polling for Pallet { fn access_poll( index: Self::Index, - f: impl FnOnce(PollStatus<&mut T::Tally, T::BlockNumber, TrackIdOf>) -> R, + f: impl FnOnce(PollStatus<&mut T::Tally, BlockNumberFor, TrackIdOf>) -> R, ) -> R { match ReferendumInfoFor::::get(index) { Some(ReferendumInfo::Ongoing(mut status)) => { @@ -732,7 +733,7 @@ impl, I: 'static> Polling for Pallet { fn try_access_poll( index: Self::Index, f: impl FnOnce( - PollStatus<&mut T::Tally, T::BlockNumber, TrackIdOf>, + PollStatus<&mut T::Tally, BlockNumberFor, TrackIdOf>, ) -> Result, ) -> Result { match ReferendumInfoFor::::get(index) { @@ -849,7 +850,7 @@ impl, I: 'static> Pallet { fn schedule_enactment( index: ReferendumIndex, track: &TrackInfoOf, - desired: DispatchTime, + desired: DispatchTime>, origin: PalletsOriginOf, call: BoundedCallOf, ) { @@ -871,8 +872,8 @@ impl, I: 'static> Pallet { /// Set an alarm to dispatch `call` at block number `when`. fn set_alarm( call: BoundedCallOf, - when: T::BlockNumber, - ) -> Option<(T::BlockNumber, ScheduleAddressOf)> { + when: BlockNumberFor, + ) -> Option<(BlockNumberFor, ScheduleAddressOf)> { let alarm_interval = T::AlarmInterval::get().max(One::one()); // Alarm must go off no earlier than `when`. // This rounds `when` upwards to the next multiple of `alarm_interval`. @@ -905,9 +906,9 @@ impl, I: 'static> Pallet { fn begin_deciding( status: &mut ReferendumStatusOf, index: ReferendumIndex, - now: T::BlockNumber, + now: BlockNumberFor, track: &TrackInfoOf, - ) -> (Option, BeginDecidingBranch) { + ) -> (Option>, BeginDecidingBranch) { let is_passing = Self::is_passing( &status.tally, Zero::zero(), @@ -943,11 +944,11 @@ impl, I: 'static> Pallet { /// /// If `None`, then it is queued and should be nudged automatically as the queue gets drained. fn ready_for_deciding( - now: T::BlockNumber, + now: BlockNumberFor, track: &TrackInfoOf, index: ReferendumIndex, status: &mut ReferendumStatusOf, - ) -> (Option, ServiceBranch) { + ) -> (Option>, ServiceBranch) { let deciding_count = DecidingCount::::get(status.track); if deciding_count < track.max_deciding { // Begin deciding. @@ -1004,7 +1005,7 @@ impl, I: 'static> Pallet { fn ensure_alarm_at( status: &mut ReferendumStatusOf, index: ReferendumIndex, - alarm: T::BlockNumber, + alarm: BlockNumberFor, ) -> bool { if status.alarm.as_ref().map_or(true, |&(when, _)| when != alarm) { // Either no alarm or one that was different @@ -1049,7 +1050,7 @@ impl, I: 'static> Pallet { /// `TrackQueue`. Basically this happens when a referendum is in the deciding queue and receives /// a vote, or when it moves into the deciding queue. fn service_referendum( - now: T::BlockNumber, + now: BlockNumberFor, index: ReferendumIndex, mut status: ReferendumStatusOf, ) -> (ReferendumInfoOf, bool, ServiceBranch) { @@ -1061,7 +1062,7 @@ impl, I: 'static> Pallet { }; // Default the alarm to the end of the world. let timeout = status.submitted + T::UndecidingTimeout::get(); - let mut alarm = T::BlockNumber::max_value(); + let mut alarm = BlockNumberFor::::max_value(); let branch; match &mut status.deciding { None => { @@ -1192,7 +1193,7 @@ impl, I: 'static> Pallet { }, } - let dirty_alarm = if alarm < T::BlockNumber::max_value() { + let dirty_alarm = if alarm < BlockNumberFor::::max_value() { Self::ensure_alarm_at(&mut status, index, alarm) } else { Self::ensure_no_alarm(&mut status) @@ -1207,7 +1208,7 @@ impl, I: 'static> Pallet { tally: &T::Tally, track_id: TrackIdOf, track: &TrackInfoOf, - ) -> T::BlockNumber { + ) -> BlockNumberFor { deciding.confirming.unwrap_or_else(|| { // Set alarm to the point where the current voting would make it pass. let approval = tally.approval(track_id); @@ -1266,8 +1267,8 @@ impl, I: 'static> Pallet { /// `approval_needed`. fn is_passing( tally: &T::Tally, - elapsed: T::BlockNumber, - period: T::BlockNumber, + elapsed: BlockNumberFor, + period: BlockNumberFor, support_needed: &Curve, approval_needed: &Curve, id: TrackIdOf, diff --git a/frame/referenda/src/migration.rs b/frame/referenda/src/migration.rs index 6f796ca40d9be..6f5e42cd49657 100644 --- a/frame/referenda/src/migration.rs +++ b/frame/referenda/src/migration.rs @@ -37,7 +37,7 @@ pub mod v0 { pub type ReferendumInfoOf = ReferendumInfo< TrackIdOf, PalletsOriginOf, - ::BlockNumber, + frame_system::pallet_prelude::BlockNumberFor, BoundedCallOf, BalanceOf, TallyOf, diff --git a/frame/referenda/src/mock.rs b/frame/referenda/src/mock.rs index b6b5905709d0d..f42df260f4759 100644 --- a/frame/referenda/src/mock.rs +++ b/frame/referenda/src/mock.rs @@ -31,19 +31,14 @@ use frame_support::{ use frame_system::{EnsureRoot, EnsureSignedBy}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, Hash, IdentityLookup}, BuildStorage, DispatchResult, Perbill, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Balances: pallet_balances, @@ -71,13 +66,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/referenda/src/types.rs b/frame/referenda/src/types.rs index d61b8955443c2..ba89383888a7d 100644 --- a/frame/referenda/src/types.rs +++ b/frame/referenda/src/types.rs @@ -42,7 +42,7 @@ pub type PalletsOriginOf = pub type ReferendumInfoOf = ReferendumInfo< TrackIdOf, PalletsOriginOf, - ::BlockNumber, + BlockNumberFor, BoundedCallOf, BalanceOf, TallyOf, @@ -52,22 +52,19 @@ pub type ReferendumInfoOf = ReferendumInfo< pub type ReferendumStatusOf = ReferendumStatus< TrackIdOf, PalletsOriginOf, - ::BlockNumber, + BlockNumberFor, BoundedCallOf, BalanceOf, TallyOf, ::AccountId, ScheduleAddressOf, >; -pub type DecidingStatusOf = DecidingStatus<::BlockNumber>; -pub type TrackInfoOf = - TrackInfo, ::BlockNumber>; -pub type TrackIdOf = <>::Tracks as TracksInfo< - BalanceOf, - ::BlockNumber, ->>::Id; +pub type DecidingStatusOf = DecidingStatus>; +pub type TrackInfoOf = TrackInfo, BlockNumberFor>; +pub type TrackIdOf = + <>::Tracks as TracksInfo, BlockNumberFor>>::Id; pub type ScheduleAddressOf = <>::Scheduler as Anon< - ::BlockNumber, + BlockNumberFor, CallOf, PalletsOriginOf, >>::Address; diff --git a/frame/remark/src/mock.rs b/frame/remark/src/mock.rs index 13f20557c6ceb..45b30dad5c161 100644 --- a/frame/remark/src/mock.rs +++ b/frame/remark/src/mock.rs @@ -21,20 +21,15 @@ use crate as pallet_remark; use frame_support::traits::{ConstU16, ConstU32, ConstU64}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; pub type Block = frame_system::mocking::MockBlock; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Remark: pallet_remark::{ Pallet, Call, Event }, @@ -48,12 +43,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); diff --git a/frame/root-offences/src/mock.rs b/frame/root-offences/src/mock.rs index d8a8e597da484..0f9df833a4c7f 100644 --- a/frame/root-offences/src/mock.rs +++ b/frame/root-offences/src/mock.rs @@ -27,14 +27,13 @@ use pallet_staking::StakerStatus; use sp_core::H256; use sp_runtime::{ curve::PiecewiseLinear, - testing::{Header, UintAuthorityId}, + testing::UintAuthorityId, traits::{BlakeTwo256, IdentityLookup, Zero}, BuildStorage, }; use sp_staking::{EraIndex, SessionIndex}; use sp_std::collections::btree_map::BTreeMap; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; type AccountId = u64; type Balance = u64; @@ -44,10 +43,7 @@ pub const INIT_TIMESTAMP: u64 = 30_000; pub const BLOCK_TIME: u64 = 1000; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, @@ -92,13 +88,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/salary/src/lib.rs b/frame/salary/src/lib.rs index 1279a30717752..53dd7224909a8 100644 --- a/frame/salary/src/lib.rs +++ b/frame/salary/src/lib.rs @@ -126,14 +126,14 @@ pub mod pallet { /// The number of blocks between sequential payout cycles is the sum of this and /// `PayoutPeriod`. #[pallet::constant] - type RegistrationPeriod: Get; + type RegistrationPeriod: Get>; /// The number of blocks within a cycle which accounts have to claim the payout. /// /// The number of blocks between sequential payout cycles is the sum of this and /// `RegistrationPeriod`. #[pallet::constant] - type PayoutPeriod: Get; + type PayoutPeriod: Get>; /// The total budget per cycle. /// @@ -142,11 +142,10 @@ pub mod pallet { type Budget: Get>; } - pub type CycleIndexOf = ::BlockNumber; + pub type CycleIndexOf = BlockNumberFor; pub type BalanceOf = <>::Paymaster as Pay>::Balance; pub type IdOf = <>::Paymaster as Pay>::Id; - pub type StatusOf = - StatusType, ::BlockNumber, BalanceOf>; + pub type StatusOf = StatusType, BlockNumberFor, BalanceOf>; pub type ClaimantStatusOf = ClaimantStatus, BalanceOf, IdOf>; /// The overall status of the system. @@ -389,7 +388,7 @@ pub mod pallet { pub fn last_active(who: &T::AccountId) -> Result, DispatchError> { Ok(Claimant::::get(&who).ok_or(Error::::NotInducted)?.last_active) } - pub fn cycle_period() -> T::BlockNumber { + pub fn cycle_period() -> BlockNumberFor { T::RegistrationPeriod::get() + T::PayoutPeriod::get() } fn do_payout(who: T::AccountId, beneficiary: T::AccountId) -> DispatchResult { diff --git a/frame/salary/src/tests.rs b/frame/salary/src/tests.rs index 7ffa819724ba1..9f63fb173214a 100644 --- a/frame/salary/src/tests.rs +++ b/frame/salary/src/tests.rs @@ -27,7 +27,6 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, Identity, IdentityLookup}, BuildStorage, DispatchResult, }; @@ -36,14 +35,10 @@ use sp_std::cell::RefCell; use super::*; use crate as pallet_salary; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Salary: pallet_salary::{Pallet, Call, Storage, Event}, @@ -61,13 +56,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/scheduler/src/benchmarking.rs b/frame/scheduler/src/benchmarking.rs index d56e007ec9a2a..b41cea449654c 100644 --- a/frame/scheduler/src/benchmarking.rs +++ b/frame/scheduler/src/benchmarking.rs @@ -23,7 +23,7 @@ use frame_support::{ ensure, traits::{schedule::Priority, BoundedInline}, }; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use sp_std::{prelude::*, vec}; use crate::Pallet as Scheduler; @@ -42,7 +42,10 @@ type SystemOrigin = ::RuntimeOrigin; /// - `None`: aborted (hash without preimage) /// - `Some(true)`: hash resolves into call if possible, plain call otherwise /// - `Some(false)`: plain call -fn fill_schedule(when: T::BlockNumber, n: u32) -> Result<(), &'static str> { +fn fill_schedule( + when: frame_system::pallet_prelude::BlockNumberFor, + n: u32, +) -> Result<(), &'static str> { let t = DispatchTime::At(when); let origin: ::PalletsOrigin = frame_system::RawOrigin::Root.into(); for i in 0..n { @@ -125,7 +128,7 @@ fn make_origin(signed: bool) -> ::PalletsOrigin { benchmarks! { // `service_agendas` when no work is done. service_agendas_base { - let now = T::BlockNumber::from(BLOCK_NUMBER); + let now = BlockNumberFor::::from(BLOCK_NUMBER); IncompleteSince::::put(now - One::one()); }: { Scheduler::::service_agendas(&mut WeightMeter::max_limit(), now, 0); @@ -224,7 +227,7 @@ benchmarks! { schedule { let s in 0 .. (T::MaxScheduledPerBlock::get() - 1); let when = BLOCK_NUMBER.into(); - let periodic = Some((T::BlockNumber::one(), 100)); + let periodic = Some((BlockNumberFor::::one(), 100)); let priority = 0; // Essentially a no-op call. let call = Box::new(SystemCall::set_storage { items: vec![] }.into()); @@ -267,7 +270,7 @@ benchmarks! { let s in 0 .. (T::MaxScheduledPerBlock::get() - 1); let id = u32_to_name(s); let when = BLOCK_NUMBER.into(); - let periodic = Some((T::BlockNumber::one(), 100)); + let periodic = Some((BlockNumberFor::::one(), 100)); let priority = 0; // Essentially a no-op call. let call = Box::new(SystemCall::set_storage { items: vec![] }.into()); diff --git a/frame/scheduler/src/lib.rs b/frame/scheduler/src/lib.rs index 8194f286c8323..4e12e0332f422 100644 --- a/frame/scheduler/src/lib.rs +++ b/frame/scheduler/src/lib.rs @@ -72,7 +72,10 @@ use frame_support::{ }, weights::{Weight, WeightMeter}, }; -use frame_system::{self as system}; +use frame_system::{ + pallet_prelude::BlockNumberFor, + {self as system}, +}; use scale_info::TypeInfo; use sp_io::hashing::blake2_256; use sp_runtime::{ @@ -123,7 +126,7 @@ use crate::{Scheduled as ScheduledV3, Scheduled as ScheduledV2}; pub type ScheduledV2Of = ScheduledV2< Vec, ::RuntimeCall, - ::BlockNumber, + BlockNumberFor, ::PalletsOrigin, ::AccountId, >; @@ -131,7 +134,7 @@ pub type ScheduledV2Of = ScheduledV2< pub type ScheduledV3Of = ScheduledV3< Vec, CallOrHashOf, - ::BlockNumber, + BlockNumberFor, ::PalletsOrigin, ::AccountId, >; @@ -139,7 +142,7 @@ pub type ScheduledV3Of = ScheduledV3< pub type ScheduledOf = Scheduled< TaskName, Bounded<::RuntimeCall>, - ::BlockNumber, + BlockNumberFor, ::PalletsOrigin, ::AccountId, >; @@ -231,14 +234,14 @@ pub mod pallet { } #[pallet::storage] - pub type IncompleteSince = StorageValue<_, T::BlockNumber>; + pub type IncompleteSince = StorageValue<_, BlockNumberFor>; /// Items to be executed, indexed by the block number that they should be executed on. #[pallet::storage] pub type Agenda = StorageMap< _, Twox64Concat, - T::BlockNumber, + BlockNumberFor, BoundedVec>, T::MaxScheduledPerBlock>, ValueQuery, >; @@ -249,28 +252,28 @@ pub mod pallet { /// identities. #[pallet::storage] pub(crate) type Lookup = - StorageMap<_, Twox64Concat, TaskName, TaskAddress>; + StorageMap<_, Twox64Concat, TaskName, TaskAddress>>; /// Events type. #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// Scheduled some task. - Scheduled { when: T::BlockNumber, index: u32 }, + Scheduled { when: BlockNumberFor, index: u32 }, /// Canceled some task. - Canceled { when: T::BlockNumber, index: u32 }, + Canceled { when: BlockNumberFor, index: u32 }, /// Dispatched some task. Dispatched { - task: TaskAddress, + task: TaskAddress>, id: Option, result: DispatchResult, }, /// The call for the provided hash was not found so the task has been aborted. - CallUnavailable { task: TaskAddress, id: Option }, + CallUnavailable { task: TaskAddress>, id: Option }, /// The given task was unable to be renewed since the agenda is full at that block. - PeriodicFailed { task: TaskAddress, id: Option }, + PeriodicFailed { task: TaskAddress>, id: Option }, /// The given task can never be executed since it is overweight. - PermanentlyOverweight { task: TaskAddress, id: Option }, + PermanentlyOverweight { task: TaskAddress>, id: Option }, } #[pallet::error] @@ -290,7 +293,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { /// Execute the scheduled calls - fn on_initialize(now: T::BlockNumber) -> Weight { + fn on_initialize(now: BlockNumberFor) -> Weight { let mut weight_counter = WeightMeter::from_limit(T::MaximumWeight::get()); Self::service_agendas(&mut weight_counter, now, u32::max_value()); weight_counter.consumed @@ -304,8 +307,8 @@ pub mod pallet { #[pallet::weight(::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))] pub fn schedule( origin: OriginFor, - when: T::BlockNumber, - maybe_periodic: Option>, + when: BlockNumberFor, + maybe_periodic: Option>>, priority: schedule::Priority, call: Box<::RuntimeCall>, ) -> DispatchResult { @@ -324,7 +327,7 @@ pub mod pallet { /// Cancel an anonymously scheduled task. #[pallet::call_index(1)] #[pallet::weight(::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))] - pub fn cancel(origin: OriginFor, when: T::BlockNumber, index: u32) -> DispatchResult { + pub fn cancel(origin: OriginFor, when: BlockNumberFor, index: u32) -> DispatchResult { T::ScheduleOrigin::ensure_origin(origin.clone())?; let origin = ::RuntimeOrigin::from(origin); Self::do_cancel(Some(origin.caller().clone()), (when, index))?; @@ -337,8 +340,8 @@ pub mod pallet { pub fn schedule_named( origin: OriginFor, id: TaskName, - when: T::BlockNumber, - maybe_periodic: Option>, + when: BlockNumberFor, + maybe_periodic: Option>>, priority: schedule::Priority, call: Box<::RuntimeCall>, ) -> DispatchResult { @@ -370,8 +373,8 @@ pub mod pallet { #[pallet::weight(::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))] pub fn schedule_after( origin: OriginFor, - after: T::BlockNumber, - maybe_periodic: Option>, + after: BlockNumberFor, + maybe_periodic: Option>>, priority: schedule::Priority, call: Box<::RuntimeCall>, ) -> DispatchResult { @@ -393,8 +396,8 @@ pub mod pallet { pub fn schedule_named_after( origin: OriginFor, id: TaskName, - after: T::BlockNumber, - maybe_periodic: Option>, + after: BlockNumberFor, + maybe_periodic: Option>>, priority: schedule::Priority, call: Box<::RuntimeCall>, ) -> DispatchResult { @@ -434,7 +437,7 @@ impl> Pallet { } Agenda::::translate::< - Vec::RuntimeCall, T::BlockNumber>>>, + Vec::RuntimeCall, BlockNumberFor>>>, _, >(|_, agenda| { Some(BoundedVec::truncate_from( @@ -669,7 +672,7 @@ impl Pallet { Scheduled< TaskName, Bounded<::RuntimeCall>, - T::BlockNumber, + BlockNumberFor, OldOrigin, T::AccountId, >, @@ -695,7 +698,9 @@ impl Pallet { }); } - fn resolve_time(when: DispatchTime) -> Result { + fn resolve_time( + when: DispatchTime>, + ) -> Result, DispatchError> { let now = frame_system::Pallet::::block_number(); let when = match when { @@ -713,9 +718,9 @@ impl Pallet { } fn place_task( - when: T::BlockNumber, + when: BlockNumberFor, what: ScheduledOf, - ) -> Result, (DispatchError, ScheduledOf)> { + ) -> Result>, (DispatchError, ScheduledOf)> { let maybe_name = what.maybe_id; let index = Self::push_to_agenda(when, what)?; let address = (when, index); @@ -727,7 +732,7 @@ impl Pallet { } fn push_to_agenda( - when: T::BlockNumber, + when: BlockNumberFor, what: ScheduledOf, ) -> Result)> { let mut agenda = Agenda::::get(when); @@ -749,7 +754,7 @@ impl Pallet { /// Remove trailing `None` items of an agenda at `when`. If all items are `None` remove the /// agenda record entirely. - fn cleanup_agenda(when: T::BlockNumber) { + fn cleanup_agenda(when: BlockNumberFor) { let mut agenda = Agenda::::get(when); match agenda.iter().rposition(|i| i.is_some()) { Some(i) if agenda.len() > i + 1 => { @@ -764,12 +769,12 @@ impl Pallet { } fn do_schedule( - when: DispatchTime, - maybe_periodic: Option>, + when: DispatchTime>, + maybe_periodic: Option>>, priority: schedule::Priority, origin: T::PalletsOrigin, call: Bounded<::RuntimeCall>, - ) -> Result, DispatchError> { + ) -> Result>, DispatchError> { let when = Self::resolve_time(when)?; let lookup_hash = call.lookup_hash(); @@ -799,7 +804,7 @@ impl Pallet { fn do_cancel( origin: Option, - (when, index): TaskAddress, + (when, index): TaskAddress>, ) -> Result<(), DispatchError> { let scheduled = Agenda::::try_mutate(when, |agenda| { agenda.get_mut(index as usize).map_or( @@ -831,9 +836,9 @@ impl Pallet { } fn do_reschedule( - (when, index): TaskAddress, - new_time: DispatchTime, - ) -> Result, DispatchError> { + (when, index): TaskAddress>, + new_time: DispatchTime>, + ) -> Result>, DispatchError> { let new_time = Self::resolve_time(new_time)?; if new_time == when { @@ -853,12 +858,12 @@ impl Pallet { fn do_schedule_named( id: TaskName, - when: DispatchTime, - maybe_periodic: Option>, + when: DispatchTime>, + maybe_periodic: Option>>, priority: schedule::Priority, origin: T::PalletsOrigin, call: Bounded<::RuntimeCall>, - ) -> Result, DispatchError> { + ) -> Result>, DispatchError> { // ensure id it is unique if Lookup::::contains_key(&id) { return Err(Error::::FailedToSchedule.into()) @@ -922,8 +927,8 @@ impl Pallet { fn do_reschedule_named( id: TaskName, - new_time: DispatchTime, - ) -> Result, DispatchError> { + new_time: DispatchTime>, + ) -> Result>, DispatchError> { let new_time = Self::resolve_time(new_time)?; let lookup = Lookup::::get(id); @@ -953,7 +958,7 @@ use ServiceTaskError::*; impl Pallet { /// Service up to `max` agendas queue starting from earliest incompletely executed agenda. - fn service_agendas(weight: &mut WeightMeter, now: T::BlockNumber, max: u32) { + fn service_agendas(weight: &mut WeightMeter, now: BlockNumberFor, max: u32) { if !weight.check_accrue(T::WeightInfo::service_agendas_base()) { return } @@ -983,8 +988,8 @@ impl Pallet { fn service_agenda( weight: &mut WeightMeter, executed: &mut u32, - now: T::BlockNumber, - when: T::BlockNumber, + now: BlockNumberFor, + when: BlockNumberFor, max: u32, ) -> bool { let mut agenda = Agenda::::get(when); @@ -1052,8 +1057,8 @@ impl Pallet { /// - Rescheduling the task for execution in a later agenda if periodic. fn service_task( weight: &mut WeightMeter, - now: T::BlockNumber, - when: T::BlockNumber, + now: BlockNumberFor, + when: BlockNumberFor, agenda_index: u32, is_first: bool, mut task: ScheduledOf, @@ -1161,14 +1166,14 @@ impl Pallet { } impl> - schedule::v2::Anon::RuntimeCall, T::PalletsOrigin> for Pallet + schedule::v2::Anon, ::RuntimeCall, T::PalletsOrigin> for Pallet { - type Address = TaskAddress; + type Address = TaskAddress>; type Hash = T::Hash; fn schedule( - when: DispatchTime, - maybe_periodic: Option>, + when: DispatchTime>, + maybe_periodic: Option>>, priority: schedule::Priority, origin: T::PalletsOrigin, call: CallOrHashOf, @@ -1184,26 +1189,26 @@ impl> fn reschedule( address: Self::Address, - when: DispatchTime, + when: DispatchTime>, ) -> Result { Self::do_reschedule(address, when) } - fn next_dispatch_time((when, index): Self::Address) -> Result { + fn next_dispatch_time((when, index): Self::Address) -> Result, ()> { Agenda::::get(when).get(index as usize).ok_or(()).map(|_| when) } } impl> - schedule::v2::Named::RuntimeCall, T::PalletsOrigin> for Pallet + schedule::v2::Named, ::RuntimeCall, T::PalletsOrigin> for Pallet { - type Address = TaskAddress; + type Address = TaskAddress>; type Hash = T::Hash; fn schedule_named( id: Vec, - when: DispatchTime, - maybe_periodic: Option>, + when: DispatchTime>, + maybe_periodic: Option>>, priority: schedule::Priority, origin: T::PalletsOrigin, call: CallOrHashOf, @@ -1221,13 +1226,13 @@ impl> fn reschedule_named( id: Vec, - when: DispatchTime, + when: DispatchTime>, ) -> Result { let name = blake2_256(&id[..]); Self::do_reschedule_named(name, when) } - fn next_dispatch_time(id: Vec) -> Result { + fn next_dispatch_time(id: Vec) -> Result, ()> { let name = blake2_256(&id[..]); Lookup::::get(name) .and_then(|(when, index)| Agenda::::get(when).get(index as usize).map(|_| when)) @@ -1235,14 +1240,14 @@ impl> } } -impl schedule::v3::Anon::RuntimeCall, T::PalletsOrigin> +impl schedule::v3::Anon, ::RuntimeCall, T::PalletsOrigin> for Pallet { - type Address = TaskAddress; + type Address = TaskAddress>; fn schedule( - when: DispatchTime, - maybe_periodic: Option>, + when: DispatchTime>, + maybe_periodic: Option>>, priority: schedule::Priority, origin: T::PalletsOrigin, call: Bounded<::RuntimeCall>, @@ -1256,12 +1261,14 @@ impl schedule::v3::Anon::RuntimeCall, T fn reschedule( address: Self::Address, - when: DispatchTime, + when: DispatchTime>, ) -> Result { Self::do_reschedule(address, when).map_err(map_err_to_v3_err::) } - fn next_dispatch_time((when, index): Self::Address) -> Result { + fn next_dispatch_time( + (when, index): Self::Address, + ) -> Result, DispatchError> { Agenda::::get(when) .get(index as usize) .ok_or(DispatchError::Unavailable) @@ -1271,15 +1278,15 @@ impl schedule::v3::Anon::RuntimeCall, T use schedule::v3::TaskName; -impl schedule::v3::Named::RuntimeCall, T::PalletsOrigin> +impl schedule::v3::Named, ::RuntimeCall, T::PalletsOrigin> for Pallet { - type Address = TaskAddress; + type Address = TaskAddress>; fn schedule_named( id: TaskName, - when: DispatchTime, - maybe_periodic: Option>, + when: DispatchTime>, + maybe_periodic: Option>>, priority: schedule::Priority, origin: T::PalletsOrigin, call: Bounded<::RuntimeCall>, @@ -1293,12 +1300,12 @@ impl schedule::v3::Named::RuntimeCall, fn reschedule_named( id: TaskName, - when: DispatchTime, + when: DispatchTime>, ) -> Result { Self::do_reschedule_named(id, when).map_err(map_err_to_v3_err::) } - fn next_dispatch_time(id: TaskName) -> Result { + fn next_dispatch_time(id: TaskName) -> Result, DispatchError> { Lookup::::get(id) .and_then(|(when, index)| Agenda::::get(when).get(index as usize).map(|_| when)) .ok_or(DispatchError::Unavailable) diff --git a/frame/scheduler/src/migration.rs b/frame/scheduler/src/migration.rs index 78313fda66412..06259768f0aa1 100644 --- a/frame/scheduler/src/migration.rs +++ b/frame/scheduler/src/migration.rs @@ -19,6 +19,7 @@ use super::*; use frame_support::traits::OnRuntimeUpgrade; +use frame_system::pallet_prelude::BlockNumberFor; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; @@ -34,22 +35,14 @@ pub mod v1 { pub(crate) type Agenda = StorageMap< Pallet, Twox64Concat, - ::BlockNumber, - Vec< - Option< - ScheduledV1<::RuntimeCall, ::BlockNumber>, - >, - >, + BlockNumberFor, + Vec::RuntimeCall, BlockNumberFor>>>, ValueQuery, >; #[frame_support::storage_alias] - pub(crate) type Lookup = StorageMap< - Pallet, - Twox64Concat, - Vec, - TaskAddress<::BlockNumber>, - >; + pub(crate) type Lookup = + StorageMap, Twox64Concat, Vec, TaskAddress>>; } pub mod v2 { @@ -60,18 +53,14 @@ pub mod v2 { pub(crate) type Agenda = StorageMap< Pallet, Twox64Concat, - ::BlockNumber, + BlockNumberFor, Vec>>, ValueQuery, >; #[frame_support::storage_alias] - pub(crate) type Lookup = StorageMap< - Pallet, - Twox64Concat, - Vec, - TaskAddress<::BlockNumber>, - >; + pub(crate) type Lookup = + StorageMap, Twox64Concat, Vec, TaskAddress>>; } pub mod v3 { @@ -82,18 +71,14 @@ pub mod v3 { pub(crate) type Agenda = StorageMap< Pallet, Twox64Concat, - ::BlockNumber, + BlockNumberFor, Vec>>, ValueQuery, >; #[frame_support::storage_alias] - pub(crate) type Lookup = StorageMap< - Pallet, - Twox64Concat, - Vec, - TaskAddress<::BlockNumber>, - >; + pub(crate) type Lookup = + StorageMap, Twox64Concat, Vec, TaskAddress>>; /// Migrate the scheduler pallet from V3 to V4. pub struct MigrateToV4(sp_std::marker::PhantomData); diff --git a/frame/scheduler/src/mock.rs b/frame/scheduler/src/mock.rs index 7a98d8e0db1c6..f6dd554866be8 100644 --- a/frame/scheduler/src/mock.rs +++ b/frame/scheduler/src/mock.rs @@ -30,7 +30,6 @@ use frame_support::{ use frame_system::{EnsureRoot, EnsureSignedBy}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, Perbill, }; @@ -93,14 +92,10 @@ pub mod logger { } } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Logger: logger::{Pallet, Call, Event}, @@ -131,12 +126,11 @@ impl system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/scored-pool/src/lib.rs b/frame/scored-pool/src/lib.rs index 6aa64ea64abf0..2bf70cbc574c8 100644 --- a/frame/scored-pool/src/lib.rs +++ b/frame/scored-pool/src/lib.rs @@ -170,7 +170,7 @@ pub mod pallet { /// Every `Period` blocks the `Members` are filled with the highest scoring /// members in the `Pool`. #[pallet::constant] - type Period: Get; + type Period: Get>; /// The receiver of the signal for when the membership has been initialized. /// This happens pre-genesis and will usually be the same as `MembershipChanged`. @@ -282,7 +282,7 @@ pub mod pallet { impl, I: 'static> Hooks> for Pallet { /// Every `Period` blocks the `Members` set is refreshed from the /// highest scoring members in the pool. - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: frame_system::pallet_prelude::BlockNumberFor) -> Weight { if n % T::Period::get() == Zero::zero() { let pool = >::get(); >::refresh_members(pool, ChangeReceiver::MembershipChanged); diff --git a/frame/scored-pool/src/mock.rs b/frame/scored-pool/src/mock.rs index e6cfea1bfb281..8cbb0eae4b613 100644 --- a/frame/scored-pool/src/mock.rs +++ b/frame/scored-pool/src/mock.rs @@ -27,19 +27,14 @@ use frame_support::{ use frame_system::EnsureSignedBy; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -62,13 +57,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/session/benchmarking/src/lib.rs b/frame/session/benchmarking/src/lib.rs index a7e326fb27ac3..f27136e820d41 100644 --- a/frame/session/benchmarking/src/lib.rs +++ b/frame/session/benchmarking/src/lib.rs @@ -31,7 +31,7 @@ use frame_support::{ codec::Decode, traits::{Get, KeyOwnerProofSystem, OnInitialize}, }; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use pallet_session::{historical::Pallet as Historical, Pallet as Session, *}; use pallet_staking::{ benchmarking::create_validator_with_nominators, testing_utils::create_validators, @@ -46,8 +46,8 @@ pub trait Config: { } -impl OnInitialize for Pallet { - fn on_initialize(n: T::BlockNumber) -> frame_support::weights::Weight { +impl OnInitialize> for Pallet { + fn on_initialize(n: BlockNumberFor) -> frame_support::weights::Weight { pallet_session::Pallet::::on_initialize(n) } } @@ -156,7 +156,7 @@ fn check_membership_proof_setup( Session::::set_keys(RawOrigin::Signed(controller).into(), keys, proof).unwrap(); } - Pallet::::on_initialize(T::BlockNumber::one()); + Pallet::::on_initialize(frame_system::pallet_prelude::BlockNumberFor::::one()); // skip sessions until the new validator set is enacted while Session::::validators().len() < n as usize { diff --git a/frame/session/benchmarking/src/mock.rs b/frame/session/benchmarking/src/mock.rs index 67c1d95f4707d..d8bc4ba9c27ab 100644 --- a/frame/session/benchmarking/src/mock.rs +++ b/frame/session/benchmarking/src/mock.rs @@ -28,17 +28,12 @@ use sp_runtime::{traits::IdentityLookup, BuildStorage}; type AccountId = u64; type AccountIndex = u32; -type BlockNumber = u64; type Balance = u64; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -54,13 +49,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; - type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index d1d6296e65730..d2b1c2b744674 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -126,6 +126,7 @@ use frame_support::{ weights::Weight, Parameter, }; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::{ traits::{AtLeast32BitUnsigned, Convert, Member, One, OpaqueKeys, Zero}, ConsensusEngineId, KeyTypeId, Permill, RuntimeAppPublic, @@ -393,12 +394,12 @@ pub mod pallet { type ValidatorIdOf: Convert>; /// Indicator for when to end the session. - type ShouldEndSession: ShouldEndSession; + type ShouldEndSession: ShouldEndSession>; /// Something that can predict the next session rotation. This should typically come from /// the same logical unit that provides [`ShouldEndSession`], yet, it gives a best effort /// estimate. It is helpful to implement [`EstimateNextNewSession`]. - type NextSessionRotation: EstimateNextSessionRotation; + type NextSessionRotation: EstimateNextSessionRotation>; /// Handler for managing new session. type SessionManager: SessionManager; @@ -559,7 +560,7 @@ pub mod pallet { impl Hooks> for Pallet { /// Called when a block is initialized. Will rotate session if it is the last /// block of the current session. - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: BlockNumberFor) -> Weight { if T::ShouldEndSession::should_end_session(n) { Self::rotate_session(); T::BlockWeights::get().max_block @@ -901,14 +902,14 @@ impl ValidatorSet for Pallet { } } -impl EstimateNextNewSession for Pallet { - fn average_session_length() -> T::BlockNumber { +impl EstimateNextNewSession> for Pallet { + fn average_session_length() -> BlockNumberFor { T::NextSessionRotation::average_session_length() } /// This session pallet always calls new_session and next_session at the same time, hence we /// do a simple proxy and pass the function to next rotation. - fn estimate_next_new_session(now: T::BlockNumber) -> (Option, Weight) { + fn estimate_next_new_session(now: BlockNumberFor) -> (Option>, Weight) { T::NextSessionRotation::estimate_next_session_rotation(now) } } diff --git a/frame/session/src/mock.rs b/frame/session/src/mock.rs index 3d74c32dcdb25..58d1d30a050ac 100644 --- a/frame/session/src/mock.rs +++ b/frame/session/src/mock.rs @@ -27,7 +27,7 @@ use std::collections::BTreeMap; use sp_core::{crypto::key_types::DUMMY, H256}; use sp_runtime::{ impl_opaque_keys, - testing::{Header, UintAuthorityId}, + testing::UintAuthorityId, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; @@ -76,15 +76,11 @@ impl OpaqueKeys for PreUpgradeMockSessionKeys { } } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; #[cfg(feature = "historical")] frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, @@ -94,10 +90,7 @@ frame_support::construct_runtime!( #[cfg(not(feature = "historical"))] frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, @@ -246,13 +239,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index 3d4b9323246d8..ca8d96e193c84 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -416,10 +416,8 @@ impl BidKind { } } -pub type PayoutsFor = BoundedVec< - (::BlockNumber, BalanceOf), - >::MaxPayouts, ->; +pub type PayoutsFor = + BoundedVec<(BlockNumberFor, BalanceOf), >::MaxPayouts>; /// Information concerning a member. #[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] @@ -439,10 +437,7 @@ pub struct PayoutRecord { pub type PayoutRecordFor = PayoutRecord< BalanceOf, - BoundedVec< - (::BlockNumber, BalanceOf), - >::MaxPayouts, - >, + BoundedVec<(BlockNumberFor, BalanceOf), >::MaxPayouts>, >; /// Record for an individual new member who was elevated from a candidate recently. @@ -491,7 +486,7 @@ pub mod pallet { type Currency: ReservableCurrency; /// Something that provides randomness in the runtime. - type Randomness: Randomness; + type Randomness: Randomness>; /// The maximum number of strikes before a member gets funds slashed. #[pallet::constant] @@ -504,23 +499,23 @@ pub mod pallet { /// The number of blocks on which new candidates should be voted on. Together with /// `ClaimPeriod`, this sums to the number of blocks between candidate intake periods. #[pallet::constant] - type VotingPeriod: Get; + type VotingPeriod: Get>; /// The number of blocks on which new candidates can claim their membership and be the /// named head. #[pallet::constant] - type ClaimPeriod: Get; + type ClaimPeriod: Get>; /// The maximum duration of the payout lock. #[pallet::constant] - type MaxLockDuration: Get; + type MaxLockDuration: Get>; /// The origin that is allowed to call `found`. type FounderSetOrigin: EnsureOrigin; /// The number of blocks between membership challenges. #[pallet::constant] - type ChallengePeriod: Get; + type ChallengePeriod: Get>; /// The maximum number of payouts a member may have waiting unclaimed. #[pallet::constant] @@ -758,7 +753,7 @@ pub mod pallet { #[pallet::hooks] impl, I: 'static> Hooks> for Pallet { - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: BlockNumberFor) -> Weight { let mut weight = Weight::zero(); let weights = T::BlockWeights::get(); @@ -1409,7 +1404,7 @@ pub enum Period { impl, I: 'static> Pallet { /// Get the period we are currently in. - fn period() -> Period { + fn period() -> Period> { let claim_period = T::ClaimPeriod::get(); let voting_period = T::VotingPeriod::get(); let rotation_period = voting_period + claim_period; @@ -1902,7 +1897,7 @@ impl, I: 'static> Pallet { candidate: &T::AccountId, value: BalanceOf, kind: BidKind>, - maturity: T::BlockNumber, + maturity: BlockNumberFor, ) { let value = match kind { BidKind::Deposit(deposit) => { @@ -1939,7 +1934,7 @@ impl, I: 'static> Pallet { /// /// It is the caller's duty to ensure that `who` is already a member. This does nothing if `who` /// is not a member or if `value` is zero. - fn bump_payout(who: &T::AccountId, when: T::BlockNumber, value: BalanceOf) { + fn bump_payout(who: &T::AccountId, when: BlockNumberFor, value: BalanceOf) { if value.is_zero() { return } @@ -2022,7 +2017,7 @@ impl, I: 'static> Pallet { /// /// This is a rather opaque calculation based on the formula here: /// https://www.desmos.com/calculator/9itkal1tce - fn lock_duration(x: u32) -> T::BlockNumber { + fn lock_duration(x: u32) -> BlockNumberFor { let lock_pc = 100 - 50_000 / (x + 500); Percent::from_percent(lock_pc as u8) * T::MaxLockDuration::get() } diff --git a/frame/society/src/migrations.rs b/frame/society/src/migrations.rs index 404b1e5fd2cb9..4685167dcbcfd 100644 --- a/frame/society/src/migrations.rs +++ b/frame/society/src/migrations.rs @@ -172,7 +172,7 @@ pub(crate) mod old { Pallet, Twox64Concat, ::AccountId, - Vec<(::BlockNumber, BalanceOf)>, + Vec<(frame_system::pallet_prelude::BlockNumberFor, BalanceOf)>, ValueQuery, >; #[storage_alias] diff --git a/frame/society/src/mock.rs b/frame/society/src/mock.rs index 1b215febac6c0..b9a283ead3c66 100644 --- a/frame/society/src/mock.rs +++ b/frame/society/src/mock.rs @@ -28,21 +28,16 @@ use frame_support_test::TestRandomness; use frame_system::EnsureSignedBy; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; use RuntimeOrigin as Origin; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -70,13 +65,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u128; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index 2a5edd6e00e56..025c5c61fcbb7 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -32,7 +32,7 @@ use sp_core::H256; use sp_io; use sp_runtime::{ curve::PiecewiseLinear, - testing::{Header, UintAuthorityId}, + testing::UintAuthorityId, traits::{IdentityLookup, Zero}, BuildStorage, }; @@ -83,14 +83,10 @@ pub fn is_disabled(controller: AccountId) -> bool { Session::disabled_validators().contains(&validator_index) } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Authorship: pallet_authorship, @@ -129,13 +125,12 @@ impl frame_system::Config for Test { type DbWeight = RocksDbWeight; type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; - type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU64<250>; type Version = (); diff --git a/frame/staking/src/pallet/impls.rs b/frame/staking/src/pallet/impls.rs index 5166608a97aab..f2aa48e3316da 100644 --- a/frame/staking/src/pallet/impls.rs +++ b/frame/staking/src/pallet/impls.rs @@ -1022,7 +1022,7 @@ impl ElectionDataProvider for Pallet { Ok(Self::get_npos_targets(None)) } - fn next_election_prediction(now: T::BlockNumber) -> T::BlockNumber { + fn next_election_prediction(now: BlockNumberFor) -> BlockNumberFor { let current_era = Self::current_era().unwrap_or(0); let current_session = Self::current_planned_session(); let current_era_start_session_index = @@ -1039,7 +1039,7 @@ impl ElectionDataProvider for Pallet { let session_length = T::NextNewSession::average_session_length(); - let sessions_left: T::BlockNumber = match ForceEra::::get() { + let sessions_left: BlockNumberFor = match ForceEra::::get() { Forcing::ForceNone => Bounded::max_value(), Forcing::ForceNew | Forcing::ForceAlways => Zero::zero(), Forcing::NotForcing if era_progress >= T::SessionsPerEra::get() => Zero::zero(), @@ -1238,7 +1238,7 @@ impl historical::SessionManager pallet_authorship::EventHandler for Pallet +impl pallet_authorship::EventHandler> for Pallet where T: Config + pallet_authorship::Config + pallet_session::Config, { diff --git a/frame/staking/src/pallet/mod.rs b/frame/staking/src/pallet/mod.rs index 41b8d4b415e1a..dfca6fec3a8f5 100644 --- a/frame/staking/src/pallet/mod.rs +++ b/frame/staking/src/pallet/mod.rs @@ -87,7 +87,7 @@ pub mod pallet { /// The staking balance. type Currency: LockableCurrency< Self::AccountId, - Moment = Self::BlockNumber, + Moment = BlockNumberFor, Balance = Self::CurrencyBalance, >; /// Just the `Currency::Balance` type; we have this item to allow us to constrain it to @@ -118,14 +118,14 @@ pub mod pallet { /// Something that provides the election functionality. type ElectionProvider: ElectionProvider< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, // we only accept an election provider that has staking as data provider. DataProvider = Pallet, >; /// Something that provides the election functionality at genesis. type GenesisElectionProvider: ElectionProvider< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, DataProvider = Pallet, >; @@ -200,7 +200,7 @@ pub mod pallet { /// Something that can estimate the next session change, accurately or as a best effort /// guess. - type NextNewSession: EstimateNextNewSession; + type NextNewSession: EstimateNextNewSession>; /// The maximum number of nominators rewarded for each validator. /// diff --git a/frame/state-trie-migration/src/lib.rs b/frame/state-trie-migration/src/lib.rs index c7d4924de1fb9..40783482ad52e 100644 --- a/frame/state-trie-migration/src/lib.rs +++ b/frame/state-trie-migration/src/lib.rs @@ -1065,15 +1065,11 @@ mod mock { BuildStorage, StorageChild, }; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; - type Block = frame_system::mocking::MockBlock; + type Block = frame_system::mocking::MockBlockU32; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Config, Storage, Event}, @@ -1092,12 +1088,11 @@ mod mock { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u32; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = sp_runtime::generic::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU32<250>; type DbWeight = (); @@ -1619,7 +1614,7 @@ pub(crate) mod remote_tests { traits::{Get, Hooks}, weights::Weight, }; - use frame_system::Pallet as System; + use frame_system::{pallet_prelude::BlockNumberFor, Pallet as System}; use remote_externalities::Mode; use sp_core::H256; use sp_runtime::{ @@ -1630,7 +1625,7 @@ pub(crate) mod remote_tests { #[allow(dead_code)] fn run_to_block>( - n: ::BlockNumber, + n: BlockNumberFor, ) -> (H256, Weight) { let mut root = Default::default(); let mut weight_sum = Weight::zero(); @@ -1670,7 +1665,7 @@ pub(crate) mod remote_tests { frame_system::Pallet::::block_number() }); - let mut duration: ::BlockNumber = Zero::zero(); + let mut duration: BlockNumberFor = Zero::zero(); // set the version to 1, as if the upgrade happened. ext.state_version = sp_core::storage::StateVersion::V1; diff --git a/frame/statement/src/mock.rs b/frame/statement/src/mock.rs index f2e81b7719021..bea06a68c0d38 100644 --- a/frame/statement/src/mock.rs +++ b/frame/statement/src/mock.rs @@ -27,12 +27,10 @@ use frame_support::{ }; use sp_core::{Pair, H256}; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, AccountId32, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; pub const MIN_ALLOWED_STATEMENTS: u32 = 4; @@ -41,10 +39,7 @@ pub const MIN_ALLOWED_BYTES: u32 = 1024; pub const MAX_ALLOWED_BYTES: u32 = 4096; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Balances: pallet_balances, @@ -60,12 +55,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId32; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/sudo/src/mock.rs b/frame/sudo/src/mock.rs index 4854b006e19d8..5423f99599c03 100644 --- a/frame/sudo/src/mock.rs +++ b/frame/sudo/src/mock.rs @@ -23,7 +23,6 @@ use frame_support::traits::{ConstU32, ConstU64, Contains}; use sp_core::H256; use sp_io; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; @@ -91,14 +90,10 @@ pub mod logger { pub(super) type I32Log = StorageValue<_, BoundedVec>, ValueQuery>; } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Sudo: sudo::{Pallet, Call, Config, Storage, Event}, @@ -121,12 +116,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/support/procedural/src/construct_runtime/expand/inherent.rs b/frame/support/procedural/src/construct_runtime/expand/inherent.rs index 8218f3746e2c3..1dc51d9cd2bc4 100644 --- a/frame/support/procedural/src/construct_runtime/expand/inherent.rs +++ b/frame/support/procedural/src/construct_runtime/expand/inherent.rs @@ -19,12 +19,12 @@ use crate::construct_runtime::Pallet; use proc_macro2::TokenStream; use quote::quote; use std::str::FromStr; -use syn::{Ident, TypePath}; +use syn::Ident; pub fn expand_outer_inherent( runtime: &Ident, - block: &TypePath, - unchecked_extrinsic: &TypePath, + block: &TokenStream, + unchecked_extrinsic: &TokenStream, pallet_decls: &[Pallet], scrate: &TokenStream, ) -> TokenStream { diff --git a/frame/support/procedural/src/construct_runtime/expand/metadata.rs b/frame/support/procedural/src/construct_runtime/expand/metadata.rs index 3f88d8c6d1353..0975fedb35d5b 100644 --- a/frame/support/procedural/src/construct_runtime/expand/metadata.rs +++ b/frame/support/procedural/src/construct_runtime/expand/metadata.rs @@ -19,13 +19,13 @@ use crate::construct_runtime::{parse::PalletPath, Pallet}; use proc_macro2::TokenStream; use quote::quote; use std::str::FromStr; -use syn::{Ident, TypePath}; +use syn::Ident; pub fn expand_runtime_metadata( runtime: &Ident, pallet_declarations: &[Pallet], scrate: &TokenStream, - extrinsic: &TypePath, + extrinsic: &TokenStream, system_path: &PalletPath, ) -> TokenStream { let pallets = pallet_declarations diff --git a/frame/support/procedural/src/construct_runtime/mod.rs b/frame/support/procedural/src/construct_runtime/mod.rs index 203d43ab3cc39..efc2244154479 100644 --- a/frame/support/procedural/src/construct_runtime/mod.rs +++ b/frame/support/procedural/src/construct_runtime/mod.rs @@ -216,10 +216,7 @@ use frame_support_procedural_tools::{ generate_crate_access, generate_crate_access_2018, generate_hidden_includes, }; use itertools::Itertools; -use parse::{ - ExplicitRuntimeDeclaration, ImplicitRuntimeDeclaration, Pallet, RuntimeDeclaration, - WhereSection, -}; +use parse::{ExplicitRuntimeDeclaration, ImplicitRuntimeDeclaration, Pallet, RuntimeDeclaration}; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::quote; @@ -337,19 +334,14 @@ fn construct_runtime_explicit_to_explicit_expanded( fn construct_runtime_final_expansion( definition: ExplicitRuntimeDeclaration, ) -> Result { - let ExplicitRuntimeDeclaration { - name, - where_section: WhereSection { block, node_block, unchecked_extrinsic }, - pallets, - pallets_token, - } = definition; + let ExplicitRuntimeDeclaration { name, pallets, pallets_token, where_section } = definition; let system_pallet = pallets.iter().find(|decl| decl.name == SYSTEM_PALLET_NAME).ok_or_else(|| { syn::Error::new( pallets_token.span.join(), "`System` pallet declaration is missing. \ - Please add this line: `System: frame_system::{Pallet, Call, Storage, Config, Event},`", + Please add this line: `System: frame_system::{Pallet, Call, Storage, Config, Event},`", ) })?; if !system_pallet.cfg_pattern.is_empty() { @@ -379,6 +371,10 @@ fn construct_runtime_final_expansion( let scrate = generate_crate_access(hidden_crate_name, "frame-support"); let scrate_decl = generate_hidden_includes(hidden_crate_name, "frame-support"); + let frame_system = generate_crate_access_2018("frame-system")?; + let block = quote!(<#name as #frame_system::Config>::Block); + let unchecked_extrinsic = quote!(<#block as #scrate::sp_runtime::traits::Block>::Extrinsic); + let outer_event = expand::expand_outer_enum(&name, &pallets, &scrate, expand::OuterEnumType::Event)?; let outer_error = @@ -407,7 +403,21 @@ fn construct_runtime_final_expansion( let integrity_test = decl_integrity_test(&scrate); let static_assertions = decl_static_assertions(&name, &pallets, &scrate); + let warning = + where_section.map_or(None, |where_section| { + Some(proc_macro_warning::Warning::new_deprecated("WhereSection") + .old("use a `where` clause in `construct_runtime`") + .new("use `frame_system::Config` to set the `Block` type and delete this clause. + It is planned to be removed in December 2023") + .help_links(&["https://github.com/paritytech/substrate/pull/14437"]) + .span(where_section.span) + .build(), + ) + }); + let res = quote!( + #warning + #scrate_decl // Prevent UncheckedExtrinsic to print unused warning. @@ -421,9 +431,6 @@ fn construct_runtime_final_expansion( #scrate::scale_info::TypeInfo )] pub struct #name; - impl #scrate::sp_runtime::traits::GetNodeBlockType for #name { - type NodeBlock = #node_block; - } impl #scrate::sp_runtime::traits::GetRuntimeBlockType for #name { type RuntimeBlock = #block; } diff --git a/frame/support/procedural/src/construct_runtime/parse.rs b/frame/support/procedural/src/construct_runtime/parse.rs index b731bb0c83e27..9b08e16469754 100644 --- a/frame/support/procedural/src/construct_runtime/parse.rs +++ b/frame/support/procedural/src/construct_runtime/parse.rs @@ -65,7 +65,7 @@ pub enum RuntimeDeclaration { #[derive(Debug)] pub struct ImplicitRuntimeDeclaration { pub name: Ident, - pub where_section: WhereSection, + pub where_section: Option, pub pallets: Vec, } @@ -73,7 +73,7 @@ pub struct ImplicitRuntimeDeclaration { #[derive(Debug)] pub struct ExplicitRuntimeDeclaration { pub name: Ident, - pub where_section: WhereSection, + pub where_section: Option, pub pallets: Vec, pub pallets_token: token::Brace, } @@ -90,7 +90,7 @@ impl Parse for RuntimeDeclaration { } let name = input.parse::()?; - let where_section = input.parse()?; + let where_section = if input.peek(token::Where) { Some(input.parse()?) } else { None }; let pallets = input.parse::>>()?; let pallets_token = pallets.token; @@ -122,6 +122,7 @@ impl Parse for RuntimeDeclaration { #[derive(Debug)] pub struct WhereSection { + pub span: Span, pub block: syn::TypePath, pub node_block: syn::TypePath, pub unchecked_extrinsic: syn::TypePath, @@ -130,6 +131,7 @@ pub struct WhereSection { impl Parse for WhereSection { fn parse(input: ParseStream) -> Result { input.parse::()?; + let mut definitions = Vec::new(); while !input.peek(token::Brace) { let definition: WhereDefinition = input.parse()?; @@ -153,7 +155,7 @@ impl Parse for WhereSection { ); return Err(Error::new(*kind_span, msg)) } - Ok(Self { block, node_block, unchecked_extrinsic }) + Ok(Self { span: input.span(), block, node_block, unchecked_extrinsic }) } } diff --git a/frame/support/procedural/src/lib.rs b/frame/support/procedural/src/lib.rs index ca82a7971aca0..570f079db82f4 100644 --- a/frame/support/procedural/src/lib.rs +++ b/frame/support/procedural/src/lib.rs @@ -856,7 +856,7 @@ pub fn storage_alias(_: TokenStream, input: TokenStream) -> TokenStream { /// type RuntimeOrigin = RuntimeOrigin; /// type OnSetCode = (); /// type PalletInfo = PalletInfo; -/// type Header = Header; +/// type Block = Block; /// // We decide to override this one. /// type AccountData = pallet_balances::AccountData; /// } @@ -902,7 +902,7 @@ pub fn storage_alias(_: TokenStream, input: TokenStream) -> TokenStream { /// type RuntimeOrigin = RuntimeOrigin; /// type OnSetCode = (); /// type PalletInfo = PalletInfo; -/// type Header = Header; +/// type Block = Block; /// type AccountData = pallet_balances::AccountData; /// type Version = ::Version; /// type BlockWeights = ::BlockWeights; @@ -1559,7 +1559,7 @@ pub fn unbounded(_: TokenStream, _: TokenStream) -> TokenStream { /// ```ignore /// #[pallet::storage] /// #[pallet::whitelist_storage] -/// pub(super) type Number = StorageValue<_, T::BlockNumber, ValueQuery>; +/// pub(super) type Number = StorageValue<_, frame_system::pallet_prelude::BlockNumberFor::, ValueQuery>; /// ``` /// /// NOTE: As with all `pallet::*` attributes, this one _must_ be written as diff --git a/frame/support/procedural/src/pallet/expand/hooks.rs b/frame/support/procedural/src/pallet/expand/hooks.rs index ef22f5a3af5be..76e1fe76116b2 100644 --- a/frame/support/procedural/src/pallet/expand/hooks.rs +++ b/frame/support/procedural/src/pallet/expand/hooks.rs @@ -75,7 +75,7 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { let frame_system = &def.frame_system; quote::quote! { impl<#type_impl_gen> - #frame_support::traits::Hooks<::BlockNumber> + #frame_support::traits::Hooks<#frame_system::pallet_prelude::BlockNumberFor::> for #pallet_ident<#type_use_gen> #where_clause {} } } else { @@ -137,50 +137,50 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { #hooks_impl impl<#type_impl_gen> - #frame_support::traits::OnFinalize<::BlockNumber> + #frame_support::traits::OnFinalize<#frame_system::pallet_prelude::BlockNumberFor::> for #pallet_ident<#type_use_gen> #where_clause { - fn on_finalize(n: ::BlockNumber) { + fn on_finalize(n: #frame_system::pallet_prelude::BlockNumberFor::) { #frame_support::sp_tracing::enter_span!( #frame_support::sp_tracing::trace_span!("on_finalize") ); < Self as #frame_support::traits::Hooks< - ::BlockNumber + #frame_system::pallet_prelude::BlockNumberFor:: > >::on_finalize(n) } } impl<#type_impl_gen> - #frame_support::traits::OnIdle<::BlockNumber> + #frame_support::traits::OnIdle<#frame_system::pallet_prelude::BlockNumberFor::> for #pallet_ident<#type_use_gen> #where_clause { fn on_idle( - n: ::BlockNumber, + n: #frame_system::pallet_prelude::BlockNumberFor::, remaining_weight: #frame_support::weights::Weight ) -> #frame_support::weights::Weight { < Self as #frame_support::traits::Hooks< - ::BlockNumber + #frame_system::pallet_prelude::BlockNumberFor:: > >::on_idle(n, remaining_weight) } } impl<#type_impl_gen> - #frame_support::traits::OnInitialize<::BlockNumber> + #frame_support::traits::OnInitialize<#frame_system::pallet_prelude::BlockNumberFor::> for #pallet_ident<#type_use_gen> #where_clause { fn on_initialize( - n: ::BlockNumber + n: #frame_system::pallet_prelude::BlockNumberFor:: ) -> #frame_support::weights::Weight { #frame_support::sp_tracing::enter_span!( #frame_support::sp_tracing::trace_span!("on_initialize") ); < Self as #frame_support::traits::Hooks< - ::BlockNumber + #frame_system::pallet_prelude::BlockNumberFor:: > >::on_initialize(n) } @@ -205,7 +205,7 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { < Self as #frame_support::traits::Hooks< - ::BlockNumber + #frame_system::pallet_prelude::BlockNumberFor:: > >::on_runtime_upgrade() } @@ -215,7 +215,7 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { < Self as - #frame_support::traits::Hooks<::BlockNumber> + #frame_support::traits::Hooks<#frame_system::pallet_prelude::BlockNumberFor::> >::pre_upgrade() } @@ -226,19 +226,19 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { < Self as - #frame_support::traits::Hooks<::BlockNumber> + #frame_support::traits::Hooks<#frame_system::pallet_prelude::BlockNumberFor::> >::post_upgrade(state) } } impl<#type_impl_gen> - #frame_support::traits::OffchainWorker<::BlockNumber> + #frame_support::traits::OffchainWorker<#frame_system::pallet_prelude::BlockNumberFor::> for #pallet_ident<#type_use_gen> #where_clause { - fn offchain_worker(n: ::BlockNumber) { + fn offchain_worker(n: #frame_system::pallet_prelude::BlockNumberFor::) { < Self as #frame_support::traits::Hooks< - ::BlockNumber + #frame_system::pallet_prelude::BlockNumberFor:: > >::offchain_worker(n) } @@ -253,7 +253,7 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { fn integrity_test() { < Self as #frame_support::traits::Hooks< - ::BlockNumber + #frame_system::pallet_prelude::BlockNumberFor:: > >::integrity_test() } @@ -262,17 +262,17 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { #[cfg(feature = "try-runtime")] impl<#type_impl_gen> - #frame_support::traits::TryState<::BlockNumber> + #frame_support::traits::TryState<#frame_system::pallet_prelude::BlockNumberFor::> for #pallet_ident<#type_use_gen> #where_clause { fn try_state( - n: ::BlockNumber, + n: #frame_system::pallet_prelude::BlockNumberFor::, _s: #frame_support::traits::TryStateSelect ) -> Result<(), #frame_support::sp_runtime::TryRuntimeError> { #log_try_state < Self as #frame_support::traits::Hooks< - ::BlockNumber + #frame_system::pallet_prelude::BlockNumberFor:: > >::try_state(n) } diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index 9981e5ad65b78..7dfac19c9407d 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -645,259 +645,6 @@ impl PaysFee for (u64, Pays) { // END TODO /// Declares a `Module` struct and a `Call` enum, which implements the dispatch logic. -/// -/// ## Declaration -/// -/// ``` -/// # #[macro_use] -/// # extern crate frame_support; -/// # use frame_support::dispatch; -/// # use frame_system::{Config, ensure_signed}; -/// decl_module! { -/// pub struct Module for enum Call where origin: T::RuntimeOrigin { -/// -/// // Private functions are dispatchable, but not available to other -/// // FRAME pallets. -/// #[weight = 0] -/// fn my_function(origin, var: u64) -> dispatch::DispatchResult { -/// // Your implementation -/// Ok(()) -/// } -/// -/// // Public functions are both dispatchable and available to other -/// // FRAME pallets. -/// #[weight = 0] -/// pub fn my_public_function(origin) -> dispatch::DispatchResult { -/// // Your implementation -/// Ok(()) -/// } -/// } -/// } -/// # fn main() {} -/// ``` -/// -/// The declaration is set with the header where: -/// -/// * `Module`: The struct generated by the macro, with type `Config`. -/// * `Call`: The enum generated for every pallet, which implements -/// [`Callable`](./dispatch/trait.Callable.html). -/// * `origin`: Alias of `T::RuntimeOrigin`. -/// * `Result`: The expected return type from pallet functions. -/// -/// The first parameter of dispatchable functions must always be `origin`. -/// -/// ### Shorthand Example -/// -/// The macro automatically expands a shorthand function declaration to return the -/// [`DispatchResult`] type. These functions are the same: -/// -/// ``` -/// # #[macro_use] -/// # extern crate frame_support; -/// # use frame_support::dispatch; -/// # use frame_system::{Config, ensure_signed}; -/// decl_module! { -/// pub struct Module for enum Call where origin: T::RuntimeOrigin { -/// #[weight = 0] -/// fn my_long_function(origin) -> dispatch::DispatchResult { -/// // Your implementation -/// Ok(()) -/// } -/// -/// #[weight = 0] -/// fn my_short_function(origin) { -/// // Your implementation -/// } -/// } -/// } -/// # fn main() {} -/// ``` -/// -/// ### Consuming only portions of the annotated static weight -/// -/// Per default a callable function consumes all of its static weight as declared via -/// the #\[weight\] attribute. However, there are use cases where only a portion of this -/// weight should be consumed. In that case the static weight is charged pre dispatch and -/// the difference is refunded post dispatch. -/// -/// In order to make use of this feature the function must return `DispatchResultWithPostInfo` -/// in place of the default `DispatchResult`. Then the actually consumed weight can be returned. -/// To consume a non default weight while returning an error -/// [`WithPostDispatchInfo::with_weight`](./weight/trait.WithPostDispatchInfo.html) can be used -/// to augment any error with custom weight information. -/// -/// ``` -/// # #[macro_use] -/// # extern crate frame_support; -/// # use frame_support::{weights::Weight, dispatch::{DispatchResultWithPostInfo, WithPostDispatchInfo, PostDispatchInfo}}; -/// # use frame_system::{Config, ensure_signed}; -/// decl_module! { -/// pub struct Module for enum Call where origin: T::RuntimeOrigin { -/// #[weight = 1_000_000] -/// fn my_long_function(origin, do_expensive_calc: bool) -> DispatchResultWithPostInfo { -/// ensure_signed(origin).map_err(|e| e.with_weight(Weight::from_parts(100_000, 0)))?; -/// if do_expensive_calc { -/// // do the expensive calculation -/// // ... -/// // return None to indicate that we are using all weight (the default) -/// return Ok(None::.into()); -/// } -/// // expensive calculation not executed: use only a portion of the weight -/// Ok(PostDispatchInfo { actual_weight: Some(Weight::from_parts(100_000, 0)), ..Default::default() }) -/// } -/// } -/// } -/// # fn main() {} -/// ``` -/// -/// ### Transactional Function Example -/// -/// Transactional function discards all changes to storage if it returns `Err`, or commits if -/// `Ok`, via the #\[transactional\] attribute. Note the attribute must be after #\[weight\]. -/// The #\[transactional\] attribute is deprecated since it is the default behaviour. -/// -/// ``` -/// # #[macro_use] -/// # extern crate frame_support; -/// # use frame_support::transactional; -/// # use frame_system::Config; -/// decl_module! { -/// pub struct Module for enum Call where origin: T::RuntimeOrigin { -/// #[weight = 0] -/// #[transactional] -/// fn my_short_function(origin) { -/// // Your implementation -/// } -/// } -/// } -/// # fn main() {} -/// ``` -/// -/// ### Privileged Function Example -/// -/// A privileged function checks that the origin of the call is `ROOT`. -/// -/// ``` -/// # #[macro_use] -/// # extern crate frame_support; -/// # use frame_support::dispatch; -/// # use frame_system::{Config, ensure_signed, ensure_root}; -/// decl_module! { -/// pub struct Module for enum Call where origin: T::RuntimeOrigin { -/// #[weight = 0] -/// fn my_privileged_function(origin) -> dispatch::DispatchResult { -/// ensure_root(origin)?; -/// // Your implementation -/// Ok(()) -/// } -/// } -/// } -/// # fn main() {} -/// ``` -/// -/// ### Attributes on Functions -/// -/// Attributes on functions are supported, but must be in the order of: -/// 1. Optional #\[doc\] attribute. -/// 2. #\[weight\] attribute. -/// 3. Optional function attributes, for instance #\[transactional\]. Those function attributes will -/// be written only on the dispatchable functions implemented on `Module`, not on the `Call` enum -/// variant. -/// -/// ## Multiple Module Instances Example -/// -/// A Substrate module can be built such that multiple instances of the same module can be used -/// within a single runtime. For example, the [Balances module](../pallet_balances/index.html) can -/// be added multiple times to your runtime in order to support multiple, independent currencies for -/// your blockchain. Here is an example of how you would declare such a module using the -/// `decl_module!` macro: -/// -/// ``` -/// # #[macro_use] -/// # extern crate frame_support; -/// # use frame_support::dispatch; -/// # use frame_system::ensure_signed; -/// # pub struct DefaultInstance; -/// # pub trait Instance: 'static {} -/// # impl Instance for DefaultInstance {} -/// pub trait Config: frame_system::Config {} -/// -/// decl_module! { -/// pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: T::RuntimeOrigin { -/// // Your implementation -/// } -/// } -/// # fn main() {} -/// ``` -/// -/// Note: `decl_storage` must be called to generate `Instance` trait and optionally -/// `DefaultInstance` type. -/// -/// ## Where clause -/// -/// Besides the default `origin: T::RuntimeOrigin`, you can also pass other bounds to the module -/// declaration. This where bound will be replicated to all types generated by this macro. The -/// chaining of multiple trait bounds with `+` is not supported. If multiple bounds for one type are -/// required, it needs to be split up into multiple bounds. -/// -/// ``` -/// # #[macro_use] -/// # extern crate frame_support; -/// # use frame_support::dispatch; -/// # use frame_system::{self as system, ensure_signed}; -/// pub trait Config: system::Config where Self::AccountId: From {} -/// -/// decl_module! { -/// pub struct Module for enum Call where origin: T::RuntimeOrigin, T::AccountId: From { -/// // Your implementation -/// } -/// } -/// # fn main() {} -/// ``` -/// -/// ## Reserved Functions -/// -/// The following are reserved function signatures: -/// -/// * `deposit_event`: Helper function for depositing an [event](https://docs.substrate.io/main-docs/build/events-errors/). -/// The default behavior is to call `deposit_event` from the [System -/// module](../frame_system/index.html). However, you can write your own implementation for events -/// in your runtime. To use the default behavior, add `fn deposit_event() = default;` to your -/// `Module`. -/// -/// The following reserved functions also take the block number (with type `T::BlockNumber`) as an -/// optional input: -/// -/// * `on_runtime_upgrade`: Executes at the beginning of a block prior to on_initialize when there -/// is a runtime upgrade. This allows each module to upgrade its storage before the storage items -/// are used. As such, **calling other modules must be avoided**!! Using this function will -/// implement the [`OnRuntimeUpgrade`](../sp_runtime/traits/trait.OnRuntimeUpgrade.html) trait. -/// Function signature must be `fn on_runtime_upgrade() -> frame_support::weights::Weight`. -/// -/// * `on_initialize`: Executes at the beginning of a block. Using this function will -/// implement the [`OnInitialize`](./trait.OnInitialize.html) trait. -/// Function signature can be either: -/// * `fn on_initialize(n: BlockNumber) -> frame_support::weights::Weight` or -/// * `fn on_initialize() -> frame_support::weights::Weight` -/// -/// * `on_idle`: Executes at the end of a block. Passes a remaining weight to provide a threshold -/// for when to execute non vital functions. Using this function will implement the -/// [`OnIdle`](./traits/trait.OnIdle.html) trait. -/// Function signature is: -/// * `fn on_idle(n: BlockNumber, remaining_weight: Weight) -> frame_support::weights::Weight` -/// -/// * `on_finalize`: Executes at the end of a block. Using this function will -/// implement the [`OnFinalize`](./traits/trait.OnFinalize.html) trait. -/// Function signature can be either: -/// * `fn on_finalize(n: BlockNumber) -> frame_support::weights::Weight` or -/// * `fn on_finalize() -> frame_support::weights::Weight` -/// -/// * `offchain_worker`: Executes at the beginning of a block and produces extrinsics for a future -/// block upon completion. Using this function will implement the -/// [`OffchainWorker`](./traits/trait.OffchainWorker.html) trait. -/// * `integrity_test`: Executes in a test generated by `construct_runtime`, note it doesn't execute -/// in an externalities-provided environment. Implement -/// [`IntegrityTest`](./trait.IntegrityTest.html) trait. #[macro_export] #[deprecated(note = "Will be removed after July 2023; use the attribute `#[pallet]` macro instead. For more info, see: ")] @@ -3587,7 +3334,7 @@ mod weight_tests { #[pallet::config] #[pallet::disable_frame_system_supertrait_check] pub trait Config: 'static { - type BlockNumber: Parameter + Default + MaxEncodedLen; + type Block: Parameter + sp_runtime::traits::Block; type AccountId; type Balance; type BaseCallFilter: crate::traits::Contains; @@ -3653,6 +3400,11 @@ mod weight_tests { pub mod pallet_prelude { pub type OriginFor = ::RuntimeOrigin; + + pub type HeaderFor = + <::Block as sp_runtime::traits::HeaderProvider>::HeaderT; + + pub type BlockNumberFor = as sp_runtime::traits::Header>::Number; } } @@ -3665,10 +3417,6 @@ mod weight_tests { crate::construct_runtime!( pub enum Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, { System: self::frame_system, } @@ -3682,7 +3430,7 @@ mod weight_tests { } impl Config for Runtime { - type BlockNumber = BlockNumber; + type Block = Block; type AccountId = AccountId; type Balance = Balance; type BaseCallFilter = crate::traits::Everything; diff --git a/frame/support/src/error.rs b/frame/support/src/error.rs index 14dc16d4dd5c2..5a7dd73f481ec 100644 --- a/frame/support/src/error.rs +++ b/frame/support/src/error.rs @@ -21,51 +21,6 @@ pub use sp_runtime::traits::{BadOrigin, LookupError}; /// Declare an error type for a runtime module. -/// -/// `decl_error!` supports only variants that do not hold any data. The dispatchable -/// functions return [`DispatchResult`](sp_runtime::DispatchResult). The error type -/// implements `From for DispatchResult` to make the error type usable as error -/// in the dispatchable functions. -/// -/// It is required that the error type is registered in `decl_module!` to make the error -/// exported in the metadata. -/// -/// # Usage -/// -/// ``` -/// # use frame_support::{decl_error, decl_module}; -/// # -/// decl_error! { -/// /// Errors that can occur in my module. -/// pub enum MyError for Module { -/// /// Hey this is an error message that indicates bla. -/// MyCoolErrorMessage, -/// /// You are just not cool enough for my module! -/// YouAreNotCoolEnough, -/// } -/// } -/// -/// # use frame_system::Config; -/// -/// // You need to register the error type in `decl_module!` as well to make the error -/// // exported in the metadata. -/// -/// decl_module! { -/// pub struct Module for enum Call where origin: T::RuntimeOrigin { -/// type Error = MyError; -/// -/// #[weight = 0] -/// fn do_something(origin) -> frame_support::dispatch::DispatchResult { -/// Err(MyError::::YouAreNotCoolEnough.into()) -/// } -/// } -/// } -/// -/// # fn main() {} -/// ``` -/// -/// For instantiable modules you also need to give the instance generic type and bound to the -/// error declaration. #[macro_export] #[deprecated(note = "Will be removed after July 2023; use the attribute `#[pallet]` macro instead. For more info, see: ")] diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 250f15bb36461..51477ee384c79 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -834,7 +834,7 @@ pub mod tests { use sp_runtime::{generic, traits::BlakeTwo256, BuildStorage}; use sp_std::result; - pub use self::frame_system::{Config, Pallet}; + pub use self::frame_system::{pallet_prelude::*, Config, Pallet}; #[pallet] pub mod frame_system { @@ -849,7 +849,7 @@ pub mod tests { #[pallet::config] #[pallet::disable_frame_system_supertrait_check] pub trait Config: 'static { - type BlockNumber: Parameter + Default + MaxEncodedLen; + type Block: Parameter + sp_runtime::traits::Block; type AccountId; type BaseCallFilter: crate::traits::Contains; type RuntimeOrigin; @@ -879,12 +879,12 @@ pub mod tests { #[pallet::storage] #[pallet::getter(fn generic_data)] pub type GenericData = - StorageMap<_, Identity, T::BlockNumber, T::BlockNumber, ValueQuery>; + StorageMap<_, Identity, BlockNumberFor, BlockNumberFor, ValueQuery>; #[pallet::storage] #[pallet::getter(fn generic_data2)] pub type GenericData2 = - StorageMap<_, Blake2_128Concat, T::BlockNumber, T::BlockNumber, OptionQuery>; + StorageMap<_, Blake2_128Concat, BlockNumberFor, BlockNumberFor, OptionQuery>; #[pallet::storage] pub type DataDM = @@ -894,10 +894,10 @@ pub mod tests { pub type GenericDataDM = StorageDoubleMap< _, Blake2_128Concat, - T::BlockNumber, + BlockNumberFor, Identity, - T::BlockNumber, - T::BlockNumber, + BlockNumberFor, + BlockNumberFor, ValueQuery, >; @@ -905,10 +905,10 @@ pub mod tests { pub type GenericData2DM = StorageDoubleMap< _, Blake2_128Concat, - T::BlockNumber, + BlockNumberFor, Twox64Concat, - T::BlockNumber, - T::BlockNumber, + BlockNumberFor, + BlockNumberFor, OptionQuery, >; @@ -919,7 +919,7 @@ pub mod tests { Blake2_128Concat, u32, Blake2_128Concat, - T::BlockNumber, + BlockNumberFor, Vec, ValueQuery, >; @@ -956,6 +956,11 @@ pub mod tests { pub mod pallet_prelude { pub type OriginFor = ::RuntimeOrigin; + + pub type HeaderFor = + <::Block as sp_runtime::traits::HeaderProvider>::HeaderT; + + pub type BlockNumberFor = as sp_runtime::traits::Header>::Number; } } @@ -967,17 +972,13 @@ pub mod tests { crate::construct_runtime!( pub enum Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, { System: self::frame_system, } ); impl Config for Runtime { - type BlockNumber = BlockNumber; + type Block = Block; type AccountId = AccountId; type BaseCallFilter = crate::traits::Everything; type RuntimeOrigin = RuntimeOrigin; @@ -1005,12 +1006,8 @@ pub mod tests { fn storage_alias_works() { new_test_ext().execute_with(|| { #[crate::storage_alias] - type GenericData2 = StorageMap< - System, - Blake2_128Concat, - ::BlockNumber, - ::BlockNumber, - >; + type GenericData2 = + StorageMap, BlockNumberFor>; assert_eq!(Pallet::::generic_data2(5), None); GenericData2::::insert(5, 5); @@ -1018,12 +1015,8 @@ pub mod tests { /// Some random docs that ensure that docs are accepted #[crate::storage_alias] - pub type GenericData = StorageMap< - Test2, - Blake2_128Concat, - ::BlockNumber, - ::BlockNumber, - >; + pub type GenericData = + StorageMap, BlockNumberFor>; }); } diff --git a/frame/support/src/migrations.rs b/frame/support/src/migrations.rs index 9ba22d3e15404..19eec194a76ad 100644 --- a/frame/support/src/migrations.rs +++ b/frame/support/src/migrations.rs @@ -257,12 +257,9 @@ pub fn migrate_from_pallet_version_to_storage_version< /// # Examples: /// ```ignore /// construct_runtime! { -/// pub enum Runtime where -/// Block = Block, -/// NodeBlock = primitives::Block, -/// UncheckedExtrinsic = UncheckedExtrinsic +/// pub enum Runtime /// { -/// System: frame_system::{Pallet, Call, Storage, Config, Event} = 0, +/// System: frame_system::{Pallet, Call, Storage, Config, Event} = 0, /// /// SomePalletToRemove: pallet_something::{Pallet, Call, Storage, Event} = 1, /// AnotherPalletToRemove: pallet_something_else::{Pallet, Call, Storage, Event} = 2, diff --git a/frame/support/src/storage/generator/mod.rs b/frame/support/src/storage/generator/mod.rs index 349f5de3ef3bc..bac9f642e37d6 100644 --- a/frame/support/src/storage/generator/mod.rs +++ b/frame/support/src/storage/generator/mod.rs @@ -58,7 +58,7 @@ mod tests { #[pallet::config] #[pallet::disable_frame_system_supertrait_check] pub trait Config: 'static { - type BlockNumber; + type Block: sp_runtime::traits::Block; type AccountId; type BaseCallFilter: crate::traits::Contains; type RuntimeOrigin; @@ -102,6 +102,11 @@ mod tests { pub mod pallet_prelude { pub type OriginFor = ::RuntimeOrigin; + + pub type HeaderFor = + <::Block as sp_runtime::traits::HeaderProvider>::HeaderT; + + pub type BlockNumberFor = as sp_runtime::traits::Header>::Number; } } @@ -113,18 +118,14 @@ mod tests { crate::construct_runtime!( pub enum Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, { System: self::frame_system, } ); impl self::frame_system::Config for Runtime { - type BlockNumber = BlockNumber; type AccountId = AccountId; + type Block = Block; type BaseCallFilter = crate::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; diff --git a/frame/support/test/compile_pass/src/lib.rs b/frame/support/test/compile_pass/src/lib.rs index 4eaa657b1e486..75911d7569f80 100644 --- a/frame/support/test/compile_pass/src/lib.rs +++ b/frame/support/test/compile_pass/src/lib.rs @@ -58,13 +58,12 @@ impl frame_system::Config for Runtime { type Index = u128; type Hash = H256; type Hashing = BlakeTwo256; - type Header = Header; + type Block = Block; type Lookup = IdentityLookup; type BlockHashCount = ConstU64<2400>; type Version = Version; type AccountData = (); type RuntimeOrigin = RuntimeOrigin; - type BlockNumber = BlockNumber; type AccountId = AccountId; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; @@ -83,12 +82,7 @@ pub type Block = generic::Block; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; construct_runtime!( - pub struct Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub struct Runtime { System: frame_system, } ); diff --git a/frame/support/test/src/lib.rs b/frame/support/test/src/lib.rs index 2a3cf13d4dac7..6b38d42d33d0d 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -22,6 +22,7 @@ #![deny(warnings)] pub use frame_support::dispatch::RawOrigin; +use frame_system::pallet_prelude::BlockNumberFor; pub use self::pallet::*; @@ -126,12 +127,12 @@ pub mod pallet_prelude { /// tests! pub struct TestRandomness(sp_std::marker::PhantomData); -impl frame_support::traits::Randomness - for TestRandomness +impl + frame_support::traits::Randomness> for TestRandomness where T: frame_system::Config, { - fn random(subject: &[u8]) -> (Output, T::BlockNumber) { + fn random(subject: &[u8]) -> (Output, BlockNumberFor) { use sp_runtime::traits::TrailingZeroInput; ( diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index acdaef190b330..ff207ddf977c6 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -22,9 +22,13 @@ #![recursion_limit = "128"] use codec::MaxEncodedLen; -use frame_support::{parameter_types, traits::PalletInfo as _}; +use frame_support::{ + derive_impl, parameter_types, traits::PalletInfo as _, weights::RuntimeDbWeight, +}; +use frame_system::limits::{BlockLength, BlockWeights}; use scale_info::TypeInfo; -use sp_core::sr25519; +use sp_api::RuntimeVersion; +use sp_core::{sr25519, ConstU64}; use sp_runtime::{ generic, traits::{BlakeTwo256, Verify}, @@ -37,9 +41,8 @@ parameter_types! { #[frame_support::pallet(dev_mode)] mod module1 { - use self::frame_system::pallet_prelude::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; + use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -75,10 +78,9 @@ mod module1 { #[frame_support::pallet(dev_mode)] mod module2 { - use self::frame_system::pallet_prelude::*; use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; + use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -122,10 +124,9 @@ mod nested { #[frame_support::pallet(dev_mode)] pub mod module3 { - use self::frame_system::pallet_prelude::*; use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; + use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -180,10 +181,9 @@ mod nested { #[frame_support::pallet(dev_mode)] pub mod module3 { - use self::frame_system::pallet_prelude::*; use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; + use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -256,15 +256,10 @@ pub type Header = generic::Header; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; pub type Block = generic::Block; -use frame_support_test as system; - frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { - System: system::{Pallet, Call, Event, Origin} = 30, + System: frame_system::{Pallet, Call, Event, Origin} = 30, Module1_1: module1::::{Pallet, Call, Storage, Event, Origin}, Module2: module2::{Pallet, Call, Storage, Event, Origin}, Module1_2: module1::::{Pallet, Call, Storage, Event, Origin}, @@ -280,15 +275,18 @@ frame_support::construct_runtime!( } ); -impl frame_support_test::Config for Runtime { - type BlockNumber = BlockNumber; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Runtime { type AccountId = AccountId; + type Lookup = sp_runtime::traits::IdentityLookup; type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; - type DbWeight = (); + type OnSetCode = (); + type Block = Block; + type BlockHashCount = ConstU64<10>; } impl module1::Config for Runtime { @@ -336,7 +334,7 @@ fn test_pub() -> AccountId { fn check_modules_error_type() { sp_io::TestExternalities::default().execute_with(|| { assert_eq!( - Module1_1::fail(system::Origin::::Root.into()), + Module1_1::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 31, error: [0; 4], @@ -344,7 +342,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module2::fail(system::Origin::::Root.into()), + Module2::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 32, error: [0; 4], @@ -352,7 +350,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module1_2::fail(system::Origin::::Root.into()), + Module1_2::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 33, error: [0; 4], @@ -360,7 +358,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - NestedModule3::fail(system::Origin::::Root.into()), + NestedModule3::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 34, error: [0; 4], @@ -368,7 +366,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module1_3::fail(system::Origin::::Root.into()), + Module1_3::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 6, error: [0; 4], @@ -376,7 +374,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module1_4::fail(system::Origin::::Root.into()), + Module1_4::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 3, error: [0; 4], @@ -384,7 +382,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module1_5::fail(system::Origin::::Root.into()), + Module1_5::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 4, error: [0; 4], @@ -392,7 +390,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module1_6::fail(system::Origin::::Root.into()), + Module1_6::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 1, error: [0; 4], @@ -400,7 +398,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module1_7::fail(system::Origin::::Root.into()), + Module1_7::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 2, error: [0; 4], @@ -408,7 +406,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module1_8::fail(system::Origin::::Root.into()), + Module1_8::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 12, error: [0; 4], @@ -416,7 +414,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module1_9::fail(system::Origin::::Root.into()), + Module1_9::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 13, error: [0; 4], @@ -436,7 +434,7 @@ fn integrity_test_works() { fn origin_codec() { use codec::Encode; - let origin = OriginCaller::system(system::RawOrigin::None); + let origin = OriginCaller::system(frame_system::RawOrigin::None); assert_eq!(origin.encode()[0], 30); let origin = OriginCaller::Module1_1(module1::Origin(Default::default())); @@ -471,7 +469,8 @@ fn origin_codec() { fn event_codec() { use codec::Encode; - let event = system::Event::::ExtrinsicSuccess; + let event = + frame_system::Event::::ExtrinsicSuccess { dispatch_info: Default::default() }; assert_eq!(RuntimeEvent::from(event).encode()[0], 30); let event = module1::Event::::A(test_pub()); @@ -508,7 +507,7 @@ fn event_codec() { #[test] fn call_codec() { use codec::Encode; - assert_eq!(RuntimeCall::System(system::Call::noop {}).encode()[0], 30); + assert_eq!(RuntimeCall::System(frame_system::Call::remark { remark: vec![1] }).encode()[0], 30); assert_eq!(RuntimeCall::Module1_1(module1::Call::fail {}).encode()[0], 31); assert_eq!(RuntimeCall::Module2(module2::Call::fail {}).encode()[0], 32); assert_eq!(RuntimeCall::Module1_2(module1::Call::fail {}).encode()[0], 33); @@ -639,15 +638,67 @@ fn call_subtype_conversion() { fn test_metadata() { use frame_support::metadata::{v14::*, *}; use scale_info::meta_type; + use sp_core::Encode; + + fn maybe_docs(doc: Vec<&'static str>) -> Vec<&'static str> { + if cfg!(feature = "no-metadata-docs") { + vec![] + } else { + doc + } + } let pallets = vec![ PalletMetadata { name: "System", storage: None, - calls: Some(meta_type::>().into()), - event: Some(meta_type::>().into()), - constants: vec![], - error: Some(meta_type::>().into()), + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![ + PalletConstantMetadata { + name: "BlockWeights", + ty: meta_type::(), + value: BlockWeights::default().encode(), + docs: maybe_docs(vec![" Block & extrinsics weights: base values and limits."]), + }, + PalletConstantMetadata { + name: "BlockLength", + ty: meta_type::(), + value: BlockLength::default().encode(), + docs: maybe_docs(vec![" The maximum length of a block (in bytes)."]), + }, + PalletConstantMetadata { + name: "BlockHashCount", + ty: meta_type::(), + value: 10u64.encode(), + docs: maybe_docs(vec![" Maximum number of block number to block hash mappings to keep (oldest pruned first)."]), + }, + PalletConstantMetadata { + name: "DbWeight", + ty: meta_type::(), + value: RuntimeDbWeight::default().encode(), + docs: maybe_docs(vec![" The weight of runtime database operations the runtime can invoke.",]), + }, + PalletConstantMetadata { + name: "Version", + ty: meta_type::(), + value: RuntimeVersion::default().encode(), + docs: maybe_docs(vec![ " Get the chain's current version."]), + }, + PalletConstantMetadata { + name: "SS58Prefix", + ty: meta_type::(), + value: 0u16.encode(), + docs: maybe_docs(vec![ + " The designated SS58 prefix of this chain.", + "", + " This replaces the \"ss58Format\" property declared in the chain spec. Reason is", + " that the runtime should know about the prefix in order to make use of it as", + " an identifier of the chain.", + ]), + }, + ], + error: Some(meta_type::>().into()), index: 30, }, PalletMetadata { @@ -781,7 +832,7 @@ fn test_metadata() { fn pallet_in_runtime_is_correct() { assert_eq!(PalletInfo::index::().unwrap(), 30); assert_eq!(PalletInfo::name::().unwrap(), "System"); - assert_eq!(PalletInfo::module_name::().unwrap(), "system"); + assert_eq!(PalletInfo::module_name::().unwrap(), "frame_system"); assert!(PalletInfo::crate_version::().is_some()); assert_eq!(PalletInfo::index::().unwrap(), 31); diff --git a/frame/support/test/tests/construct_runtime_ui/both_use_and_excluded_parts.rs b/frame/support/test/tests/construct_runtime_ui/both_use_and_excluded_parts.rs index ea468d6de13ee..4cb249714650e 100644 --- a/frame/support/test/tests/construct_runtime_ui/both_use_and_excluded_parts.rs +++ b/frame/support/test/tests/construct_runtime_ui/both_use_and_excluded_parts.rs @@ -20,12 +20,9 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic}, + System: system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet exclude_parts { Pallet } use_parts { Pallet }, } } diff --git a/frame/support/test/tests/construct_runtime_ui/both_use_and_excluded_parts.stderr b/frame/support/test/tests/construct_runtime_ui/both_use_and_excluded_parts.stderr index b1c1879aa56ad..1ea62b7d6fd65 100644 --- a/frame/support/test/tests/construct_runtime_ui/both_use_and_excluded_parts.stderr +++ b/frame/support/test/tests/construct_runtime_ui/both_use_and_excluded_parts.stderr @@ -1,7 +1,7 @@ error: Unexpected tokens, expected one of `=`, `,` - --> tests/construct_runtime_ui/both_use_and_excluded_parts.rs:29:43 + --> tests/construct_runtime_ui/both_use_and_excluded_parts.rs:26:43 | -29 | Pallet: pallet exclude_parts { Pallet } use_parts { Pallet }, +26 | Pallet: pallet exclude_parts { Pallet } use_parts { Pallet }, | ^^^^^^^^^ error[E0412]: cannot find type `RuntimeCall` in this scope diff --git a/frame/support/test/tests/construct_runtime_ui/conflicting_module_name.rs b/frame/support/test/tests/construct_runtime_ui/conflicting_module_name.rs index dd8340daa0233..513fbcfb51354 100644 --- a/frame/support/test/tests/construct_runtime_ui/conflicting_module_name.rs +++ b/frame/support/test/tests/construct_runtime_ui/conflicting_module_name.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system::{Pallet}, Balance: balances::{Pallet}, diff --git a/frame/support/test/tests/construct_runtime_ui/conflicting_module_name.stderr b/frame/support/test/tests/construct_runtime_ui/conflicting_module_name.stderr index 27c5644e0d736..6fb983f03a961 100644 --- a/frame/support/test/tests/construct_runtime_ui/conflicting_module_name.stderr +++ b/frame/support/test/tests/construct_runtime_ui/conflicting_module_name.stderr @@ -1,11 +1,11 @@ error: Two pallets with the same name! - --> $DIR/conflicting_module_name.rs:10:3 - | -10 | Balance: balances::{Pallet}, - | ^^^^^^^ + --> tests/construct_runtime_ui/conflicting_module_name.rs:7:3 + | +7 | Balance: balances::{Pallet}, + | ^^^^^^^ error: Two pallets with the same name! - --> $DIR/conflicting_module_name.rs:11:3 - | -11 | Balance: balances::{Pallet}, - | ^^^^^^^ + --> tests/construct_runtime_ui/conflicting_module_name.rs:8:3 + | +8 | Balance: balances::{Pallet}, + | ^^^^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.rs b/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.rs new file mode 100644 index 0000000000000..c0e325085b5e5 --- /dev/null +++ b/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.rs @@ -0,0 +1,13 @@ +use frame_support::construct_runtime; + +construct_runtime! { + pub struct Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = Uxt, + { + System: frame_system::{Pallet, Call, Storage, Config, Event}, + } +} + +fn main() {} diff --git a/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.stderr b/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.stderr new file mode 100644 index 0000000000000..946277e9068e3 --- /dev/null +++ b/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.stderr @@ -0,0 +1,442 @@ +error: use of deprecated constant `WhereSection::_w`: + It is deprecated to use a `where` clause in `construct_runtime`. + Please instead use `frame_system::Config` to set the `Block` type and delete this clause. + It is planned to be removed in December 2023. + + For more info see: + + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | / construct_runtime! { +4 | | pub struct Runtime where +5 | | Block = Block, +6 | | NodeBlock = Block, +... | +10 | | } +11 | | } + | |_^ + | + = note: `-D deprecated` implied by `-D warnings` + = note: this error originates in the macro `frame_support::match_and_insert` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | +note: required by a bound in `frame_system::Event` + --> $WORKSPACE/frame/system/src/lib.rs + | + | pub enum Event { + | ^^^^^^ required by this bound in `Event` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied in `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | +note: required because it appears within the type `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `Clone` + --> $RUST/core/src/clone.rs + | + | pub trait Clone: Sized { + | ^^^^^ required by this bound in `Clone` + = note: this error originates in the derive macro `Clone` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied in `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | +note: required because it appears within the type `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `EncodeLike` + --> $CARGO/parity-scale-codec-3.6.1/src/encode_like.rs + | + | pub trait EncodeLike: Sized + Encode {} + | ^^^^^ required by this bound in `EncodeLike` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied in `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | +note: required because it appears within the type `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `Decode` + --> $CARGO/parity-scale-codec-3.6.1/src/codec.rs + | + | pub trait Decode: Sized { + | ^^^^^ required by this bound in `Decode` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied in `frame_system::Event` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = note: required because it appears within the type `Event` +note: required by a bound in `From` + --> $RUST/core/src/convert/mod.rs + | + | pub trait From: Sized { + | ^ required by this bound in `From` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied in `frame_system::Event` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = note: required because it appears within the type `Event` +note: required by a bound in `TryInto` + --> $RUST/core/src/convert/mod.rs + | + | pub trait TryInto: Sized { + | ^ required by this bound in `TryInto` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | construct_runtime! { + | ^ the trait `Config` is not implemented for `Runtime` + | + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `RawOrigin<_>: TryFrom` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = help: the trait `TryFrom` is implemented for `RawOrigin<::AccountId>` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = help: the trait `Callable` is implemented for `Pallet` + = note: required for `Pallet` to implement `Callable` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = note: required for `Pallet` to implement `Callable` +note: required because it appears within the type `RuntimeCall` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `Clone` + --> $RUST/core/src/clone.rs + | + | pub trait Clone: Sized { + | ^^^^^ required by this bound in `Clone` + = note: this error originates in the derive macro `Clone` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = note: required for `Pallet` to implement `Callable` +note: required because it appears within the type `RuntimeCall` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `EncodeLike` + --> $CARGO/parity-scale-codec-3.6.1/src/encode_like.rs + | + | pub trait EncodeLike: Sized + Encode {} + | ^^^^^ required by this bound in `EncodeLike` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = note: required for `Pallet` to implement `Callable` +note: required because it appears within the type `RuntimeCall` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `Decode` + --> $CARGO/parity-scale-codec-3.6.1/src/codec.rs + | + | pub trait Decode: Sized { + | ^^^^^ required by this bound in `Decode` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:9:3 + | +9 | System: frame_system::{Pallet, Call, Storage, Config, Event}, + | ^^^^^^ the trait `Config` is not implemented for `Runtime` + | +note: required by a bound in `frame_system::GenesisConfig` + --> $WORKSPACE/frame/system/src/lib.rs + | + | pub struct GenesisConfig { + | ^^^^^^ required by this bound in `GenesisConfig` + +error[E0277]: the trait bound `Runtime: Config` is not satisfied in `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | +note: required because it appears within the type `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `Result` + --> $RUST/core/src/result.rs + | + | pub enum Result { + | ^ required by this bound in `Result` + = note: this error originates in the derive macro `self::sp_api_hidden_includes_construct_runtime::hidden_include::codec::Decode` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied in `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | +note: required because it appears within the type `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `TryInto` + --> $RUST/core/src/convert/mod.rs + | + | pub trait TryInto: Sized { + | ^^^^^ required by this bound in `TryInto` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = note: required for `Pallet` to implement `Callable` +note: required because it appears within the type `RuntimeCall` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `Result` + --> $RUST/core/src/result.rs + | + | pub enum Result { + | ^ required by this bound in `Result` + = note: this error originates in the derive macro `self::sp_api_hidden_includes_construct_runtime::hidden_include::codec::Decode` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/construct_runtime_ui/double_module_parts.rs b/frame/support/test/tests/construct_runtime_ui/double_module_parts.rs index 3269d22434fdf..68a2523d3bcb2 100644 --- a/frame/support/test/tests/construct_runtime_ui/double_module_parts.rs +++ b/frame/support/test/tests/construct_runtime_ui/double_module_parts.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system::{Pallet}, Balance: balances::{Config, Call, Config, Origin}, diff --git a/frame/support/test/tests/construct_runtime_ui/double_module_parts.stderr b/frame/support/test/tests/construct_runtime_ui/double_module_parts.stderr index 9d10474ce85ab..e3f694781441f 100644 --- a/frame/support/test/tests/construct_runtime_ui/double_module_parts.stderr +++ b/frame/support/test/tests/construct_runtime_ui/double_module_parts.stderr @@ -1,5 +1,5 @@ error: `Config` was already declared before. Please remove the duplicate declaration - --> $DIR/double_module_parts.rs:10:37 - | -10 | Balance: balances::{Config, Call, Config, Origin}, - | ^^^^^^ + --> tests/construct_runtime_ui/double_module_parts.rs:7:37 + | +7 | Balance: balances::{Config, Call, Config, Origin}, + | ^^^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/empty_pallet_path.rs b/frame/support/test/tests/construct_runtime_ui/empty_pallet_path.rs index 44b7fd0ba25f7..23badd76276e2 100644 --- a/frame/support/test/tests/construct_runtime_ui/empty_pallet_path.rs +++ b/frame/support/test/tests/construct_runtime_ui/empty_pallet_path.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { system: , } diff --git a/frame/support/test/tests/construct_runtime_ui/empty_pallet_path.stderr b/frame/support/test/tests/construct_runtime_ui/empty_pallet_path.stderr index 7102076e5acb0..f0c0f17779d67 100644 --- a/frame/support/test/tests/construct_runtime_ui/empty_pallet_path.stderr +++ b/frame/support/test/tests/construct_runtime_ui/empty_pallet_path.stderr @@ -1,5 +1,5 @@ error: expected one of: `crate`, `self`, `super`, identifier - --> $DIR/empty_pallet_path.rs:9:11 + --> tests/construct_runtime_ui/empty_pallet_path.rs:6:11 | -9 | system: , +6 | system: , | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/exclude_undefined_part.rs b/frame/support/test/tests/construct_runtime_ui/exclude_undefined_part.rs index 83a166fc00552..10cda7b4e7e8a 100644 --- a/frame/support/test/tests/construct_runtime_ui/exclude_undefined_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/exclude_undefined_part.rs @@ -25,12 +25,9 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic}, + System: system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet exclude_parts { Call }, } } diff --git a/frame/support/test/tests/construct_runtime_ui/exclude_undefined_part.stderr b/frame/support/test/tests/construct_runtime_ui/exclude_undefined_part.stderr index 66098898bb877..4b85613838ab5 100644 --- a/frame/support/test/tests/construct_runtime_ui/exclude_undefined_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/exclude_undefined_part.stderr @@ -1,7 +1,7 @@ error: Invalid pallet part specified, the pallet `Pallet` doesn't have the `Call` part. Available parts are: `Pallet`, `Storage`. - --> tests/construct_runtime_ui/exclude_undefined_part.rs:34:34 + --> tests/construct_runtime_ui/exclude_undefined_part.rs:31:34 | -34 | Pallet: pallet exclude_parts { Call }, +31 | Pallet: pallet exclude_parts { Call }, | ^^^^ error[E0412]: cannot find type `RuntimeCall` in this scope diff --git a/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.rs b/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.rs index e566f7d458233..35d49a4d8a23b 100644 --- a/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.rs +++ b/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { #[cfg(test)] System: frame_system::{Pallet, Call, Storage, Config, Event}, diff --git a/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.stderr b/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.stderr index 31ae4c987bbe3..6a6c4b4158889 100644 --- a/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.stderr +++ b/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.stderr @@ -1,5 +1,5 @@ error: `System` pallet declaration is feature gated, please remove any `#[cfg]` attributes - --> tests/construct_runtime_ui/feature_gated_system_pallet.rs:10:3 - | -10 | System: frame_system::{Pallet, Call, Storage, Config, Event}, - | ^^^^^^ + --> tests/construct_runtime_ui/feature_gated_system_pallet.rs:7:3 + | +7 | System: frame_system::{Pallet, Call, Storage, Config, Event}, + | ^^^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.rs b/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.rs index 0912ffc98d54b..1ad1f8e0b1d5f 100644 --- a/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.rs +++ b/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system::{Pallet}, Balance: balances::::{Call, Origin}, diff --git a/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.stderr b/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.stderr index ca2bb998e06d3..a6adb37d04949 100644 --- a/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.stderr +++ b/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.stderr @@ -1,5 +1,5 @@ error: `Call` is not allowed to have generics. Only the following pallets are allowed to have generics: `Event`, `Error`, `Origin`, `Config`. - --> $DIR/generics_in_invalid_module.rs:10:36 - | -10 | Balance: balances::::{Call, Origin}, - | ^^^^ + --> tests/construct_runtime_ui/generics_in_invalid_module.rs:7:36 + | +7 | Balance: balances::::{Call, Origin}, + | ^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_meta_literal.rs b/frame/support/test/tests/construct_runtime_ui/invalid_meta_literal.rs index c253444ee31db..bce87c51336eb 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_meta_literal.rs +++ b/frame/support/test/tests/construct_runtime_ui/invalid_meta_literal.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system::{Pallet}, #[cfg(feature = 1)] diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_meta_literal.stderr b/frame/support/test/tests/construct_runtime_ui/invalid_meta_literal.stderr index 68366a3410bf1..bfee2910cd2a4 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_meta_literal.stderr +++ b/frame/support/test/tests/construct_runtime_ui/invalid_meta_literal.stderr @@ -1,6 +1,6 @@ error: feature = 1 ^ expected one of ``, `all`, `any`, `not` here - --> tests/construct_runtime_ui/invalid_meta_literal.rs:10:3 - | -10 | #[cfg(feature = 1)] - | ^ + --> tests/construct_runtime_ui/invalid_meta_literal.rs:7:3 + | +7 | #[cfg(feature = 1)] + | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_module_details.rs b/frame/support/test/tests/construct_runtime_ui/invalid_module_details.rs index 9fb3169e1df77..bf6919f5a58ef 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_module_details.rs +++ b/frame/support/test/tests/construct_runtime_ui/invalid_module_details.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { system: System::(), } diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_module_details.stderr b/frame/support/test/tests/construct_runtime_ui/invalid_module_details.stderr index 0a20cf4e39a88..1f9277c3f0a8e 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_module_details.stderr +++ b/frame/support/test/tests/construct_runtime_ui/invalid_module_details.stderr @@ -1,5 +1,5 @@ error: Unexpected tokens, expected one of `::$ident` `::{`, `exclude_parts`, `use_parts`, `=`, `,` - --> tests/construct_runtime_ui/invalid_module_details.rs:9:17 + --> tests/construct_runtime_ui/invalid_module_details.rs:6:17 | -9 | system: System::(), +6 | system: System::(), | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.rs b/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.rs index 6ba268b73eea6..51f14e6883e4a 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.rs +++ b/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { system: System::{enum}, } diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.stderr b/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.stderr index f1c3929fff25f..dfcc9b8be42c6 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.stderr +++ b/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.stderr @@ -1,5 +1,5 @@ error: expected one of: `Pallet`, `Call`, `Storage`, `Event`, `Error`, `Config`, `Origin`, `Inherent`, `ValidateUnsigned`, `FreezeReason`, `HoldReason`, `LockId`, `SlashReason` - --> $DIR/invalid_module_details_keyword.rs:9:20 + --> tests/construct_runtime_ui/invalid_module_details_keyword.rs:6:20 | -9 | system: System::{enum}, +6 | system: System::{enum}, | ^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.rs b/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.rs index 173916f2ff6eb..607741d7823d4 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.rs +++ b/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system::{Pallet}, Balance: balances::{Unexpected}, diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.stderr b/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.stderr index 2d5eeb5108fb9..9dd849ff0412e 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.stderr +++ b/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.stderr @@ -1,5 +1,5 @@ error: expected one of: `Pallet`, `Call`, `Storage`, `Event`, `Error`, `Config`, `Origin`, `Inherent`, `ValidateUnsigned`, `FreezeReason`, `HoldReason`, `LockId`, `SlashReason` - --> $DIR/invalid_module_entry.rs:10:23 - | -10 | Balance: balances::{Unexpected}, - | ^^^^^^^^^^ + --> tests/construct_runtime_ui/invalid_module_entry.rs:7:23 + | +7 | Balance: balances::{Unexpected}, + | ^^^^^^^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.rs b/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.rs index 09c316e6ebaed..c132fa01b2297 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.rs +++ b/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { system: System ? } diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.stderr b/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.stderr index 6025de82bd206..80be1b8dd42fd 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.stderr +++ b/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.stderr @@ -1,5 +1,5 @@ error: Unexpected tokens, expected one of `::$ident` `::{`, `exclude_parts`, `use_parts`, `=`, `,` - --> $DIR/invalid_token_after_module.rs:9:18 + --> tests/construct_runtime_ui/invalid_token_after_module.rs:6:18 | -9 | system: System ? +6 | system: System ? | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.rs b/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.rs index 18d367d102d3a..42e7759f87f2b 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.rs +++ b/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { system ? } diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.stderr b/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.stderr index eaae082c8460c..8988f8a35b0a4 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.stderr +++ b/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.stderr @@ -1,5 +1,5 @@ error: expected `:` - --> $DIR/invalid_token_after_name.rs:9:10 + --> tests/construct_runtime_ui/invalid_token_after_name.rs:6:10 | -9 | system ? +6 | system ? | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.rs b/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.rs index d3018f02f89e3..bc2039c4e8180 100644 --- a/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.rs +++ b/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system expanded::{}::{Pallet}, Balance: balances:: expanded::{}::{Event}, diff --git a/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.stderr b/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.stderr index 97968df36a482..30fcba4c710d0 100644 --- a/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.stderr +++ b/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.stderr @@ -1,5 +1,5 @@ error: Instantiable pallet with no generic `Event` cannot be constructed: pallet `Balance` must have generic `Event` - --> $DIR/missing_event_generic_on_module_with_instance.rs:10:3 - | -10 | Balance: balances:: expanded::{}::{Event}, - | ^^^^^^^ + --> tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.rs:7:3 + | +7 | Balance: balances:: expanded::{}::{Event}, + | ^^^^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/missing_module_instance.rs b/frame/support/test/tests/construct_runtime_ui/missing_module_instance.rs index 24e4ee979bd76..afd96a04854f2 100644 --- a/frame/support/test/tests/construct_runtime_ui/missing_module_instance.rs +++ b/frame/support/test/tests/construct_runtime_ui/missing_module_instance.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { system: System::<>, } diff --git a/frame/support/test/tests/construct_runtime_ui/missing_module_instance.stderr b/frame/support/test/tests/construct_runtime_ui/missing_module_instance.stderr index 6303c74e42e5c..5072f718db12e 100644 --- a/frame/support/test/tests/construct_runtime_ui/missing_module_instance.stderr +++ b/frame/support/test/tests/construct_runtime_ui/missing_module_instance.stderr @@ -1,5 +1,5 @@ error: expected identifier - --> $DIR/missing_module_instance.rs:9:20 + --> tests/construct_runtime_ui/missing_module_instance.rs:6:20 | -9 | system: System::<>, +6 | system: System::<>, | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.rs b/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.rs index 5fc238067f287..42db63ae90a3a 100644 --- a/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.rs +++ b/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system expanded::{}::{Pallet}, Balance: balances:: expanded::{}::{Origin}, diff --git a/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.stderr b/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.stderr index f7df25d4c363f..6c076d7b49fc0 100644 --- a/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.stderr +++ b/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.stderr @@ -1,5 +1,5 @@ error: Instantiable pallet with no generic `Origin` cannot be constructed: pallet `Balance` must have generic `Origin` - --> $DIR/missing_origin_generic_on_module_with_instance.rs:10:3 - | -10 | Balance: balances:: expanded::{}::{Origin}, - | ^^^^^^^ + --> tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.rs:7:3 + | +7 | Balance: balances:: expanded::{}::{Origin}, + | ^^^^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/missing_system_module.rs b/frame/support/test/tests/construct_runtime_ui/missing_system_module.rs index 7ab902c3aadd8..685f9059b1be2 100644 --- a/frame/support/test/tests/construct_runtime_ui/missing_system_module.rs +++ b/frame/support/test/tests/construct_runtime_ui/missing_system_module.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { } } diff --git a/frame/support/test/tests/construct_runtime_ui/missing_system_module.stderr b/frame/support/test/tests/construct_runtime_ui/missing_system_module.stderr index 7648f5c1bfb33..c8631f44051ca 100644 --- a/frame/support/test/tests/construct_runtime_ui/missing_system_module.stderr +++ b/frame/support/test/tests/construct_runtime_ui/missing_system_module.stderr @@ -1,6 +1,6 @@ -error: `System` pallet declaration is missing. Please add this line: `System: frame_system::{Pallet, Call, Storage, Config, Event},` - --> $DIR/missing_system_module.rs:8:2 +error: `System` pallet declaration is missing. Please add this line: `System: frame_system::{Pallet, Call, Storage, Config, Event},` + --> tests/construct_runtime_ui/missing_system_module.rs:5:2 | -8 | / { -9 | | } +5 | / { +6 | | } | |_____^ diff --git a/frame/support/test/tests/construct_runtime_ui/missing_where_block.rs b/frame/support/test/tests/construct_runtime_ui/missing_where_block.rs deleted file mode 100644 index 303df6b03d72e..0000000000000 --- a/frame/support/test/tests/construct_runtime_ui/missing_where_block.rs +++ /dev/null @@ -1,7 +0,0 @@ -use frame_support::construct_runtime; - -construct_runtime! { - pub struct Runtime {} -} - -fn main() {} diff --git a/frame/support/test/tests/construct_runtime_ui/missing_where_block.stderr b/frame/support/test/tests/construct_runtime_ui/missing_where_block.stderr deleted file mode 100644 index d2a66f95101f4..0000000000000 --- a/frame/support/test/tests/construct_runtime_ui/missing_where_block.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: expected `where` - --> tests/construct_runtime_ui/missing_where_block.rs:4:21 - | -4 | pub struct Runtime {} - | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs b/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs index 577dbf4091048..738ff0df3a07f 100644 --- a/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs +++ b/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs @@ -23,13 +23,12 @@ impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -47,10 +46,7 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet1: pallet::{Pallet}, diff --git a/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.stderr b/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.stderr index 19a9a7bd08e32..55cef6704ee3f 100644 --- a/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.stderr +++ b/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.stderr @@ -1,7 +1,7 @@ error: The number of pallets exceeds the maximum number of tuple elements. To increase this limit, enable the tuples-96 feature of [frame_support]. - --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:50:2 + --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:49:2 | -50 | pub struct Runtime where +49 | pub struct Runtime | ^^^ error[E0412]: cannot find type `RuntimeCall` in this scope @@ -34,26 +34,26 @@ error[E0412]: cannot find type `RuntimeOrigin` in this scope | ^^^^^^^^^^^^^ help: you might have meant to use the associated type: `Self::RuntimeOrigin` error[E0412]: cannot find type `RuntimeCall` in this scope - --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:27:21 + --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:26:21 | -27 | type RuntimeCall = RuntimeCall; +26 | type RuntimeCall = RuntimeCall; | ^^^^^^^^^^^ help: you might have meant to use the associated type: `Self::RuntimeCall` error[E0412]: cannot find type `RuntimeEvent` in this scope - --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:33:22 + --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:32:22 | -33 | type RuntimeEvent = RuntimeEvent; +32 | type RuntimeEvent = RuntimeEvent; | ^^^^^^^^^^^^ help: you might have meant to use the associated type: `Self::RuntimeEvent` error[E0412]: cannot find type `PalletInfo` in this scope - --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:39:20 + --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:38:20 | -39 | type PalletInfo = PalletInfo; +38 | type PalletInfo = PalletInfo; | ^^^^^^^^^^ | help: you might have meant to use the associated type | -39 | type PalletInfo = Self::PalletInfo; +38 | type PalletInfo = Self::PalletInfo; | ~~~~~~~~~~~~~~~~ help: consider importing this trait | diff --git a/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs b/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs index 3b5773f2c9386..e21ddf65921a1 100644 --- a/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs +++ b/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs @@ -48,13 +48,12 @@ impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -72,10 +71,7 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet::{Pallet}, diff --git a/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.stderr b/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.stderr index b9cec02a2b092..47504573515a2 100644 --- a/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.stderr +++ b/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.stderr @@ -1,13 +1,13 @@ error[E0080]: evaluation of constant value failed - --> tests/construct_runtime_ui/pallet_error_too_large.rs:74:1 + --> tests/construct_runtime_ui/pallet_error_too_large.rs:73:1 | -74 | / construct_runtime! { -75 | | pub struct Runtime where -76 | | Block = Block, -77 | | NodeBlock = Block, -... | -82 | | } -83 | | } - | |_^ the evaluated program panicked at 'The maximum encoded size of the error type in the `Pallet` pallet exceeds `MAX_MODULE_ERROR_ENCODED_SIZE`', $DIR/tests/construct_runtime_ui/pallet_error_too_large.rs:74:1 +73 | / construct_runtime! { +74 | | pub struct Runtime +75 | | { +76 | | System: frame_system::{Pallet, Call, Storage, Config, Event}, +77 | | Pallet: pallet::{Pallet}, +78 | | } +79 | | } + | |_^ the evaluated program panicked at 'The maximum encoded size of the error type in the `Pallet` pallet exceeds `MAX_MODULE_ERROR_ENCODED_SIZE`', $DIR/tests/construct_runtime_ui/pallet_error_too_large.rs:73:1 | = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs index a65acf43584c7..c57272c2caa33 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs @@ -23,13 +23,12 @@ impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -47,10 +46,7 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet::{Pallet, Call}, diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_call_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_call_part.stderr index c2092edea05b5..f3f29e4c69554 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_call_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_call_part.stderr @@ -4,13 +4,13 @@ error: `Pallet` does not have #[pallet::call] defined, perhaps you should remove 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet::{Pallet, Call}, +53 | | } +54 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_call_check::is_call_part_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs index fdc8a44930666..6fa4389b98ddf 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs @@ -23,13 +23,12 @@ impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -47,10 +46,7 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, Pallet: pallet expanded::{}::{Pallet, Event}, diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.stderr index eb667fe04a39e..81e42cec3b97a 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.stderr @@ -4,27 +4,27 @@ error: `Pallet` does not have #[pallet::event] defined, perhaps you should remov 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Event}, +53 | | } +54 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_event_check::is_event_part_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0412]: cannot find type `Event` in module `pallet` - --> tests/construct_runtime_ui/undefined_event_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_event_part.rs:48:1 | -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Event}, +53 | | } +54 | | } | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs index c245f65119776..8470ae3a78a7e 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs @@ -23,13 +23,12 @@ impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -47,10 +46,7 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, Pallet: pallet expanded::{}::{Pallet, Config}, diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.stderr index cdab7d3afa18c..920785fc96291 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.stderr @@ -4,27 +4,27 @@ error: `Pallet` does not have #[pallet::genesis_config] defined, perhaps you sho 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Config}, +53 | | } +54 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_genesis_config_check::is_genesis_config_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0412]: cannot find type `GenesisConfig` in module `pallet` - --> tests/construct_runtime_ui/undefined_genesis_config_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_genesis_config_part.rs:48:1 | -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Config}, +53 | | } +54 | | } | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs index 966d2d119baab..0ebee2b980e17 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs @@ -23,13 +23,12 @@ impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -47,10 +46,7 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, Pallet: pallet expanded::{}::{Pallet, Inherent}, diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.stderr index a068cab4cb1ab..659d43b151006 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.stderr @@ -4,31 +4,31 @@ error: `Pallet` does not have #[pallet::inherent] defined, perhaps you should re 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +53 | | } +54 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_inherent_check::is_inherent_part_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no function or associated item named `create_inherent` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_inherent_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_inherent_part.rs:48:1 | 11 | pub struct Pallet(_); | -------------------- function or associated item `create_inherent` not found for this struct ... -49 | construct_runtime! { +48 | construct_runtime! { | _^ -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +53 | | } +54 | | } | |_^ function or associated item not found in `Pallet` | = help: items from traits can only be used if the trait is implemented and in scope @@ -37,19 +37,19 @@ error[E0599]: no function or associated item named `create_inherent` found for s = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no function or associated item named `is_inherent` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_inherent_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_inherent_part.rs:48:1 | 11 | pub struct Pallet(_); | -------------------- function or associated item `is_inherent` not found for this struct ... -49 | construct_runtime! { +48 | construct_runtime! { | _^ -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +53 | | } +54 | | } | |_^ function or associated item not found in `Pallet` | = help: items from traits can only be used if the trait is implemented and in scope @@ -58,19 +58,19 @@ error[E0599]: no function or associated item named `is_inherent` found for struc = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no function or associated item named `check_inherent` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_inherent_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_inherent_part.rs:48:1 | 11 | pub struct Pallet(_); | -------------------- function or associated item `check_inherent` not found for this struct ... -49 | construct_runtime! { +48 | construct_runtime! { | _^ -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +53 | | } +54 | | } | |_^ function or associated item not found in `Pallet` | = help: items from traits can only be used if the trait is implemented and in scope @@ -79,19 +79,19 @@ error[E0599]: no function or associated item named `check_inherent` found for st = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no associated item named `INHERENT_IDENTIFIER` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_inherent_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_inherent_part.rs:48:1 | 11 | pub struct Pallet(_); | -------------------- associated item `INHERENT_IDENTIFIER` not found for this struct ... -49 | construct_runtime! { +48 | construct_runtime! { | _^ -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +53 | | } +54 | | } | |_^ associated item not found in `Pallet` | = help: items from traits can only be used if the trait is implemented and in scope @@ -100,19 +100,19 @@ error[E0599]: no associated item named `INHERENT_IDENTIFIER` found for struct `p = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no function or associated item named `is_inherent_required` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_inherent_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_inherent_part.rs:48:1 | 11 | pub struct Pallet(_); | -------------------- function or associated item `is_inherent_required` not found for this struct ... -49 | construct_runtime! { +48 | construct_runtime! { | _^ -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +53 | | } +54 | | } | |_^ function or associated item not found in `Pallet` | = help: items from traits can only be used if the trait is implemented and in scope diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs index fb712dbf05acc..75059716f6bc4 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs @@ -23,13 +23,12 @@ impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -47,10 +46,7 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, Pallet: pallet expanded::{}::{Pallet, Origin}, diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.stderr index 0677340e25c12..c41dbe79421ea 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.stderr @@ -4,27 +4,27 @@ error: `Pallet` does not have #[pallet::origin] defined, perhaps you should remo 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Origin}, +53 | | } +54 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_origin_check::is_origin_part_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0412]: cannot find type `Origin` in module `pallet` - --> tests/construct_runtime_ui/undefined_origin_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_origin_part.rs:48:1 | -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Origin}, +53 | | } +54 | | } | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs index 3fb42f9a1ee04..4ef93084835dc 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs @@ -23,13 +23,12 @@ impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -47,10 +46,7 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet::{Pallet, ValidateUnsigned}, diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.stderr index c2205c5286084..007b77250736e 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.stderr @@ -4,48 +4,46 @@ error: `Pallet` does not have #[pallet::validate_unsigned] defined, perhaps you 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet::{Pallet, ValidateUnsigned}, +53 | | } +54 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_validate_unsigned_check::is_validate_unsigned_part_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no variant or associated item named `Pallet` found for enum `RuntimeCall` in the current scope - --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:56:3 + --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:52:3 | -49 | // construct_runtime! { -50 | || pub struct Runtime where -51 | || Block = Block, -52 | || NodeBlock = Block, -... || -55 | || System: frame_system::{Pallet, Call, Storage, Config, Event}, -56 | || Pallet: pallet::{Pallet, ValidateUnsigned}, +48 | // construct_runtime! { +49 | || pub struct Runtime +50 | || { +51 | || System: frame_system::{Pallet, Call, Storage, Config, Event}, +52 | || Pallet: pallet::{Pallet, ValidateUnsigned}, | || -^^^^^^ variant or associated item not found in `RuntimeCall` | ||________| | | ... | error[E0599]: no function or associated item named `pre_dispatch` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:48:1 | 11 | pub struct Pallet(_); | -------------------- function or associated item `pre_dispatch` not found for this struct ... -49 | construct_runtime! { +48 | construct_runtime! { | __^ | | _| | || -50 | || pub struct Runtime where -51 | || Block = Block, -52 | || NodeBlock = Block, -... || -57 | || } -58 | || } +49 | || pub struct Runtime +50 | || { +51 | || System: frame_system::{Pallet, Call, Storage, Config, Event}, +52 | || Pallet: pallet::{Pallet, ValidateUnsigned}, +53 | || } +54 | || } | ||_- in this macro invocation ... | | @@ -56,21 +54,21 @@ error[E0599]: no function or associated item named `pre_dispatch` found for stru = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no function or associated item named `validate_unsigned` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:48:1 | 11 | pub struct Pallet(_); | -------------------- function or associated item `validate_unsigned` not found for this struct ... -49 | construct_runtime! { +48 | construct_runtime! { | __^ | | _| | || -50 | || pub struct Runtime where -51 | || Block = Block, -52 | || NodeBlock = Block, -... || -57 | || } -58 | || } +49 | || pub struct Runtime +50 | || { +51 | || System: frame_system::{Pallet, Call, Storage, Config, Event}, +52 | || Pallet: pallet::{Pallet, ValidateUnsigned}, +53 | || } +54 | || } | ||_- in this macro invocation ... | | diff --git a/frame/support/test/tests/construct_runtime_ui/unsupported_meta_structure.rs b/frame/support/test/tests/construct_runtime_ui/unsupported_meta_structure.rs index e5fd284dc8722..e4e2d3dca021e 100644 --- a/frame/support/test/tests/construct_runtime_ui/unsupported_meta_structure.rs +++ b/frame/support/test/tests/construct_runtime_ui/unsupported_meta_structure.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system::{Pallet}, #[cfg(feature(test))] diff --git a/frame/support/test/tests/construct_runtime_ui/unsupported_meta_structure.stderr b/frame/support/test/tests/construct_runtime_ui/unsupported_meta_structure.stderr index 98d99a0d34997..34637269db617 100644 --- a/frame/support/test/tests/construct_runtime_ui/unsupported_meta_structure.stderr +++ b/frame/support/test/tests/construct_runtime_ui/unsupported_meta_structure.stderr @@ -1,6 +1,6 @@ error: feature(test) ^ expected one of `=`, `,`, `)` here - --> tests/construct_runtime_ui/unsupported_meta_structure.rs:10:3 - | -10 | #[cfg(feature(test))] - | ^ + --> tests/construct_runtime_ui/unsupported_meta_structure.rs:7:3 + | +7 | #[cfg(feature(test))] + | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/unsupported_pallet_attr.rs b/frame/support/test/tests/construct_runtime_ui/unsupported_pallet_attr.rs index 03363d30a6429..491cc2c90533d 100644 --- a/frame/support/test/tests/construct_runtime_ui/unsupported_pallet_attr.rs +++ b/frame/support/test/tests/construct_runtime_ui/unsupported_pallet_attr.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system::{Pallet}, #[attr] diff --git a/frame/support/test/tests/construct_runtime_ui/unsupported_pallet_attr.stderr b/frame/support/test/tests/construct_runtime_ui/unsupported_pallet_attr.stderr index fceb2b8a99db8..da1b61b1c3078 100644 --- a/frame/support/test/tests/construct_runtime_ui/unsupported_pallet_attr.stderr +++ b/frame/support/test/tests/construct_runtime_ui/unsupported_pallet_attr.stderr @@ -1,5 +1,5 @@ error: Unsupported attribute, only #[cfg] is supported on pallet declarations in `construct_runtime` - --> tests/construct_runtime_ui/unsupported_pallet_attr.rs:10:3 - | -10 | #[attr] - | ^ + --> tests/construct_runtime_ui/unsupported_pallet_attr.rs:7:3 + | +7 | #[attr] + | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/use_undefined_part.rs b/frame/support/test/tests/construct_runtime_ui/use_undefined_part.rs index 971e2b831ae08..8563be1008cd9 100644 --- a/frame/support/test/tests/construct_runtime_ui/use_undefined_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/use_undefined_part.rs @@ -25,12 +25,9 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic}, + System: system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet use_parts { Call }, } } diff --git a/frame/support/test/tests/construct_runtime_ui/use_undefined_part.stderr b/frame/support/test/tests/construct_runtime_ui/use_undefined_part.stderr index cb6b6a44d61da..4058ccab2c5d7 100644 --- a/frame/support/test/tests/construct_runtime_ui/use_undefined_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/use_undefined_part.stderr @@ -1,7 +1,7 @@ error: Invalid pallet part specified, the pallet `Pallet` doesn't have the `Call` part. Available parts are: `Pallet`, `Storage`. - --> tests/construct_runtime_ui/use_undefined_part.rs:34:30 + --> tests/construct_runtime_ui/use_undefined_part.rs:31:30 | -34 | Pallet: pallet use_parts { Call }, +31 | Pallet: pallet use_parts { Call }, | ^^^^ error[E0412]: cannot find type `RuntimeCall` in this scope diff --git a/frame/support/test/tests/final_keys.rs b/frame/support/test/tests/final_keys.rs index 164da3ff444a5..765afaf1e6604 100644 --- a/frame/support/test/tests/final_keys.rs +++ b/frame/support/test/tests/final_keys.rs @@ -16,8 +16,10 @@ // limitations under the License. use codec::Encode; -use frame_support::{storage::unhashed, StoragePrefixedMap}; -use sp_core::sr25519; +use frame_support::{derive_impl, storage::unhashed, StoragePrefixedMap}; +use frame_system::pallet_prelude::BlockNumberFor; + +use sp_core::{sr25519, ConstU32}; use sp_io::{ hashing::{blake2_128, twox_128, twox_64}, TestExternalities, @@ -31,7 +33,6 @@ use sp_runtime::{ mod no_instance { use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; #[pallet::pallet] pub struct Pallet(_); @@ -59,7 +60,7 @@ mod no_instance { #[pallet::storage] #[pallet::getter(fn test_generic_value)] - pub type TestGenericValue = StorageValue<_, T::BlockNumber, OptionQuery>; + pub type TestGenericValue = StorageValue<_, BlockNumberFor, OptionQuery>; #[pallet::storage] #[pallet::getter(fn foo2)] pub type TestGenericDoubleMap = StorageDoubleMap< @@ -67,7 +68,7 @@ mod no_instance { Blake2_128Concat, u32, Blake2_128Concat, - T::BlockNumber, + BlockNumberFor, u32, ValueQuery, >; @@ -75,8 +76,8 @@ mod no_instance { #[pallet::genesis_config] pub struct GenesisConfig { pub value: u32, - pub test_generic_value: T::BlockNumber, - pub test_generic_double_map: Vec<(u32, T::BlockNumber, u32)>, + pub test_generic_value: BlockNumberFor, + pub test_generic_double_map: Vec<(u32, BlockNumberFor, u32)>, } impl Default for GenesisConfig { @@ -105,7 +106,6 @@ mod no_instance { mod instance { use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; #[pallet::pallet] pub struct Pallet(PhantomData<(T, I)>); @@ -136,7 +136,7 @@ mod instance { #[pallet::storage] #[pallet::getter(fn test_generic_value)] pub type TestGenericValue, I: 'static = ()> = - StorageValue<_, T::BlockNumber, OptionQuery>; + StorageValue<_, BlockNumberFor, OptionQuery>; #[pallet::storage] #[pallet::getter(fn foo2)] pub type TestGenericDoubleMap, I: 'static = ()> = StorageDoubleMap< @@ -144,7 +144,7 @@ mod instance { Blake2_128Concat, u32, Blake2_128Concat, - T::BlockNumber, + BlockNumberFor, u32, ValueQuery, >; @@ -152,8 +152,8 @@ mod instance { #[pallet::genesis_config] pub struct GenesisConfig, I: 'static = ()> { pub value: u32, - pub test_generic_value: T::BlockNumber, - pub test_generic_double_map: Vec<(u32, T::BlockNumber, u32)>, + pub test_generic_value: BlockNumberFor, + pub test_generic_double_map: Vec<(u32, BlockNumberFor, u32)>, pub phantom: PhantomData, } @@ -201,27 +201,25 @@ pub type Block = generic::Block; frame_support::construct_runtime!( pub enum Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + { - System: frame_support_test, + System: frame_system, FinalKeysNone: no_instance, FinalKeysSome: instance, Instance2FinalKeysSome: instance::, } ); -impl frame_support_test::Config for Runtime { - type BlockNumber = BlockNumber; - type AccountId = AccountId; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU32<10>; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; - type DbWeight = (); + type OnSetCode = (); } impl no_instance::Config for Runtime {} diff --git a/frame/support/test/tests/genesisconfig.rs b/frame/support/test/tests/genesisconfig.rs index 8ac7bc37e2e72..c6781220692a9 100644 --- a/frame/support/test/tests/genesisconfig.rs +++ b/frame/support/test/tests/genesisconfig.rs @@ -15,7 +15,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -use sp_core::sr25519; +use frame_support::derive_impl; +use frame_system::pallet_prelude::BlockNumberFor; +use sp_core::{sr25519, ConstU32}; use sp_runtime::{ generic, traits::{BlakeTwo256, Verify}, @@ -25,7 +27,6 @@ use sp_runtime::{ pub mod pallet { use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; #[pallet::pallet] pub struct Pallet(_); @@ -39,11 +40,11 @@ pub mod pallet { #[pallet::storage] #[pallet::unbounded] pub type AppendableDM = - StorageDoubleMap<_, Identity, u32, Identity, T::BlockNumber, Vec>; + StorageDoubleMap<_, Identity, u32, Identity, BlockNumberFor, Vec>; #[pallet::genesis_config] pub struct GenesisConfig { - pub t: Vec<(u32, T::BlockNumber, Vec)>, + pub t: Vec<(u32, BlockNumberFor, Vec)>, } impl Default for GenesisConfig { @@ -71,25 +72,23 @@ pub type Block = generic::Block; frame_support::construct_runtime!( pub enum Test - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + { - System: frame_support_test, + System: frame_system, MyPallet: pallet, } ); -impl frame_support_test::Config for Test { - type BlockNumber = BlockNumber; - type AccountId = AccountId; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU32<10>; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; - type DbWeight = (); + type OnSetCode = (); } impl pallet::Config for Test {} diff --git a/frame/support/test/tests/instance.rs b/frame/support/test/tests/instance.rs index 8d5d49927721f..2fb6d7658d6ab 100644 --- a/frame/support/test/tests/instance.rs +++ b/frame/support/test/tests/instance.rs @@ -18,6 +18,7 @@ #![recursion_limit = "128"] use frame_support::{ + derive_impl, inherent::{InherentData, InherentIdentifier, MakeFatalError, ProvideInherent}, metadata_ir::{ PalletStorageMetadataIR, StorageEntryMetadataIR, StorageEntryModifierIR, @@ -25,6 +26,7 @@ use frame_support::{ }, traits::ConstU32, }; +use frame_system::pallet_prelude::BlockNumberFor; use sp_core::sr25519; use sp_runtime::{ generic, @@ -39,10 +41,9 @@ pub trait Currency {} // * Origin, Inherent, Event #[frame_support::pallet(dev_mode)] mod module1 { - use self::frame_system::pallet_prelude::*; use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; + use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -77,7 +78,7 @@ mod module1 { #[pallet::genesis_config] pub struct GenesisConfig, I: 'static = ()> { pub value: >::GenericType, - pub test: ::BlockNumber, + pub test: BlockNumberFor, } impl, I: 'static> Default for GenesisConfig { @@ -89,7 +90,7 @@ mod module1 { #[pallet::genesis_build] impl, I: 'static> BuildGenesisConfig for GenesisConfig where - T::BlockNumber: std::fmt::Display, + BlockNumberFor: std::fmt::Display, { fn build(&self) { >::put(self.value.clone()); @@ -123,7 +124,7 @@ mod module1 { #[pallet::inherent] impl, I: 'static> ProvideInherent for Pallet where - T::BlockNumber: From, + BlockNumberFor: From, { type Call = Call; type Error = MakeFatalError<()>; @@ -150,7 +151,6 @@ mod module1 { mod module2 { use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; #[pallet::pallet] pub struct Pallet(PhantomData<(T, I)>); @@ -198,7 +198,7 @@ mod module2 { #[pallet::genesis_build] impl, I: 'static> BuildGenesisConfig for GenesisConfig where - T::BlockNumber: std::fmt::Display, + BlockNumberFor: std::fmt::Display, { fn build(&self) { >::put(self.value.clone()); @@ -252,7 +252,6 @@ mod module2 { mod module3 { use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; #[pallet::pallet] pub struct Pallet(PhantomData<(T, I)>); @@ -277,12 +276,9 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; frame_support::construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub enum Runtime { - System: frame_support_test::{Pallet, Call, Event}, + System: frame_system::{Pallet, Call, Event}, Module1_1: module1::::{ Pallet, Call, Storage, Event, Config, Origin, Inherent }, @@ -303,15 +299,16 @@ frame_support::construct_runtime!( } ); -impl frame_support_test::Config for Runtime { - type BlockNumber = BlockNumber; - type AccountId = AccountId; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU32<10>; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; - type DbWeight = (); + type OnSetCode = (); } impl module1::Config for Runtime { diff --git a/frame/support/test/tests/issue2219.rs b/frame/support/test/tests/issue2219.rs index e6230dfc71018..4016707b51a8d 100644 --- a/frame/support/test/tests/issue2219.rs +++ b/frame/support/test/tests/issue2219.rs @@ -15,6 +15,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +use frame_support::derive_impl; +use frame_system::pallet_prelude::BlockNumberFor; use sp_core::{sr25519, ConstU64}; use sp_runtime::{ generic, @@ -25,10 +27,8 @@ use sp_runtime::{ mod module { use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; - pub type Request = - (::AccountId, Role, ::BlockNumber); + pub type Request = (::AccountId, Role, BlockNumberFor); pub type Requests = Vec>; #[derive(Copy, Clone, Eq, PartialEq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)] @@ -46,35 +46,35 @@ mod module { pub max_actors: u32, // payouts are made at this block interval - pub reward_period: T::BlockNumber, + pub reward_period: BlockNumberFor, // minimum amount of time before being able to unstake - pub bonding_period: T::BlockNumber, + pub bonding_period: BlockNumberFor, // how long tokens remain locked for after unstaking - pub unbonding_period: T::BlockNumber, + pub unbonding_period: BlockNumberFor, // minimum period required to be in service. unbonding before this time is highly penalized - pub min_service_period: T::BlockNumber, + pub min_service_period: BlockNumberFor, // "startup" time allowed for roles that need to sync their infrastructure // with other providers before they are considered in service and punishable for // not delivering required level of service. - pub startup_grace_period: T::BlockNumber, + pub startup_grace_period: BlockNumberFor, } impl Default for RoleParameters { fn default() -> Self { Self { max_actors: 10, - reward_period: T::BlockNumber::default(), - unbonding_period: T::BlockNumber::default(), + reward_period: BlockNumberFor::::default(), + unbonding_period: BlockNumberFor::::default(), // not currently used min_actors: 5, - bonding_period: T::BlockNumber::default(), - min_service_period: T::BlockNumber::default(), - startup_grace_period: T::BlockNumber::default(), + bonding_period: BlockNumberFor::::default(), + min_service_period: BlockNumberFor::::default(), + startup_grace_period: BlockNumberFor::::default(), } } } @@ -115,7 +115,7 @@ mod module { /// tokens locked until given block number #[pallet::storage] #[pallet::getter(fn bondage)] - pub type Bondage = StorageMap<_, Blake2_128Concat, T::AccountId, T::BlockNumber>; + pub type Bondage = StorageMap<_, Blake2_128Concat, T::AccountId, BlockNumberFor>; /// First step before enter a role is registering intent with a new account/key. /// This is done by sending a role_entry_request() from the new account. @@ -161,27 +161,23 @@ pub type Header = generic::Header; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; pub type Block = generic::Block; -impl frame_support_test::Config for Runtime { - type BlockNumber = BlockNumber; - type AccountId = AccountId; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU64<10>; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; - type DbWeight = (); + type OnSetCode = (); } impl module::Config for Runtime {} frame_support::construct_runtime!( - pub struct Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_support_test, + pub struct Runtime { + System: frame_system, Module: module, } ); @@ -189,6 +185,7 @@ frame_support::construct_runtime!( #[test] fn create_genesis_config() { let config = RuntimeGenesisConfig { + system: Default::default(), module: module::GenesisConfig { request_life_time: 0, enable_storage_role: true, diff --git a/frame/support/test/tests/origin.rs b/frame/support/test/tests/origin.rs index 0d9a13c1bd8bc..5682bb500c7e3 100644 --- a/frame/support/test/tests/origin.rs +++ b/frame/support/test/tests/origin.rs @@ -19,15 +19,18 @@ #![recursion_limit = "128"] -use frame_support::traits::{Contains, OriginTrait}; +use frame_support::{ + derive_impl, + traits::{Contains, OriginTrait}, +}; +use sp_core::ConstU32; use sp_runtime::{generic, traits::BlakeTwo256}; mod nested { #[frame_support::pallet(dev_mode)] pub mod module { - use self::frame_system::pallet_prelude::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; + use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -75,9 +78,8 @@ mod nested { #[frame_support::pallet(dev_mode)] pub mod module { - use self::frame_system::pallet_prelude::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; + use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -160,26 +162,24 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; frame_support::construct_runtime!( - pub enum RuntimeOriginTest where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub enum RuntimeOriginTest { - System: frame_support_test, + System: frame_system, NestedModule: nested::module, Module: module, } ); -impl frame_support_test::Config for RuntimeOriginTest { - type BlockNumber = BlockNumber; - type AccountId = AccountId; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for RuntimeOriginTest { type BaseCallFilter = BaseCallFilter; + type Block = Block; + type BlockHashCount = ConstU32<10>; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; - type DbWeight = (); + type OnSetCode = (); } impl nested::module::Config for RuntimeOriginTest { diff --git a/frame/support/test/tests/pallet.rs b/frame/support/test/tests/pallet.rs index e382176431b21..eddc3728612c2 100644 --- a/frame/support/test/tests/pallet.rs +++ b/frame/support/test/tests/pallet.rs @@ -657,13 +657,12 @@ impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU32<250>; type BlockWeights = (); @@ -709,10 +708,7 @@ pub type UncheckedExtrinsic = sp_runtime::testing::TestXt>; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { // Exclude part `Storage` in order not to check its metadata in tests. System: frame_system exclude_parts { Pallet, Storage }, diff --git a/frame/support/test/tests/pallet_instance.rs b/frame/support/test/tests/pallet_instance.rs index ed9ba048cf63c..0cd843c9bffe8 100644 --- a/frame/support/test/tests/pallet_instance.rs +++ b/frame/support/test/tests/pallet_instance.rs @@ -292,13 +292,12 @@ impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU32<250>; type BlockWeights = (); @@ -336,10 +335,7 @@ pub type Block = sp_runtime::generic::Block; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { // Exclude part `Storage` in order not to check its metadata in tests. System: frame_system exclude_parts { Storage }, diff --git a/frame/support/test/tests/pallet_outer_enums_explicit.rs b/frame/support/test/tests/pallet_outer_enums_explicit.rs index 8c03f7ecf27aa..a8250f8b15325 100644 --- a/frame/support/test/tests/pallet_outer_enums_explicit.rs +++ b/frame/support/test/tests/pallet_outer_enums_explicit.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::traits::ConstU32; +use frame_support::{derive_impl, traits::ConstU32}; mod common; @@ -25,31 +25,16 @@ pub type Header = sp_runtime::generic::Header; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU32<10>; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; - type Hash = sp_runtime::testing::H256; - type Hashing = sp_runtime::traits::BlakeTwo256; - type AccountId = u64; - type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; type RuntimeEvent = RuntimeEvent; - type BlockHashCount = ConstU32<250>; - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); type OnSetCode = (); - type MaxConsumers = ConstU32<16>; } impl common::outer_enums::pallet::Config for Runtime { @@ -72,10 +57,7 @@ impl common::outer_enums::pallet3::Config, Call, Event }, diff --git a/frame/support/test/tests/pallet_outer_enums_implicit.rs b/frame/support/test/tests/pallet_outer_enums_implicit.rs index 9a14538c35930..191f095f5d78d 100644 --- a/frame/support/test/tests/pallet_outer_enums_implicit.rs +++ b/frame/support/test/tests/pallet_outer_enums_implicit.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::traits::ConstU32; +use frame_support::{derive_impl, traits::ConstU32}; mod common; @@ -25,31 +25,16 @@ pub type Header = sp_runtime::generic::Header; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU32<10>; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; - type Hash = sp_runtime::testing::H256; - type Hashing = sp_runtime::traits::BlakeTwo256; - type AccountId = u64; - type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; type RuntimeEvent = RuntimeEvent; - type BlockHashCount = ConstU32<250>; - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); type OnSetCode = (); - type MaxConsumers = ConstU32<16>; } impl common::outer_enums::pallet::Config for Runtime { @@ -72,10 +57,7 @@ impl common::outer_enums::pallet3::Config; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU32<250>; type BlockWeights = (); @@ -89,10 +88,7 @@ pub type Block = sp_runtime::generic::Block; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { // Exclude part `Storage` in order not to check its metadata in tests. System: frame_system exclude_parts { Pallet, Storage }, diff --git a/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs b/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs index 7682caf6bf1ce..8f50d09e0f0d6 100644 --- a/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs +++ b/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs @@ -14,13 +14,12 @@ impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -38,10 +37,7 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: test_pallet::{Pallet, Config}, diff --git a/frame/support/test/tests/runtime_metadata.rs b/frame/support/test/tests/runtime_metadata.rs index 70ca307d4428c..44c375a9a674f 100644 --- a/frame/support/test/tests/runtime_metadata.rs +++ b/frame/support/test/tests/runtime_metadata.rs @@ -37,13 +37,12 @@ impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU32<250>; type Version = (); @@ -58,10 +57,7 @@ impl frame_system::Config for Runtime { } frame_support::construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub enum Runtime { System: frame_system, } diff --git a/frame/support/test/tests/storage_layers.rs b/frame/support/test/tests/storage_layers.rs index 3e306834869bb..93a541ad91162 100644 --- a/frame/support/test/tests/storage_layers.rs +++ b/frame/support/test/tests/storage_layers.rs @@ -71,12 +71,11 @@ impl frame_system::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = Index; - type BlockNumber = BlockNumber; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU32<250>; type DbWeight = (); @@ -94,12 +93,7 @@ impl frame_system::Config for Runtime { impl Config for Runtime {} frame_support::construct_runtime!( - pub struct Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub struct Runtime { System: frame_system, MyPallet: pallet, } diff --git a/frame/support/test/tests/storage_transaction.rs b/frame/support/test/tests/storage_transaction.rs index 5fc4ba7cca6d9..c477433086098 100644 --- a/frame/support/test/tests/storage_transaction.rs +++ b/frame/support/test/tests/storage_transaction.rs @@ -19,12 +19,12 @@ #![allow(deprecated)] use frame_support::{ - assert_noop, assert_ok, assert_storage_noop, + assert_noop, assert_ok, assert_storage_noop, derive_impl, dispatch::DispatchResult, storage::{with_transaction, TransactionOutcome::*}, transactional, }; -use sp_core::sr25519; +use sp_core::{sr25519, ConstU32}; use sp_io::TestExternalities; use sp_runtime::{ generic, @@ -36,10 +36,9 @@ pub use self::pallet::*; #[frame_support::pallet] pub mod pallet { - use self::frame_system::pallet_prelude::*; use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; + use frame_system::pallet_prelude::*; #[pallet::pallet] #[pallet::generate_store(pub (super) trait Store)] @@ -82,25 +81,23 @@ pub type Block = generic::Block; frame_support::construct_runtime!( pub enum Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + { - System: frame_support_test, + System: frame_system, MyPallet: pallet, } ); -impl frame_support_test::Config for Runtime { - type BlockNumber = BlockNumber; - type AccountId = AccountId; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU32<10>; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; - type DbWeight = (); + type OnSetCode = (); } impl Config for Runtime {} diff --git a/frame/support/test/tests/versioned_runtime_upgrade.rs b/frame/support/test/tests/versioned_runtime_upgrade.rs index 338d0776974ad..93d87df8ca185 100644 --- a/frame/support/test/tests/versioned_runtime_upgrade.rs +++ b/frame/support/test/tests/versioned_runtime_upgrade.rs @@ -27,9 +27,9 @@ use frame_support::{ weights::constants::RocksDbWeight, }; use frame_system::Config; +use sp_core::ConstU64; use sp_runtime::BuildStorage; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; #[frame_support::pallet] @@ -64,10 +64,7 @@ mod dummy_pallet { impl dummy_pallet::Config for Test {} construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, DummyPallet: dummy_pallet::{Pallet, Config, Storage} = 1, @@ -77,6 +74,8 @@ construct_runtime!( #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU64<10>; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; diff --git a/frame/system/benches/bench.rs b/frame/system/benches/bench.rs index f344e041a0d49..93e2c61ad5cd8 100644 --- a/frame/system/benches/bench.rs +++ b/frame/system/benches/bench.rs @@ -19,7 +19,6 @@ use criterion::{black_box, criterion_group, criterion_main, Criterion}; use frame_support::traits::{ConstU32, ConstU64}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, Perbill, }; @@ -42,14 +41,10 @@ mod module { } } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub struct Runtime { System: frame_system::{Pallet, Call, Config, Storage, Event}, Module: module::{Pallet, Event}, @@ -69,13 +64,12 @@ impl frame_system::Config for Runtime { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/system/benchmarking/src/mock.rs b/frame/system/benchmarking/src/mock.rs index 98f8ea6e07ebf..4201f9dcc6f97 100644 --- a/frame/system/benchmarking/src/mock.rs +++ b/frame/system/benchmarking/src/mock.rs @@ -24,16 +24,11 @@ use sp_runtime::{traits::IdentityLookup, BuildStorage}; type AccountId = u64; type AccountIndex = u32; -type BlockNumber = u64; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, } @@ -46,13 +41,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; - type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); diff --git a/frame/system/src/extensions/check_genesis.rs b/frame/system/src/extensions/check_genesis.rs index 5964ec452842f..76a711a823e7d 100644 --- a/frame/system/src/extensions/check_genesis.rs +++ b/frame/system/src/extensions/check_genesis.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{Config, Pallet}; +use crate::{pallet_prelude::BlockNumberFor, Config, Pallet}; use codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_runtime::{ @@ -60,7 +60,7 @@ impl SignedExtension for CheckGenesis { const IDENTIFIER: &'static str = "CheckGenesis"; fn additional_signed(&self) -> Result { - Ok(>::block_hash(T::BlockNumber::zero())) + Ok(>::block_hash(BlockNumberFor::::zero())) } fn pre_dispatch( diff --git a/frame/system/src/extensions/check_mortality.rs b/frame/system/src/extensions/check_mortality.rs index 23c357d481350..148dfd4aad471 100644 --- a/frame/system/src/extensions/check_mortality.rs +++ b/frame/system/src/extensions/check_mortality.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{BlockHash, Config, Pallet}; +use crate::{pallet_prelude::BlockNumberFor, BlockHash, Config, Pallet}; use codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_runtime::{ @@ -78,7 +78,7 @@ impl SignedExtension for CheckMortality { fn additional_signed(&self) -> Result { let current_u64 = >::block_number().saturated_into::(); - let n = self.0.birth(current_u64).saturated_into::(); + let n = self.0.birth(current_u64).saturated_into::>(); if !>::contains_key(n) { Err(InvalidTransaction::AncientBirthBlock.into()) } else { diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index 9fcd7c12fec4e..a4c40032c8972 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -64,6 +64,7 @@ #![cfg_attr(not(feature = "std"), no_std)] +use pallet_prelude::{BlockNumberFor, HeaderFor}; #[cfg(feature = "std")] use serde::Serialize; use sp_io::hashing::blake2_256; @@ -72,9 +73,9 @@ use sp_runtime::traits::TrailingZeroInput; use sp_runtime::{ generic, traits::{ - self, AtLeast32Bit, AtLeast32BitUnsigned, BadOrigin, BlockNumberProvider, Bounded, - CheckEqual, Dispatchable, Hash, Lookup, LookupError, MaybeDisplay, - MaybeSerializeDeserialize, Member, One, Saturating, SimpleBitOps, StaticLookup, Zero, + self, AtLeast32Bit, BadOrigin, BlockNumberProvider, Bounded, CheckEqual, Dispatchable, + Hash, Header, Lookup, LookupError, MaybeDisplay, MaybeSerializeDeserialize, Member, One, + Saturating, SimpleBitOps, StaticLookup, Zero, }, DispatchError, RuntimeDebug, }; @@ -217,13 +218,10 @@ pub mod pallet { #[frame_support::register_default_impl(TestDefaultConfig)] impl DefaultConfig for TestDefaultConfig { type Index = u32; - type BlockNumber = u32; - type Header = sp_runtime::generic::Header; type Hash = sp_core::hash::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type BlockHashCount = frame_support::traits::ConstU32<10>; type MaxConsumers = frame_support::traits::ConstU32<16>; type AccountData = (); type OnNewAccount = (); @@ -287,21 +285,6 @@ pub mod pallet { + Copy + MaxEncodedLen; - /// The block number type used by the runtime. - type BlockNumber: Parameter - + Member - + MaybeSerializeDeserialize - + Debug - + MaybeDisplay - + AtLeast32BitUnsigned - + Default - + Bounded - + Copy - + sp_std::hash::Hash - + sp_std::str::FromStr - + MaxEncodedLen - + TypeInfo; - /// The output of the `Hashing` function. type Hash: Parameter + Member @@ -338,12 +321,15 @@ pub mod pallet { /// functional/efficient alternatives. type Lookup: StaticLookup; - /// The block header. - type Header: Parameter + traits::Header; + /// The Block type used by the runtime. This is used by `construct_runtime` to retrieve the + /// extrinsics or other block specific data as needed. + #[pallet::no_default] + type Block: Parameter + Member + traits::Block; /// Maximum number of block number to block hash mappings to keep (oldest pruned first). #[pallet::constant] - type BlockHashCount: Get; + #[pallet::no_default] + type BlockHashCount: Get>; /// The weight of runtime database operations the runtime can invoke. #[pallet::constant] @@ -590,7 +576,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn block_hash)] pub type BlockHash = - StorageMap<_, Twox64Concat, T::BlockNumber, T::Hash, ValueQuery>; + StorageMap<_, Twox64Concat, BlockNumberFor, T::Hash, ValueQuery>; /// Extrinsics data for the current block (maps an extrinsic's index to its data). #[pallet::storage] @@ -603,7 +589,7 @@ pub mod pallet { #[pallet::storage] #[pallet::whitelist_storage] #[pallet::getter(fn block_number)] - pub(super) type Number = StorageValue<_, T::BlockNumber, ValueQuery>; + pub(super) type Number = StorageValue<_, BlockNumberFor, ValueQuery>; /// Hash of the previous block. #[pallet::storage] @@ -642,14 +628,14 @@ pub mod pallet { /// allows light-clients to leverage the changes trie storage tracking mechanism and /// in case of changes fetch the list of events of interest. /// - /// The value has the type `(T::BlockNumber, EventIndex)` because if we used only just + /// The value has the type `(BlockNumberFor, EventIndex)` because if we used only just /// the `EventIndex` then in case if the topic has the same contents on the next block /// no notification will be triggered thus the event might be lost. #[pallet::storage] #[pallet::unbounded] #[pallet::getter(fn event_topics)] pub(super) type EventTopics = - StorageMap<_, Blake2_128Concat, T::Hash, Vec<(T::BlockNumber, EventIndex)>, ValueQuery>; + StorageMap<_, Blake2_128Concat, T::Hash, Vec<(BlockNumberFor, EventIndex)>, ValueQuery>; /// Stores the `spec_version` and `spec_name` of when the last runtime upgrade happened. #[pallet::storage] @@ -682,7 +668,7 @@ pub mod pallet { #[pallet::genesis_build] impl BuildGenesisConfig for GenesisConfig { fn build(&self) { - >::insert::<_, T::Hash>(T::BlockNumber::zero(), hash69()); + >::insert::<_, T::Hash>(BlockNumberFor::::zero(), hash69()); >::put::(hash69()); >::put(LastRuntimeUpgradeInfo::from(T::Version::get())); >::put(true); @@ -1370,7 +1356,7 @@ impl Pallet { } /// Start the execution of a particular block. - pub fn initialize(number: &T::BlockNumber, parent_hash: &T::Hash, digest: &generic::Digest) { + pub fn initialize(number: &BlockNumberFor, parent_hash: &T::Hash, digest: &generic::Digest) { // populate environment ExecutionPhase::::put(Phase::Initialization); storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32); @@ -1387,7 +1373,7 @@ impl Pallet { /// Remove temporary "environment" entries in storage, compute the storage root and return the /// resulting header for this block. - pub fn finalize() -> T::Header { + pub fn finalize() -> HeaderFor { log::debug!( target: LOG_TARGET, "[{:?}] {} extrinsics, length: {} (normal {}%, op: {}%, mandatory {}%) / normal weight:\ @@ -1459,13 +1445,7 @@ impl Pallet { let storage_root = T::Hash::decode(&mut &sp_io::storage::root(version)[..]) .expect("Node is configured to use the same hash; qed"); - ::new( - number, - extrinsics_root, - storage_root, - parent_hash, - digest, - ) + HeaderFor::::new(number, extrinsics_root, storage_root, parent_hash, digest) } /// Deposits a log and ensures it matches the block's log data. @@ -1478,8 +1458,8 @@ impl Pallet { pub fn externalities() -> TestExternalities { TestExternalities::new(sp_core::storage::Storage { top: map![ - >::hashed_key_for(T::BlockNumber::zero()) => [69u8; 32].encode(), - >::hashed_key().to_vec() => T::BlockNumber::one().encode(), + >::hashed_key_for(BlockNumberFor::::zero()) => [69u8; 32].encode(), + >::hashed_key().to_vec() => BlockNumberFor::::one().encode(), >::hashed_key().to_vec() => [69u8; 32].encode() ], children_default: map![], @@ -1524,7 +1504,7 @@ impl Pallet { /// Set the block number to something in particular. Can be used as an alternative to /// `initialize` for tests that don't need to bother with the other environment entries. #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))] - pub fn set_block_number(n: T::BlockNumber) { + pub fn set_block_number(n: BlockNumberFor) { >::put(n); } @@ -1742,7 +1722,7 @@ impl HandleLifetime for Consumer { } impl BlockNumberProvider for Pallet { - type BlockNumber = ::BlockNumber; + type BlockNumber = BlockNumberFor; fn current_block_number() -> Self::BlockNumber { Pallet::::block_number() @@ -1813,6 +1793,10 @@ pub mod pallet_prelude { /// Type alias for the `Origin` associated type of system config. pub type OriginFor = ::RuntimeOrigin; + /// Type alias for the `Header`. + pub type HeaderFor = + <::Block as sp_runtime::traits::HeaderProvider>::HeaderT; + /// Type alias for the `BlockNumber` associated type of system config. - pub type BlockNumberFor = ::BlockNumber; + pub type BlockNumberFor = as sp_runtime::traits::Header>::Number; } diff --git a/frame/system/src/mock.rs b/frame/system/src/mock.rs index 0325c970b8616..cb9bbcb246a10 100644 --- a/frame/system/src/mock.rs +++ b/frame/system/src/mock.rs @@ -22,19 +22,14 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, Perbill, }; -type UncheckedExtrinsic = mocking::MockUncheckedExtrinsic; type Block = mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, } @@ -97,12 +92,11 @@ impl Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<10>; type DbWeight = DbWeight; diff --git a/frame/system/src/mocking.rs b/frame/system/src/mocking.rs index 8f76c1b8e08ba..833309e05ecc9 100644 --- a/frame/system/src/mocking.rs +++ b/frame/system/src/mocking.rs @@ -29,6 +29,19 @@ pub type MockUncheckedExtrinsic = generic::Unchec /// An implementation of `sp_runtime::traits::Block` to be used in tests. pub type MockBlock = generic::Block< - generic::Header<::BlockNumber, sp_runtime::traits::BlakeTwo256>, + generic::Header, + MockUncheckedExtrinsic, +>; + +/// An implementation of `sp_runtime::traits::Block` to be used in tests with u32 BlockNumber type. +pub type MockBlockU32 = generic::Block< + generic::Header, + MockUncheckedExtrinsic, +>; + +/// An implementation of `sp_runtime::traits::Block` to be used in tests with u128 BlockNumber +/// type. +pub type MockBlockU128 = generic::Block< + generic::Header, MockUncheckedExtrinsic, >; diff --git a/frame/timestamp/src/lib.rs b/frame/timestamp/src/lib.rs index e707764beb95c..4eb95941d7828 100644 --- a/frame/timestamp/src/lib.rs +++ b/frame/timestamp/src/lib.rs @@ -130,7 +130,7 @@ pub mod pallet { type Moment: Parameter + Default + AtLeast32Bit - + Scale + + Scale, Output = Self::Moment> + Copy + MaxEncodedLen + scale_info::StaticTypeInfo; diff --git a/frame/timestamp/src/mock.rs b/frame/timestamp/src/mock.rs index 2144322e62128..00e9e0b17c720 100644 --- a/frame/timestamp/src/mock.rs +++ b/frame/timestamp/src/mock.rs @@ -27,20 +27,15 @@ use frame_support::{ use sp_core::H256; use sp_io::TestExternalities; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; type Moment = u64; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, @@ -54,13 +49,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/tips/src/benchmarking.rs b/frame/tips/src/benchmarking.rs index 613f684afdf56..4a991b11b9331 100644 --- a/frame/tips/src/benchmarking.rs +++ b/frame/tips/src/benchmarking.rs @@ -78,7 +78,7 @@ fn create_tips, I: 'static>( } Tips::::mutate(hash, |maybe_tip| { if let Some(open_tip) = maybe_tip { - open_tip.closes = Some(T::BlockNumber::zero()); + open_tip.closes = Some(frame_system::pallet_prelude::BlockNumberFor::::zero()); } }); Ok(()) diff --git a/frame/tips/src/lib.rs b/frame/tips/src/lib.rs index 970e2ac152c4b..6e8f72e0540e6 100644 --- a/frame/tips/src/lib.rs +++ b/frame/tips/src/lib.rs @@ -74,6 +74,7 @@ use frame_support::{ }, Parameter, }; +use frame_system::pallet_prelude::BlockNumberFor; pub use pallet::*; pub use weights::WeightInfo; @@ -143,7 +144,7 @@ pub mod pallet { /// The period for which a tip remains open after is has achieved threshold tippers. #[pallet::constant] - type TipCountdown: Get; + type TipCountdown: Get>; /// The percent of the final tip which goes to the original reporter of the tip. #[pallet::constant] @@ -173,7 +174,7 @@ pub mod pallet { _, Twox64Concat, T::Hash, - OpenTip, T::BlockNumber, T::Hash>, + OpenTip, BlockNumberFor, T::Hash>, OptionQuery, >; @@ -470,7 +471,7 @@ impl, I: 'static> Pallet { /// /// `O(T)` and one storage access. fn insert_tip_and_check_closing( - tip: &mut OpenTip, T::BlockNumber, T::Hash>, + tip: &mut OpenTip, BlockNumberFor, T::Hash>, tipper: T::AccountId, tip_value: BalanceOf, ) -> bool { @@ -515,7 +516,7 @@ impl, I: 'static> Pallet { /// Plus `O(T)` (`T` is Tippers length). fn payout_tip( hash: T::Hash, - tip: OpenTip, T::BlockNumber, T::Hash>, + tip: OpenTip, BlockNumberFor, T::Hash>, ) { let mut tips = tip.tips; Self::retain_active_tips(&mut tips); @@ -577,7 +578,7 @@ impl, I: 'static> Pallet { for (hash, old_tip) in storage_key_iter::< T::Hash, - OldOpenTip, T::BlockNumber, T::Hash>, + OldOpenTip, BlockNumberFor, T::Hash>, Twox64Concat, >(module, item) .drain() diff --git a/frame/tips/src/tests.rs b/frame/tips/src/tests.rs index 4026e54863a32..3abbe5428f1d8 100644 --- a/frame/tips/src/tests.rs +++ b/frame/tips/src/tests.rs @@ -21,7 +21,6 @@ use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BadOrigin, BlakeTwo256, IdentityLookup}, BuildStorage, Perbill, Permill, }; @@ -37,14 +36,10 @@ use frame_support::{ use super::*; use crate::{self as pallet_tips, Event as TipEvent}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -65,13 +60,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u128; // u64 is not enough to hold bytes used to generate bounty account type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/transaction-payment/asset-conversion-tx-payment/src/mock.rs b/frame/transaction-payment/asset-conversion-tx-payment/src/mock.rs index 6e05ec6163ddb..683b93ad1f3fe 100644 --- a/frame/transaction-payment/asset-conversion-tx-payment/src/mock.rs +++ b/frame/transaction-payment/asset-conversion-tx-payment/src/mock.rs @@ -33,21 +33,16 @@ use pallet_asset_conversion::{NativeOrAssetId, NativeOrAssetIdConverter}; use pallet_transaction_payment::CurrencyAdapter; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{AccountIdConversion, BlakeTwo256, IdentityLookup, SaturatedConversion}, Permill, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; type Balance = u64; type AccountId = u64; frame_support::construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Runtime { System: system, Balances: pallet_balances, @@ -90,13 +85,12 @@ impl frame_system::Config for Runtime { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/transaction-payment/asset-tx-payment/src/mock.rs b/frame/transaction-payment/asset-tx-payment/src/mock.rs index 740915023a32d..fbc70c118da7b 100644 --- a/frame/transaction-payment/asset-tx-payment/src/mock.rs +++ b/frame/transaction-payment/asset-tx-payment/src/mock.rs @@ -29,23 +29,14 @@ use frame_system as system; use frame_system::EnsureRoot; use pallet_transaction_payment::CurrencyAdapter; use sp_core::H256; -use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, ConvertInto, IdentityLookup, SaturatedConversion}, -}; +use sp_runtime::traits::{BlakeTwo256, ConvertInto, IdentityLookup, SaturatedConversion}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; type Balance = u64; type AccountId = u64; frame_support::construct_runtime!( - pub struct Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub struct Runtime { System: system, Balances: pallet_balances, TransactionPayment: pallet_transaction_payment, @@ -86,13 +77,12 @@ impl frame_system::Config for Runtime { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index bff32456cba4a..d61be5540c3a4 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -410,7 +410,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_finalize(_: T::BlockNumber) { + fn on_finalize(_: frame_system::pallet_prelude::BlockNumberFor) { >::mutate(|fm| { *fm = T::FeeMultiplierUpdate::convert(*fm); }); diff --git a/frame/transaction-payment/src/mock.rs b/frame/transaction-payment/src/mock.rs index 448079000cab8..6d9c8c5d1d210 100644 --- a/frame/transaction-payment/src/mock.rs +++ b/frame/transaction-payment/src/mock.rs @@ -19,10 +19,7 @@ use super::*; use crate as pallet_transaction_payment; use sp_core::H256; -use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, IdentityLookup}, -}; +use sp_runtime::traits::{BlakeTwo256, IdentityLookup}; use frame_support::{ dispatch::DispatchClass, @@ -33,14 +30,10 @@ use frame_support::{ use frame_system as system; use pallet_balances::Call as BalancesCall; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub struct Runtime { System: system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -83,13 +76,12 @@ impl frame_system::Config for Runtime { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/transaction-storage/src/benchmarking.rs b/frame/transaction-storage/src/benchmarking.rs index dfea3331569f9..fdbaeb1f95181 100644 --- a/frame/transaction-storage/src/benchmarking.rs +++ b/frame/transaction-storage/src/benchmarking.rs @@ -22,7 +22,7 @@ use super::*; use frame_benchmarking::v1::{benchmarks, whitelisted_caller}; use frame_support::traits::{Currency, Get, OnFinalize, OnInitialize}; -use frame_system::{EventRecord, Pallet as System, RawOrigin}; +use frame_system::{pallet_prelude::BlockNumberFor, EventRecord, Pallet as System, RawOrigin}; use sp_runtime::traits::{Bounded, One, Zero}; use sp_std::*; use sp_transaction_storage_proof::TransactionStorageProof; @@ -113,7 +113,7 @@ fn assert_last_event(generic_event: ::RuntimeEvent) { assert_eq!(event, &system_event); } -pub fn run_to_block(n: T::BlockNumber) { +pub fn run_to_block(n: frame_system::pallet_prelude::BlockNumberFor) { while frame_system::Pallet::::block_number() < n { crate::Pallet::::on_finalize(frame_system::Pallet::::block_number()); frame_system::Pallet::::on_finalize(frame_system::Pallet::::block_number()); @@ -144,7 +144,7 @@ benchmarks! { vec![0u8; T::MaxTransactionSize::get() as usize], )?; run_to_block::(1u32.into()); - }: _(RawOrigin::Signed(caller.clone()), T::BlockNumber::zero(), 0) + }: _(RawOrigin::Signed(caller.clone()), BlockNumberFor::::zero(), 0) verify { assert_last_event::(Event::Renewed { index: 0 }.into()); } @@ -159,7 +159,7 @@ benchmarks! { vec![0u8; T::MaxTransactionSize::get() as usize], )?; } - run_to_block::(StoragePeriod::::get() + T::BlockNumber::one()); + run_to_block::(StoragePeriod::::get() + BlockNumberFor::::one()); let encoded_proof = proof(); let proof = TransactionStorageProof::decode(&mut &*encoded_proof).unwrap(); }: check_proof(RawOrigin::None, proof) diff --git a/frame/transaction-storage/src/lib.rs b/frame/transaction-storage/src/lib.rs index 4004dbd0a435b..e784d20a0cfd7 100644 --- a/frame/transaction-storage/src/lib.rs +++ b/frame/transaction-storage/src/lib.rs @@ -145,7 +145,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: BlockNumberFor) -> Weight { // Drop obsolete roots. The proof for `obsolete` will be checked later // in this block, so we drop `obsolete` - 1. let period = >::get(); @@ -158,7 +158,7 @@ pub mod pallet { T::DbWeight::get().reads_writes(2, 4) } - fn on_finalize(n: T::BlockNumber) { + fn on_finalize(n: BlockNumberFor) { assert!( >::take() || { // Proof is not required for early or empty blocks. @@ -238,7 +238,7 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::renew())] pub fn renew( origin: OriginFor, - block: T::BlockNumber, + block: BlockNumberFor, index: u32, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; @@ -342,7 +342,7 @@ pub mod pallet { pub(super) type Transactions = StorageMap< _, Blake2_128Concat, - T::BlockNumber, + BlockNumberFor, BoundedVec, OptionQuery, >; @@ -350,7 +350,7 @@ pub mod pallet { /// Count indexed chunks for each block. #[pallet::storage] pub(super) type ChunkCount = - StorageMap<_, Blake2_128Concat, T::BlockNumber, u32, ValueQuery>; + StorageMap<_, Blake2_128Concat, BlockNumberFor, u32, ValueQuery>; #[pallet::storage] #[pallet::getter(fn byte_fee)] @@ -365,7 +365,7 @@ pub mod pallet { /// Storage period for data in blocks. Should match `sp_storage_proof::DEFAULT_STORAGE_PERIOD` /// for block authoring. #[pallet::storage] - pub(super) type StoragePeriod = StorageValue<_, T::BlockNumber, ValueQuery>; + pub(super) type StoragePeriod = StorageValue<_, BlockNumberFor, ValueQuery>; // Intermediates #[pallet::storage] @@ -380,7 +380,7 @@ pub mod pallet { pub struct GenesisConfig { pub byte_fee: BalanceOf, pub entry_fee: BalanceOf, - pub storage_period: T::BlockNumber, + pub storage_period: BlockNumberFor, } impl Default for GenesisConfig { diff --git a/frame/transaction-storage/src/mock.rs b/frame/transaction-storage/src/mock.rs index efabcb97f081d..94705cd9340bd 100644 --- a/frame/transaction-storage/src/mock.rs +++ b/frame/transaction-storage/src/mock.rs @@ -24,20 +24,15 @@ use crate::{ use frame_support::traits::{ConstU16, ConstU32, ConstU64, OnFinalize, OnInitialize}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; pub type Block = frame_system::mocking::MockBlock; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Config, Storage, Event}, @@ -54,12 +49,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); diff --git a/frame/treasury/src/benchmarking.rs b/frame/treasury/src/benchmarking.rs index a3761083e4faa..449549d6c53b7 100644 --- a/frame/treasury/src/benchmarking.rs +++ b/frame/treasury/src/benchmarking.rs @@ -135,7 +135,7 @@ benchmarks_instance_pallet! { setup_pot_account::(); create_approved_proposals::(p)?; }: { - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(frame_system::pallet_prelude::BlockNumberFor::::zero()); } impl_benchmark_test_suite!(Treasury, crate::tests::new_test_ext(), crate::tests::Test); diff --git a/frame/treasury/src/lib.rs b/frame/treasury/src/lib.rs index 01cda66edbb25..49be4d91a4568 100644 --- a/frame/treasury/src/lib.rs +++ b/frame/treasury/src/lib.rs @@ -175,7 +175,7 @@ pub mod pallet { /// Period between successive spends. #[pallet::constant] - type SpendPeriod: Get; + type SpendPeriod: Get>; /// Percentage of spare funds (if any) that are burnt per spend period. #[pallet::constant] @@ -299,7 +299,7 @@ pub mod pallet { impl, I: 'static> Hooks> for Pallet { /// ## Complexity /// - `O(A)` where `A` is the number of approvals - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: frame_system::pallet_prelude::BlockNumberFor) -> Weight { let pot = Self::pot(); let deactivated = Deactivated::::get(); if pot != deactivated { diff --git a/frame/treasury/src/tests.rs b/frame/treasury/src/tests.rs index e1cbffc2f2a31..39db42a22a382 100644 --- a/frame/treasury/src/tests.rs +++ b/frame/treasury/src/tests.rs @@ -21,7 +21,6 @@ use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BadOrigin, BlakeTwo256, Dispatchable, IdentityLookup}, BuildStorage, }; @@ -35,16 +34,12 @@ use frame_support::{ use super::*; use crate as treasury; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; type UtilityCall = pallet_utility::Call; type TreasuryCall = crate::Call; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -60,13 +55,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u128; // u64 is not enough to hold bytes used to generate bounty account type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/uniques/src/mock.rs b/frame/uniques/src/mock.rs index b975f6bac6a55..6ff7278cce8aa 100644 --- a/frame/uniques/src/mock.rs +++ b/frame/uniques/src/mock.rs @@ -26,19 +26,14 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -53,12 +48,11 @@ impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); diff --git a/frame/utility/src/tests.rs b/frame/utility/src/tests.rs index e39820ae251dd..3587b55762b7c 100644 --- a/frame/utility/src/tests.rs +++ b/frame/utility/src/tests.rs @@ -33,7 +33,6 @@ use frame_support::{ use pallet_collective::{EnsureProportionAtLeast, Instance1}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, Hash, IdentityLookup}, BuildStorage, TokenError, }; @@ -125,14 +124,10 @@ mod mock_democracy { } } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Timestamp: pallet_timestamp::{Call, Inherent}, @@ -156,13 +151,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/vesting/src/benchmarking.rs b/frame/vesting/src/benchmarking.rs index 15be519842992..4af48f5d368db 100644 --- a/frame/vesting/src/benchmarking.rs +++ b/frame/vesting/src/benchmarking.rs @@ -21,7 +21,7 @@ use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller}; use frame_support::assert_ok; -use frame_system::{Pallet as System, RawOrigin}; +use frame_system::{pallet_prelude::BlockNumberFor, Pallet as System, RawOrigin}; use sp_runtime::traits::{Bounded, CheckedDiv, CheckedMul}; use super::*; @@ -55,7 +55,7 @@ fn add_vesting_schedules( let source_lookup = T::Lookup::unlookup(source.clone()); T::Currency::make_free_balance_be(&source, BalanceOf::::max_value()); - System::::set_block_number(T::BlockNumber::zero()); + System::::set_block_number(BlockNumberFor::::zero()); let mut total_locked: BalanceOf = Zero::zero(); for _ in 0..n { @@ -88,7 +88,7 @@ benchmarks! { let expected_balance = add_vesting_schedules::(caller_lookup, s)?; // At block zero, everything is vested. - assert_eq!(System::::block_number(), T::BlockNumber::zero()); + assert_eq!(System::::block_number(), BlockNumberFor::::zero()); assert_eq!( Vesting::::vesting_balance(&caller), Some(expected_balance), @@ -144,7 +144,7 @@ benchmarks! { let expected_balance = add_vesting_schedules::(other_lookup.clone(), s)?; // At block zero, everything is vested. - assert_eq!(System::::block_number(), T::BlockNumber::zero()); + assert_eq!(System::::block_number(), BlockNumberFor::::zero()); assert_eq!( Vesting::::vesting_balance(&other), Some(expected_balance), @@ -284,7 +284,7 @@ benchmarks! { let expected_balance = add_vesting_schedules::(caller_lookup, s)?; // Schedules are not vesting at block 0. - assert_eq!(System::::block_number(), T::BlockNumber::zero()); + assert_eq!(System::::block_number(), BlockNumberFor::::zero()); assert_eq!( Vesting::::vesting_balance(&caller), Some(expected_balance), diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index f19e38d311914..eb829121e9797 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -67,6 +67,7 @@ use frame_support::{ }, weights::Weight, }; +use frame_system::pallet_prelude::BlockNumberFor; use scale_info::TypeInfo; use sp_runtime::{ traits::{ @@ -127,8 +128,8 @@ impl VestingAction { /// Pick the schedules that this action dictates should continue vesting undisturbed. fn pick_schedules( &self, - schedules: Vec, T::BlockNumber>>, - ) -> impl Iterator, T::BlockNumber>> + '_ { + schedules: Vec, BlockNumberFor>>, + ) -> impl Iterator, BlockNumberFor>> + '_ { schedules.into_iter().enumerate().filter_map(move |(index, schedule)| { if self.should_remove(index) { None @@ -162,7 +163,7 @@ pub mod pallet { type Currency: LockableCurrency; /// Convert the block number into a balance. - type BlockNumberToBalance: Convert>; + type BlockNumberToBalance: Convert, BalanceOf>; /// The minimum amount transferred to call `vested_transfer`. #[pallet::constant] @@ -201,7 +202,7 @@ pub mod pallet { _, Blake2_128Concat, T::AccountId, - BoundedVec, T::BlockNumber>, MaxVestingSchedulesGet>, + BoundedVec, BlockNumberFor>, MaxVestingSchedulesGet>, >; /// Storage version of the pallet. @@ -216,7 +217,7 @@ pub mod pallet { #[pallet::genesis_config] #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { - pub vesting: Vec<(T::AccountId, T::BlockNumber, T::BlockNumber, BalanceOf)>, + pub vesting: Vec<(T::AccountId, BlockNumberFor, BlockNumberFor, BalanceOf)>, } #[pallet::genesis_build] @@ -342,7 +343,7 @@ pub mod pallet { pub fn vested_transfer( origin: OriginFor, target: AccountIdLookupOf, - schedule: VestingInfo, T::BlockNumber>, + schedule: VestingInfo, BlockNumberFor>, ) -> DispatchResult { let transactor = ensure_signed(origin)?; let transactor = ::unlookup(transactor); @@ -371,7 +372,7 @@ pub mod pallet { origin: OriginFor, source: AccountIdLookupOf, target: AccountIdLookupOf, - schedule: VestingInfo, T::BlockNumber>, + schedule: VestingInfo, BlockNumberFor>, ) -> DispatchResult { ensure_root(origin)?; Self::do_vested_transfer(source, target, schedule) @@ -433,10 +434,10 @@ impl Pallet { // Create a new `VestingInfo`, based off of two other `VestingInfo`s. // NOTE: We assume both schedules have had funds unlocked up through the current block. fn merge_vesting_info( - now: T::BlockNumber, - schedule1: VestingInfo, T::BlockNumber>, - schedule2: VestingInfo, T::BlockNumber>, - ) -> Option, T::BlockNumber>> { + now: BlockNumberFor, + schedule1: VestingInfo, BlockNumberFor>, + schedule2: VestingInfo, BlockNumberFor>, + ) -> Option, BlockNumberFor>> { let schedule1_ending_block = schedule1.ending_block_as_balance::(); let schedule2_ending_block = schedule2.ending_block_as_balance::(); let now_as_balance = T::BlockNumberToBalance::convert(now); @@ -483,7 +484,7 @@ impl Pallet { fn do_vested_transfer( source: AccountIdLookupOf, target: AccountIdLookupOf, - schedule: VestingInfo, T::BlockNumber>, + schedule: VestingInfo, BlockNumberFor>, ) -> DispatchResult { // Validate user inputs. ensure!(schedule.locked() >= T::MinVestedTransfer::get(), Error::::AmountLow); @@ -531,9 +532,9 @@ impl Pallet { /// /// NOTE: the amount locked does not include any schedules that are filtered out via `action`. fn report_schedule_updates( - schedules: Vec, T::BlockNumber>>, + schedules: Vec, BlockNumberFor>>, action: VestingAction, - ) -> (Vec, T::BlockNumber>>, BalanceOf) { + ) -> (Vec, BlockNumberFor>>, BalanceOf) { let now = >::block_number(); let mut total_locked_now: BalanceOf = Zero::zero(); @@ -570,10 +571,10 @@ impl Pallet { /// Write an accounts updated vesting schedules to storage. fn write_vesting( who: &T::AccountId, - schedules: Vec, T::BlockNumber>>, + schedules: Vec, BlockNumberFor>>, ) -> Result<(), DispatchError> { let schedules: BoundedVec< - VestingInfo, T::BlockNumber>, + VestingInfo, BlockNumberFor>, MaxVestingSchedulesGet, > = schedules.try_into().map_err(|_| Error::::AtMaxVestingSchedules)?; @@ -602,9 +603,9 @@ impl Pallet { /// Execute a `VestingAction` against the given `schedules`. Returns the updated schedules /// and locked amount. fn exec_action( - schedules: Vec, T::BlockNumber>>, + schedules: Vec, BlockNumberFor>>, action: VestingAction, - ) -> Result<(Vec, T::BlockNumber>>, BalanceOf), DispatchError> { + ) -> Result<(Vec, BlockNumberFor>>, BalanceOf), DispatchError> { let (schedules, locked_now) = match action { VestingAction::Merge { index1: idx1, index2: idx2 } => { // The schedule index is based off of the schedule ordering prior to filtering out @@ -649,7 +650,7 @@ where BalanceOf: MaybeSerializeDeserialize + Debug, { type Currency = T::Currency; - type Moment = T::BlockNumber; + type Moment = BlockNumberFor; /// Get the amount that is currently being vested and cannot be transferred out of this account. fn vesting_balance(who: &T::AccountId) -> Option> { @@ -680,7 +681,7 @@ where who: &T::AccountId, locked: BalanceOf, per_block: BalanceOf, - starting_block: T::BlockNumber, + starting_block: BlockNumberFor, ) -> DispatchResult { if locked.is_zero() { return Ok(()) @@ -713,7 +714,7 @@ where who: &T::AccountId, locked: BalanceOf, per_block: BalanceOf, - starting_block: T::BlockNumber, + starting_block: BlockNumberFor, ) -> DispatchResult { // Check for `per_block` or `locked` of 0. if !VestingInfo::new(locked, per_block, starting_block).is_valid() { diff --git a/frame/vesting/src/migrations.rs b/frame/vesting/src/migrations.rs index 69bbc97296500..cac3c90b403ab 100644 --- a/frame/vesting/src/migrations.rs +++ b/frame/vesting/src/migrations.rs @@ -40,12 +40,12 @@ pub mod v1 { pub fn migrate() -> Weight { let mut reads_writes = 0; - Vesting::::translate::, T::BlockNumber>, _>( + Vesting::::translate::, BlockNumberFor>, _>( |_key, vesting_info| { reads_writes += 1; let v: Option< BoundedVec< - VestingInfo, T::BlockNumber>, + VestingInfo, BlockNumberFor>, MaxVestingSchedulesGet, >, > = vec![vesting_info].try_into().ok(); diff --git a/frame/vesting/src/mock.rs b/frame/vesting/src/mock.rs index d0c25221cd5e9..c569ec96b99e0 100644 --- a/frame/vesting/src/mock.rs +++ b/frame/vesting/src/mock.rs @@ -21,7 +21,6 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, Identity, IdentityLookup}, BuildStorage, }; @@ -29,14 +28,10 @@ use sp_runtime::{ use super::*; use crate as pallet_vesting; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -50,14 +45,13 @@ impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockHashCount = ConstU64<250>; type BlockLength = (); - type BlockNumber = u64; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); type RuntimeEvent = RuntimeEvent; type Hash = H256; type Hashing = BlakeTwo256; - type Header = Header; + type Block = Block; type Index = u64; type Lookup = IdentityLookup; type OnKilledAccount = (); diff --git a/frame/whitelist/src/mock.rs b/frame/whitelist/src/mock.rs index afb9d00861563..3b25cdd4d14ae 100644 --- a/frame/whitelist/src/mock.rs +++ b/frame/whitelist/src/mock.rs @@ -28,19 +28,14 @@ use frame_support::{ use frame_system::EnsureRoot; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Balances: pallet_balances, @@ -56,13 +51,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type Index = u64; - type BlockNumber = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/primitives/runtime/src/generic/block.rs b/primitives/runtime/src/generic/block.rs index 6261e412eb8ad..05146e880cb16 100644 --- a/primitives/runtime/src/generic/block.rs +++ b/primitives/runtime/src/generic/block.rs @@ -25,7 +25,10 @@ use serde::{Deserialize, Serialize}; use crate::{ codec::{Codec, Decode, Encode}, - traits::{self, Block as BlockT, Header as HeaderT, MaybeSerialize, Member, NumberFor}, + traits::{ + self, Block as BlockT, Header as HeaderT, MaybeSerialize, MaybeSerializeDeserialize, + Member, NumberFor, + }, Justifications, }; use sp_core::RuntimeDebug; @@ -79,16 +82,23 @@ impl fmt::Display for BlockId { #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] #[cfg_attr(feature = "serde", serde(deny_unknown_fields))] -pub struct Block { +pub struct Block { /// The block header. pub header: Header, /// The accompanying extrinsics. pub extrinsics: Vec, } -impl traits::Block for Block +impl traits::HeaderProvider for Block where Header: HeaderT, +{ + type HeaderT = Header; +} + +impl traits::Block for Block +where + Header: HeaderT + MaybeSerializeDeserialize, Extrinsic: Member + Codec + traits::Extrinsic, { type Extrinsic = Extrinsic; diff --git a/primitives/runtime/src/generic/header.rs b/primitives/runtime/src/generic/header.rs index 6fdf43ac08105..82ab9a61f96d8 100644 --- a/primitives/runtime/src/generic/header.rs +++ b/primitives/runtime/src/generic/header.rs @@ -26,6 +26,7 @@ use crate::{ MaybeSerializeDeserialize, Member, }, }; +use codec::{FullCodec, MaxEncodedLen}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use sp_core::U256; @@ -33,6 +34,7 @@ use sp_std::fmt::Debug; /// Abstraction over a block header for a substrate chain. #[derive(Encode, Decode, PartialEq, Eq, Clone, sp_core::RuntimeDebug, TypeInfo)] +#[scale_info(skip_type_params(Hash))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] #[cfg_attr(feature = "serde", serde(deny_unknown_fields))] @@ -81,13 +83,16 @@ where + MaybeSerializeDeserialize + MaybeFromStr + Debug + + Default + sp_std::hash::Hash + MaybeDisplay + AtLeast32BitUnsigned - + Codec + + FullCodec + Copy + + MaxEncodedLen + Into - + TryFrom, + + TryFrom + + TypeInfo, Hash: HashT, { type Number = Number; diff --git a/primitives/runtime/src/testing.rs b/primitives/runtime/src/testing.rs index abf4d81634691..5f94c834a8f29 100644 --- a/primitives/runtime/src/testing.rs +++ b/primitives/runtime/src/testing.rs @@ -235,7 +235,7 @@ impl Deref for ExtrinsicWrapper { } /// Testing block -#[derive(PartialEq, Eq, Clone, Serialize, Debug, Encode, Decode)] +#[derive(PartialEq, Eq, Clone, Serialize, Debug, Encode, Decode, TypeInfo)] pub struct Block { /// Block header pub header: Header, @@ -243,6 +243,10 @@ pub struct Block { pub extrinsics: Vec, } +impl traits::HeaderProvider for Block { + type HeaderT = Header; +} + impl< Xt: 'static + Codec + Sized + Send + Sync + Serialize + Clone + Eq + Debug + traits::Extrinsic, > traits::Block for Block diff --git a/primitives/runtime/src/traits.rs b/primitives/runtime/src/traits.rs index 3aa27234fbce2..51d91958ab533 100644 --- a/primitives/runtime/src/traits.rs +++ b/primitives/runtime/src/traits.rs @@ -26,7 +26,7 @@ use crate::{ }, DispatchResult, }; -use codec::{Codec, Decode, Encode, EncodeLike, MaxEncodedLen}; +use codec::{Codec, Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen}; use impl_trait_for_tuples::impl_for_tuples; #[cfg(feature = "serde")] use serde::{de::DeserializeOwned, Deserialize, Serialize}; @@ -1154,7 +1154,9 @@ pub trait IsMember { /// `parent_hash`, as well as a `digest` and a block `number`. /// /// You can also create a `new` one from those fields. -pub trait Header: Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug + 'static { +pub trait Header: + Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug + TypeInfo + 'static +{ /// Header number. type Number: Member + MaybeSerializeDeserialize @@ -1164,7 +1166,10 @@ pub trait Header: Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug + 's + Copy + MaybeDisplay + AtLeast32BitUnsigned - + Codec; + + Default + + TypeInfo + + MaxEncodedLen + + FullCodec; /// Header hash type type Hash: HashOutput; /// Hashing algorithm @@ -1210,15 +1215,50 @@ pub trait Header: Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug + 's } } +// Something that provides the Header Type. Only for internal usage and should only be used +// via `HeaderFor` or `BlockNumberFor`. +// +// This is needed to fix the "cyclical" issue in loading Header/BlockNumber as part of a +// `pallet::call`. Essentially, `construct_runtime` aggregates all calls to create a `RuntimeCall` +// that is then used to define `UncheckedExtrinsic`. +// ```ignore +// pub type UncheckedExtrinsic = +// generic::UncheckedExtrinsic; +// ``` +// This `UncheckedExtrinsic` is supplied to the `Block`. +// ```ignore +// pub type Block = generic::Block; +// ``` +// So, if we do not create a trait outside of `Block` that doesn't have `Extrinsic`, we go into a +// recursive loop leading to a build error. +// +// Note that this is a workaround for a compiler bug and should be removed when the compiler +// bug is fixed. +#[doc(hidden)] +pub trait HeaderProvider { + /// Header type. + type HeaderT: Header; +} + /// Something which fulfills the abstract idea of a Substrate block. It has types for /// `Extrinsic` pieces of information as well as a `Header`. /// /// You can get an iterator over each of the `extrinsics` and retrieve the `header`. -pub trait Block: Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug + 'static { +pub trait Block: + HeaderProvider::Header> + + Clone + + Send + + Sync + + Codec + + Eq + + MaybeSerialize + + Debug + + 'static +{ /// Type for extrinsics. type Extrinsic: Member + Codec + Extrinsic + MaybeSerialize; /// Header type. - type Header: Header; + type Header: Header + MaybeSerializeDeserialize; /// Block hash type. type Hash: HashOutput; diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index 8beed61d3d3d9..6ba4e9939e408 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -293,10 +293,7 @@ impl sp_runtime::traits::SignedExtension for CheckSubstrateCall { } construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = Extrinsic + pub enum Runtime { System: frame_system, Babe: pallet_babe, @@ -349,12 +346,11 @@ impl frame_system::pallet::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = Index; - type BlockNumber = BlockNumber; type Hash = H256; type Hashing = Hashing; type AccountId = AccountId; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<2400>; type DbWeight = (); diff --git a/utils/frame/rpc/support/src/lib.rs b/utils/frame/rpc/support/src/lib.rs index 424d16bd14c68..29d49b44b74a3 100644 --- a/utils/frame/rpc/support/src/lib.rs +++ b/utils/frame/rpc/support/src/lib.rs @@ -40,10 +40,7 @@ use sp_storage::{StorageData, StorageKey}; /// # use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::Header}; /// # /// # construct_runtime!( -/// # pub enum TestRuntime where -/// # Block = frame_system::mocking::MockBlock, -/// # NodeBlock = frame_system::mocking::MockBlock, -/// # UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic, +/// # pub enum TestRuntime /// # { /// # System: frame_system::{Pallet, Call, Config, Storage, Event}, /// # Test: pallet_test::{Pallet, Storage}, @@ -59,12 +56,11 @@ use sp_storage::{StorageData, StorageKey}; /// # type RuntimeOrigin = RuntimeOrigin; /// # type RuntimeCall = RuntimeCall; /// # type Index = u64; -/// # type BlockNumber = u64; /// # type Hash = Hash; /// # type Hashing = BlakeTwo256; /// # type AccountId = u64; /// # type Lookup = IdentityLookup; -/// # type Header = Header; +/// # type Block = frame_system::mocking::MockBlock; /// # type RuntimeEvent = RuntimeEvent; /// # type BlockHashCount = (); /// # type DbWeight = (); From 5591c9b8cb346e356d2e9a63064af2f61bd54bd1 Mon Sep 17 00:00:00 2001 From: Jegor Sidorenko <5252494+jsidorenko@users.noreply.github.com> Date: Thu, 13 Jul 2023 15:44:05 +0200 Subject: [PATCH 24/39] Refactor the asset-conversion-tx-payment pallet (#14558) * Code refactoring * Fix imports * Typo * Update frame/asset-conversion/src/types.rs Co-authored-by: joe petrowski <25483142+joepetrowski@users.noreply.github.com> * Sync docs --------- Co-authored-by: parity-processbot <> Co-authored-by: joe petrowski <25483142+joepetrowski@users.noreply.github.com> --- frame/asset-conversion/src/lib.rs | 234 ++++++++++-------- frame/asset-conversion/src/types.rs | 47 +++- .../src/traits/tokens/fungibles/mod.rs | 2 +- .../src/traits/tokens/fungibles/regular.rs | 37 --- .../asset-conversion-tx-payment/Cargo.toml | 3 +- .../asset-conversion-tx-payment/src/lib.rs | 12 +- .../src/payment.rs | 45 ++-- 7 files changed, 215 insertions(+), 165 deletions(-) diff --git a/frame/asset-conversion/src/lib.rs b/frame/asset-conversion/src/lib.rs index 5887295f973c3..73f193c7ff55d 100644 --- a/frame/asset-conversion/src/lib.rs +++ b/frame/asset-conversion/src/lib.rs @@ -81,11 +81,10 @@ use sp_arithmetic::traits::Unsigned; use sp_runtime::{ traits::{ CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, Ensure, MaybeDisplay, TrailingZeroInput, - Zero, }, DispatchError, }; -use sp_std::vec; +use sp_std::prelude::*; pub use types::*; pub use weights::WeightInfo; @@ -111,7 +110,6 @@ pub mod pallet { traits::{IntegerSquareRoot, One, Zero}, Saturating, }; - use sp_std::prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -148,7 +146,7 @@ pub mod pallet { type AssetId: AssetId + PartialOrd; /// Type that identifies either the native currency or a token class from `Assets`. - type MultiAssetId: AssetId + Ord; + type MultiAssetId: AssetId + Ord + From; /// Type to convert an `AssetId` into `MultiAssetId`. type MultiAssetIdConverter: MultiAssetIdConverter; @@ -644,18 +642,14 @@ pub mod pallet { keep_alive: bool, ) -> DispatchResult { let sender = ensure_signed(origin)?; - - ensure!( - amount_in > Zero::zero() && amount_out_min > Zero::zero(), - Error::::ZeroAmount - ); - Self::validate_swap_path(&path)?; - - let amounts = Self::get_amounts_out(&amount_in, &path)?; - let amount_out = *amounts.last().expect("Has always more than 1 element"); - ensure!(amount_out >= amount_out_min, Error::::ProvidedMinimumNotSufficientForSwap); - - Self::do_swap(sender, &amounts, path, send_to, keep_alive)?; + Self::do_swap_exact_tokens_for_tokens( + sender, + path, + amount_in, + Some(amount_out_min), + send_to, + keep_alive, + )?; Ok(()) } @@ -676,23 +670,95 @@ pub mod pallet { keep_alive: bool, ) -> DispatchResult { let sender = ensure_signed(origin)?; + Self::do_swap_tokens_for_exact_tokens( + sender, + path, + amount_out, + Some(amount_in_max), + send_to, + keep_alive, + )?; + Ok(()) + } + } + + impl Pallet { + /// Swap exactly `amount_in` of asset `path[0]` for asset `path[1]`. + /// If an `amount_out_min` is specified, it will return an error if it is unable to acquire + /// the amount desired. + /// + /// Withdraws the `path[0]` asset from `sender`, deposits the `path[1]` asset to `send_to`, + /// respecting `keep_alive`. + /// + /// If successful, returns the amount of `path[1]` acquired for the `amount_in`. + pub fn do_swap_exact_tokens_for_tokens( + sender: T::AccountId, + path: BoundedVec, + amount_in: T::AssetBalance, + amount_out_min: Option, + send_to: T::AccountId, + keep_alive: bool, + ) -> Result { + ensure!(amount_in > Zero::zero(), Error::::ZeroAmount); + if let Some(amount_out_min) = amount_out_min { + ensure!(amount_out_min > Zero::zero(), Error::::ZeroAmount); + } + + Self::validate_swap_path(&path)?; + + let amounts = Self::get_amounts_out(&amount_in, &path)?; + let amount_out = + *amounts.last().defensive_ok_or("get_amounts_out() returned an empty result")?; + + if let Some(amount_out_min) = amount_out_min { + ensure!( + amount_out >= amount_out_min, + Error::::ProvidedMinimumNotSufficientForSwap + ); + } + + Self::do_swap(sender, &amounts, path, send_to, keep_alive)?; + Ok(amount_out) + } + + /// Take the `path[0]` asset and swap some amount for `amount_out` of the `path[1]`. If an + /// `amount_in_max` is specified, it will return an error if acquiring `amount_out` would be + /// too costly. + /// + /// Withdraws `path[0]` asset from `sender`, deposits the `path[1]` asset to `send_to`, + /// respecting `keep_alive`. + /// + /// If successful returns the amount of the `path[0]` taken to provide `path[1]`. + pub fn do_swap_tokens_for_exact_tokens( + sender: T::AccountId, + path: BoundedVec, + amount_out: T::AssetBalance, + amount_in_max: Option, + send_to: T::AccountId, + keep_alive: bool, + ) -> Result { + ensure!(amount_out > Zero::zero(), Error::::ZeroAmount); + if let Some(amount_in_max) = amount_in_max { + ensure!(amount_in_max > Zero::zero(), Error::::ZeroAmount); + } - ensure!( - amount_out > Zero::zero() && amount_in_max > Zero::zero(), - Error::::ZeroAmount - ); Self::validate_swap_path(&path)?; let amounts = Self::get_amounts_in(&amount_out, &path)?; - let amount_in = *amounts.first().expect("Always has more than one element"); - ensure!(amount_in <= amount_in_max, Error::::ProvidedMaximumNotSufficientForSwap); + let amount_in = + *amounts.first().defensive_ok_or("get_amounts_in() returned an empty result")?; + + if let Some(amount_in_max) = amount_in_max { + ensure!( + amount_in <= amount_in_max, + Error::::ProvidedMaximumNotSufficientForSwap + ); + } Self::do_swap(sender, &amounts, path, send_to, keep_alive)?; - Ok(()) + Ok(amount_in) } - } - impl Pallet { /// Transfer an `amount` of `asset_id`, respecting the `keep_alive` requirements. fn transfer( asset_id: &T::MultiAssetId, @@ -749,6 +815,13 @@ pub mod pallet { .map_err(|_| Error::::Overflow) } + /// Convert a `HigherPrecisionBalance` type to an `AssetBalance`. + pub(crate) fn convert_hpb_to_asset_balance( + amount: T::HigherPrecisionBalance, + ) -> Result> { + amount.try_into().map_err(|_| Error::::Overflow) + } + /// Swap assets along a `path`, depositing in `send_to`. pub(crate) fn do_swap( sender: T::AccountId, @@ -1123,92 +1196,47 @@ pub mod pallet { } } -impl - frame_support::traits::tokens::fungibles::SwapNative< - T::RuntimeOrigin, - T::AccountId, - T::Balance, - T::AssetBalance, - T::AssetId, - > for Pallet -where - ::Currency: - frame_support::traits::tokens::fungible::Inspect<::AccountId>, -{ - /// Take an `asset_id` and swap some amount for `amount_out` of the chain's native asset. If an - /// `amount_in_max` is specified, it will return an error if acquiring `amount_out` would be - /// too costly. - /// - /// If successful returns the amount of the `asset_id` taken to provide `amount_out`. - fn swap_tokens_for_exact_native( +impl Swap for Pallet { + fn swap_exact_tokens_for_tokens( sender: T::AccountId, - asset_id: T::AssetId, - amount_out: T::Balance, - amount_in_max: Option, + path: Vec, + amount_in: T::HigherPrecisionBalance, + amount_out_min: Option, send_to: T::AccountId, keep_alive: bool, - ) -> Result { - ensure!(amount_out > Zero::zero(), Error::::ZeroAmount); - if let Some(amount_in_max) = amount_in_max { - ensure!(amount_in_max > Zero::zero(), Error::::ZeroAmount); - } - let mut path = sp_std::vec::Vec::new(); - path.push(T::MultiAssetIdConverter::into_multiasset_id(&asset_id)); - path.push(T::MultiAssetIdConverter::get_native()); - let path = path.try_into().unwrap(); - - // convert `amount_out` from native balance type, to asset balance type - let amount_out = Self::convert_native_balance_to_asset_balance(amount_out)?; - - // calculate the amount we need to provide - let amounts = Self::get_amounts_in(&amount_out, &path)?; - let amount_in = - *amounts.first().defensive_ok_or("get_amounts_in() returned an empty result")?; - if let Some(amount_in_max) = amount_in_max { - ensure!(amount_in <= amount_in_max, Error::::ProvidedMaximumNotSufficientForSwap); - } - - Self::do_swap(sender, &amounts, path, send_to, keep_alive)?; - Ok(amount_in) + ) -> Result { + let path = path.try_into().map_err(|_| Error::::PathError)?; + let amount_out_min = amount_out_min.map(Self::convert_hpb_to_asset_balance).transpose()?; + let amount_out = Self::do_swap_exact_tokens_for_tokens( + sender, + path, + Self::convert_hpb_to_asset_balance(amount_in)?, + amount_out_min, + send_to, + keep_alive, + )?; + Ok(amount_out.into()) } - /// Take an `asset_id` and swap `amount_in` of the chain's native asset for it. If an - /// `amount_out_min` is specified, it will return an error if it is unable to acquire the amount - /// desired. - /// - /// If successful, returns the amount of `asset_id` acquired for the `amount_in`. - fn swap_exact_native_for_tokens( + fn swap_tokens_for_exact_tokens( sender: T::AccountId, - asset_id: T::AssetId, - amount_in: T::Balance, - amount_out_min: Option, + path: Vec, + amount_out: T::HigherPrecisionBalance, + amount_in_max: Option, send_to: T::AccountId, keep_alive: bool, - ) -> Result { - ensure!(amount_in > Zero::zero(), Error::::ZeroAmount); - if let Some(amount_out_min) = amount_out_min { - ensure!(amount_out_min > Zero::zero(), Error::::ZeroAmount); - } - let mut path = sp_std::vec::Vec::new(); - path.push(T::MultiAssetIdConverter::get_native()); - path.push(T::MultiAssetIdConverter::into_multiasset_id(&asset_id)); - let path = path.try_into().expect( - "`MaxSwapPathLength` is ensured by to be greater than 2; pushed only twice; qed", - ); - - // convert `amount_in` from native balance type, to asset balance type - let amount_in = Self::convert_native_balance_to_asset_balance(amount_in)?; - - // calculate the amount we should receive - let amounts = Self::get_amounts_out(&amount_in, &path)?; - let amount_out = - *amounts.last().defensive_ok_or("get_amounts_out() returned an empty result")?; - if let Some(amount_out_min) = amount_out_min { - ensure!(amount_out >= amount_out_min, Error::::ProvidedMaximumNotSufficientForSwap); - } - - Self::do_swap(sender, &amounts, path, send_to, keep_alive)?; - Ok(amount_out) + ) -> Result { + let path = path.try_into().map_err(|_| Error::::PathError)?; + let amount_in_max = amount_in_max.map(Self::convert_hpb_to_asset_balance).transpose()?; + let amount_in = Self::do_swap_tokens_for_exact_tokens( + sender, + path, + Self::convert_hpb_to_asset_balance(amount_out)?, + amount_in_max, + send_to, + keep_alive, + )?; + Ok(amount_in.into()) } } diff --git a/frame/asset-conversion/src/types.rs b/frame/asset-conversion/src/types.rs index cbe201f01c10b..0612e363f0560 100644 --- a/frame/asset-conversion/src/types.rs +++ b/frame/asset-conversion/src/types.rs @@ -33,7 +33,7 @@ pub struct PoolInfo { /// A trait that converts between a MultiAssetId and either the native currency or an AssetId. pub trait MultiAssetIdConverter { - /// Returns the MultiAssetId reperesenting the native currency of the chain. + /// Returns the MultiAssetId representing the native currency of the chain. fn get_native() -> MultiAssetId; /// Returns true if the given MultiAssetId is the native currency. @@ -42,7 +42,7 @@ pub trait MultiAssetIdConverter { /// If it's not native, returns the AssetId for the given MultiAssetId. fn try_convert(asset: &MultiAssetId) -> Result; - /// Wrapps an AssetId as a MultiAssetId. + /// Wraps an AssetId as a MultiAssetId. fn into_multiasset_id(asset: &AssetId) -> MultiAssetId; } @@ -76,6 +76,12 @@ where Asset(AssetId), } +impl From for NativeOrAssetId { + fn from(asset: AssetId) -> Self { + Self::Asset(asset) + } +} + impl Ord for NativeOrAssetId { fn cmp(&self, other: &Self) -> Ordering { match (self, other) { @@ -126,3 +132,40 @@ impl MultiAssetIdConverter, Asset NativeOrAssetId::Asset((*asset).clone()) } } + +/// Trait for providing methods to swap between the various asset classes. +pub trait Swap { + /// Swap exactly `amount_in` of asset `path[0]` for asset `path[1]`. + /// If an `amount_out_min` is specified, it will return an error if it is unable to acquire + /// the amount desired. + /// + /// Withdraws the `path[0]` asset from `sender`, deposits the `path[1]` asset to `send_to`, + /// respecting `keep_alive`. + /// + /// If successful, returns the amount of `path[1]` acquired for the `amount_in`. + fn swap_exact_tokens_for_tokens( + sender: AccountId, + path: Vec, + amount_in: Balance, + amount_out_min: Option, + send_to: AccountId, + keep_alive: bool, + ) -> Result; + + /// Take the `path[0]` asset and swap some amount for `amount_out` of the `path[1]`. If an + /// `amount_in_max` is specified, it will return an error if acquiring `amount_out` would be + /// too costly. + /// + /// Withdraws `path[0]` asset from `sender`, deposits `path[1]` asset to `send_to`, + /// respecting `keep_alive`. + /// + /// If successful returns the amount of the `path[0]` taken to provide `path[1]`. + fn swap_tokens_for_exact_tokens( + sender: AccountId, + path: Vec, + amount_out: Balance, + amount_in_max: Option, + send_to: AccountId, + keep_alive: bool, + ) -> Result; +} diff --git a/frame/support/src/traits/tokens/fungibles/mod.rs b/frame/support/src/traits/tokens/fungibles/mod.rs index 8070d916fb330..697eff39ff748 100644 --- a/frame/support/src/traits/tokens/fungibles/mod.rs +++ b/frame/support/src/traits/tokens/fungibles/mod.rs @@ -36,5 +36,5 @@ pub use hold::{ pub use imbalance::{Credit, Debt, HandleImbalanceDrop, Imbalance}; pub use lifetime::{Create, Destroy}; pub use regular::{ - Balanced, DecreaseIssuance, Dust, IncreaseIssuance, Inspect, Mutate, SwapNative, Unbalanced, + Balanced, DecreaseIssuance, Dust, IncreaseIssuance, Inspect, Mutate, Unbalanced, }; diff --git a/frame/support/src/traits/tokens/fungibles/regular.rs b/frame/support/src/traits/tokens/fungibles/regular.rs index 3df0a6b6d3def..5570659e8115a 100644 --- a/frame/support/src/traits/tokens/fungibles/regular.rs +++ b/frame/support/src/traits/tokens/fungibles/regular.rs @@ -583,40 +583,3 @@ pub trait Balanced: Inspect + Unbalanced { fn done_deposit(_asset: Self::AssetId, _who: &AccountId, _amount: Self::Balance) {} fn done_withdraw(_asset: Self::AssetId, _who: &AccountId, _amount: Self::Balance) {} } - -/// Trait for providing methods to swap between the chain's native token and other asset classes. -pub trait SwapNative { - /// Take an `asset_id` and swap some amount for `amount_out` of the chain's native asset. If an - /// `amount_in_max` is specified, it will return an error if acquiring `amount_out` would be - /// too costly. - /// - /// Withdraws `asset_id` from `sender`, deposits native asset to `send_to`, respecting - /// `keep_alive`. - /// - /// If successful returns the amount of the `asset_id` taken to provide `amount_out`. - fn swap_tokens_for_exact_native( - sender: AccountId, - asset_id: AssetId, - amount_out: Balance, - amount_in_max: Option, - send_to: AccountId, - keep_alive: bool, - ) -> Result; - - /// Take an `asset_id` and swap `amount_in` of the chain's native asset for it. If an - /// `amount_out_min` is specified, it will return an error if it is unable to acquire the amount - /// desired. - /// - /// Withdraws native asset from `sender`, deposits `asset_id` to `send_to`, respecting - /// `keep_alive`. - /// - /// If successful, returns the amount of `asset_id` acquired for the `amount_in`. - fn swap_exact_native_for_tokens( - sender: AccountId, - asset_id: AssetId, - amount_in: Balance, - amount_out_min: Option, - send_to: AccountId, - keep_alive: bool, - ) -> Result; -} diff --git a/frame/transaction-payment/asset-conversion-tx-payment/Cargo.toml b/frame/transaction-payment/asset-conversion-tx-payment/Cargo.toml index 8f9e1af04a76a..1555f4d91365d 100644 --- a/frame/transaction-payment/asset-conversion-tx-payment/Cargo.toml +++ b/frame/transaction-payment/asset-conversion-tx-payment/Cargo.toml @@ -18,6 +18,7 @@ sp-runtime = { version = "24.0.0", default-features = false, path = "../../../pr sp-std = { version = "8.0.0", default-features = false, path = "../../../primitives/std" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../../system" } +pallet-asset-conversion = { version = "4.0.0-dev", default-features = false, path = "../../asset-conversion" } pallet-transaction-payment = { version = "4.0.0-dev", default-features = false, path = ".." } codec = { package = "parity-scale-codec", version = "3.2.2", default-features = false, features = ["derive"] } scale-info = { version = "2.5.0", default-features = false, features = ["derive"] } @@ -28,7 +29,6 @@ sp-io = { version = "23.0.0", default-features = false, path = "../../../primiti sp-storage = { version = "13.0.0", default-features = false, path = "../../../primitives/storage" } pallet-assets = { version = "4.0.0-dev", path = "../../assets" } pallet-balances = { version = "4.0.0-dev", path = "../../balances" } -pallet-asset-conversion = { version = "4.0.0-dev", path = "../../asset-conversion" } [features] default = ["std"] @@ -41,6 +41,7 @@ std = [ "frame-system/std", "sp-io/std", "sp-core/std", + "pallet-asset-conversion/std", "pallet-transaction-payment/std", ] try-runtime = ["frame-support/try-runtime"] diff --git a/frame/transaction-payment/asset-conversion-tx-payment/src/lib.rs b/frame/transaction-payment/asset-conversion-tx-payment/src/lib.rs index 7f6da90dfe95f..efc7386ae8c00 100644 --- a/frame/transaction-payment/asset-conversion-tx-payment/src/lib.rs +++ b/frame/transaction-payment/asset-conversion-tx-payment/src/lib.rs @@ -69,6 +69,8 @@ mod mock; mod tests; mod payment; +use frame_support::traits::tokens::AssetId; +use pallet_asset_conversion::MultiAssetIdConverter; pub use payment::*; /// Type aliases used for interaction with `OnChargeTransaction`. @@ -116,7 +118,9 @@ pub mod pallet { use super::*; #[pallet::config] - pub trait Config: frame_system::Config + pallet_transaction_payment::Config { + pub trait Config: + frame_system::Config + pallet_transaction_payment::Config + pallet_asset_conversion::Config + { /// The overarching event type. type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// The fungibles instance used to pay for transactions in assets. @@ -187,12 +191,12 @@ where debug_assert!(self.tip <= fee, "tip should be included in the computed fee"); if fee.is_zero() { Ok((fee, InitialPayment::Nothing)) - } else if let Some(asset_id) = self.asset_id { + } else if let Some(asset_id) = &self.asset_id { T::OnChargeAssetTransaction::withdraw_fee( who, call, info, - asset_id, + asset_id.clone(), fee.into(), self.tip.into(), ) @@ -324,7 +328,7 @@ where tip.into(), used_for_fee.into(), received_exchanged.into(), - asset_id, + asset_id.clone(), asset_consumed.into(), )?; diff --git a/frame/transaction-payment/asset-conversion-tx-payment/src/payment.rs b/frame/transaction-payment/asset-conversion-tx-payment/src/payment.rs index 86b2c09e541ac..0d090211d0352 100644 --- a/frame/transaction-payment/asset-conversion-tx-payment/src/payment.rs +++ b/frame/transaction-payment/asset-conversion-tx-payment/src/payment.rs @@ -17,26 +17,25 @@ use super::*; use crate::Config; -use codec::FullCodec; use frame_support::{ ensure, - traits::{fungible::Inspect, fungibles::SwapNative, tokens::Balance}, + traits::{fungible::Inspect, tokens::Balance}, unsigned::TransactionValidityError, }; -use scale_info::TypeInfo; +use pallet_asset_conversion::Swap; use sp_runtime::{ - traits::{DispatchInfoOf, MaybeSerializeDeserialize, PostDispatchInfoOf, Zero}, + traits::{DispatchInfoOf, PostDispatchInfoOf, Zero}, transaction_validity::InvalidTransaction, Saturating, }; -use sp_std::{fmt::Debug, marker::PhantomData}; +use sp_std::marker::PhantomData; /// Handle withdrawing, refunding and depositing of transaction fees. pub trait OnChargeAssetTransaction { /// The underlying integer type in which fees are calculated. type Balance: Balance; /// The type used to identify the assets used for transaction payment. - type AssetId: FullCodec + Copy + MaybeSerializeDeserialize + Debug + Default + Eq + TypeInfo; + type AssetId: AssetId; /// The type used to store the intermediate values between pre- and post-dispatch. type LiquidityInfo; @@ -74,8 +73,7 @@ pub trait OnChargeAssetTransaction { ) -> Result, TransactionValidityError>; } -/// Implements the asset transaction for a balance to asset converter (implementing -/// [`SwapNative`]). +/// Implements the asset transaction for a balance to asset converter (implementing [`Swap`]). /// /// The converter is given the complete fee in terms of the asset used for the transaction. pub struct AssetConversionAdapter(PhantomData<(C, CON)>); @@ -85,8 +83,9 @@ impl OnChargeAssetTransaction for AssetConversionAdapter where T: Config, C: Inspect<::AccountId>, - CON: SwapNative, AssetBalanceOf, AssetIdOf>, - AssetIdOf: FullCodec + Copy + MaybeSerializeDeserialize + Debug + Default + Eq + TypeInfo, + CON: Swap, + T::HigherPrecisionBalance: From> + TryInto>, + T::MultiAssetId: From>, BalanceOf: IsType<::AccountId>>::Balance>, { type Balance = BalanceOf; @@ -115,16 +114,20 @@ where let native_asset_required = if C::balance(&who) >= ed.saturating_add(fee.into()) { fee } else { fee + ed.into() }; - let asset_consumed = CON::swap_tokens_for_exact_native( + let asset_consumed = CON::swap_tokens_for_exact_tokens( who.clone(), - asset_id, - native_asset_required, + vec![asset_id.into(), T::MultiAssetIdConverter::get_native()], + T::HigherPrecisionBalance::from(native_asset_required), None, who.clone(), true, ) .map_err(|_| TransactionValidityError::from(InvalidTransaction::Payment))?; + let asset_consumed = asset_consumed + .try_into() + .map_err(|_| TransactionValidityError::from(InvalidTransaction::Payment))?; + ensure!(asset_consumed > Zero::zero(), InvalidTransaction::Payment); // charge the fee in native currency @@ -166,17 +169,25 @@ where // If this fails, the account might have dropped below the existential balance or there // is not enough liquidity left in the pool. In that case we don't throw an error and // the account will keep the native currency. - match CON::swap_exact_native_for_tokens( + match CON::swap_exact_tokens_for_tokens( who.clone(), // we already deposited the native to `who` - asset_id, // we want asset_id back - swap_back, // amount of the native asset to convert to `asset_id` + vec![ + T::MultiAssetIdConverter::get_native(), // we provide the native + asset_id.into(), // we want asset_id back + ], + T::HigherPrecisionBalance::from(swap_back), /* amount of the native asset to + * convert to `asset_id` */ None, // no minimum amount back who.clone(), // we will refund to `who` false, // no need to keep alive ) .ok() { - Some(acquired) => asset_refund = acquired, + Some(acquired) => { + asset_refund = acquired + .try_into() + .map_err(|_| TransactionValidityError::from(InvalidTransaction::Payment))?; + }, None => { Pallet::::deposit_event(Event::::AssetRefundFailed { native_amount_kept: swap_back, From f2a5ca03d7cb65f6dd34bf31d61a6f8caa8e6d35 Mon Sep 17 00:00:00 2001 From: Oliver Tale-Yazdi Date: Thu, 13 Jul 2023 19:41:56 +0200 Subject: [PATCH 25/39] Re-add deprecated `--execution` arg on `benchmark pallet` (#14567) * Add DeferGuard::new Signed-off-by: Oliver Tale-Yazdi * Re-add deprecated 'execution' arg to benchmark pallet cmd. Signed-off-by: Oliver Tale-Yazdi * Extend tests Signed-off-by: Oliver Tale-Yazdi * Remove from tests Signed-off-by: Oliver Tale-Yazdi --------- Signed-off-by: Oliver Tale-Yazdi --- bin/node/cli/tests/benchmark_block_works.rs | 2 +- bin/node/cli/tests/benchmark_extrinsic_works.rs | 1 + bin/node/cli/tests/benchmark_overhead_works.rs | 1 + bin/node/cli/tests/benchmark_pallet_works.rs | 16 ++++++++++------ primitives/core/src/defer.rs | 7 +++++++ .../frame/benchmarking-cli/src/pallet/command.rs | 10 ++++++++++ utils/frame/benchmarking-cli/src/pallet/mod.rs | 4 ++++ 7 files changed, 34 insertions(+), 7 deletions(-) diff --git a/bin/node/cli/tests/benchmark_block_works.rs b/bin/node/cli/tests/benchmark_block_works.rs index 09c2f262e2c29..19a074081c550 100644 --- a/bin/node/cli/tests/benchmark_block_works.rs +++ b/bin/node/cli/tests/benchmark_block_works.rs @@ -39,7 +39,7 @@ async fn benchmark_block_works() { .arg(base_dir.path()) .args(["--from", "1", "--to", "1"]) .args(["--repeat", "1"]) - .args(["--wasm-execution", "compiled"]) + .args(["--wasm-execution=compiled"]) .status() .unwrap(); diff --git a/bin/node/cli/tests/benchmark_extrinsic_works.rs b/bin/node/cli/tests/benchmark_extrinsic_works.rs index 9cdb971def522..8e6363b7d0665 100644 --- a/bin/node/cli/tests/benchmark_extrinsic_works.rs +++ b/bin/node/cli/tests/benchmark_extrinsic_works.rs @@ -39,6 +39,7 @@ fn benchmark_extrinsic(pallet: &str, extrinsic: &str) { .args(&["--pallet", pallet, "--extrinsic", extrinsic]) // Run with low repeats for faster execution. .args(["--warmup=10", "--repeat=10", "--max-ext-per-block=10"]) + .args(["--wasm-execution=compiled"]) .status() .unwrap(); diff --git a/bin/node/cli/tests/benchmark_overhead_works.rs b/bin/node/cli/tests/benchmark_overhead_works.rs index 92ab93b7f6f26..3273e6f868112 100644 --- a/bin/node/cli/tests/benchmark_overhead_works.rs +++ b/bin/node/cli/tests/benchmark_overhead_works.rs @@ -36,6 +36,7 @@ fn benchmark_overhead_works() { .args(["--warmup", "10", "--repeat", "10"]) .args(["--add", "100", "--mul", "1.2", "--metric", "p75"]) .args(["--max-ext-per-block", "10"]) + .args(["--wasm-execution=compiled"]) .status() .unwrap(); assert!(status.success()); diff --git a/bin/node/cli/tests/benchmark_pallet_works.rs b/bin/node/cli/tests/benchmark_pallet_works.rs index 2d9946543eed2..9c3e7e2995391 100644 --- a/bin/node/cli/tests/benchmark_pallet_works.rs +++ b/bin/node/cli/tests/benchmark_pallet_works.rs @@ -34,16 +34,20 @@ fn benchmark_pallet_works() { } fn benchmark_pallet(steps: u32, repeat: u32, should_work: bool) { - let output = Command::new(cargo_bin("substrate")) + let status = Command::new(cargo_bin("substrate")) .args(["benchmark", "pallet", "--dev"]) // Use the `addition` benchmark since is the fastest. .args(["--pallet", "frame-benchmarking", "--extrinsic", "addition"]) .args(["--steps", &format!("{}", steps), "--repeat", &format!("{}", repeat)]) - .output() + .args([ + "--wasm-execution=compiled", + "--no-storage-info", + "--no-median-slopes", + "--no-min-squares", + "--heap-pages=4096", + ]) + .status() .unwrap(); - if output.status.success() != should_work { - let log = String::from_utf8_lossy(&output.stderr).to_string(); - panic!("Test failed:\n{}", log); - } + assert_eq!(status.success(), should_work); } diff --git a/primitives/core/src/defer.rs b/primitives/core/src/defer.rs index c5ff502593692..efa9ee5cebb70 100644 --- a/primitives/core/src/defer.rs +++ b/primitives/core/src/defer.rs @@ -25,6 +25,13 @@ #[must_use] pub struct DeferGuard(pub Option); +impl DeferGuard { + /// Creates a new `DeferGuard` with the given closure. + pub fn new(f: F) -> Self { + Self(Some(f)) + } +} + impl Drop for DeferGuard { fn drop(&mut self) { self.0.take().map(|f| f()); diff --git a/utils/frame/benchmarking-cli/src/pallet/command.rs b/utils/frame/benchmarking-cli/src/pallet/command.rs index 1d2d81e357724..d98111d1f0999 100644 --- a/utils/frame/benchmarking-cli/src/pallet/command.rs +++ b/utils/frame/benchmarking-cli/src/pallet/command.rs @@ -147,6 +147,16 @@ impl PalletCmd { <<::Header as HeaderT>::Number as std::str::FromStr>::Err: std::fmt::Debug, ExtraHostFunctions: sp_wasm_interface::HostFunctions, { + let _d = self.execution.as_ref().map(|exec| { + // We print the warning at the end, since there is often A LOT of output. + sp_core::defer::DeferGuard::new(move || { + log::warn!( + target: LOG_TARGET, + "⚠️ Argument `--execution` is deprecated. Its value of `{exec}` has on effect.", + ) + }) + }); + if let Some(output_path) = &self.output { if !output_path.is_dir() && output_path.file_name().is_none() { return Err("Output file or path is invalid!".into()) diff --git a/utils/frame/benchmarking-cli/src/pallet/mod.rs b/utils/frame/benchmarking-cli/src/pallet/mod.rs index 5090a601f0c9a..c69ce1765fc9d 100644 --- a/utils/frame/benchmarking-cli/src/pallet/mod.rs +++ b/utils/frame/benchmarking-cli/src/pallet/mod.rs @@ -150,6 +150,10 @@ pub struct PalletCmd { )] pub wasmtime_instantiation_strategy: WasmtimeInstantiationStrategy, + /// DEPRECATED: This argument has no effect. + #[arg(long = "execution")] + pub execution: Option, + /// Limit the memory the database cache can use. #[arg(long = "db-cache", value_name = "MiB", default_value_t = 1024)] pub database_cache_size: u32, From bc22c8f9971b6c476eb3d643d9a18c7b6729a6b7 Mon Sep 17 00:00:00 2001 From: Tonimir Kisasondi Date: Thu, 13 Jul 2023 23:25:25 +0200 Subject: [PATCH 26/39] Fixes link to inflation documentation (#14573) Original link in the source code pointed to a dead URL since the original documentation has moved. This pull request updates the URL with the current version. --- frame/staking/reward-fn/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/staking/reward-fn/src/lib.rs b/frame/staking/reward-fn/src/lib.rs index 2c7f4613b466e..d34a534c0425d 100644 --- a/frame/staking/reward-fn/src/lib.rs +++ b/frame/staking/reward-fn/src/lib.rs @@ -41,7 +41,7 @@ use sp_arithmetic::{ /// The result is meant to be scaled with minimum inflation and maximum inflation. /// /// (as detailed -/// [here](https://research.web3.foundation/en/latest/polkadot/economics/1-token-economics.html#inflation-model-with-parachains)) +/// [here](https://research.web3.foundation/Polkadot/overview/token-economics#inflation-model-with-parachains)) /// /// Arguments are: /// * `stake`: The fraction of total issued tokens that actively staked behind validators. Known as From 130c9ad2573dffecc2c97ccfd64878c242ac42f0 Mon Sep 17 00:00:00 2001 From: Francisco Gamundi <52399794+fgamundi@users.noreply.github.com> Date: Fri, 14 Jul 2023 08:14:14 +0200 Subject: [PATCH 27/39] WasmExecutor flag to ignore onchain heappages value (#14508) * WasmExecutor flag to ignore onchain heappages value * fmt --- client/executor/src/executor.rs | 51 +++++++++++++++++++++++++-------- 1 file changed, 39 insertions(+), 12 deletions(-) diff --git a/client/executor/src/executor.rs b/client/executor/src/executor.rs index a3717f4d29002..7c292a83da089 100644 --- a/client/executor/src/executor.rs +++ b/client/executor/src/executor.rs @@ -88,6 +88,7 @@ pub struct WasmExecutorBuilder { method: WasmExecutionMethod, onchain_heap_alloc_strategy: Option, offchain_heap_alloc_strategy: Option, + ignore_onchain_heap_pages: bool, max_runtime_instances: usize, cache_path: Option, allow_missing_host_functions: bool, @@ -104,6 +105,7 @@ impl WasmExecutorBuilder { method: WasmExecutionMethod::default(), onchain_heap_alloc_strategy: None, offchain_heap_alloc_strategy: None, + ignore_onchain_heap_pages: false, max_runtime_instances: 2, runtime_cache_size: 4, allow_missing_host_functions: false, @@ -137,6 +139,14 @@ impl WasmExecutorBuilder { self } + /// Create the wasm executor and follow/ignore onchain heap pages value. + /// + /// By default this the onchain heap pages value is followed. + pub fn with_ignore_onchain_heap_pages(mut self, ignore_onchain_heap_pages: bool) -> Self { + self.ignore_onchain_heap_pages = ignore_onchain_heap_pages; + self + } + /// Create the wasm executor with the given maximum number of `instances`. /// /// The number of `instances` defines how many different instances of a runtime the cache is @@ -193,6 +203,7 @@ impl WasmExecutorBuilder { default_onchain_heap_alloc_strategy: unwrap_heap_pages( self.onchain_heap_alloc_strategy, ), + ignore_onchain_heap_pages: self.ignore_onchain_heap_pages, cache: Arc::new(RuntimeCache::new( self.max_runtime_instances, self.cache_path.clone(), @@ -214,6 +225,8 @@ pub struct WasmExecutor { default_onchain_heap_alloc_strategy: HeapAllocStrategy, /// The heap allocation strategy for offchain Wasm calls. default_offchain_heap_alloc_strategy: HeapAllocStrategy, + /// Ignore onchain heap pages value. + ignore_onchain_heap_pages: bool, /// WASM runtime cache. cache: Arc, /// The path to a directory which the executor can leverage for a file cache, e.g. put there @@ -230,6 +243,7 @@ impl Clone for WasmExecutor { method: self.method, default_onchain_heap_alloc_strategy: self.default_onchain_heap_alloc_strategy, default_offchain_heap_alloc_strategy: self.default_offchain_heap_alloc_strategy, + ignore_onchain_heap_pages: self.ignore_onchain_heap_pages, cache: self.cache.clone(), cache_path: self.cache_path.clone(), allow_missing_host_functions: self.allow_missing_host_functions, @@ -276,6 +290,7 @@ where default_offchain_heap_alloc_strategy: unwrap_heap_pages( default_heap_pages.map(|h| HeapAllocStrategy::Static { extra_pages: h as _ }), ), + ignore_onchain_heap_pages: false, cache: Arc::new(RuntimeCache::new( max_runtime_instances, cache_path.clone(), @@ -486,10 +501,14 @@ where "Executing function", ); - let on_chain_heap_alloc_strategy = runtime_code - .heap_pages - .map(|h| HeapAllocStrategy::Static { extra_pages: h as _ }) - .unwrap_or_else(|| self.default_onchain_heap_alloc_strategy); + let on_chain_heap_alloc_strategy = if self.ignore_onchain_heap_pages { + self.default_onchain_heap_alloc_strategy + } else { + runtime_code + .heap_pages + .map(|h| HeapAllocStrategy::Static { extra_pages: h as _ }) + .unwrap_or_else(|| self.default_onchain_heap_alloc_strategy) + }; let heap_alloc_strategy = match context { CallContext::Offchain => self.default_offchain_heap_alloc_strategy, @@ -518,10 +537,14 @@ where ext: &mut dyn Externalities, runtime_code: &RuntimeCode, ) -> Result { - let on_chain_heap_pages = runtime_code - .heap_pages - .map(|h| HeapAllocStrategy::Static { extra_pages: h as _ }) - .unwrap_or_else(|| self.default_onchain_heap_alloc_strategy); + let on_chain_heap_pages = if self.ignore_onchain_heap_pages { + self.default_onchain_heap_alloc_strategy + } else { + runtime_code + .heap_pages + .map(|h| HeapAllocStrategy::Static { extra_pages: h as _ }) + .unwrap_or_else(|| self.default_onchain_heap_alloc_strategy) + }; self.with_instance( runtime_code, @@ -631,10 +654,14 @@ impl CodeExecutor for NativeElseWasmExecut "Executing function", ); - let on_chain_heap_alloc_strategy = runtime_code - .heap_pages - .map(|h| HeapAllocStrategy::Static { extra_pages: h as _ }) - .unwrap_or_else(|| self.wasm.default_onchain_heap_alloc_strategy); + let on_chain_heap_alloc_strategy = if self.wasm.ignore_onchain_heap_pages { + self.wasm.default_onchain_heap_alloc_strategy + } else { + runtime_code + .heap_pages + .map(|h| HeapAllocStrategy::Static { extra_pages: h as _ }) + .unwrap_or_else(|| self.wasm.default_onchain_heap_alloc_strategy) + }; let heap_alloc_strategy = match context { CallContext::Offchain => self.wasm.default_offchain_heap_alloc_strategy, From c446786a498dee7b413de101efc3c339d3eddf44 Mon Sep 17 00:00:00 2001 From: Juan Date: Fri, 14 Jul 2023 08:56:48 +0200 Subject: [PATCH 28/39] Replace system config `Index` for `Nonce` (#14290) * replace Index by Nonce * replace Index by Nonce * replace Index by Nonce * replace Index by Nonce * replace Index by Nonce * wip * remove index in lieu of nonce * wip * remove accountnonce in lieu of nonce * add minor improvement * rebase and merge conflicts --- bin/node-template/node/src/rpc.rs | 4 ++-- .../pallets/template/src/mock.rs | 2 +- bin/node-template/runtime/src/lib.rs | 10 ++++----- bin/node/executor/tests/basic.rs | 18 ++++++++-------- bin/node/executor/tests/fees.rs | 10 ++++----- bin/node/primitives/src/lib.rs | 2 +- bin/node/rpc/src/lib.rs | 4 ++-- bin/node/runtime/src/lib.rs | 10 ++++----- bin/node/testing/src/keyring.rs | 4 ++-- client/transaction-pool/tests/pool.rs | 8 +++---- frame/alliance/src/mock.rs | 2 +- frame/asset-conversion/src/mock.rs | 2 +- frame/asset-rate/src/mock.rs | 2 +- frame/assets/src/mock.rs | 2 +- frame/atomic-swap/src/tests.rs | 2 +- frame/aura/src/mock.rs | 2 +- frame/authority-discovery/src/lib.rs | 2 +- frame/authorship/src/lib.rs | 2 +- frame/babe/src/mock.rs | 2 +- frame/bags-list/src/mock.rs | 2 +- frame/balances/src/tests/mod.rs | 2 +- frame/beefy-mmr/src/mock.rs | 2 +- frame/beefy/src/mock.rs | 2 +- frame/benchmarking/pov/src/benchmarking.rs | 4 ++-- frame/benchmarking/pov/src/tests.rs | 2 +- frame/benchmarking/src/baseline.rs | 4 ++-- frame/benchmarking/src/tests.rs | 2 +- frame/benchmarking/src/tests_instance.rs | 2 +- frame/bounties/src/tests.rs | 2 +- frame/child-bounties/src/tests.rs | 2 +- frame/collective/src/tests.rs | 2 +- frame/contracts/src/tests.rs | 2 +- frame/conviction-voting/src/tests.rs | 2 +- frame/core-fellowship/src/tests.rs | 2 +- frame/democracy/src/tests.rs | 2 +- .../election-provider-multi-phase/src/mock.rs | 2 +- .../test-staking-e2e/src/mock.rs | 4 ++-- .../election-provider-support/src/onchain.rs | 3 ++- frame/elections-phragmen/src/lib.rs | 2 +- frame/examples/basic/src/tests.rs | 2 +- frame/examples/default-config/src/lib.rs | 2 +- frame/examples/dev-mode/src/tests.rs | 2 +- frame/examples/offchain-worker/src/tests.rs | 2 +- frame/executive/src/lib.rs | 2 +- frame/fast-unstake/src/mock.rs | 4 ++-- frame/glutton/src/mock.rs | 2 +- frame/grandpa/src/mock.rs | 2 +- frame/identity/src/tests.rs | 2 +- frame/im-online/src/mock.rs | 2 +- frame/indices/src/mock.rs | 2 +- .../src/lib.rs | 2 +- frame/lottery/src/mock.rs | 2 +- frame/membership/src/lib.rs | 2 +- frame/merkle-mountain-range/src/mock.rs | 2 +- frame/message-queue/src/integration_test.rs | 2 +- frame/message-queue/src/mock.rs | 2 +- frame/multisig/src/tests.rs | 2 +- frame/nft-fractionalization/src/mock.rs | 2 +- frame/nfts/src/mock.rs | 2 +- frame/nicks/src/lib.rs | 2 +- frame/nis/src/mock.rs | 2 +- frame/node-authorization/src/mock.rs | 2 +- .../nomination-pools/benchmarking/src/mock.rs | 4 ++-- frame/nomination-pools/src/mock.rs | 2 +- .../nomination-pools/test-staking/src/mock.rs | 4 ++-- frame/offences/benchmarking/src/mock.rs | 4 ++-- frame/offences/src/mock.rs | 2 +- frame/preimage/src/mock.rs | 2 +- frame/proxy/src/tests.rs | 2 +- frame/ranked-collective/src/tests.rs | 2 +- frame/recovery/src/mock.rs | 2 +- frame/referenda/src/mock.rs | 2 +- frame/remark/src/mock.rs | 2 +- frame/root-offences/src/mock.rs | 2 +- frame/salary/src/tests.rs | 2 +- frame/scheduler/src/mock.rs | 2 +- frame/scored-pool/src/mock.rs | 2 +- frame/session/benchmarking/src/mock.rs | 4 ++-- frame/session/src/mock.rs | 2 +- frame/society/src/mock.rs | 2 +- frame/staking/src/mock.rs | 4 ++-- frame/state-trie-migration/src/lib.rs | 2 +- frame/statement/src/mock.rs | 2 +- frame/sudo/src/mock.rs | 2 +- frame/support/procedural/src/lib.rs | 4 ++-- frame/support/test/compile_pass/src/lib.rs | 3 +-- .../number_of_pallets_exceeds_tuple_size.rs | 2 +- .../pallet_error_too_large.rs | 12 +++++------ .../undefined_call_part.rs | 4 ++-- .../undefined_event_part.rs | 4 ++-- .../undefined_genesis_config_part.rs | 4 ++-- .../undefined_inherent_part.rs | 4 ++-- .../undefined_origin_part.rs | 4 ++-- .../undefined_validate_unsigned_part.rs | 2 +- frame/support/test/tests/pallet.rs | 2 +- frame/support/test/tests/pallet_instance.rs | 2 +- .../pallet_ui/pallet_doc_arg_non_path.rs | 2 +- .../test/tests/pallet_ui/pallet_doc_empty.rs | 2 +- .../tests/pallet_ui/pallet_doc_invalid_arg.rs | 2 +- .../pallet_ui/pallet_doc_multiple_args.rs | 2 +- .../tests/pallet_ui/pass/dev_mode_valid.rs | 16 +++++--------- .../pallet_ui/pass/no_std_genesis_config.rs | 4 ++-- .../pass/where_clause_missing_hooks.rs | 15 +++++++++---- frame/support/test/tests/runtime_metadata.rs | 3 +-- frame/support/test/tests/storage_layers.rs | 4 ++-- frame/system/README.md | 2 +- frame/system/benches/bench.rs | 2 +- frame/system/benchmarking/src/mock.rs | 4 ++-- frame/system/rpc/runtime-api/src/lib.rs | 8 +++---- frame/system/src/extensions/check_nonce.rs | 6 +++--- frame/system/src/lib.rs | 21 +++++++++---------- frame/system/src/migrations/mod.rs | 16 +++++++------- frame/system/src/mock.rs | 2 +- frame/system/src/offchain.rs | 2 +- frame/timestamp/src/mock.rs | 2 +- frame/tips/src/tests.rs | 2 +- .../asset-conversion-tx-payment/src/mock.rs | 2 +- .../asset-tx-payment/src/mock.rs | 2 +- frame/transaction-payment/src/mock.rs | 2 +- frame/transaction-storage/src/mock.rs | 2 +- frame/treasury/src/tests.rs | 2 +- frame/uniques/src/mock.rs | 2 +- frame/utility/src/tests.rs | 2 +- frame/vesting/src/mock.rs | 2 +- frame/whitelist/src/mock.rs | 2 +- .../api/proc-macro/src/runtime_metadata.rs | 6 +++--- primitives/test-primitives/src/lib.rs | 2 +- test-utils/runtime/src/extrinsic.rs | 6 +++--- test-utils/runtime/src/lib.rs | 10 ++++----- .../runtime/transaction-pool/src/lib.rs | 4 ++-- utils/frame/rpc/support/src/lib.rs | 2 +- utils/frame/rpc/system/src/lib.rs | 18 ++++++++-------- 132 files changed, 234 insertions(+), 235 deletions(-) diff --git a/bin/node-template/node/src/rpc.rs b/bin/node-template/node/src/rpc.rs index f6995e95945a4..f4f1540f732f7 100644 --- a/bin/node-template/node/src/rpc.rs +++ b/bin/node-template/node/src/rpc.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use jsonrpsee::RpcModule; -use node_template_runtime::{opaque::Block, AccountId, Balance, Index}; +use node_template_runtime::{opaque::Block, AccountId, Balance, Nonce}; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; use sp_block_builder::BlockBuilder; @@ -34,7 +34,7 @@ where C: ProvideRuntimeApi, C: HeaderBackend + HeaderMetadata + 'static, C: Send + Sync + 'static, - C::Api: substrate_frame_rpc_system::AccountNonceApi, + C::Api: substrate_frame_rpc_system::AccountNonceApi, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, C::Api: BlockBuilder, P: TransactionPool + 'static, diff --git a/bin/node-template/pallets/template/src/mock.rs b/bin/node-template/pallets/template/src/mock.rs index 65fe3fa94327b..244ae1b37859b 100644 --- a/bin/node-template/pallets/template/src/mock.rs +++ b/bin/node-template/pallets/template/src/mock.rs @@ -24,7 +24,7 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; diff --git a/bin/node-template/runtime/src/lib.rs b/bin/node-template/runtime/src/lib.rs index 90de167e41ea7..2347d37330be4 100644 --- a/bin/node-template/runtime/src/lib.rs +++ b/bin/node-template/runtime/src/lib.rs @@ -63,7 +63,7 @@ pub type AccountId = <::Signer as IdentifyAccount>::Account pub type Balance = u128; /// Index of a transaction in the chain. -pub type Index = u32; +pub type Nonce = u32; /// A hash of some data used by the chain. pub type Hash = sp_core::H256; @@ -167,8 +167,8 @@ impl frame_system::Config for Runtime { type RuntimeCall = RuntimeCall; /// The lookup mechanism to get account ID from whatever is passed in dispatchers. type Lookup = AccountIdLookup; - /// The index type for storing how many extrinsics an account has signed. - type Index = Index; + /// The type for storing how many extrinsics an account has signed. + type Nonce = Nonce; /// The type for hashing blocks and tries. type Hash = Hash; /// The hashing algorithm used. @@ -455,8 +455,8 @@ impl_runtime_apis! { } } - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Index { + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Nonce { System::account_nonce(account) } } diff --git a/bin/node/executor/tests/basic.rs b/bin/node/executor/tests/basic.rs index d301aa06f90b0..a2f46e9fdbe99 100644 --- a/bin/node/executor/tests/basic.rs +++ b/bin/node/executor/tests/basic.rs @@ -183,7 +183,7 @@ fn panic_execution_with_foreign_code_gives_error() { let mut t = new_test_ext(bloaty_code_unwrap()); t.insert( >::hashed_key_for(alice()), - AccountInfo::<::Index, _> { + AccountInfo::<::Nonce, _> { providers: 1, data: (69u128, 0u128, 0u128, 1u128 << 127), ..Default::default() @@ -209,7 +209,7 @@ fn bad_extrinsic_with_native_equivalent_code_gives_error() { let mut t = new_test_ext(compact_code_unwrap()); t.insert( >::hashed_key_for(alice()), - AccountInfo::<::Index, _> { + AccountInfo::<::Nonce, _> { providers: 1, data: (69u128, 0u128, 0u128, 1u128 << 127), ..Default::default() @@ -235,7 +235,7 @@ fn successful_execution_with_native_equivalent_code_gives_ok() { let mut t = new_test_ext(compact_code_unwrap()); t.insert( >::hashed_key_for(alice()), - AccountInfo::<::Index, _> { + AccountInfo::<::Nonce, _> { providers: 1, data: (111 * DOLLARS, 0u128, 0u128, 1u128 << 127), ..Default::default() @@ -245,7 +245,7 @@ fn successful_execution_with_native_equivalent_code_gives_ok() { t.insert( >::hashed_key_for(bob()), AccountInfo::< - ::Index, + ::Nonce, ::AccountData, >::default() .encode(), @@ -277,7 +277,7 @@ fn successful_execution_with_foreign_code_gives_ok() { let mut t = new_test_ext(bloaty_code_unwrap()); t.insert( >::hashed_key_for(alice()), - AccountInfo::<::Index, _> { + AccountInfo::<::Nonce, _> { providers: 1, data: (111 * DOLLARS, 0u128, 0u128, 1u128 << 127), ..Default::default() @@ -287,7 +287,7 @@ fn successful_execution_with_foreign_code_gives_ok() { t.insert( >::hashed_key_for(bob()), AccountInfo::< - ::Index, + ::Nonce, ::AccountData, >::default() .encode(), @@ -766,7 +766,7 @@ fn panic_execution_gives_error() { let mut t = new_test_ext(bloaty_code_unwrap()); t.insert( >::hashed_key_for(alice()), - AccountInfo::<::Index, _> { + AccountInfo::<::Nonce, _> { data: (0 * DOLLARS, 0u128, 0u128, 0u128), ..Default::default() } @@ -795,7 +795,7 @@ fn successful_execution_gives_ok() { let mut t = new_test_ext(compact_code_unwrap()); t.insert( >::hashed_key_for(alice()), - AccountInfo::<::Index, _> { + AccountInfo::<::Nonce, _> { providers: 1, data: (111 * DOLLARS, 0u128, 0u128, 1u128 << 127), ..Default::default() @@ -805,7 +805,7 @@ fn successful_execution_gives_ok() { t.insert( >::hashed_key_for(bob()), AccountInfo::< - ::Index, + ::Nonce, ::AccountData, >::default() .encode(), diff --git a/bin/node/executor/tests/fees.rs b/bin/node/executor/tests/fees.rs index 970d790a87d3b..7519ce6e8b1b4 100644 --- a/bin/node/executor/tests/fees.rs +++ b/bin/node/executor/tests/fees.rs @@ -196,7 +196,7 @@ fn transaction_fee_is_correct() { fn block_weight_capacity_report() { // Just report how many transfer calls you could fit into a block. The number should at least // be a few hundred (250 at the time of writing but can change over time). Runs until panic. - use node_primitives::Index; + use node_primitives::Nonce; // execution ext. let mut t = new_test_ext(compact_code_unwrap()); @@ -205,7 +205,7 @@ fn block_weight_capacity_report() { let factor = 50; let mut time = 10; - let mut nonce: Index = 0; + let mut nonce: Nonce = 0; let mut block_number = 1; let mut previous_hash: node_primitives::Hash = GENESIS_HASH.into(); @@ -213,7 +213,7 @@ fn block_weight_capacity_report() { let num_transfers = block_number * factor; let mut xts = (0..num_transfers) .map(|i| CheckedExtrinsic { - signed: Some((charlie(), signed_extra(nonce + i as Index, 0))), + signed: Some((charlie(), signed_extra(nonce + i as Nonce, 0))), function: RuntimeCall::Balances(pallet_balances::Call::transfer_allow_death { dest: bob().into(), value: 0, @@ -266,7 +266,7 @@ fn block_length_capacity_report() { // Just report how big a block can get. Executes until panic. Should be ignored unless if // manually inspected. The number should at least be a few megabytes (5 at the time of // writing but can change over time). - use node_primitives::Index; + use node_primitives::Nonce; // execution ext. let mut t = new_test_ext(compact_code_unwrap()); @@ -275,7 +275,7 @@ fn block_length_capacity_report() { let factor = 256 * 1024; let mut time = 10; - let mut nonce: Index = 0; + let mut nonce: Nonce = 0; let mut block_number = 1; let mut previous_hash: node_primitives::Hash = GENESIS_HASH.into(); diff --git a/bin/node/primitives/src/lib.rs b/bin/node/primitives/src/lib.rs index e2fa5c3108149..24a67cbdd8f78 100644 --- a/bin/node/primitives/src/lib.rs +++ b/bin/node/primitives/src/lib.rs @@ -46,7 +46,7 @@ pub type Balance = u128; pub type Moment = u64; /// Index of a transaction in the chain. -pub type Index = u32; +pub type Nonce = u32; /// A hash of some data used by the chain. pub type Hash = sp_core::H256; diff --git a/bin/node/rpc/src/lib.rs b/bin/node/rpc/src/lib.rs index 40c4741dbc1c8..a2ae46904dbfc 100644 --- a/bin/node/rpc/src/lib.rs +++ b/bin/node/rpc/src/lib.rs @@ -34,7 +34,7 @@ use std::sync::Arc; use jsonrpsee::RpcModule; -use node_primitives::{AccountId, Balance, Block, BlockNumber, Hash, Index}; +use node_primitives::{AccountId, Balance, Block, BlockNumber, Hash, Nonce}; use sc_client_api::AuxStore; use sc_consensus_babe::BabeWorkerHandle; use sc_consensus_grandpa::{ @@ -117,7 +117,7 @@ where + Sync + Send + 'static, - C::Api: substrate_frame_rpc_system::AccountNonceApi, + C::Api: substrate_frame_rpc_system::AccountNonceApi, C::Api: mmr_rpc::MmrRuntimeApi::Hash, BlockNumber>, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, C::Api: BabeApi, diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 6f75fff1348ff..6a093996e8e52 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -53,7 +53,7 @@ use frame_system::{ EnsureRoot, EnsureRootWithSuccess, EnsureSigned, EnsureSignedBy, EnsureWithSuccess, }; pub use node_primitives::{AccountId, Signature}; -use node_primitives::{AccountIndex, Balance, BlockNumber, Hash, Index, Moment}; +use node_primitives::{AccountIndex, Balance, BlockNumber, Hash, Moment, Nonce}; use pallet_asset_conversion::{NativeOrAssetId, NativeOrAssetIdConverter}; #[cfg(feature = "runtime-benchmarks")] use pallet_contracts::NoopMigration; @@ -226,7 +226,7 @@ impl frame_system::Config for Runtime { type DbWeight = RocksDbWeight; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = Index; + type Nonce = Nonce; type Hash = Hash; type Hashing = BlakeTwo256; type AccountId = AccountId; @@ -1279,7 +1279,7 @@ where call: RuntimeCall, public: ::Signer, account: AccountId, - nonce: Index, + nonce: Nonce, ) -> Option<(RuntimeCall, ::SignaturePayload)> { let tip = 0; // take the biggest period possible. @@ -2254,8 +2254,8 @@ impl_runtime_apis! { } } - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Index { + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Nonce { System::account_nonce(account) } } diff --git a/bin/node/testing/src/keyring.rs b/bin/node/testing/src/keyring.rs index c3f8d8e6d9485..b4b714d9083d6 100644 --- a/bin/node/testing/src/keyring.rs +++ b/bin/node/testing/src/keyring.rs @@ -20,7 +20,7 @@ use codec::Encode; use kitchensink_runtime::{CheckedExtrinsic, SessionKeys, SignedExtra, UncheckedExtrinsic}; -use node_primitives::{AccountId, Balance, Index}; +use node_primitives::{AccountId, Balance, Nonce}; use sp_keyring::{AccountKeyring, Ed25519Keyring, Sr25519Keyring}; use sp_runtime::generic::Era; @@ -68,7 +68,7 @@ pub fn to_session_keys( } /// Returns transaction extra. -pub fn signed_extra(nonce: Index, extra_fee: Balance) -> SignedExtra { +pub fn signed_extra(nonce: Nonce, extra_fee: Balance) -> SignedExtra { ( frame_system::CheckNonZeroSender::new(), frame_system::CheckSpecVersion::new(), diff --git a/client/transaction-pool/tests/pool.rs b/client/transaction-pool/tests/pool.rs index ac029d71700da..4adf811b42521 100644 --- a/client/transaction-pool/tests/pool.rs +++ b/client/transaction-pool/tests/pool.rs @@ -39,7 +39,7 @@ use sp_runtime::{ }; use std::{collections::BTreeSet, pin::Pin, sync::Arc}; use substrate_test_runtime_client::{ - runtime::{Block, Extrinsic, ExtrinsicBuilder, Hash, Header, Index, Transfer, TransferData}, + runtime::{Block, Extrinsic, ExtrinsicBuilder, Hash, Header, Nonce, Transfer, TransferData}, AccountKeyring::*, ClientBlockImportExt, }; @@ -119,7 +119,7 @@ fn early_nonce_should_be_culled() { .ready() .map(|a| TransferData::try_from(&a.data).unwrap().nonce) .collect(); - assert_eq!(pending, Vec::::new()); + assert_eq!(pending, Vec::::new()); } #[test] @@ -132,7 +132,7 @@ fn late_nonce_should_be_queued() { .ready() .map(|a| TransferData::try_from(&a.data).unwrap().nonce) .collect(); - assert_eq!(pending, Vec::::new()); + assert_eq!(pending, Vec::::new()); block_on(pool.submit_one(&BlockId::number(0), SOURCE, uxt(Alice, 209))).unwrap(); let pending: Vec<_> = pool @@ -182,7 +182,7 @@ fn should_ban_invalid_transactions() { .ready() .map(|a| TransferData::try_from(&a.data).unwrap().nonce) .collect(); - assert_eq!(pending, Vec::::new()); + assert_eq!(pending, Vec::::new()); // then block_on(pool.submit_one(&BlockId::number(0), SOURCE, uxt.clone())).unwrap_err(); diff --git a/frame/alliance/src/mock.rs b/frame/alliance/src/mock.rs index f141ead43ca8b..f04e7e414ed94 100644 --- a/frame/alliance/src/mock.rs +++ b/frame/alliance/src/mock.rs @@ -51,7 +51,7 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; diff --git a/frame/asset-conversion/src/mock.rs b/frame/asset-conversion/src/mock.rs index 022f9d6337580..2b587161f1544 100644 --- a/frame/asset-conversion/src/mock.rs +++ b/frame/asset-conversion/src/mock.rs @@ -53,7 +53,7 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u128; diff --git a/frame/asset-rate/src/mock.rs b/frame/asset-rate/src/mock.rs index 966eb7fad8ae5..33a134628c863 100644 --- a/frame/asset-rate/src/mock.rs +++ b/frame/asset-rate/src/mock.rs @@ -43,7 +43,7 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; diff --git a/frame/assets/src/mock.rs b/frame/assets/src/mock.rs index 5a7b244754c8a..32ad02da90412 100644 --- a/frame/assets/src/mock.rs +++ b/frame/assets/src/mock.rs @@ -52,7 +52,7 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; diff --git a/frame/atomic-swap/src/tests.rs b/frame/atomic-swap/src/tests.rs index eaba60c41bbc0..858417e8007fb 100644 --- a/frame/atomic-swap/src/tests.rs +++ b/frame/atomic-swap/src/tests.rs @@ -27,7 +27,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/aura/src/mock.rs b/frame/aura/src/mock.rs index eb6c08d17566a..53b87ff36ec60 100644 --- a/frame/aura/src/mock.rs +++ b/frame/aura/src/mock.rs @@ -45,7 +45,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; diff --git a/frame/authority-discovery/src/lib.rs b/frame/authority-discovery/src/lib.rs index 80a35071d1e35..87b743ae19677 100644 --- a/frame/authority-discovery/src/lib.rs +++ b/frame/authority-discovery/src/lib.rs @@ -231,7 +231,7 @@ mod tests { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index 2065439439b7b..a9bd0c38cb67c 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -125,7 +125,7 @@ mod tests { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/babe/src/mock.rs b/frame/babe/src/mock.rs index 2b1c62d20622a..b4a7e89ceb04e 100644 --- a/frame/babe/src/mock.rs +++ b/frame/babe/src/mock.rs @@ -65,7 +65,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Version = (); diff --git a/frame/bags-list/src/mock.rs b/frame/bags-list/src/mock.rs index 860a07eb7f05c..ae50adabd508a 100644 --- a/frame/bags-list/src/mock.rs +++ b/frame/bags-list/src/mock.rs @@ -52,7 +52,7 @@ impl frame_system::Config for Runtime { type SS58Prefix = (); type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/balances/src/tests/mod.rs b/frame/balances/src/tests/mod.rs index 60ea7b9eeefc5..45f34110a6e9e 100644 --- a/frame/balances/src/tests/mod.rs +++ b/frame/balances/src/tests/mod.rs @@ -92,7 +92,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; diff --git a/frame/beefy-mmr/src/mock.rs b/frame/beefy-mmr/src/mock.rs index af73c6a9a4966..8594184ad71ab 100644 --- a/frame/beefy-mmr/src/mock.rs +++ b/frame/beefy-mmr/src/mock.rs @@ -64,7 +64,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/beefy/src/mock.rs b/frame/beefy/src/mock.rs index 1d7052a62d2c9..40dcf4d7e70d3 100644 --- a/frame/beefy/src/mock.rs +++ b/frame/beefy/src/mock.rs @@ -72,7 +72,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/benchmarking/pov/src/benchmarking.rs b/frame/benchmarking/pov/src/benchmarking.rs index 1ed446d972136..473947b171ac5 100644 --- a/frame/benchmarking/pov/src/benchmarking.rs +++ b/frame/benchmarking/pov/src/benchmarking.rs @@ -342,7 +342,7 @@ mod mock { use sp_runtime::{testing::H256, BuildStorage}; type AccountId = u64; - type AccountIndex = u32; + type Nonce = u32; type Block = frame_system::mocking::MockBlock; @@ -360,7 +360,7 @@ mod mock { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; diff --git a/frame/benchmarking/pov/src/tests.rs b/frame/benchmarking/pov/src/tests.rs index a6101a72e9c98..f09e37a5288a9 100644 --- a/frame/benchmarking/pov/src/tests.rs +++ b/frame/benchmarking/pov/src/tests.rs @@ -180,7 +180,7 @@ mod mock { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u32; + type Nonce = u32; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; diff --git a/frame/benchmarking/src/baseline.rs b/frame/benchmarking/src/baseline.rs index 6940947471e20..94c066269d91b 100644 --- a/frame/benchmarking/src/baseline.rs +++ b/frame/benchmarking/src/baseline.rs @@ -114,7 +114,7 @@ pub mod mock { use sp_runtime::{testing::H256, BuildStorage}; type AccountId = u64; - type AccountIndex = u32; + type Nonce = u32; type Block = frame_system::mocking::MockBlock; @@ -131,7 +131,7 @@ pub mod mock { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; diff --git a/frame/benchmarking/src/tests.rs b/frame/benchmarking/src/tests.rs index d4abb437a360c..4b8339f65913d 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -82,7 +82,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/benchmarking/src/tests_instance.rs b/frame/benchmarking/src/tests_instance.rs index 2ccad38a8b746..822efa70a2597 100644 --- a/frame/benchmarking/src/tests_instance.rs +++ b/frame/benchmarking/src/tests_instance.rs @@ -92,7 +92,7 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; diff --git a/frame/bounties/src/tests.rs b/frame/bounties/src/tests.rs index f02c9cbffdbff..355483ddac94d 100644 --- a/frame/bounties/src/tests.rs +++ b/frame/bounties/src/tests.rs @@ -62,7 +62,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/child-bounties/src/tests.rs b/frame/child-bounties/src/tests.rs index 60161c88f510a..24a6410f29f78 100644 --- a/frame/child-bounties/src/tests.rs +++ b/frame/child-bounties/src/tests.rs @@ -65,7 +65,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/collective/src/tests.rs b/frame/collective/src/tests.rs index d67747a2b78f5..86b85e07a8bd9 100644 --- a/frame/collective/src/tests.rs +++ b/frame/collective/src/tests.rs @@ -96,7 +96,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index a07390329cd4d..b6755a69cc76f 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -309,7 +309,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/conviction-voting/src/tests.rs b/frame/conviction-voting/src/tests.rs index b0b692446d5d2..656112deebfbb 100644 --- a/frame/conviction-voting/src/tests.rs +++ b/frame/conviction-voting/src/tests.rs @@ -57,7 +57,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/core-fellowship/src/tests.rs b/frame/core-fellowship/src/tests.rs index 7e984c1efed34..c95699e66e41b 100644 --- a/frame/core-fellowship/src/tests.rs +++ b/frame/core-fellowship/src/tests.rs @@ -56,7 +56,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/democracy/src/tests.rs b/frame/democracy/src/tests.rs index 0339b46d03a9f..e5cfcc5b40029 100644 --- a/frame/democracy/src/tests.rs +++ b/frame/democracy/src/tests.rs @@ -83,7 +83,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/election-provider-multi-phase/src/mock.rs b/frame/election-provider-multi-phase/src/mock.rs index 5dfb7f7744f4f..911e93d35860e 100644 --- a/frame/election-provider-multi-phase/src/mock.rs +++ b/frame/election-provider-multi-phase/src/mock.rs @@ -208,7 +208,7 @@ impl frame_system::Config for Runtime { type SS58Prefix = (); type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs b/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs index 85fafa25c4c8b..b04f863668ec3 100644 --- a/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs +++ b/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs @@ -64,7 +64,7 @@ frame_support::construct_runtime!( ); pub(crate) type AccountId = u128; -pub(crate) type AccountIndex = u32; +pub(crate) type Nonce = u32; pub(crate) type BlockNumber = u64; pub(crate) type Balance = u64; pub(crate) type VoterIndex = u32; @@ -77,7 +77,7 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/election-provider-support/src/onchain.rs b/frame/election-provider-support/src/onchain.rs index 4adcf99b3345a..bfdc21a8fe2d6 100644 --- a/frame/election-provider-support/src/onchain.rs +++ b/frame/election-provider-support/src/onchain.rs @@ -190,6 +190,7 @@ mod tests { use sp_npos_elections::Support; use sp_runtime::Perbill; type AccountId = u64; + type Nonce = u64; type BlockNumber = u64; pub type Header = sp_runtime::generic::Header; @@ -207,7 +208,7 @@ mod tests { type SS58Prefix = (); type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = AccountId; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 55c16dfda995d..b23ddda4e8d1c 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -1323,7 +1323,7 @@ mod tests { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/examples/basic/src/tests.rs b/frame/examples/basic/src/tests.rs index 14f4d64d5c68c..addf219dc3c39 100644 --- a/frame/examples/basic/src/tests.rs +++ b/frame/examples/basic/src/tests.rs @@ -51,7 +51,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/examples/default-config/src/lib.rs b/frame/examples/default-config/src/lib.rs index a2c11e168fe27..63a6a941b829f 100644 --- a/frame/examples/default-config/src/lib.rs +++ b/frame/examples/default-config/src/lib.rs @@ -137,7 +137,7 @@ pub mod tests { // all of this is coming from `frame_system::config_preludes::TestDefaultConfig`. - // type Index = u32; + // type Nonce = u32; // type BlockNumber = u32; // type Header = // sp_runtime::generic::Header, diff --git a/frame/examples/dev-mode/src/tests.rs b/frame/examples/dev-mode/src/tests.rs index 83f66f0031b83..ba98f5174ce20 100644 --- a/frame/examples/dev-mode/src/tests.rs +++ b/frame/examples/dev-mode/src/tests.rs @@ -45,7 +45,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/examples/offchain-worker/src/tests.rs b/frame/examples/offchain-worker/src/tests.rs index 84d9c3f972891..203a59a8af03c 100644 --- a/frame/examples/offchain-worker/src/tests.rs +++ b/frame/examples/offchain-worker/src/tests.rs @@ -53,7 +53,7 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = sp_core::sr25519::Public; diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index f758cfc841d61..4e24717a39e93 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -868,7 +868,7 @@ mod tests { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = BlakeTwo256; diff --git a/frame/fast-unstake/src/mock.rs b/frame/fast-unstake/src/mock.rs index b78d0e84dad29..192d525e278d7 100644 --- a/frame/fast-unstake/src/mock.rs +++ b/frame/fast-unstake/src/mock.rs @@ -32,7 +32,7 @@ use pallet_staking::{Exposure, IndividualExposure, StakerStatus}; use sp_std::prelude::*; pub type AccountId = u128; -pub type AccountIndex = u32; +pub type Nonce = u32; pub type BlockNumber = u64; pub type Balance = u128; pub type T = Runtime; @@ -50,7 +50,7 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/glutton/src/mock.rs b/frame/glutton/src/mock.rs index b05d25ab62a3e..c79ddd53718eb 100644 --- a/frame/glutton/src/mock.rs +++ b/frame/glutton/src/mock.rs @@ -44,7 +44,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/grandpa/src/mock.rs b/frame/grandpa/src/mock.rs index 47d07c73904b8..35a0d99c566c0 100644 --- a/frame/grandpa/src/mock.rs +++ b/frame/grandpa/src/mock.rs @@ -69,7 +69,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/identity/src/tests.rs b/frame/identity/src/tests.rs index 57b372ef57912..1532980574c2a 100644 --- a/frame/identity/src/tests.rs +++ b/frame/identity/src/tests.rs @@ -49,7 +49,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/im-online/src/mock.rs b/frame/im-online/src/mock.rs index 6cc134c98ac6e..85da061fe904a 100644 --- a/frame/im-online/src/mock.rs +++ b/frame/im-online/src/mock.rs @@ -119,7 +119,7 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/indices/src/mock.rs b/frame/indices/src/mock.rs index 3e7d6240b1087..d63081e0b73f8 100644 --- a/frame/indices/src/mock.rs +++ b/frame/indices/src/mock.rs @@ -42,7 +42,7 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = u64; diff --git a/frame/insecure-randomness-collective-flip/src/lib.rs b/frame/insecure-randomness-collective-flip/src/lib.rs index 13dff14da7b9b..474087777c46e 100644 --- a/frame/insecure-randomness-collective-flip/src/lib.rs +++ b/frame/insecure-randomness-collective-flip/src/lib.rs @@ -195,7 +195,7 @@ mod tests { type BlockLength = BlockLength; type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/lottery/src/mock.rs b/frame/lottery/src/mock.rs index 5578c0add1d1e..aefb6a1cce2bf 100644 --- a/frame/lottery/src/mock.rs +++ b/frame/lottery/src/mock.rs @@ -53,7 +53,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index 4f4bc9fdda982..24b9fb5fe9069 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -556,7 +556,7 @@ mod tests { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/merkle-mountain-range/src/mock.rs b/frame/merkle-mountain-range/src/mock.rs index 286b0b2084a6d..ecc254278bf0f 100644 --- a/frame/merkle-mountain-range/src/mock.rs +++ b/frame/merkle-mountain-range/src/mock.rs @@ -41,7 +41,7 @@ impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = sp_core::sr25519::Public; diff --git a/frame/message-queue/src/integration_test.rs b/frame/message-queue/src/integration_test.rs index 2b9e9a0a7878c..4fc639101a01f 100644 --- a/frame/message-queue/src/integration_test.rs +++ b/frame/message-queue/src/integration_test.rs @@ -56,7 +56,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/message-queue/src/mock.rs b/frame/message-queue/src/mock.rs index 8c2ba8805aaad..5a68a161eb374 100644 --- a/frame/message-queue/src/mock.rs +++ b/frame/message-queue/src/mock.rs @@ -49,7 +49,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/multisig/src/tests.rs b/frame/multisig/src/tests.rs index e3cdd086fb757..8e704b923742a 100644 --- a/frame/multisig/src/tests.rs +++ b/frame/multisig/src/tests.rs @@ -49,7 +49,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/nft-fractionalization/src/mock.rs b/frame/nft-fractionalization/src/mock.rs index 569429552d268..6565adaf6fc7e 100644 --- a/frame/nft-fractionalization/src/mock.rs +++ b/frame/nft-fractionalization/src/mock.rs @@ -55,7 +55,7 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; diff --git a/frame/nfts/src/mock.rs b/frame/nfts/src/mock.rs index e791c85b67f3f..f091a53f8d7c7 100644 --- a/frame/nfts/src/mock.rs +++ b/frame/nfts/src/mock.rs @@ -52,7 +52,7 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; diff --git a/frame/nicks/src/lib.rs b/frame/nicks/src/lib.rs index a0dd3125db75d..612443f5dfd56 100644 --- a/frame/nicks/src/lib.rs +++ b/frame/nicks/src/lib.rs @@ -260,7 +260,7 @@ mod tests { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/nis/src/mock.rs b/frame/nis/src/mock.rs index 4fb51ed324e22..76fdf5f3f0693 100644 --- a/frame/nis/src/mock.rs +++ b/frame/nis/src/mock.rs @@ -56,7 +56,7 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; diff --git a/frame/node-authorization/src/mock.rs b/frame/node-authorization/src/mock.rs index 0733016b82cb9..84e3336b3bd68 100644 --- a/frame/node-authorization/src/mock.rs +++ b/frame/node-authorization/src/mock.rs @@ -49,7 +49,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/nomination-pools/benchmarking/src/mock.rs b/frame/nomination-pools/benchmarking/src/mock.rs index 60ca5166abb87..2298f611d7fff 100644 --- a/frame/nomination-pools/benchmarking/src/mock.rs +++ b/frame/nomination-pools/benchmarking/src/mock.rs @@ -24,7 +24,7 @@ use sp_runtime::{ }; type AccountId = u128; -type AccountIndex = u32; +type Nonce = u32; type BlockNumber = u64; type Balance = u128; @@ -34,7 +34,7 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/nomination-pools/src/mock.rs b/frame/nomination-pools/src/mock.rs index fd8514bfc8bfe..7d0d729a40d41 100644 --- a/frame/nomination-pools/src/mock.rs +++ b/frame/nomination-pools/src/mock.rs @@ -168,7 +168,7 @@ impl frame_system::Config for Runtime { type SS58Prefix = (); type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/nomination-pools/test-staking/src/mock.rs b/frame/nomination-pools/test-staking/src/mock.rs index 8c8618913d518..ffc1ed56d08c4 100644 --- a/frame/nomination-pools/test-staking/src/mock.rs +++ b/frame/nomination-pools/test-staking/src/mock.rs @@ -29,7 +29,7 @@ use sp_runtime::{ }; type AccountId = u128; -type AccountIndex = u32; +type Nonce = u32; type BlockNumber = u64; type Balance = u128; @@ -44,7 +44,7 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/offences/benchmarking/src/mock.rs b/frame/offences/benchmarking/src/mock.rs index 6089025dcb2b2..0e3dfd09fe7ab 100644 --- a/frame/offences/benchmarking/src/mock.rs +++ b/frame/offences/benchmarking/src/mock.rs @@ -34,7 +34,7 @@ use sp_runtime::{ }; type AccountId = u64; -type AccountIndex = u32; +type Nonce = u32; type Balance = u64; impl frame_system::Config for Test { @@ -43,7 +43,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; diff --git a/frame/offences/src/mock.rs b/frame/offences/src/mock.rs index 150ab3665269d..990ceae5ac01e 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -81,7 +81,7 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = RocksDbWeight; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/preimage/src/mock.rs b/frame/preimage/src/mock.rs index f196a18acae36..2fb9f36dec454 100644 --- a/frame/preimage/src/mock.rs +++ b/frame/preimage/src/mock.rs @@ -50,7 +50,7 @@ impl frame_system::Config for Test { type DbWeight = RocksDbWeight; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; diff --git a/frame/proxy/src/tests.rs b/frame/proxy/src/tests.rs index 54466e5d5bbce..1f4d2617700e6 100644 --- a/frame/proxy/src/tests.rs +++ b/frame/proxy/src/tests.rs @@ -53,7 +53,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/ranked-collective/src/tests.rs b/frame/ranked-collective/src/tests.rs index 7f3cd27705e97..ba8c5a0f937ba 100644 --- a/frame/ranked-collective/src/tests.rs +++ b/frame/ranked-collective/src/tests.rs @@ -51,7 +51,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/recovery/src/mock.rs b/frame/recovery/src/mock.rs index 16de531867c24..2f2bd866a7198 100644 --- a/frame/recovery/src/mock.rs +++ b/frame/recovery/src/mock.rs @@ -48,7 +48,7 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; diff --git a/frame/referenda/src/mock.rs b/frame/referenda/src/mock.rs index f42df260f4759..d4a23d3e24b4e 100644 --- a/frame/referenda/src/mock.rs +++ b/frame/referenda/src/mock.rs @@ -65,7 +65,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/remark/src/mock.rs b/frame/remark/src/mock.rs index 45b30dad5c161..e597a1ca4dfe8 100644 --- a/frame/remark/src/mock.rs +++ b/frame/remark/src/mock.rs @@ -42,7 +42,7 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; diff --git a/frame/root-offences/src/mock.rs b/frame/root-offences/src/mock.rs index 0f9df833a4c7f..92d188f49fb92 100644 --- a/frame/root-offences/src/mock.rs +++ b/frame/root-offences/src/mock.rs @@ -87,7 +87,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/salary/src/tests.rs b/frame/salary/src/tests.rs index 9f63fb173214a..034dce24b8b38 100644 --- a/frame/salary/src/tests.rs +++ b/frame/salary/src/tests.rs @@ -55,7 +55,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/scheduler/src/mock.rs b/frame/scheduler/src/mock.rs index f6dd554866be8..28e334958d924 100644 --- a/frame/scheduler/src/mock.rs +++ b/frame/scheduler/src/mock.rs @@ -125,7 +125,7 @@ impl system::Config for Test { type DbWeight = RocksDbWeight; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; diff --git a/frame/scored-pool/src/mock.rs b/frame/scored-pool/src/mock.rs index 8cbb0eae4b613..d8c6ef9b0f444 100644 --- a/frame/scored-pool/src/mock.rs +++ b/frame/scored-pool/src/mock.rs @@ -56,7 +56,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/session/benchmarking/src/mock.rs b/frame/session/benchmarking/src/mock.rs index d8bc4ba9c27ab..dbbd437bbd938 100644 --- a/frame/session/benchmarking/src/mock.rs +++ b/frame/session/benchmarking/src/mock.rs @@ -27,7 +27,7 @@ use frame_support::{ use sp_runtime::{traits::IdentityLookup, BuildStorage}; type AccountId = u64; -type AccountIndex = u32; +type Nonce = u32; type Balance = u64; type Block = frame_system::mocking::MockBlock; @@ -48,7 +48,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; diff --git a/frame/session/src/mock.rs b/frame/session/src/mock.rs index 58d1d30a050ac..b45ebfd25c44a 100644 --- a/frame/session/src/mock.rs +++ b/frame/session/src/mock.rs @@ -238,7 +238,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/society/src/mock.rs b/frame/society/src/mock.rs index b9a283ead3c66..a318c2e794b7a 100644 --- a/frame/society/src/mock.rs +++ b/frame/society/src/mock.rs @@ -64,7 +64,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index 025c5c61fcbb7..232b37de7c1b8 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -43,7 +43,7 @@ pub const BLOCK_TIME: u64 = 1000; /// The AccountId alias in this test module. pub(crate) type AccountId = u64; -pub(crate) type AccountIndex = u64; +pub(crate) type Nonce = u64; pub(crate) type BlockNumber = u64; pub(crate) type Balance = u128; @@ -124,7 +124,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = RocksDbWeight; type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; diff --git a/frame/state-trie-migration/src/lib.rs b/frame/state-trie-migration/src/lib.rs index 40783482ad52e..4bbabef1dd4bd 100644 --- a/frame/state-trie-migration/src/lib.rs +++ b/frame/state-trie-migration/src/lib.rs @@ -1087,7 +1087,7 @@ mod mock { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; diff --git a/frame/statement/src/mock.rs b/frame/statement/src/mock.rs index bea06a68c0d38..79d2aa7d891d5 100644 --- a/frame/statement/src/mock.rs +++ b/frame/statement/src/mock.rs @@ -54,7 +54,7 @@ impl frame_system::Config for Test { type DbWeight = RocksDbWeight; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId32; diff --git a/frame/sudo/src/mock.rs b/frame/sudo/src/mock.rs index 5423f99599c03..9e78e474f4e5a 100644 --- a/frame/sudo/src/mock.rs +++ b/frame/sudo/src/mock.rs @@ -115,7 +115,7 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; diff --git a/frame/support/procedural/src/lib.rs b/frame/support/procedural/src/lib.rs index 570f079db82f4..a0f2c995514a5 100644 --- a/frame/support/procedural/src/lib.rs +++ b/frame/support/procedural/src/lib.rs @@ -873,7 +873,7 @@ pub fn storage_alias(_: TokenStream, input: TokenStream) -> TokenStream { /// type BlockWeights = (); /// type BlockLength = (); /// type DbWeight = (); -/// type Index = u64; +/// type Nonce = u64; /// type BlockNumber = u64; /// type Hash = sp_core::hash::H256; /// type Hashing = sp_runtime::traits::BlakeTwo256; @@ -908,7 +908,7 @@ pub fn storage_alias(_: TokenStream, input: TokenStream) -> TokenStream { /// type BlockWeights = ::BlockWeights; /// type BlockLength = ::BlockLength; /// type DbWeight = ::DbWeight; -/// type Index = ::Index; +/// type Nonce = ::Nonce; /// type BlockNumber = ::BlockNumber; /// type Hash = ::Hash; /// type Hashing = ::Hashing; diff --git a/frame/support/test/compile_pass/src/lib.rs b/frame/support/test/compile_pass/src/lib.rs index 75911d7569f80..bf90d73acb320 100644 --- a/frame/support/test/compile_pass/src/lib.rs +++ b/frame/support/test/compile_pass/src/lib.rs @@ -45,7 +45,6 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { pub type Signature = sr25519::Signature; pub type AccountId = ::Signer; pub type BlockNumber = u64; -pub type Index = u64; parameter_types! { pub const Version: RuntimeVersion = VERSION; @@ -55,7 +54,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = Everything; type BlockWeights = (); type BlockLength = (); - type Index = u128; + type Nonce = u128; type Hash = H256; type Hashing = BlakeTwo256; type Block = Block; diff --git a/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs b/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs index 738ff0df3a07f..0d6afbcdc2c65 100644 --- a/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs +++ b/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs @@ -22,7 +22,7 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs b/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs index e21ddf65921a1..8b3e26bc5e2e4 100644 --- a/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs +++ b/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs @@ -1,6 +1,6 @@ use frame_support::construct_runtime; -use sp_runtime::{generic, traits::BlakeTwo256}; use sp_core::sr25519; +use sp_runtime::{generic, traits::BlakeTwo256}; #[frame_support::pallet] mod pallet { @@ -18,22 +18,22 @@ mod pallet { #[derive(scale_info::TypeInfo, frame_support::PalletError, codec::Encode, codec::Decode)] pub enum Nested1 { - Nested2(Nested2) + Nested2(Nested2), } #[derive(scale_info::TypeInfo, frame_support::PalletError, codec::Encode, codec::Decode)] pub enum Nested2 { - Nested3(Nested3) + Nested3(Nested3), } #[derive(scale_info::TypeInfo, frame_support::PalletError, codec::Encode, codec::Decode)] pub enum Nested3 { - Nested4(Nested4) + Nested4(Nested4), } #[derive(scale_info::TypeInfo, frame_support::PalletError, codec::Encode, codec::Decode)] pub enum Nested4 { - Num(u8) + Num(u8), } pub type Signature = sr25519::Signature; @@ -47,7 +47,7 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs index c57272c2caa33..25cb5e93f652e 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs @@ -1,6 +1,6 @@ use frame_support::construct_runtime; -use sp_runtime::{generic, traits::BlakeTwo256}; use sp_core::sr25519; +use sp_runtime::{generic, traits::BlakeTwo256}; #[frame_support::pallet] mod pallet { @@ -22,7 +22,7 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs index 6fa4389b98ddf..c44cceef81a12 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs @@ -1,6 +1,6 @@ use frame_support::construct_runtime; -use sp_runtime::{generic, traits::BlakeTwo256}; use sp_core::sr25519; +use sp_runtime::{generic, traits::BlakeTwo256}; #[frame_support::pallet] mod pallet { @@ -22,7 +22,7 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs index 8470ae3a78a7e..4436202f04fc7 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs @@ -1,6 +1,6 @@ use frame_support::construct_runtime; -use sp_runtime::{generic, traits::BlakeTwo256}; use sp_core::sr25519; +use sp_runtime::{generic, traits::BlakeTwo256}; #[frame_support::pallet] mod pallet { @@ -22,7 +22,7 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs index 0ebee2b980e17..8b48c4d0d6af7 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs @@ -1,6 +1,6 @@ use frame_support::construct_runtime; -use sp_runtime::{generic, traits::BlakeTwo256}; use sp_core::sr25519; +use sp_runtime::{generic, traits::BlakeTwo256}; #[frame_support::pallet] mod pallet { @@ -22,7 +22,7 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs index 75059716f6bc4..974928785f748 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs @@ -1,6 +1,6 @@ use frame_support::construct_runtime; -use sp_runtime::{generic, traits::BlakeTwo256}; use sp_core::sr25519; +use sp_runtime::{generic, traits::BlakeTwo256}; #[frame_support::pallet] mod pallet { @@ -22,7 +22,7 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs index 4ef93084835dc..505b249d92d58 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs @@ -22,7 +22,7 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/support/test/tests/pallet.rs b/frame/support/test/tests/pallet.rs index eddc3728612c2..99010ffc8dbdf 100644 --- a/frame/support/test/tests/pallet.rs +++ b/frame/support/test/tests/pallet.rs @@ -656,7 +656,7 @@ frame_support::parameter_types!( impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/support/test/tests/pallet_instance.rs b/frame/support/test/tests/pallet_instance.rs index 0cd843c9bffe8..4ecb9bcb58ae9 100644 --- a/frame/support/test/tests/pallet_instance.rs +++ b/frame/support/test/tests/pallet_instance.rs @@ -291,7 +291,7 @@ pub mod pallet2 { impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/support/test/tests/pallet_ui/pallet_doc_arg_non_path.rs b/frame/support/test/tests/pallet_ui/pallet_doc_arg_non_path.rs index ef3097d23007d..32df5d6183653 100644 --- a/frame/support/test/tests/pallet_ui/pallet_doc_arg_non_path.rs +++ b/frame/support/test/tests/pallet_ui/pallet_doc_arg_non_path.rs @@ -5,7 +5,7 @@ mod pallet { #[pallet::config] pub trait Config: frame_system::Config where - ::Index: From, + ::Nonce: From, { } diff --git a/frame/support/test/tests/pallet_ui/pallet_doc_empty.rs b/frame/support/test/tests/pallet_ui/pallet_doc_empty.rs index fe40806d2fa75..6ff01e9fb44b8 100644 --- a/frame/support/test/tests/pallet_ui/pallet_doc_empty.rs +++ b/frame/support/test/tests/pallet_ui/pallet_doc_empty.rs @@ -5,7 +5,7 @@ mod pallet { #[pallet::config] pub trait Config: frame_system::Config where - ::Index: From, + ::Nonce: From, { } diff --git a/frame/support/test/tests/pallet_ui/pallet_doc_invalid_arg.rs b/frame/support/test/tests/pallet_ui/pallet_doc_invalid_arg.rs index 8f0ccb3777a49..c7d3b556a08e2 100644 --- a/frame/support/test/tests/pallet_ui/pallet_doc_invalid_arg.rs +++ b/frame/support/test/tests/pallet_ui/pallet_doc_invalid_arg.rs @@ -5,7 +5,7 @@ mod pallet { #[pallet::config] pub trait Config: frame_system::Config where - ::Index: From, + ::Nonce: From, { } diff --git a/frame/support/test/tests/pallet_ui/pallet_doc_multiple_args.rs b/frame/support/test/tests/pallet_ui/pallet_doc_multiple_args.rs index ffbed9d950799..a799879fe4442 100644 --- a/frame/support/test/tests/pallet_ui/pallet_doc_multiple_args.rs +++ b/frame/support/test/tests/pallet_ui/pallet_doc_multiple_args.rs @@ -5,7 +5,7 @@ mod pallet { #[pallet::config] pub trait Config: frame_system::Config where - ::Index: From, + ::Nonce: From, { } diff --git a/frame/support/test/tests/pallet_ui/pass/dev_mode_valid.rs b/frame/support/test/tests/pallet_ui/pass/dev_mode_valid.rs index 516aa1e131aca..ed779da80a188 100644 --- a/frame/support/test/tests/pallet_ui/pass/dev_mode_valid.rs +++ b/frame/support/test/tests/pallet_ui/pass/dev_mode_valid.rs @@ -1,10 +1,6 @@ #![cfg_attr(not(feature = "std"), no_std)] -use frame_support::{ - traits::{ - ConstU32, - }, -}; +use frame_support::traits::ConstU32; pub use pallet::*; @@ -60,7 +56,7 @@ pub mod pallet { impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; @@ -96,17 +92,15 @@ frame_support::construct_runtime!( } ); -impl pallet::Config for Runtime { - -} +impl pallet::Config for Runtime {} fn main() { - use frame_support::{pallet_prelude::*}; - use storage::unhashed; + use frame_support::pallet_prelude::*; use sp_io::{ hashing::{blake2_128, twox_128}, TestExternalities, }; + use storage::unhashed; fn blake2_128_concat(d: &[u8]) -> Vec { let mut v = blake2_128(d).to_vec(); diff --git a/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs b/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs index 8f50d09e0f0d6..87659a0bab513 100644 --- a/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs +++ b/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs @@ -1,6 +1,6 @@ use frame_support::construct_runtime; -use sp_runtime::{generic, traits::BlakeTwo256}; use sp_core::sr25519; +use sp_runtime::{generic, traits::BlakeTwo256}; pub type Signature = sr25519::Signature; pub type BlockNumber = u32; @@ -13,7 +13,7 @@ impl test_pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/support/test/tests/pallet_ui/pass/where_clause_missing_hooks.rs b/frame/support/test/tests/pallet_ui/pass/where_clause_missing_hooks.rs index bf5f22306207a..15fff372a1dd1 100644 --- a/frame/support/test/tests/pallet_ui/pass/where_clause_missing_hooks.rs +++ b/frame/support/test/tests/pallet_ui/pass/where_clause_missing_hooks.rs @@ -1,17 +1,24 @@ #[frame_support::pallet] mod pallet { #[pallet::config] - pub trait Config: frame_system::Config where ::Index: From {} + pub trait Config: frame_system::Config + where + ::Nonce: From, + { + } #[pallet::pallet] pub struct Pallet(core::marker::PhantomData); #[pallet::call] - impl Pallet where ::Index: From {} + impl Pallet where ::Nonce: From {} - impl Pallet where ::Index: From { + impl Pallet + where + ::Nonce: From, + { fn foo(x: u128) { - let _index = ::Index::from(x); + let _index = ::Nonce::from(x); } } } diff --git a/frame/support/test/tests/runtime_metadata.rs b/frame/support/test/tests/runtime_metadata.rs index 44c375a9a674f..50bad87d32eb0 100644 --- a/frame/support/test/tests/runtime_metadata.rs +++ b/frame/support/test/tests/runtime_metadata.rs @@ -25,7 +25,6 @@ use scale_info::{form::MetaForm, meta_type}; use sp_runtime::traits::Block as BlockT; pub type BlockNumber = u64; -pub type Index = u64; pub type Header = sp_runtime::generic::Header; pub type Block = sp_runtime::generic::Block; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; @@ -36,7 +35,7 @@ impl frame_system::Config for Runtime { type DbWeight = (); type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; diff --git a/frame/support/test/tests/storage_layers.rs b/frame/support/test/tests/storage_layers.rs index 93a541ad91162..b825c85f9564c 100644 --- a/frame/support/test/tests/storage_layers.rs +++ b/frame/support/test/tests/storage_layers.rs @@ -58,7 +58,7 @@ pub mod pallet { } pub type BlockNumber = u32; -pub type Index = u64; +pub type Nonce = u64; pub type AccountId = u64; pub type Header = sp_runtime::generic::Header; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; @@ -70,7 +70,7 @@ impl frame_system::Config for Runtime { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = Index; + type Nonce = Nonce; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; diff --git a/frame/system/README.md b/frame/system/README.md index c22b41e42d798..30b2ea73720cf 100644 --- a/frame/system/README.md +++ b/frame/system/README.md @@ -33,7 +33,7 @@ The System module defines the following extensions: - [`CheckWeight`]: Checks the weight and length of the block and ensure that it does not exceed the limits. - [`CheckNonce`]: Checks the nonce of the transaction. Contains a single payload of type - `T::Index`. + `T::Nonce`. - [`CheckEra`]: Checks the era of the transaction. Contains a single payload of type `Era`. - [`CheckGenesis`]: Checks the provided genesis hash of the transaction. Must be a part of the signed payload of the transaction. diff --git a/frame/system/benches/bench.rs b/frame/system/benches/bench.rs index 93e2c61ad5cd8..da8bb10fd4e42 100644 --- a/frame/system/benches/bench.rs +++ b/frame/system/benches/bench.rs @@ -63,7 +63,7 @@ impl frame_system::Config for Runtime { type BlockLength = BlockLength; type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/system/benchmarking/src/mock.rs b/frame/system/benchmarking/src/mock.rs index 4201f9dcc6f97..4e6b1221da356 100644 --- a/frame/system/benchmarking/src/mock.rs +++ b/frame/system/benchmarking/src/mock.rs @@ -23,7 +23,7 @@ use codec::Encode; use sp_runtime::{traits::IdentityLookup, BuildStorage}; type AccountId = u64; -type AccountIndex = u32; +type Nonce = u32; type Block = frame_system::mocking::MockBlock; @@ -40,7 +40,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; diff --git a/frame/system/rpc/runtime-api/src/lib.rs b/frame/system/rpc/runtime-api/src/lib.rs index 2ea9f2f62e11c..f59988d818f07 100644 --- a/frame/system/rpc/runtime-api/src/lib.rs +++ b/frame/system/rpc/runtime-api/src/lib.rs @@ -24,12 +24,12 @@ #![cfg_attr(not(feature = "std"), no_std)] sp_api::decl_runtime_apis! { - /// The API to query account nonce (aka transaction index). - pub trait AccountNonceApi where + /// The API to query account nonce. + pub trait AccountNonceApi where AccountId: codec::Codec, - Index: codec::Codec, + Nonce: codec::Codec, { /// Get current account nonce of given `AccountId`. - fn account_nonce(account: AccountId) -> Index; + fn account_nonce(account: AccountId) -> Nonce; } } diff --git a/frame/system/src/extensions/check_nonce.rs b/frame/system/src/extensions/check_nonce.rs index 57ebd7701ef6a..2939fd6534c09 100644 --- a/frame/system/src/extensions/check_nonce.rs +++ b/frame/system/src/extensions/check_nonce.rs @@ -37,11 +37,11 @@ use sp_std::vec; /// some kind of priority upon validating transactions. #[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] #[scale_info(skip_type_params(T))] -pub struct CheckNonce(#[codec(compact)] pub T::Index); +pub struct CheckNonce(#[codec(compact)] pub T::Nonce); impl CheckNonce { /// utility constructor. Used only in client/factory code. - pub fn from(nonce: T::Index) -> Self { + pub fn from(nonce: T::Nonce) -> Self { Self(nonce) } } @@ -88,7 +88,7 @@ where } .into()) } - account.nonce += T::Index::one(); + account.nonce += T::Nonce::one(); crate::Account::::insert(who, account); Ok(()) } diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index a4c40032c8972..cdd9f7630818a 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -50,7 +50,7 @@ //! - [`CheckWeight`]: Checks the weight and length of the block and ensure that it does not //! exceed the limits. //! - [`CheckNonce`]: Checks the nonce of the transaction. Contains a single payload of type -//! `T::Index`. +//! `T::Nonce`. //! - [`CheckEra`]: Checks the era of the transaction. Contains a single payload of type `Era`. //! - [`CheckGenesis`]: Checks the provided genesis hash of the transaction. Must be a part of the //! signed payload of the transaction. @@ -217,7 +217,7 @@ pub mod pallet { #[frame_support::register_default_impl(TestDefaultConfig)] impl DefaultConfig for TestDefaultConfig { - type Index = u32; + type Nonce = u32; type Hash = sp_core::hash::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; @@ -273,9 +273,8 @@ pub mod pallet { + Debug + From>; - /// Account index (aka nonce) type. This stores the number of previous transactions - /// associated with a sender account. - type Index: Parameter + /// This stores the number of previous transactions associated with a sender account. + type Nonce: Parameter + Member + MaybeSerializeDeserialize + Debug @@ -554,7 +553,7 @@ pub mod pallet { _, Blake2_128Concat, T::AccountId, - AccountInfo, + AccountInfo, ValueQuery, >; @@ -732,9 +731,9 @@ pub type RefCount = u32; /// Information of an account. #[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)] -pub struct AccountInfo { +pub struct AccountInfo { /// The number of transactions this account has sent. - pub nonce: Index, + pub nonce: Nonce, /// The number of other modules that currently depend on this account's existence. The account /// cannot be reaped until this is zero. pub consumers: RefCount, @@ -1570,13 +1569,13 @@ impl Pallet { } /// Retrieve the account transaction counter from storage. - pub fn account_nonce(who: impl EncodeLike) -> T::Index { + pub fn account_nonce(who: impl EncodeLike) -> T::Nonce { Account::::get(who).nonce } /// Increment a particular account's nonce by 1. pub fn inc_account_nonce(who: impl EncodeLike) { - Account::::mutate(who, |a| a.nonce += T::Index::one()); + Account::::mutate(who, |a| a.nonce += T::Nonce::one()); } /// Note what the extrinsic data of the current extrinsic index is. @@ -1632,7 +1631,7 @@ impl Pallet { } /// An account is being created. - pub fn on_created_account(who: T::AccountId, _a: &mut AccountInfo) { + pub fn on_created_account(who: T::AccountId, _a: &mut AccountInfo) { T::OnNewAccount::on_new_account(&who); Self::deposit_event(Event::NewAccount { account: who }); } diff --git a/frame/system/src/migrations/mod.rs b/frame/system/src/migrations/mod.rs index f8ebfab33b891..6f873061dbab9 100644 --- a/frame/system/src/migrations/mod.rs +++ b/frame/system/src/migrations/mod.rs @@ -31,8 +31,8 @@ type RefCount = u32; /// Information of an account. #[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)] -struct AccountInfo { - nonce: Index, +struct AccountInfo { + nonce: Nonce, consumers: RefCount, providers: RefCount, sufficients: RefCount, @@ -47,8 +47,8 @@ pub trait V2ToV3 { /// System config account id type AccountId: 'static + FullCodec; - /// System config index - type Index: 'static + FullCodec + Copy; + /// System config nonce + type Nonce: 'static + FullCodec + Copy; /// System config account data type AccountData: 'static + FullCodec; @@ -65,13 +65,13 @@ type Account = StorageMap< Pallet, Blake2_128Concat, ::AccountId, - AccountInfo<::Index, ::AccountData>, + AccountInfo<::Nonce, ::AccountData>, >; /// Migrate from unique `u8` reference counting to triple `u32` reference counting. pub fn migrate_from_single_u8_to_triple_ref_count() -> Weight { let mut translated: usize = 0; - >::translate::<(V::Index, u8, V::AccountData), _>(|_key, (nonce, rc, data)| { + >::translate::<(V::Nonce, u8, V::AccountData), _>(|_key, (nonce, rc, data)| { translated += 1; Some(AccountInfo { nonce, consumers: rc as RefCount, providers: 1, sufficients: 0, data }) }); @@ -88,7 +88,7 @@ pub fn migrate_from_single_u8_to_triple_ref_count() -> Wei /// Migrate from unique `u32` reference counting to triple `u32` reference counting. pub fn migrate_from_single_to_triple_ref_count() -> Weight { let mut translated: usize = 0; - >::translate::<(V::Index, RefCount, V::AccountData), _>( + >::translate::<(V::Nonce, RefCount, V::AccountData), _>( |_key, (nonce, consumers, data)| { translated += 1; Some(AccountInfo { nonce, consumers, providers: 1, sufficients: 0, data }) @@ -106,7 +106,7 @@ pub fn migrate_from_single_to_triple_ref_count() -> Weight /// Migrate from dual `u32` reference counting to triple `u32` reference counting. pub fn migrate_from_dual_to_triple_ref_count() -> Weight { let mut translated: usize = 0; - >::translate::<(V::Index, RefCount, RefCount, V::AccountData), _>( + >::translate::<(V::Nonce, RefCount, RefCount, V::AccountData), _>( |_key, (nonce, consumers, providers, data)| { translated += 1; Some(AccountInfo { nonce, consumers, providers, sufficients: 0, data }) diff --git a/frame/system/src/mock.rs b/frame/system/src/mock.rs index cb9bbcb246a10..c016ea9e1cd14 100644 --- a/frame/system/src/mock.rs +++ b/frame/system/src/mock.rs @@ -91,7 +91,7 @@ impl Config for Test { type BlockLength = RuntimeBlockLength; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; diff --git a/frame/system/src/offchain.rs b/frame/system/src/offchain.rs index 742146d1642c8..313a557c44d76 100644 --- a/frame/system/src/offchain.rs +++ b/frame/system/src/offchain.rs @@ -486,7 +486,7 @@ pub trait CreateSignedTransaction: call: Self::OverarchingCall, public: Self::Public, account: Self::AccountId, - nonce: Self::Index, + nonce: Self::Nonce, ) -> Option<(Self::OverarchingCall, ::SignaturePayload)>; } diff --git a/frame/timestamp/src/mock.rs b/frame/timestamp/src/mock.rs index 00e9e0b17c720..418d257b3f005 100644 --- a/frame/timestamp/src/mock.rs +++ b/frame/timestamp/src/mock.rs @@ -48,7 +48,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/tips/src/tests.rs b/frame/tips/src/tests.rs index 3abbe5428f1d8..a700892d42703 100644 --- a/frame/tips/src/tests.rs +++ b/frame/tips/src/tests.rs @@ -59,7 +59,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/transaction-payment/asset-conversion-tx-payment/src/mock.rs b/frame/transaction-payment/asset-conversion-tx-payment/src/mock.rs index 683b93ad1f3fe..bfbe8b4178cee 100644 --- a/frame/transaction-payment/asset-conversion-tx-payment/src/mock.rs +++ b/frame/transaction-payment/asset-conversion-tx-payment/src/mock.rs @@ -84,7 +84,7 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/transaction-payment/asset-tx-payment/src/mock.rs b/frame/transaction-payment/asset-tx-payment/src/mock.rs index fbc70c118da7b..b8d7b523ca258 100644 --- a/frame/transaction-payment/asset-tx-payment/src/mock.rs +++ b/frame/transaction-payment/asset-tx-payment/src/mock.rs @@ -76,7 +76,7 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/transaction-payment/src/mock.rs b/frame/transaction-payment/src/mock.rs index 6d9c8c5d1d210..97253be463058 100644 --- a/frame/transaction-payment/src/mock.rs +++ b/frame/transaction-payment/src/mock.rs @@ -75,7 +75,7 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/transaction-storage/src/mock.rs b/frame/transaction-storage/src/mock.rs index 94705cd9340bd..243e26b559053 100644 --- a/frame/transaction-storage/src/mock.rs +++ b/frame/transaction-storage/src/mock.rs @@ -48,7 +48,7 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; diff --git a/frame/treasury/src/tests.rs b/frame/treasury/src/tests.rs index 39db42a22a382..79497d55867d6 100644 --- a/frame/treasury/src/tests.rs +++ b/frame/treasury/src/tests.rs @@ -54,7 +54,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; diff --git a/frame/uniques/src/mock.rs b/frame/uniques/src/mock.rs index 6ff7278cce8aa..5c44a7ed7a539 100644 --- a/frame/uniques/src/mock.rs +++ b/frame/uniques/src/mock.rs @@ -47,7 +47,7 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; diff --git a/frame/utility/src/tests.rs b/frame/utility/src/tests.rs index 3587b55762b7c..c2fd3a851c319 100644 --- a/frame/utility/src/tests.rs +++ b/frame/utility/src/tests.rs @@ -150,7 +150,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/frame/vesting/src/mock.rs b/frame/vesting/src/mock.rs index c569ec96b99e0..fe1779475a69a 100644 --- a/frame/vesting/src/mock.rs +++ b/frame/vesting/src/mock.rs @@ -52,7 +52,7 @@ impl frame_system::Config for Test { type Hash = H256; type Hashing = BlakeTwo256; type Block = Block; - type Index = u64; + type Nonce = u64; type Lookup = IdentityLookup; type OnKilledAccount = (); type OnNewAccount = (); diff --git a/frame/whitelist/src/mock.rs b/frame/whitelist/src/mock.rs index 3b25cdd4d14ae..d91f43b33af91 100644 --- a/frame/whitelist/src/mock.rs +++ b/frame/whitelist/src/mock.rs @@ -50,7 +50,7 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; diff --git a/primitives/api/proc-macro/src/runtime_metadata.rs b/primitives/api/proc-macro/src/runtime_metadata.rs index 458248cbd3d16..d027e86fac4ef 100644 --- a/primitives/api/proc-macro/src/runtime_metadata.rs +++ b/primitives/api/proc-macro/src/runtime_metadata.rs @@ -30,13 +30,13 @@ use crate::{ /// Get the type parameter argument without lifetime or mutability /// of a runtime metadata function. /// -/// In the following example, both the `AccountId` and `Index` generic +/// In the following example, both the `AccountId` and `Nonce` generic /// type parameters must implement `scale_info::TypeInfo` because they /// are added into the metadata using `scale_info::meta_type`. /// /// ```ignore -/// trait ExampleAccountNonceApi { -/// fn account_nonce<'a>(account: &'a AccountId) -> Index; +/// trait ExampleAccountNonceApi { +/// fn account_nonce<'a>(account: &'a AccountId) -> Nonce; /// } /// ``` /// diff --git a/primitives/test-primitives/src/lib.rs b/primitives/test-primitives/src/lib.rs index 913cb762d92a5..82bdb6967b842 100644 --- a/primitives/test-primitives/src/lib.rs +++ b/primitives/test-primitives/src/lib.rs @@ -71,7 +71,7 @@ pub type Hash = H256; /// The block number type used in this runtime. pub type BlockNumber = u64; /// Index of a transaction. -pub type Index = u64; +pub type Nonce = u64; /// The item of a block digest. pub type DigestItem = sp_runtime::generic::DigestItem; /// The digest of a block. diff --git a/test-utils/runtime/src/extrinsic.rs b/test-utils/runtime/src/extrinsic.rs index a6e13226face0..05ffb7db5d5b9 100644 --- a/test-utils/runtime/src/extrinsic.rs +++ b/test-utils/runtime/src/extrinsic.rs @@ -19,7 +19,7 @@ use crate::{ substrate_test_pallet::pallet::Call as PalletCall, AccountId, Balance, BalancesCall, - CheckSubstrateCall, Extrinsic, Index, Pair, RuntimeCall, SignedPayload, TransferData, + CheckSubstrateCall, Extrinsic, Nonce, Pair, RuntimeCall, SignedPayload, TransferData, }; use codec::Encode; use frame_system::{CheckNonce, CheckWeight}; @@ -81,7 +81,7 @@ impl TryFrom<&Extrinsic> for TransferData { pub struct ExtrinsicBuilder { function: RuntimeCall, signer: Option, - nonce: Option, + nonce: Option, } impl ExtrinsicBuilder { @@ -176,7 +176,7 @@ impl ExtrinsicBuilder { } /// Given `nonce` will be set in `Extrinsic` - pub fn nonce(mut self, nonce: Index) -> Self { + pub fn nonce(mut self, nonce: Nonce) -> Self { self.nonce = Some(nonce); self } diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index 6ba4e9939e408..ee391a6ec2147 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -130,7 +130,7 @@ pub struct TransferData { pub from: AccountId, pub to: AccountId, pub amount: Balance, - pub nonce: Index, + pub nonce: Nonce, } /// The address format for describing accounts. @@ -156,7 +156,7 @@ pub type Hashing = BlakeTwo256; /// The block number type used in this runtime. pub type BlockNumber = u64; /// Index of a transaction. -pub type Index = u64; +pub type Nonce = u64; /// The item of a block digest. pub type DigestItem = sp_runtime::generic::DigestItem; /// The digest of a block. @@ -345,7 +345,7 @@ impl frame_system::pallet::Config for Runtime { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = Index; + type Nonce = Nonce; type Hash = H256; type Hashing = Hashing; type AccountId = AccountId; @@ -526,8 +526,8 @@ impl_runtime_apis! { } } - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Index { + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Nonce { System::account_nonce(account) } } diff --git a/test-utils/runtime/transaction-pool/src/lib.rs b/test-utils/runtime/transaction-pool/src/lib.rs index 8e28449661650..7b52920044027 100644 --- a/test-utils/runtime/transaction-pool/src/lib.rs +++ b/test-utils/runtime/transaction-pool/src/lib.rs @@ -36,7 +36,7 @@ use sp_runtime::{ use std::collections::{BTreeMap, HashMap, HashSet}; use substrate_test_runtime_client::{ runtime::{ - AccountId, Block, BlockNumber, Extrinsic, ExtrinsicBuilder, Hash, Header, Index, Transfer, + AccountId, Block, BlockNumber, Extrinsic, ExtrinsicBuilder, Hash, Header, Nonce, Transfer, TransferData, }, AccountKeyring::{self, *}, @@ -377,7 +377,7 @@ impl sp_blockchain::HeaderMetadata for TestApi { /// Generate transfer extrinsic with a given nonce. /// /// Part of the test api. -pub fn uxt(who: AccountKeyring, nonce: Index) -> Extrinsic { +pub fn uxt(who: AccountKeyring, nonce: Nonce) -> Extrinsic { let dummy = codec::Decode::decode(&mut TrailingZeroInput::zeroes()).unwrap(); let transfer = Transfer { from: who.into(), to: dummy, nonce, amount: 1 }; ExtrinsicBuilder::new_transfer(transfer).build() diff --git a/utils/frame/rpc/support/src/lib.rs b/utils/frame/rpc/support/src/lib.rs index 29d49b44b74a3..2d8e45cbfc69f 100644 --- a/utils/frame/rpc/support/src/lib.rs +++ b/utils/frame/rpc/support/src/lib.rs @@ -55,7 +55,7 @@ use sp_storage::{StorageData, StorageKey}; /// # type BlockLength = (); /// # type RuntimeOrigin = RuntimeOrigin; /// # type RuntimeCall = RuntimeCall; -/// # type Index = u64; +/// # type Nonce = u64; /// # type Hash = Hash; /// # type Hashing = BlakeTwo256; /// # type AccountId = u64; diff --git a/utils/frame/rpc/system/src/lib.rs b/utils/frame/rpc/system/src/lib.rs index 26efa02970efe..1eff71e3390a3 100644 --- a/utils/frame/rpc/system/src/lib.rs +++ b/utils/frame/rpc/system/src/lib.rs @@ -38,14 +38,14 @@ pub use frame_system_rpc_runtime_api::AccountNonceApi; /// System RPC methods. #[rpc(client, server)] -pub trait SystemApi { +pub trait SystemApi { /// Returns the next valid index (aka nonce) for given account. /// /// This method takes into consideration all pending transactions /// currently in the pool and if no transactions are found in the pool /// it fallbacks to query the index from the runtime (aka. state nonce). #[method(name = "system_accountNextIndex", aliases = ["account_nextIndex"])] - async fn nonce(&self, account: AccountId) -> RpcResult; + async fn nonce(&self, account: AccountId) -> RpcResult; /// Dry run an extrinsic at a given block. Return SCALE encoded ApplyExtrinsicResult. #[method(name = "system_dryRun", aliases = ["system_dryRunAt"])] @@ -85,20 +85,20 @@ impl System { } #[async_trait] -impl - SystemApiServer<::Hash, AccountId, Index> for System +impl + SystemApiServer<::Hash, AccountId, Nonce> for System where C: sp_api::ProvideRuntimeApi, C: HeaderBackend, C: Send + Sync + 'static, - C::Api: AccountNonceApi, + C::Api: AccountNonceApi, C::Api: BlockBuilder, P: TransactionPool + 'static, Block: traits::Block, AccountId: Clone + Display + Codec + Send + 'static, - Index: Clone + Display + Codec + Send + traits::AtLeast32Bit + 'static, + Nonce: Clone + Display + Codec + Send + traits::AtLeast32Bit + 'static, { - async fn nonce(&self, account: AccountId) -> RpcResult { + async fn nonce(&self, account: AccountId) -> RpcResult { let api = self.client.runtime_api(); let best = self.client.info().best_hash; @@ -176,11 +176,11 @@ where /// Adjust account nonce from state, so that tx with the nonce will be /// placed after all ready txpool transactions. -fn adjust_nonce(pool: &P, account: AccountId, nonce: Index) -> Index +fn adjust_nonce(pool: &P, account: AccountId, nonce: Nonce) -> Nonce where P: TransactionPool, AccountId: Clone + std::fmt::Display + Encode, - Index: Clone + std::fmt::Display + Encode + traits::AtLeast32Bit + 'static, + Nonce: Clone + std::fmt::Display + Encode + traits::AtLeast32Bit + 'static, { log::debug!(target: "rpc", "State nonce for {}: {}", account, nonce); // Now we need to query the transaction pool From 5bbdcfd1befc9686c5aa522bc6a3ea150dbf6801 Mon Sep 17 00:00:00 2001 From: Aten Jin Date: Fri, 14 Jul 2023 18:07:07 +0800 Subject: [PATCH 29/39] do not filter word `www` in `is_node_name_valid` check (#14575) --- client/cli/src/commands/run_cmd.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/client/cli/src/commands/run_cmd.rs b/client/cli/src/commands/run_cmd.rs index 975f7638191ea..2942cfac4c7a3 100644 --- a/client/cli/src/commands/run_cmd.rs +++ b/client/cli/src/commands/run_cmd.rs @@ -404,7 +404,7 @@ pub fn is_node_name_valid(_name: &str) -> std::result::Result<(), &str> { return Err("Node name should not contain invalid chars such as '.' and '@'") } - let invalid_patterns = r"(https?:\\/+)?(www)+"; + let invalid_patterns = r"^https?:\/\/"; let re = Regex::new(invalid_patterns).unwrap(); if re.is_match(&name) { return Err("Node name should not contain urls") @@ -490,6 +490,10 @@ mod tests { #[test] fn tests_node_name_good() { assert!(is_node_name_valid("short name").is_ok()); + assert!(is_node_name_valid("www").is_ok()); + assert!(is_node_name_valid("aawww").is_ok()); + assert!(is_node_name_valid("wwwaa").is_ok()); + assert!(is_node_name_valid("www aa").is_ok()); } #[test] @@ -502,6 +506,8 @@ mod tests { assert!(is_node_name_valid("http://visit.me").is_err()); assert!(is_node_name_valid("https://visit.me").is_err()); assert!(is_node_name_valid("www.visit.me").is_err()); + assert!(is_node_name_valid("www.visit").is_err()); + assert!(is_node_name_valid("visit.www").is_err()); assert!(is_node_name_valid("email@domain").is_err()); } } From b06e109177e45ec2c54822a97487eefaf2facf24 Mon Sep 17 00:00:00 2001 From: Vsevolod Stakhov Date: Fri, 14 Jul 2023 11:47:38 +0100 Subject: [PATCH 30/39] Remove redundant sync primitives for metrics (#14564) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Remove redundant locks * Re-enable warning for a sender when a queue got processed * Apply suggestions from code review Co-authored-by: Bastian Köcher Co-authored-by: Anton * Use debug for subsequent logging * Update client/network/src/service/out_events.rs Co-authored-by: Bastian Köcher --------- Co-authored-by: Bastian Köcher Co-authored-by: Anton Co-authored-by: parity-processbot <> --- client/network/src/service/out_events.rs | 103 ++++++++++++++--------- 1 file changed, 64 insertions(+), 39 deletions(-) diff --git a/client/network/src/service/out_events.rs b/client/network/src/service/out_events.rs index 398c26793fd41..ededccd5e3233 100644 --- a/client/network/src/service/out_events.rs +++ b/client/network/src/service/out_events.rs @@ -34,37 +34,48 @@ use crate::event::Event; use futures::{prelude::*, ready, stream::FusedStream}; -use log::error; -use parking_lot::Mutex; +use log::{debug, error}; use prometheus_endpoint::{register, CounterVec, GaugeVec, Opts, PrometheusError, Registry, U64}; use std::{ backtrace::Backtrace, cell::RefCell, fmt, pin::Pin, - sync::Arc, task::{Context, Poll}, }; +/// Log target for this file. +pub const LOG_TARGET: &str = "sub-libp2p::out_events"; + /// Creates a new channel that can be associated to a [`OutChannels`]. /// /// The name is used in Prometheus reports, the queue size threshold is used /// to warn if there are too many unprocessed events in the channel. pub fn channel(name: &'static str, queue_size_warning: usize) -> (Sender, Receiver) { let (tx, rx) = async_channel::unbounded(); - let metrics = Arc::new(Mutex::new(None)); let tx = Sender { inner: tx, name, queue_size_warning, - warning_fired: false, + warning_fired: SenderWarningState::NotFired, creation_backtrace: Backtrace::force_capture(), - metrics: metrics.clone(), + metrics: None, }; - let rx = Receiver { inner: rx, name, metrics }; + let rx = Receiver { inner: rx, name, metrics: None }; (tx, rx) } +/// A state of a sender warning that is used to avoid spamming the logs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum SenderWarningState { + /// The warning has not been fired yet. + NotFired, + /// The warning has been fired, and the channel is full + FiredFull, + /// The warning has been fired and the channel is not full anymore. + FiredFree, +} + /// Sending side of a channel. /// /// Must be associated with an [`OutChannels`] before anything can be sent on it @@ -78,13 +89,14 @@ pub struct Sender { name: &'static str, /// Threshold queue size to generate an error message in the logs. queue_size_warning: usize, - /// We generate the error message only once to not spam the logs. - warning_fired: bool, + /// We generate the error message only once to not spam the logs after the first error. + /// Subsequently we indicate channel fullness on debug level. + warning_fired: SenderWarningState, /// Backtrace of a place where the channel was created. creation_backtrace: Backtrace, /// Clone of [`Receiver::metrics`]. Will be initialized when [`Sender`] is added to /// [`OutChannels`] with `OutChannels::push()`. - metrics: Arc>>>>, + metrics: Option, } impl fmt::Debug for Sender { @@ -95,8 +107,7 @@ impl fmt::Debug for Sender { impl Drop for Sender { fn drop(&mut self) { - let metrics = self.metrics.lock(); - if let Some(Some(metrics)) = metrics.as_ref().map(|m| &**m) { + if let Some(metrics) = self.metrics.as_ref() { metrics.num_channels.with_label_values(&[self.name]).dec(); } } @@ -108,7 +119,7 @@ pub struct Receiver { name: &'static str, /// Initially contains `None`, and will be set to a value once the corresponding [`Sender`] /// is assigned to an instance of [`OutChannels`]. - metrics: Arc>>>>, + metrics: Option, } impl Stream for Receiver { @@ -116,13 +127,8 @@ impl Stream for Receiver { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> { if let Some(ev) = ready!(Pin::new(&mut self.inner).poll_next(cx)) { - let metrics = self.metrics.lock().clone(); - match metrics.as_ref().map(|m| m.as_ref()) { - Some(Some(metrics)) => metrics.event_out(&ev, self.name), - Some(None) => (), // no registry - None => log::warn!( - "Inconsistency in out_events: event happened before sender associated" - ), + if let Some(metrics) = &self.metrics { + metrics.event_out(&ev, self.name); } Poll::Ready(Some(ev)) } else { @@ -151,7 +157,7 @@ pub struct OutChannels { event_streams: Vec, /// The metrics we collect. A clone of this is sent to each [`Receiver`] associated with this /// object. - metrics: Arc>, + metrics: Option, } impl OutChannels { @@ -160,17 +166,15 @@ impl OutChannels { let metrics = if let Some(registry) = registry { Some(Metrics::register(registry)?) } else { None }; - Ok(Self { event_streams: Vec::new(), metrics: Arc::new(metrics) }) + Ok(Self { event_streams: Vec::new(), metrics }) } /// Adds a new [`Sender`] to the collection. - pub fn push(&mut self, sender: Sender) { - let mut metrics = sender.metrics.lock(); - debug_assert!(metrics.is_none()); - *metrics = Some(self.metrics.clone()); - drop(metrics); + pub fn push(&mut self, mut sender: Sender) { + debug_assert!(sender.metrics.is_none()); + sender.metrics = self.metrics.clone(); - if let Some(metrics) = &*self.metrics { + if let Some(metrics) = &self.metrics { metrics.num_channels.with_label_values(&[sender.name]).inc(); } @@ -180,22 +184,42 @@ impl OutChannels { /// Sends an event. pub fn send(&mut self, event: Event) { self.event_streams.retain_mut(|sender| { - if sender.inner.len() >= sender.queue_size_warning && !sender.warning_fired { - sender.warning_fired = true; - error!( - "The number of unprocessed events in channel `{}` exceeded {}.\n\ - The channel was created at:\n{:}\n - The last event was sent from:\n{:}", - sender.name, - sender.queue_size_warning, - sender.creation_backtrace, - Backtrace::force_capture(), + let current_pending = sender.inner.len(); + if current_pending >= sender.queue_size_warning { + if sender.warning_fired == SenderWarningState::NotFired { + error!( + "The number of unprocessed events in channel `{}` exceeded {}.\n\ + The channel was created at:\n{:}\n + The last event was sent from:\n{:}", + sender.name, + sender.queue_size_warning, + sender.creation_backtrace, + Backtrace::force_capture(), + ); + } else if sender.warning_fired == SenderWarningState::FiredFree { + // We don't want to spam the logs, so we only log on debug level + debug!( + target: LOG_TARGET, + "Channel `{}` is overflowed again. Number of events: {}", + sender.name, current_pending + ); + } + sender.warning_fired = SenderWarningState::FiredFull; + } else if sender.warning_fired == SenderWarningState::FiredFull && + current_pending < sender.queue_size_warning.wrapping_div(2) + { + sender.warning_fired = SenderWarningState::FiredFree; + debug!( + target: LOG_TARGET, + "Channel `{}` is no longer overflowed. Number of events: {}", + sender.name, current_pending ); } + sender.inner.try_send(event.clone()).is_ok() }); - if let Some(metrics) = &*self.metrics { + if let Some(metrics) = &self.metrics { for ev in &self.event_streams { metrics.event_in(&event, ev.name); } @@ -211,6 +235,7 @@ impl fmt::Debug for OutChannels { } } +#[derive(Clone)] struct Metrics { // This list is ordered alphabetically events_total: CounterVec, From a7f365281a6044e4891bf04af825aa1eb58c0089 Mon Sep 17 00:00:00 2001 From: Marijn Schouten <122525541+deepink-mas@users.noreply.github.com> Date: Fri, 14 Jul 2023 14:43:24 +0200 Subject: [PATCH 31/39] change $location from tt* to ty and remove unnecessary cb_* versions (#14571) * change $location from tt* to ty and remove unnecessary cb_* versions * fmt * ".git/.scripts/commands/bench/bench.sh" pallet dev pallet_balances --------- Co-authored-by: Liam Aharon Co-authored-by: parity-processbot <> --- frame/balances/src/weights.rs | 81 +++++++++++++++++------------------ frame/benchmarking/src/v1.rs | 58 ++++++------------------- 2 files changed, 53 insertions(+), 86 deletions(-) diff --git a/frame/balances/src/weights.rs b/frame/balances/src/weights.rs index d394666a40923..5671374948cdf 100644 --- a/frame/balances/src/weights.rs +++ b/frame/balances/src/weights.rs @@ -18,10 +18,10 @@ //! Autogenerated weights for pallet_balances //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-07-07, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-07-14, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-xerhrdyb-project-145-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` -//! EXECUTION: `Some(Wasm)`, WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! HOSTNAME: `runner-o7yfgx5n-project-145-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: // target/production/substrate @@ -30,11 +30,10 @@ // --steps=50 // --repeat=20 // --extrinsic=* -// --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 // --json-file=/builds/parity/mirrors/substrate/.git/.artifacts/bench.json -// --pallet=pallet-balances +// --pallet=pallet_balances // --chain=dev // --header=./HEADER-APACHE2 // --output=./frame/balances/src/weights.rs @@ -69,8 +68,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 58_450_000 picoseconds. - Weight::from_parts(59_566_000, 3593) + // Minimum execution time: 58_474_000 picoseconds. + Weight::from_parts(59_117_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -80,8 +79,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 44_753_000 picoseconds. - Weight::from_parts(46_235_000, 3593) + // Minimum execution time: 44_629_000 picoseconds. + Weight::from_parts(45_798_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -91,8 +90,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 16_771_000 picoseconds. - Weight::from_parts(17_172_000, 3593) + // Minimum execution time: 16_483_000 picoseconds. + Weight::from_parts(16_939_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -102,8 +101,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 24_196_000 picoseconds. - Weight::from_parts(24_925_000, 3593) + // Minimum execution time: 24_638_000 picoseconds. + Weight::from_parts(25_487_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -113,8 +112,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `103` // Estimated: `6196` - // Minimum execution time: 60_133_000 picoseconds. - Weight::from_parts(61_069_000, 6196) + // Minimum execution time: 60_041_000 picoseconds. + Weight::from_parts(63_365_000, 6196) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -124,8 +123,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 53_938_000 picoseconds. - Weight::from_parts(55_123_000, 3593) + // Minimum execution time: 54_445_000 picoseconds. + Weight::from_parts(55_623_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -135,8 +134,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 19_914_000 picoseconds. - Weight::from_parts(20_435_000, 3593) + // Minimum execution time: 19_309_000 picoseconds. + Weight::from_parts(19_953_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -147,10 +146,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0 + u * (135 ±0)` // Estimated: `990 + u * (2603 ±0)` - // Minimum execution time: 19_319_000 picoseconds. - Weight::from_parts(19_644_000, 990) - // Standard Error: 11_800 - .saturating_add(Weight::from_parts(16_340_188, 0).saturating_mul(u.into())) + // Minimum execution time: 19_362_000 picoseconds. + Weight::from_parts(19_612_000, 990) + // Standard Error: 13_108 + .saturating_add(Weight::from_parts(16_444_591, 0).saturating_mul(u.into())) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(u.into()))) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(u.into()))) .saturating_add(Weight::from_parts(0, 2603).saturating_mul(u.into())) @@ -165,8 +164,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 58_450_000 picoseconds. - Weight::from_parts(59_566_000, 3593) + // Minimum execution time: 58_474_000 picoseconds. + Weight::from_parts(59_117_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -176,8 +175,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 44_753_000 picoseconds. - Weight::from_parts(46_235_000, 3593) + // Minimum execution time: 44_629_000 picoseconds. + Weight::from_parts(45_798_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -187,8 +186,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 16_771_000 picoseconds. - Weight::from_parts(17_172_000, 3593) + // Minimum execution time: 16_483_000 picoseconds. + Weight::from_parts(16_939_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -198,8 +197,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 24_196_000 picoseconds. - Weight::from_parts(24_925_000, 3593) + // Minimum execution time: 24_638_000 picoseconds. + Weight::from_parts(25_487_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -209,8 +208,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `103` // Estimated: `6196` - // Minimum execution time: 60_133_000 picoseconds. - Weight::from_parts(61_069_000, 6196) + // Minimum execution time: 60_041_000 picoseconds. + Weight::from_parts(63_365_000, 6196) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -220,8 +219,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 53_938_000 picoseconds. - Weight::from_parts(55_123_000, 3593) + // Minimum execution time: 54_445_000 picoseconds. + Weight::from_parts(55_623_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -231,8 +230,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 19_914_000 picoseconds. - Weight::from_parts(20_435_000, 3593) + // Minimum execution time: 19_309_000 picoseconds. + Weight::from_parts(19_953_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -243,10 +242,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0 + u * (135 ±0)` // Estimated: `990 + u * (2603 ±0)` - // Minimum execution time: 19_319_000 picoseconds. - Weight::from_parts(19_644_000, 990) - // Standard Error: 11_800 - .saturating_add(Weight::from_parts(16_340_188, 0).saturating_mul(u.into())) + // Minimum execution time: 19_362_000 picoseconds. + Weight::from_parts(19_612_000, 990) + // Standard Error: 13_108 + .saturating_add(Weight::from_parts(16_444_591, 0).saturating_mul(u.into())) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(u.into()))) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(u.into()))) .saturating_add(Weight::from_parts(0, 2603).saturating_mul(u.into())) diff --git a/frame/benchmarking/src/v1.rs b/frame/benchmarking/src/v1.rs index 0e8368aa8bf9c..d9f1c7dde0059 100644 --- a/frame/benchmarking/src/v1.rs +++ b/frame/benchmarking/src/v1.rs @@ -1826,9 +1826,9 @@ pub fn show_benchmark_debug_info( /// ``` #[macro_export] macro_rules! add_benchmark { - ( $params:ident, $batches:ident, $name:path, $( $location:tt )* ) => ( + ( $params:ident, $batches:ident, $name:path, $location:ty ) => { let name_string = stringify!($name).as_bytes(); - let instance_string = stringify!( $( $location )* ).as_bytes(); + let instance_string = stringify!($location).as_bytes(); let (config, whitelist) = $params; let $crate::BenchmarkConfig { pallet, @@ -1838,7 +1838,7 @@ macro_rules! add_benchmark { internal_repeats, } = config; if &pallet[..] == &name_string[..] { - let benchmark_result = $( $location )*::run_benchmark( + let benchmark_result = <$location>::run_benchmark( &benchmark[..], &selected_components[..], whitelist, @@ -1855,9 +1855,7 @@ macro_rules! add_benchmark { $crate::str::from_utf8(benchmark) .expect("benchmark name is always a valid string!") ); - result.keys.insert(0, - (b"Benchmark Override".to_vec(), 0, 0, false) - ); + result.keys.insert(0, (b"Benchmark Override".to_vec(), 0, 0, false)); Some($crate::vec![result]) }, Err($crate::BenchmarkError::Stop(e)) => { @@ -1868,7 +1866,7 @@ macro_rules! add_benchmark { verify, e, ); - return Err(e.into()); + return Err(e.into()) }, Err($crate::BenchmarkError::Skip) => { $crate::log::error!( @@ -1886,9 +1884,9 @@ macro_rules! add_benchmark { ); Some(vec![$crate::BenchmarkResult { components: selected_components.clone(), - .. Default::default() + ..Default::default() }]) - } + }, }; if let Some(final_results) = final_results { @@ -1900,21 +1898,7 @@ macro_rules! add_benchmark { }); } } - ) -} - -/// Callback for `define_benchmarks` to call `add_benchmark`. -#[macro_export] -macro_rules! cb_add_benchmarks { - // anchor - ( $params:ident, $batches:ident, [ $name:path, $( $location:tt )* ] ) => { - $crate::add_benchmark!( $params, $batches, $name, $( $location )* ); }; - // recursion tail - ( $params:ident, $batches:ident, [ $name:path, $( $location:tt )* ] $([ $names:path, $( $locations:tt )* ])+ ) => { - $crate::cb_add_benchmarks!( $params, $batches, [ $name, $( $location )* ] ); - $crate::cb_add_benchmarks!( $params, $batches, $([ $names, $( $locations )* ])+ ); - } } /// This macro allows users to easily generate a list of benchmarks for the pallets configured @@ -1938,31 +1922,17 @@ macro_rules! cb_add_benchmarks { /// This should match what exists with the `add_benchmark!` macro. #[macro_export] macro_rules! list_benchmark { - ( $list:ident, $extra:ident, $name:path, $( $location:tt )* ) => ( + ( $list:ident, $extra:ident, $name:path, $location:ty ) => { let pallet_string = stringify!($name).as_bytes(); - let instance_string = stringify!( $( $location )* ).as_bytes(); - let benchmarks = $( $location )*::benchmarks($extra); + let instance_string = stringify!($location).as_bytes(); + let benchmarks = <$location>::benchmarks($extra); let pallet_benchmarks = BenchmarkList { pallet: pallet_string.to_vec(), instance: instance_string.to_vec(), benchmarks: benchmarks.to_vec(), }; $list.push(pallet_benchmarks) - ) -} - -/// Callback for `define_benchmarks` to call `list_benchmark`. -#[macro_export] -macro_rules! cb_list_benchmarks { - // anchor - ( $list:ident, $extra:ident, [ $name:path, $( $location:tt )* ] ) => { - $crate::list_benchmark!( $list, $extra, $name, $( $location )* ); }; - // recursion tail - ( $list:ident, $extra:ident, [ $name:path, $( $location:tt )* ] $([ $names:path, $( $locations:tt )* ])+ ) => { - $crate::cb_list_benchmarks!( $list, $extra, [ $name, $( $location )* ] ); - $crate::cb_list_benchmarks!( $list, $extra, $([ $names, $( $locations )* ])+ ); - } } /// Defines pallet configs that `add_benchmarks` and `list_benchmarks` use. @@ -1970,7 +1940,7 @@ macro_rules! cb_list_benchmarks { /// in `add_benchmark` and `list_benchmark`. #[macro_export] macro_rules! define_benchmarks { - ( $([ $names:path, $( $locations:tt )* ])* ) => { + ( $([ $names:path, $locations:ty ])* ) => { /// Calls `list_benchmark` with all configs from `define_benchmarks` /// and passes the first two parameters on. /// @@ -1981,7 +1951,7 @@ macro_rules! define_benchmarks { #[macro_export] macro_rules! list_benchmarks { ( $list:ident, $extra:ident ) => { - $crate::cb_list_benchmarks!( $list, $extra, $([ $names, $( $locations )* ])+ ); + $( $crate::list_benchmark!( $list, $extra, $names, $locations); )* } } @@ -1995,7 +1965,7 @@ macro_rules! define_benchmarks { #[macro_export] macro_rules! add_benchmarks { ( $params:ident, $batches:ident ) => { - $crate::cb_add_benchmarks!( $params, $batches, $([ $names, $( $locations )* ])+ ); + $( $crate::add_benchmark!( $params, $batches, $names, $locations ); )* } } } @@ -2007,8 +1977,6 @@ pub use benchmarks; pub use benchmarks_instance; pub use benchmarks_instance_pallet; pub use benchmarks_iter; -pub use cb_add_benchmarks; -pub use cb_list_benchmarks; pub use define_benchmarks; pub use impl_bench_case_tests; pub use impl_bench_name_tests; From 74ae05142849bdf2a816df38e80f419741b10dc6 Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Fri, 14 Jul 2023 14:49:47 +0200 Subject: [PATCH 32/39] Contracts add code_len to ContractsInfo (#14523) * add code_len to v12 * fix * Update frame/contracts/src/wasm/mod.rs * fix * fixes * rm test * add test back * fix * update test * Fix comments * fix build * del * fix clippy * fix * re-rename --- frame/contracts/src/migration/v12.rs | 3 +++ frame/contracts/src/tests.rs | 14 +++++----- frame/contracts/src/tests/pallet_dummy.rs | 33 +++++++++++++++++++++++ frame/contracts/src/wasm/mod.rs | 22 +++++---------- frame/contracts/src/wasm/prepare.rs | 6 +++-- 5 files changed, 54 insertions(+), 24 deletions(-) create mode 100644 frame/contracts/src/tests/pallet_dummy.rs diff --git a/frame/contracts/src/migration/v12.rs b/frame/contracts/src/migration/v12.rs index c7987075f54b4..4fb7ca76fea92 100644 --- a/frame/contracts/src/migration/v12.rs +++ b/frame/contracts/src/migration/v12.rs @@ -80,6 +80,7 @@ pub struct CodeInfo { #[codec(compact)] refcount: u64, determinism: Determinism, + code_len: u32, } #[storage_alias] @@ -177,6 +178,7 @@ impl MigrationStep for Migration { owner: old_info.owner, deposit, refcount: old_info.refcount, + code_len: code_len as u32, }; let amount = old_info.deposit.saturating_sub(info.deposit); @@ -221,6 +223,7 @@ impl MigrationStep for Migration { deposit: v.deposit, refcount: v.refcount, owner: v.owner, + code_len: module.code.len() as u32, }; (k, info) }) diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index b6755a69cc76f..b25487469ba0e 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -1,4 +1,5 @@ // This file is part of Substrate. +mod pallet_dummy; // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 @@ -68,6 +69,7 @@ frame_support::construct_runtime!( Utility: pallet_utility::{Pallet, Call, Storage, Event}, Contracts: pallet_contracts::{Pallet, Call, Storage, Event}, Proxy: pallet_proxy::{Pallet, Call, Storage, Event}, + Dummy: pallet_dummy } ); @@ -373,6 +375,8 @@ impl pallet_proxy::Config for Test { type AnnouncementDepositFactor = ConstU64<1>; } +impl pallet_dummy::Config for Test {} + parameter_types! { pub MySchedule: Schedule = { let schedule = >::default(); @@ -2999,7 +3003,7 @@ fn gas_estimation_call_runtime() { .unwrap() .account_id; - let addr_callee = Contracts::bare_instantiate( + Contracts::bare_instantiate( ALICE, min_balance * 100, GAS_LIMIT, @@ -3011,15 +3015,11 @@ fn gas_estimation_call_runtime() { CollectEvents::Skip, ) .result - .unwrap() - .account_id; + .unwrap(); // Call something trivial with a huge gas limit so that we can observe the effects // of pre-charging. This should create a difference between consumed and required. - let call = RuntimeCall::Balances(pallet_balances::Call::transfer_allow_death { - dest: addr_callee, - value: min_balance * 10, - }); + let call = RuntimeCall::Dummy(pallet_dummy::Call::overestimate_pre_charge {}); let result = Contracts::bare_call( ALICE, addr_caller.clone(), diff --git a/frame/contracts/src/tests/pallet_dummy.rs b/frame/contracts/src/tests/pallet_dummy.rs new file mode 100644 index 0000000000000..d84e34de06c8d --- /dev/null +++ b/frame/contracts/src/tests/pallet_dummy.rs @@ -0,0 +1,33 @@ +pub use pallet::*; + +#[frame_support::pallet(dev_mode)] +pub mod pallet { + use frame_support::{ + dispatch::{Pays, PostDispatchInfo}, + pallet_prelude::DispatchResultWithPostInfo, + weights::Weight, + }; + use frame_system::pallet_prelude::*; + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: frame_system::Config {} + + #[pallet::call] + impl Pallet { + /// Dummy function that overcharges the predispatch weight, allowing us to test the correct + /// values of [`ContractResult::gas_consumed`] and [`ContractResult::gas_required`] in + /// tests. + #[pallet::call_index(1)] + #[pallet::weight(Weight::from_parts(10_000_000, 0))] + pub fn overestimate_pre_charge(origin: OriginFor) -> DispatchResultWithPostInfo { + ensure_signed(origin)?; + Ok(PostDispatchInfo { + actual_weight: Some(Weight::from_parts(100, 0)), + pays_fee: Pays::Yes, + }) + } + } +} diff --git a/frame/contracts/src/wasm/mod.rs b/frame/contracts/src/wasm/mod.rs index aa37b6fea2c73..b975a39a81052 100644 --- a/frame/contracts/src/wasm/mod.rs +++ b/frame/contracts/src/wasm/mod.rs @@ -92,6 +92,8 @@ pub struct CodeInfo { /// to be run on-chain. Specifically, such a code can never be instantiated into a contract /// and can just be used through a delegate call. determinism: Determinism, + /// length of the code in bytes. + code_len: u32, } /// Defines the required determinism level of a wasm blob when either running or uploading code. @@ -268,15 +270,11 @@ impl WasmBlob { fn load_code( code_hash: CodeHash, gas_meter: &mut GasMeter, - ) -> Result, DispatchError> { - let max_code_len = T::MaxCodeLen::get(); - let charged = gas_meter.charge(CodeLoadToken(max_code_len))?; - + ) -> Result<(CodeVec, CodeInfo), DispatchError> { + let code_info = >::get(code_hash).ok_or(Error::::CodeNotFound)?; + gas_meter.charge(CodeLoadToken(code_info.code_len))?; let code = >::get(code_hash).ok_or(Error::::CodeNotFound)?; - let code_len = code.len() as u32; - gas_meter.adjust_gas(charged, CodeLoadToken(code_len)); - - Ok(code) + Ok((code, code_info)) } /// Create the module without checking the passed code. @@ -309,13 +307,7 @@ impl Executable for WasmBlob { code_hash: CodeHash, gas_meter: &mut GasMeter, ) -> Result { - let code = Self::load_code(code_hash, gas_meter)?; - // We store `code_info` at the same time as contract code, - // therefore this query shouldn't really fail. - // We consider its failure equal to `CodeNotFound`, as contract code without - // `code_info` is unusable in this pallet. - let code_info = >::get(code_hash).ok_or(Error::::CodeNotFound)?; - + let (code, code_info) = Self::load_code(code_hash, gas_meter)?; Ok(Self { code, code_info, code_hash }) } diff --git a/frame/contracts/src/wasm/prepare.rs b/frame/contracts/src/wasm/prepare.rs index ee89aae642b4a..7deccdde7a069 100644 --- a/frame/contracts/src/wasm/prepare.rs +++ b/frame/contracts/src/wasm/prepare.rs @@ -286,11 +286,12 @@ where validate::(code.as_ref(), schedule, determinism)?; // Calculate deposit for storing contract code and `code_info` in two different storage items. - let bytes_added = code.len().saturating_add(>::max_encoded_len()) as u32; + let code_len = code.len() as u32; + let bytes_added = code_len.saturating_add(>::max_encoded_len() as u32); let deposit = Diff { bytes_added, items_added: 2, ..Default::default() } .update_contract::(None) .charge_or_zero(); - let code_info = CodeInfo { owner, deposit, determinism, refcount: 0 }; + let code_info = CodeInfo { owner, deposit, determinism, refcount: 0, code_len }; let code_hash = T::Hashing::hash(&code); Ok(WasmBlob { code, code_info, code_hash }) @@ -320,6 +321,7 @@ pub mod benchmarking { // this is a helper function for benchmarking which skips deposit collection deposit: Default::default(), refcount: 0, + code_len: code.len() as u32, determinism, }; let code_hash = T::Hashing::hash(&code); From 5a7003b5bafb1343adaa47fc1d25ab1097b92836 Mon Sep 17 00:00:00 2001 From: Jacob T Firek <106350168+jtfirek@users.noreply.github.com> Date: Fri, 14 Jul 2023 12:39:07 -0700 Subject: [PATCH 33/39] fixing return types in crypto module documentation (#14554) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fixing return types in documentation * Apply suggestions from code review --------- Co-authored-by: Bastian Köcher --- primitives/core/src/crypto.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/primitives/core/src/crypto.rs b/primitives/core/src/crypto.rs index 800942065f558..72f996b336832 100644 --- a/primitives/core/src/crypto.rs +++ b/primitives/core/src/crypto.rs @@ -872,7 +872,7 @@ pub trait Pair: CryptoType + Sized + Clone + Send + Sync + 'static { (pair, phrase.to_owned(), seed) } - /// Returns the KeyPair from the English BIP39 seed `phrase`, or `None` if it's invalid. + /// Returns the KeyPair from the English BIP39 seed `phrase`, or an error if it's invalid. #[cfg(feature = "std")] fn from_phrase( phrase: &str, @@ -907,7 +907,7 @@ pub trait Pair: CryptoType + Sized + Clone + Send + Sync + 'static { } /// Make a new key pair from secret seed material. The slice must be the correct size or - /// it will return `None`. + /// an error will be returned. /// /// @WARNING: THIS WILL ONLY BE SECURE IF THE `seed` IS SECURE. If it can be guessed /// by an attacker then they can also derive your key. @@ -949,8 +949,6 @@ pub trait Pair: CryptoType + Sized + Clone + Send + Sync + 'static { /// Notably, integer junction indices may be legally prefixed with arbitrary number of zeros. /// Similarly an empty password (ending the SURI with `///`) is perfectly valid and will /// generally be equivalent to no password at all. - /// - /// `None` is returned if no matches are found. #[cfg(feature = "std")] fn from_string_with_seed( s: &str, From 75b962d721c1f31991da9072e424424eb22c7316 Mon Sep 17 00:00:00 2001 From: Kian Paimani <5588131+kianenigma@users.noreply.github.com> Date: Mon, 17 Jul 2023 11:36:37 +0200 Subject: [PATCH 34/39] basic improvements to sp-runtime docs (#14583) --- primitives/runtime/src/generic/mod.rs | 5 ++--- primitives/runtime/src/lib.rs | 27 ++++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/primitives/runtime/src/generic/mod.rs b/primitives/runtime/src/generic/mod.rs index d9eee7fee8b20..3687f7cdb3b2b 100644 --- a/primitives/runtime/src/generic/mod.rs +++ b/primitives/runtime/src/generic/mod.rs @@ -15,9 +15,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -// tag::description[] -//! Generic implementations of Extrinsic/Header/Block. -// end::description[] +//! Generic implementations of [`crate::traits::Header`], [`crate::traits::Block`] and +//! [`crate::traits::Extrinsic`]. mod block; mod checked_extrinsic; diff --git a/primitives/runtime/src/lib.rs b/primitives/runtime/src/lib.rs index e2f890a46b3db..dd861ad05de9b 100644 --- a/primitives/runtime/src/lib.rs +++ b/primitives/runtime/src/lib.rs @@ -15,7 +15,32 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Runtime Modules shared primitive types. +//! # Substrate Runtime Primitives. +//! +//! This crate, among other things, contains a large library of types and utilities that are used in +//! the Substrate runtime, but are not particularly `FRAME`-oriented. +//! +//! ## Block, Header and Extrinsics +//! +//! Most notable, this crate contains some of the types and trait that enable important +//! communication between the client and the runtime. This includes: +//! +//! - A set of traits to declare what any block/header/extrinsic type should provide. +//! - [`traits::Block`], [`traits::Header`], [`traits::Extrinsic`] +//! - A set of types that implement these traits, whilst still providing a high degree of +//! configurability via generics. +//! - [`generic::Block`], [`generic::Header`], [`generic::UncheckedExtrinsic`] and +//! [`generic::CheckedExtrinsic`] +//! +//! ## Runtime API Types +//! +//! This crate also contains some types that are often used in conjuncture with Runtime APIs. Most +//! notable: +//! +//! - [`ApplyExtrinsicResult`], and [`DispatchOutcome`], which dictate how the client and runtime +//! communicate about the success or failure of an extrinsic. +//! - [`transaction_validity`], which dictates how the client and runtime communicate about the +//! validity of an extrinsic while still in the transaction-queue. #![warn(missing_docs)] #![cfg_attr(not(feature = "std"), no_std)] From f9e67cda1b286e9ab1e93f3895d5c22da89e9159 Mon Sep 17 00:00:00 2001 From: Kian Paimani <5588131+kianenigma@users.noreply.github.com> Date: Mon, 17 Jul 2023 12:37:01 +0200 Subject: [PATCH 35/39] improve pallet hooks docs (#14578) * improve pallet hooks docs * Update frame/support/src/traits/hooks.rs Co-authored-by: Sam Johnson * Update frame/support/src/traits/hooks.rs Co-authored-by: Sam Johnson * Update frame/support/src/traits/hooks.rs Co-authored-by: Sam Johnson * fix mastekn removal * Apply suggestions from code review Co-authored-by: Juan * add diagram * fix all links * fix diagram * improve diagram with some notes * update --------- Co-authored-by: Sam Johnson Co-authored-by: parity-processbot <> Co-authored-by: Juan --- Cargo.lock | 34 ++++ frame/support/Cargo.toml | 2 + frame/support/src/traits/hooks.rs | 273 +++++++++++++++++------------- 3 files changed, 196 insertions(+), 113 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b975b4c32b034..ba5b855db9a65 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -273,6 +273,20 @@ dependencies = [ "num-traits", ] +[[package]] +name = "aquamarine" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df752953c49ce90719c7bf1fc587bc8227aed04732ea0c0f85e5397d7fdbd1a1" +dependencies = [ + "include_dir", + "itertools", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "arbitrary" version = "1.3.0" @@ -2801,6 +2815,7 @@ dependencies = [ name = "frame-support" version = "4.0.0-dev" dependencies = [ + "aquamarine", "array-bytes", "assert_matches", "bitflags", @@ -3694,6 +3709,25 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "include_dir" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18762faeff7122e89e0857b02f7ce6fcc0d101d5e9ad2ad7846cc01d61b7f19e" +dependencies = [ + "include_dir_macros", +] + +[[package]] +name = "include_dir_macros" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b139284b5cf57ecfa712bcc66950bb635b31aff41c188e8a4cfc758eca374a3f" +dependencies = [ + "proc-macro2", + "quote", +] + [[package]] name = "indexmap" version = "1.9.3" diff --git a/frame/support/Cargo.toml b/frame/support/Cargo.toml index bfcb821b8c8e4..f483c632a9698 100644 --- a/frame/support/Cargo.toml +++ b/frame/support/Cargo.toml @@ -41,6 +41,8 @@ sp-core-hashing-proc-macro = { version = "9.0.0", path = "../../primitives/core/ k256 = { version = "0.13.0", default-features = false, features = ["ecdsa"] } environmental = { version = "1.1.4", default-features = false } +aquamarine = { version = "0.3.2" } + [dev-dependencies] serde_json = "1.0.85" assert_matches = "1.3.0" diff --git a/frame/support/src/traits/hooks.rs b/frame/support/src/traits/hooks.rs index 58da1ad569929..b612363f42e3f 100644 --- a/frame/support/src/traits/hooks.rs +++ b/frame/support/src/traits/hooks.rs @@ -15,7 +15,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Traits for hooking tasks to events in a blockchain's lifecycle. +//! Traits relating to pallet hooks. +//! +//! See [`Hooks`] as the main entry-point. + +#![deny(missing_docs)] use crate::weights::Weight; use impl_trait_for_tuples::impl_for_tuples; @@ -25,18 +29,9 @@ use sp_std::prelude::*; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; -/// The block initialization trait. -/// -/// Implementing this lets you express what should happen for your pallet when the block is -/// beginning (right before the first extrinsic is executed). +/// See [`Hooks::on_initialize`]. pub trait OnInitialize { - /// The block is being initialized. Implement to have something happen. - /// - /// Return the non-negotiable weight consumed in the block. - /// - /// NOTE: This function is called BEFORE ANY extrinsic in a block is applied, - /// including inherent extrinsics. Hence for instance, if you runtime includes - /// `pallet_timestamp`, the `timestamp` is not yet up to date at this point. + /// See [`Hooks::on_initialize`]. fn on_initialize(_n: BlockNumber) -> Weight { Weight::zero() } @@ -53,32 +48,18 @@ impl OnInitialize for Tuple { } } -/// The block finalization trait. -/// -/// Implementing this lets you express what should happen for your pallet when the block is ending. +/// See [`Hooks::on_finalize`]. #[cfg_attr(all(not(feature = "tuples-96"), not(feature = "tuples-128")), impl_for_tuples(64))] #[cfg_attr(all(feature = "tuples-96", not(feature = "tuples-128")), impl_for_tuples(96))] #[cfg_attr(feature = "tuples-128", impl_for_tuples(128))] pub trait OnFinalize { - /// The block is being finalized. Implement to have something happen. - /// - /// NOTE: This function is called AFTER ALL extrinsics in a block are applied, - /// including inherent extrinsics. + /// See [`Hooks::on_finalize`]. fn on_finalize(_n: BlockNumber) {} } -/// The block's on idle trait. -/// -/// Implementing this lets you express what should happen for your pallet before -/// block finalization (see `on_finalize` hook) in case any remaining weight is left. +/// See [`Hooks::on_idle`]. pub trait OnIdle { - /// The block is being finalized. - /// Implement to have something happen in case there is leftover weight. - /// Check the passed `remaining_weight` to make sure it is high enough to allow for - /// your pallet's extra computation. - /// - /// NOTE: This function is called AFTER ALL extrinsics - including inherent extrinsics - - /// in a block are applied but before `on_finalize` is executed. + /// See [`Hooks::on_idle`]. fn on_idle(_n: BlockNumber, _remaining_weight: Weight) -> Weight { Weight::zero() } @@ -118,26 +99,14 @@ pub trait OnGenesis { fn on_genesis() {} } -/// The runtime upgrade trait. -/// -/// Implementing this lets you express what should happen when the runtime upgrades, -/// and changes may need to occur to your module. +/// See [`Hooks::on_runtime_upgrade`]. pub trait OnRuntimeUpgrade { - /// Perform a module upgrade. - /// - /// # Warning - /// - /// This function will be called before we initialized any runtime state, aka `on_initialize` - /// wasn't called yet. So, information like the block number and any other - /// block local data are not accessible. - /// - /// Return the non-negotiable weight consumed for runtime upgrade. + /// See [`Hooks::on_runtime_upgrade`]. fn on_runtime_upgrade() -> Weight { Weight::zero() } - /// Same as `on_runtime_upgrade`, but perform the optional `pre_upgrade` and `post_upgrade` as - /// well. + /// See [`Hooks::on_runtime_upgrade`]. #[cfg(feature = "try-runtime")] fn try_on_runtime_upgrade(checks: bool) -> Result { let maybe_state = if checks { @@ -159,31 +128,13 @@ pub trait OnRuntimeUpgrade { Ok(weight) } - /// Execute some pre-checks prior to a runtime upgrade. - /// - /// Return a `Vec` that can contain arbitrary encoded data (usually some pre-upgrade state), - /// which will be passed to `post_upgrade` after upgrading for post-check. An empty vector - /// should be returned if there is no such need. - /// - /// This hook is never meant to be executed on-chain but is meant to be used by testing tools. - /// - /// This hook must not write to any state, as it would make the main `on_runtime_upgrade` path - /// inaccurate. + /// See [`Hooks::on_runtime_upgrade`]. #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, TryRuntimeError> { Ok(Vec::new()) } - /// Execute some post-checks after a runtime upgrade. - /// - /// The `state` parameter is the `Vec` returned by `pre_upgrade` before upgrading, which - /// can be used for post-check. NOTE: if `pre_upgrade` is not implemented an empty vector will - /// be passed in, in such case `post_upgrade` should ignore it. - /// - /// This hook is never meant to be executed on-chain but is meant to be used by testing tools. - /// - /// This hook must not write to any state, as it would make the main `on_runtime_upgrade` path - /// inaccurate. + /// See [`Hooks::on_runtime_upgrade`]. #[cfg(feature = "try-runtime")] fn post_upgrade(_state: Vec) -> Result<(), TryRuntimeError> { Ok(()) @@ -200,9 +151,9 @@ impl OnRuntimeUpgrade for Tuple { weight } - /// We are executing pre- and post-checks sequentially in order to be able to test several - /// consecutive migrations for the same pallet without errors. Therefore pre and post upgrade - /// hooks for tuples are a noop. + // We are executing pre- and post-checks sequentially in order to be able to test several + // consecutive migrations for the same pallet without errors. Therefore pre and post upgrade + // hooks for tuples are a noop. #[cfg(feature = "try-runtime")] fn try_on_runtime_upgrade(checks: bool) -> Result { let mut weight = Weight::zero(); @@ -239,64 +190,150 @@ impl OnRuntimeUpgrade for Tuple { } } -/// Type that provide some integrity tests. -/// -/// This implemented for modules by `decl_module`. +/// See [`Hooks::integrity_test`]. #[cfg_attr(all(not(feature = "tuples-96"), not(feature = "tuples-128")), impl_for_tuples(64))] #[cfg_attr(all(feature = "tuples-96", not(feature = "tuples-128")), impl_for_tuples(96))] #[cfg_attr(feature = "tuples-128", impl_for_tuples(128))] pub trait IntegrityTest { - /// Run integrity test. - /// - /// The test is not executed in a externalities provided environment. + /// See [`Hooks::integrity_test`]. fn integrity_test() {} } -/// The pallet hooks trait. Implementing this lets you express some logic to execute. +#[cfg_attr(doc, aquamarine::aquamarine)] +/// The pallet hooks trait. This is merely an umbrella trait for: +/// +/// - [`OnInitialize`] +/// - [`OnFinalize`] +/// - [`OnRuntimeUpgrade`] +/// - [`crate::traits::misc::OffchainWorker`] +/// - [`OnIdle`] +/// - [`IntegrityTest`] +/// +/// ## Ordering +/// +/// For all hooks, except [`OnIdle`] the order of execution is derived from how the pallets are +/// ordered in [`crate::construct_runtime`]. +/// +/// ## Summary +/// +/// In short, the following diagram shows the flow of hooks in a pallet +/// +/// ```mermaid +/// graph LR +/// Optional --> BeforeExtrinsics +/// BeforeExtrinsics --> Extrinsics +/// Extrinsics --> AfterExtrinsics +/// subgraph Optional +/// OnRuntimeUpgrade +/// end +/// +/// subgraph BeforeExtrinsics +/// OnInitialize +/// end +/// +/// subgraph Extrinsics +/// direction TB +/// Inherent1 +/// Inherent2 +/// Extrinsic1 +/// Extrinsic2 +/// +/// Inherent1 --> Inherent2 +/// Inherent2 --> Extrinsic1 +/// Extrinsic1 --> Extrinsic2 +/// end +/// +/// subgraph AfterExtrinsics +/// OnIdle +/// OnFinalize +/// +/// OnIdle --> OnFinalize +/// end +/// ``` +/// +/// * `OnRuntimeUpgrade` is only executed before everything else if a code +/// * `OnRuntimeUpgrade` is mandatorily at the beginning of the block body (extrinsics) being +/// processed. change is detected. +/// * Extrinsics start with inherents, and continue with other signed or unsigned extrinsics. +/// * `OnIdle` optionally comes after extrinsics. +/// `OnFinalize` mandatorily comes after `OnIdle`. +/// +/// > `OffchainWorker` is not part of this flow, as it is not really part of the consensus/main +/// > block import path, and is called optionally, and in other circumstances. See +/// > [`crate::traits::misc::OffchainWorker`] for more information. +/// +/// To learn more about the execution of hooks see `frame-executive` as this component is is charge +/// of dispatching extrinsics and placing the hooks in the correct order. pub trait Hooks { - /// The block is being finalized. Implement to have something happen. + /// Block initialization hook. This is called at the very beginning of block execution. + /// + /// Must return the non-negotiable weight of both itself and whatever [`Hooks::on_finalize`] + /// wishes to consume. + /// + /// The weight returned by this is treated as `DispatchClass::Mandatory`, meaning that + /// it MUST BE EXECUTED. If this is not the case, consider using [`Hooks::on_idle`] instead. + /// + /// NOTE: This function is called BEFORE ANY extrinsic in a block is applied, including inherent + /// extrinsics. Hence for instance, if you runtime includes `pallet-timestamp`, the `timestamp` + /// is not yet up to date at this point. + fn on_initialize(_n: BlockNumber) -> Weight { + Weight::zero() + } + + /// Block finalization hook. This is called at the very end of block execution. + /// + /// Note that this has nothing to do with finality in the "consensus" sense. + /// + /// Note that the non-negotiable weight for this has must have already been returned by + /// [`Hooks::on_initialize`]. It usage alone is not permitted. + /// + /// Similar to [`Hooks::on_initialize`] it should only be used when execution is absolutely + /// necessary. In other cases, consider using [`Hooks::on_idle`] instead. fn on_finalize(_n: BlockNumber) {} - /// This will be run when the block is being finalized (before `on_finalize`). + /// Hook to consume a block's idle time. This will run when the block is being finalized (before + /// [`Hooks::on_finalize`]). /// - /// Implement to have something happen using the remaining weight. Will not fire if the - /// remaining weight is 0. + /// Given that all dispatchables are already executed and noted (and the weight for + /// [`Hooks::on_finalize`], which comes next, is also already accounted for via + /// `on_initialize`), this hook consumes anything that is leftover. /// /// Each pallet's `on_idle` is chosen to be the first to execute in a round-robin fashion /// indexed by the block number. /// /// Return the weight used, the caller will use this to calculate the remaining weight and then /// call the next pallet `on_idle` hook if there is still weight left. + /// + /// Any implementation should always respect `_remaining_weight` and never consume (and + /// therefore return) more than this amount. fn on_idle(_n: BlockNumber, _remaining_weight: Weight) -> Weight { Weight::zero() } - /// The block is being initialized. Implement to have something happen. + /// Hook executed when a code change (aka. a "runtime upgrade") is detected by FRAME. /// - /// Return the non-negotiable weight consumed in the block. - fn on_initialize(_n: BlockNumber) -> Weight { - Weight::zero() - } - - /// Perform a module upgrade. + /// Be aware that this is called before [`Hooks::on_initialize`] of any pallet; therefore, a lot + /// of the critical storage items such as `block_number` in system pallet might have not been + /// set. /// - /// NOTE: this doesn't include all pallet logic triggered on runtime upgrade. For instance it - /// doesn't include the write of the pallet version in storage. The final complete logic - /// triggered on runtime upgrade is given by implementation of `OnRuntimeUpgrade` trait by - /// `Pallet`. + /// Vert similar to [`Hooks::on_initialize`], any code in this block is mandatory and MUST + /// execute. Use with care. /// - /// # Warning + /// ## Implementation Note: Versioning /// - /// This function will be called before we initialized any runtime state, aka `on_initialize` - /// wasn't called yet. So, information like the block number and any other block local data are - /// not accessible. + /// 1. An implementation of this should typically follow a pattern where the version of the + /// pallet is checked against the onchain version, and a decision is made about what needs to be + /// done. This is helpful to prevent accidental repetitive execution of this hook, which can be + /// catastrophic. /// - /// Return the non-negotiable weight consumed for runtime upgrade. + /// Alternatively, `migrations::VersionedRuntimeUpgrade` can be used to assist with + /// this. /// - /// While this function can be freely implemented, using `on_runtime_upgrade` from inside the - /// pallet is discouraged and might get deprecated in the future. Alternatively, export the same - /// logic as a free-function from your pallet, and pass it to `type Executive` from the - /// top-level runtime. + /// ## Implementation Note: Runtime Level Migration + /// + /// Additional "upgrade hooks" can be created by pallets by a manual implementation of + /// [`Hooks::on_runtime_upgrade`] which can be passed on to `Executive` at the top level + /// runtime. fn on_runtime_upgrade() -> Weight { Weight::zero() } @@ -336,26 +373,36 @@ pub trait Hooks { Ok(()) } - /// Implementing this function on a module allows you to perform long-running tasks - /// that make (by default) validators generate transactions that feed results - /// of those long-running computations back on chain. + /// Implementing this function on a pallet allows you to perform long-running tasks that are + /// dispatched as separate threads, and entirely independent of the main wasm runtime. /// - /// NOTE: This function runs off-chain, so it can access the block state, - /// but cannot preform any alterations. More specifically alterations are - /// not forbidden, but they are not persisted in any way after the worker - /// has finished. + /// This function can freely read from the state, but any change it makes to the state is + /// meaningless. Writes can be pushed back to the chain by submitting extrinsics from the + /// offchain worker to the transaction pool. See `pallet-example-offchain-worker` for more + /// details on this. /// - /// This function is being called after every block import (when fully synced). + /// Moreover, the code in this function has access to a wider range of host functions in + /// [`sp-io`], namely [`sp_io::offchain`]. This includes exotic operations such as HTTP calls + /// that are not really possible in the rest of the runtime code. /// - /// Implement this and use any of the `Offchain` `sp_io` set of APIs - /// to perform off-chain computations, calls and submit transactions - /// with results to trigger any on-chain changes. - /// Any state alterations are lost and are not persisted. + /// The execution of this hook is entirely optional and is left at the discretion of the + /// node-side software and its configuration. In a normal substrate-cli, look for the CLI + /// flags related to offchain-workers to learn more. fn offchain_worker(_n: BlockNumber) {} - /// Run integrity test. + /// Check the integrity of this pallet's configuration. + /// + /// Any code located in this hook is placed in an auto-generated test, and generated as a part + /// of [`crate::construct_runtime`]'s expansion. Look for a test case with a name along the + /// lines of: `__construct_runtime_integrity_test`. + /// + /// This hook is the location where the values/types provided to the `Config` trait + /// of the pallet can be tested for correctness. For example, if two `type Foo: Get` and + /// `type Bar: Get` where `Foo::get()` must always be greater than `Bar::get()`, such + /// checks can be asserted upon here. /// - /// The test is not executed in a externalities provided environment. + /// Note that this hook is not executed in an externality environment, so if access to state is + /// needed, the code should be wrapped in `sp_io::TestExternalities`. fn integrity_test() {} } From dd6aedee3b8d5a957dc2e961d0c4e44dd7c037fc Mon Sep 17 00:00:00 2001 From: Evgeny Snitko Date: Mon, 17 Jul 2023 18:34:14 +0300 Subject: [PATCH 36/39] ci-unified:bullseye-1.70.0-2023-05-23 image for ci (#14532) --- .gitlab-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 6cb4cf444a4cd..e84c19d73cf8f 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -48,7 +48,7 @@ variables: CARGO_INCREMENTAL: 0 DOCKER_OS: "debian:bullseye" ARCH: "x86_64" - CI_IMAGE: "paritytech/ci-linux:production" + CI_IMAGE: "paritytech/ci-unified:bullseye-1.70.0-2023-05-23" BUILDAH_IMAGE: "quay.io/buildah/stable:v1.29" BUILDAH_COMMAND: "buildah --storage-driver overlay2" RELENG_SCRIPTS_BRANCH: "master" From 08f585742c63694f80bd8be53f8f5349d1af6925 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Silva?= <123550+andresilva@users.noreply.github.com> Date: Mon, 17 Jul 2023 18:38:34 +0100 Subject: [PATCH 37/39] grandpa: avoid importing unnecessary justifications (#14423) * grandpa: avoid importing unnecessary justifications * grandpa: make justification_import_period configurable * grandpa: keep the first justification * grandpa: add test for justification import period * grandpa: fix test --- bin/node-template/node/src/service.rs | 7 +- bin/node/cli/src/service.rs | 7 +- .../grandpa/src/communication/gossip.rs | 2 +- .../grandpa/src/communication/tests.rs | 2 +- client/consensus/grandpa/src/environment.rs | 59 ++++++--- client/consensus/grandpa/src/import.rs | 55 +++++--- client/consensus/grandpa/src/lib.rs | 19 ++- client/consensus/grandpa/src/tests.rs | 119 +++++++++++------- 8 files changed, 179 insertions(+), 91 deletions(-) diff --git a/bin/node-template/node/src/service.rs b/bin/node-template/node/src/service.rs index 355e24c95620b..36be0b1a938bd 100644 --- a/bin/node-template/node/src/service.rs +++ b/bin/node-template/node/src/service.rs @@ -37,6 +37,10 @@ pub(crate) type FullClient = type FullBackend = sc_service::TFullBackend; type FullSelectChain = sc_consensus::LongestChain; +/// The minimum period of blocks on which justifications will be +/// imported and generated. +const GRANDPA_JUSTIFICATION_PERIOD: u32 = 512; + #[allow(clippy::type_complexity)] pub fn new_partial( config: &Configuration, @@ -97,6 +101,7 @@ pub fn new_partial( let (grandpa_block_import, grandpa_link) = sc_consensus_grandpa::block_import( client.clone(), + GRANDPA_JUSTIFICATION_PERIOD, &client, select_chain.clone(), telemetry.as_ref().map(|x| x.handle()), @@ -290,7 +295,7 @@ pub fn new_full(config: Configuration) -> Result { let grandpa_config = sc_consensus_grandpa::Config { // FIXME #1578 make this available through chainspec gossip_duration: Duration::from_millis(333), - justification_period: 512, + justification_generation_period: GRANDPA_JUSTIFICATION_PERIOD, name: Some(name), observer_enabled: false, keystore, diff --git a/bin/node/cli/src/service.rs b/bin/node/cli/src/service.rs index 487c6c48f0061..5fb5e77c06012 100644 --- a/bin/node/cli/src/service.rs +++ b/bin/node/cli/src/service.rs @@ -54,6 +54,10 @@ type FullGrandpaBlockImport = /// The transaction pool type defintion. pub type TransactionPool = sc_transaction_pool::FullPool; +/// The minimum period of blocks on which justifications will be +/// imported and generated. +const GRANDPA_JUSTIFICATION_PERIOD: u32 = 512; + /// Fetch the nonce of the given `account` from the chain state. /// /// Note: Should only be used for tests. @@ -193,6 +197,7 @@ pub fn new_partial( let (grandpa_block_import, grandpa_link) = grandpa::block_import( client.clone(), + GRANDPA_JUSTIFICATION_PERIOD, &(client.clone() as Arc<_>), select_chain.clone(), telemetry.as_ref().map(|x| x.handle()), @@ -524,7 +529,7 @@ pub fn new_full_base( let grandpa_config = grandpa::Config { // FIXME #1578 make this available through chainspec gossip_duration: std::time::Duration::from_millis(333), - justification_period: 512, + justification_generation_period: GRANDPA_JUSTIFICATION_PERIOD, name: Some(name), observer_enabled: false, keystore, diff --git a/client/consensus/grandpa/src/communication/gossip.rs b/client/consensus/grandpa/src/communication/gossip.rs index 2c0fe3d8571e5..c4c885d48e9b9 100644 --- a/client/consensus/grandpa/src/communication/gossip.rs +++ b/client/consensus/grandpa/src/communication/gossip.rs @@ -1700,7 +1700,7 @@ mod tests { fn config() -> crate::Config { crate::Config { gossip_duration: Duration::from_millis(10), - justification_period: 256, + justification_generation_period: 256, keystore: None, name: None, local_role: Role::Authority, diff --git a/client/consensus/grandpa/src/communication/tests.rs b/client/consensus/grandpa/src/communication/tests.rs index eee9fddcea2d3..504fde74be603 100644 --- a/client/consensus/grandpa/src/communication/tests.rs +++ b/client/consensus/grandpa/src/communication/tests.rs @@ -244,7 +244,7 @@ impl Tester { fn config() -> crate::Config { crate::Config { gossip_duration: std::time::Duration::from_millis(10), - justification_period: 256, + justification_generation_period: 256, keystore: None, name: None, local_role: Role::Authority, diff --git a/client/consensus/grandpa/src/environment.rs b/client/consensus/grandpa/src/environment.rs index eeb9ff4468291..d3e2beb84e79c 100644 --- a/client/consensus/grandpa/src/environment.rs +++ b/client/consensus/grandpa/src/environment.rs @@ -1102,7 +1102,7 @@ where finalize_block( self.client.clone(), &self.authority_set, - Some(self.config.justification_period.into()), + Some(self.config.justification_generation_period), hash, number, (round, commit).into(), @@ -1315,6 +1315,38 @@ where .or_else(|| Some((target_header.hash(), *target_header.number())))) } +/// Whether we should process a justification for the given block. +/// +/// This can be used to decide whether to import a justification (when +/// importing a block), or whether to generate a justification from a +/// commit (when validating). Justifications for blocks that change the +/// authority set will always be processed, otherwise we'll only process +/// justifications if the last one was `justification_period` blocks ago. +pub(crate) fn should_process_justification( + client: &Client, + justification_period: u32, + number: NumberFor, + enacts_change: bool, +) -> bool +where + Block: BlockT, + BE: BackendT, + Client: ClientForGrandpa, +{ + if enacts_change { + return true + } + + let last_finalized_number = client.info().finalized_number; + + // keep the first justification before reaching the justification period + if last_finalized_number.is_zero() { + return true + } + + last_finalized_number / justification_period.into() != number / justification_period.into() +} + /// Finalize the given block and apply any authority set changes. If an /// authority set change is enacted then a justification is created (if not /// given) and stored with the block when finalizing it. @@ -1322,7 +1354,7 @@ where pub(crate) fn finalize_block( client: Arc, authority_set: &SharedAuthoritySet>, - justification_period: Option>, + justification_generation_period: Option, hash: Block::Hash, number: NumberFor, justification_or_commit: JustificationOrCommit, @@ -1393,22 +1425,13 @@ where let (justification_required, justification) = match justification_or_commit { JustificationOrCommit::Justification(justification) => (true, justification), JustificationOrCommit::Commit((round_number, commit)) => { - let mut justification_required = - // justification is always required when block that enacts new authorities - // set is finalized - status.new_set_block.is_some(); - - // justification is required every N blocks to be able to prove blocks - // finalization to remote nodes - if !justification_required { - if let Some(justification_period) = justification_period { - let last_finalized_number = client.info().finalized_number; - justification_required = (!last_finalized_number.is_zero() || - number - last_finalized_number == justification_period) && - (last_finalized_number / justification_period != - number / justification_period); - } - } + let enacts_change = status.new_set_block.is_some(); + + let justification_required = justification_generation_period + .map(|period| { + should_process_justification(&*client, period, number, enacts_change) + }) + .unwrap_or(enacts_change); let justification = GrandpaJustification::from_commit(&client, round_number, commit)?; diff --git a/client/consensus/grandpa/src/import.rs b/client/consensus/grandpa/src/import.rs index cd13f832ce6dc..760cb2da0484d 100644 --- a/client/consensus/grandpa/src/import.rs +++ b/client/consensus/grandpa/src/import.rs @@ -41,7 +41,7 @@ use sp_runtime::{ use crate::{ authorities::{AuthoritySet, DelayKind, PendingChange, SharedAuthoritySet}, - environment::finalize_block, + environment, justification::GrandpaJustification, notification::GrandpaJustificationSender, AuthoritySetChanges, ClientForGrandpa, CommandOrError, Error, NewAuthoritySet, VoterCommand, @@ -59,6 +59,7 @@ use crate::{ /// object. pub struct GrandpaBlockImport { inner: Arc, + justification_import_period: u32, select_chain: SC, authority_set: SharedAuthoritySet>, send_voter_commands: TracingUnboundedSender>>, @@ -74,6 +75,7 @@ impl Clone fn clone(&self) -> Self { GrandpaBlockImport { inner: self.inner.clone(), + justification_import_period: self.justification_import_period, select_chain: self.select_chain.clone(), authority_set: self.authority_set.clone(), send_voter_commands: self.send_voter_commands.clone(), @@ -648,26 +650,39 @@ where match grandpa_justification { Some(justification) => { - let import_res = self.import_justification( - hash, + if environment::should_process_justification( + &*self.inner, + self.justification_import_period, number, - (GRANDPA_ENGINE_ID, justification), needs_justification, - initial_sync, - ); + ) { + let import_res = self.import_justification( + hash, + number, + (GRANDPA_ENGINE_ID, justification), + needs_justification, + initial_sync, + ); - import_res.unwrap_or_else(|err| { - if needs_justification { - debug!( - target: LOG_TARGET, - "Requesting justification from peers due to imported block #{} that enacts authority set change with invalid justification: {}", - number, - err - ); - imported_aux.bad_justification = true; - imported_aux.needs_justification = true; - } - }); + import_res.unwrap_or_else(|err| { + if needs_justification { + debug!( + target: LOG_TARGET, + "Requesting justification from peers due to imported block #{} that enacts authority set change with invalid justification: {}", + number, + err + ); + imported_aux.bad_justification = true; + imported_aux.needs_justification = true; + } + }); + } else { + debug!( + target: LOG_TARGET, + "Ignoring unnecessary justification for block #{}", + number, + ); + } }, None => if needs_justification { @@ -695,6 +710,7 @@ where impl GrandpaBlockImport { pub(crate) fn new( inner: Arc, + justification_import_period: u32, select_chain: SC, authority_set: SharedAuthoritySet>, send_voter_commands: TracingUnboundedSender>>, @@ -733,6 +749,7 @@ impl GrandpaBlockImport justification, }; - let result = finalize_block( + let result = environment::finalize_block( self.inner.clone(), &self.authority_set, None, diff --git a/client/consensus/grandpa/src/lib.rs b/client/consensus/grandpa/src/lib.rs index c888340f70a34..ff0412aeb314c 100644 --- a/client/consensus/grandpa/src/lib.rs +++ b/client/consensus/grandpa/src/lib.rs @@ -215,10 +215,10 @@ impl Clone for SharedVoterState { pub struct Config { /// The expected duration for a message to be gossiped across the network. pub gossip_duration: Duration, - /// Justification generation period (in blocks). GRANDPA will try to generate justifications - /// at least every justification_period blocks. There are some other events which might cause - /// justification generation. - pub justification_period: u32, + /// Justification generation period (in blocks). GRANDPA will try to generate + /// justifications at least every justification_generation_period blocks. There + /// are some other events which might cause justification generation. + pub justification_generation_period: u32, /// Whether the GRANDPA observer protocol is live on the network and thereby /// a full-node not running as a validator is running the GRANDPA observer /// protocol (we will only issue catch-up requests to authorities when the @@ -495,8 +495,16 @@ where /// Make block importer and link half necessary to tie the background voter /// to it. +/// +/// The `justification_import_period` sets the minimum period on which +/// justifications will be imported. When importing a block, if it includes a +/// justification it will only be processed if it fits within this period, +/// otherwise it will be ignored (and won't be validated). This is to avoid +/// slowing down sync by a peer serving us unnecessary justifications which +/// aren't trivial to validate. pub fn block_import( client: Arc, + justification_import_period: u32, genesis_authorities_provider: &dyn GenesisAuthoritySetProvider, select_chain: SC, telemetry: Option, @@ -508,6 +516,7 @@ where { block_import_with_authority_set_hard_forks( client, + justification_import_period, genesis_authorities_provider, select_chain, Default::default(), @@ -540,6 +549,7 @@ pub struct AuthoritySetHardFork { /// given static authorities. pub fn block_import_with_authority_set_hard_forks( client: Arc, + justification_import_period: u32, genesis_authorities_provider: &dyn GenesisAuthoritySetProvider, select_chain: SC, authority_set_hard_forks: Vec>, @@ -599,6 +609,7 @@ where Ok(( GrandpaBlockImport::new( client.clone(), + justification_import_period, select_chain.clone(), persistent_data.authority_set.clone(), voter_commands_tx, diff --git a/client/consensus/grandpa/src/tests.rs b/client/consensus/grandpa/src/tests.rs index 4fbeed71a1bf5..0175f7d1b473c 100644 --- a/client/consensus/grandpa/src/tests.rs +++ b/client/consensus/grandpa/src/tests.rs @@ -69,6 +69,8 @@ type GrandpaBlockImport = crate::GrandpaBlockImport< LongestChain, >; +const JUSTIFICATION_IMPORT_PERIOD: u32 = 32; + #[derive(Default)] struct GrandpaTestNet { peers: Vec, @@ -126,6 +128,7 @@ impl TestNetFactory for GrandpaTestNet { let (client, backend) = (client.as_client(), client.as_backend()); let (import, link) = block_import( client.clone(), + JUSTIFICATION_IMPORT_PERIOD, &self.test_config, LongestChain::new(backend.clone()), None, @@ -318,7 +321,7 @@ fn initialize_grandpa( let grandpa_params = GrandpaParams { config: Config { gossip_duration: TEST_GOSSIP_DURATION, - justification_period: 32, + justification_generation_period: 32, keystore: Some(keystore), name: Some(format!("peer#{}", peer_id)), local_role: Role::Authority, @@ -446,11 +449,14 @@ async fn finalize_3_voters_no_observers() { let net = Arc::new(Mutex::new(net)); run_to_completion(20, net.clone(), peers).await; - // normally there's no justification for finalized blocks - assert!( - net.lock().peer(0).client().justifications(hashof20).unwrap().is_none(), - "Extra justification for block#1", - ); + // all peers should have stored the justification for the best finalized block #20 + for peer_id in 0..3 { + let client = net.lock().peers[peer_id].client().as_client(); + let justification = + crate::aux_schema::best_justification::<_, Block>(&*client).unwrap().unwrap(); + + assert_eq!(justification.justification.commit.target_number, 20); + } } #[tokio::test] @@ -470,7 +476,7 @@ async fn finalize_3_voters_1_full_observer() { let grandpa_params = GrandpaParams { config: Config { gossip_duration: TEST_GOSSIP_DURATION, - justification_period: 32, + justification_generation_period: 32, keystore: None, name: Some(format!("peer#{}", peer_id)), local_role: Role::Authority, @@ -565,7 +571,7 @@ async fn transition_3_voters_twice_1_full_observer() { let grandpa_params = GrandpaParams { config: Config { gossip_duration: TEST_GOSSIP_DURATION, - justification_period: 32, + justification_generation_period: 32, keystore: Some(keystore), name: Some(format!("peer#{}", peer_id)), local_role: Role::Authority, @@ -695,8 +701,8 @@ async fn justification_is_generated_periodically() { let net = Arc::new(Mutex::new(net)); run_to_completion(32, net.clone(), peers).await; - // when block#32 (justification_period) is finalized, justification - // is required => generated + // when block#32 (justification_generation_period) is finalized, + // justification is required => generated for i in 0..3 { assert!(net.lock().peer(i).client().justifications(hashof32).unwrap().is_some()); } @@ -993,7 +999,7 @@ async fn voter_persists_its_votes() { let bob_network = { let config = Config { gossip_duration: TEST_GOSSIP_DURATION, - justification_period: 32, + justification_generation_period: 32, keystore: Some(bob_keystore.clone()), name: Some(format!("peer#{}", 1)), local_role: Role::Authority, @@ -1035,7 +1041,7 @@ async fn voter_persists_its_votes() { let grandpa_params = GrandpaParams { config: Config { gossip_duration: TEST_GOSSIP_DURATION, - justification_period: 32, + justification_generation_period: 32, keystore: Some(keystore), name: Some(format!("peer#{}", 0)), local_role: Role::Authority, @@ -1081,7 +1087,7 @@ async fn voter_persists_its_votes() { let grandpa_params = GrandpaParams { config: Config { gossip_duration: TEST_GOSSIP_DURATION, - justification_period: 32, + justification_generation_period: 32, keystore: Some(keystore), name: Some(format!("peer#{}", 0)), local_role: Role::Authority, @@ -1246,7 +1252,7 @@ async fn finalize_3_voters_1_light_observer() { let observer = observer::run_grandpa_observer( Config { gossip_duration: TEST_GOSSIP_DURATION, - justification_period: 32, + justification_generation_period: 32, keystore: None, name: Some("observer".to_string()), local_role: Role::Full, @@ -1294,7 +1300,7 @@ async fn voter_catches_up_to_latest_round_when_behind() { let grandpa_params = GrandpaParams { config: Config { gossip_duration: TEST_GOSSIP_DURATION, - justification_period: 32, + justification_generation_period: 32, keystore, name: Some(format!("peer#{}", peer_id)), local_role: Role::Authority, @@ -1409,7 +1415,7 @@ where let config = Config { gossip_duration: TEST_GOSSIP_DURATION, - justification_period: 32, + justification_generation_period: 32, keystore, name: None, local_role: Role::Authority, @@ -1903,24 +1909,19 @@ async fn imports_justification_for_regular_blocks_on_import() { let client = net.peer(0).client().clone(); let (mut block_import, ..) = net.make_block_import(client.clone()); - let full_client = client.as_client(); - let builder = full_client - .new_block_at(full_client.chain_info().genesis_hash, Default::default(), false) - .unwrap(); - let block = builder.build().unwrap().block; - let block_hash = block.hash(); + // create a new block (without importing it) + let generate_block = |parent| { + let builder = full_client.new_block_at(parent, Default::default(), false).unwrap(); + builder.build().unwrap().block + }; // create a valid justification, with one precommit targeting the block - let justification = { - let round = 1; + let make_justification = |round, hash, number| { let set_id = 0; - let precommit = finality_grandpa::Precommit { - target_hash: block_hash, - target_number: *block.header.number(), - }; + let precommit = finality_grandpa::Precommit { target_hash: hash, target_number: number }; let msg = finality_grandpa::Message::Precommit(precommit.clone()); let encoded = sp_consensus_grandpa::localized_payload(round, set_id, &msg); @@ -1933,33 +1934,59 @@ async fn imports_justification_for_regular_blocks_on_import() { }; let commit = finality_grandpa::Commit { - target_hash: block_hash, - target_number: *block.header.number(), + target_hash: hash, + target_number: number, precommits: vec![precommit], }; GrandpaJustification::from_commit(&full_client, round, commit).unwrap() }; - // we import the block with justification attached - let mut import = BlockImportParams::new(BlockOrigin::File, block.header); - import.justifications = Some((GRANDPA_ENGINE_ID, justification.encode()).into()); - import.body = Some(block.extrinsics); - import.fork_choice = Some(ForkChoiceStrategy::LongestChain); + let mut generate_and_import_block_with_justification = |parent| { + // we import the block with justification attached + let block = generate_block(parent); + let block_hash = block.hash(); + let justification = make_justification(1, block_hash, *block.header.number()); - assert_eq!( - block_import.import_block(import).await.unwrap(), - ImportResult::Imported(ImportedAux { - needs_justification: false, - clear_justification_requests: false, - bad_justification: false, - is_new_best: true, - ..Default::default() - }), - ); + let mut import = BlockImportParams::new(BlockOrigin::File, block.header); + import.justifications = Some((GRANDPA_ENGINE_ID, justification.encode()).into()); + import.body = Some(block.extrinsics); + import.fork_choice = Some(ForkChoiceStrategy::LongestChain); + + assert_eq!( + // NOTE: we use `block_on` here because async closures are + // unsupported and it doesn't matter if we block in a test + futures::executor::block_on(block_import.import_block(import)).unwrap(), + ImportResult::Imported(ImportedAux { + needs_justification: false, + clear_justification_requests: false, + bad_justification: false, + is_new_best: true, + ..Default::default() + }), + ); + + block_hash + }; + + let block1 = + generate_and_import_block_with_justification(full_client.chain_info().genesis_hash); // the justification should be imported and available from the client - assert!(client.justifications(block_hash).unwrap().is_some()); + assert!(client.justifications(block1).unwrap().is_some()); + + // subsequent justifications should be ignored and not imported + let mut parent = block1; + for _ in 2..JUSTIFICATION_IMPORT_PERIOD { + parent = generate_and_import_block_with_justification(parent); + assert!(client.justifications(parent).unwrap().is_none()); + } + + let block32 = generate_and_import_block_with_justification(parent); + + // until we reach a block in the next justification import period, at + // which point we should import it + assert!(client.justifications(block32).unwrap().is_some()); } #[tokio::test] From 8463ca3f2ce53b3dcbe9c3b382d946934e1f37c9 Mon Sep 17 00:00:00 2001 From: Arkadiy Paronyan Date: Mon, 17 Jul 2023 20:41:41 +0200 Subject: [PATCH 38/39] Encryption support for the statement store (#14440) * Added ECIES encryption * tweaks * fmt * Make clippy happy * Use local keystore * qed --- Cargo.lock | 8 + bin/node/cli/src/service.rs | 1 + client/cli/src/runner.rs | 2 +- client/keystore/src/lib.rs | 1 + client/network/src/discovery.rs | 2 +- client/network/src/protocol_controller.rs | 8 +- .../rpc-spec-v2/src/chain_head/chain_head.rs | 3 +- .../src/chain_head/chain_head_follow.rs | 4 +- .../src/chain_head/subscription/inner.rs | 4 +- client/service/src/lib.rs | 2 +- client/statement-store/Cargo.toml | 1 + client/statement-store/src/lib.rs | 78 +++++++- frame/glutton/src/lib.rs | 8 +- frame/support/procedural/src/benchmark.rs | 6 +- .../construct_runtime/expand/outer_enums.rs | 4 +- .../api/proc-macro/src/runtime_metadata.rs | 12 +- primitives/api/proc-macro/src/utils.rs | 4 +- primitives/application-crypto/src/lib.rs | 7 + .../src/multiply_by_rational_with_rounding.rs | 4 +- primitives/blockchain/src/backend.rs | 4 +- primitives/core/Cargo.toml | 1 - primitives/core/src/ed25519.rs | 8 +- primitives/core/src/sr25519.rs | 8 +- primitives/io/src/lib.rs | 4 +- primitives/statement-store/Cargo.toml | 17 ++ primitives/statement-store/src/ecies.rs | 174 ++++++++++++++++++ primitives/statement-store/src/lib.rs | 45 ++++- utils/wasm-builder/src/lib.rs | 2 +- 28 files changed, 351 insertions(+), 71 deletions(-) create mode 100644 primitives/statement-store/src/ecies.rs diff --git a/Cargo.lock b/Cargo.lock index ba5b855db9a65..d0578a77a91e9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10159,6 +10159,7 @@ dependencies = [ "parity-db", "parking_lot 0.12.1", "sc-client-api", + "sc-keystore", "sp-api", "sp-blockchain", "sp-core", @@ -11592,8 +11593,14 @@ dependencies = [ name = "sp-statement-store" version = "4.0.0-dev" dependencies = [ + "aes-gcm 0.10.2", + "curve25519-dalek 3.2.0", + "ed25519-dalek", + "hkdf", "parity-scale-codec", + "rand 0.8.5", "scale-info", + "sha2 0.10.6", "sp-api", "sp-application-crypto", "sp-core", @@ -11602,6 +11609,7 @@ dependencies = [ "sp-runtime-interface", "sp-std", "thiserror", + "x25519-dalek 2.0.0-pre.1", ] [[package]] diff --git a/bin/node/cli/src/service.rs b/bin/node/cli/src/service.rs index 5fb5e77c06012..99608c04d38b5 100644 --- a/bin/node/cli/src/service.rs +++ b/bin/node/cli/src/service.rs @@ -241,6 +241,7 @@ pub fn new_partial( &config.data_path, Default::default(), client.clone(), + keystore_container.local_keystore(), config.prometheus_registry(), &task_manager.spawn_handle(), ) diff --git a/client/cli/src/runner.rs b/client/cli/src/runner.rs index c96f494354f9a..59f53200a192b 100644 --- a/client/cli/src/runner.rs +++ b/client/cli/src/runner.rs @@ -400,7 +400,7 @@ mod tests { }, ); - let Some(output) = output else { return } ; + let Some(output) = output else { return }; let stderr = dbg!(String::from_utf8(output.stderr).unwrap()); diff --git a/client/keystore/src/lib.rs b/client/keystore/src/lib.rs index 4151f8c4dc1a4..2d353f3ceba5d 100644 --- a/client/keystore/src/lib.rs +++ b/client/keystore/src/lib.rs @@ -26,6 +26,7 @@ use std::io; /// Local keystore implementation mod local; pub use local::LocalKeystore; +pub use sp_keystore::Keystore; /// Keystore error. #[derive(Debug, thiserror::Error)] diff --git a/client/network/src/discovery.rs b/client/network/src/discovery.rs index b6cb29584658f..d9fad53844346 100644 --- a/client/network/src/discovery.rs +++ b/client/network/src/discovery.rs @@ -548,7 +548,7 @@ impl NetworkBehaviour for DiscoveryBehaviour { addresses: &[Multiaddr], effective_role: Endpoint, ) -> Result, ConnectionDenied> { - let Some(peer_id) = maybe_peer else { return Ok(Vec::new()); }; + let Some(peer_id) = maybe_peer else { return Ok(Vec::new()) }; let mut list = self .permanent_addresses diff --git a/client/network/src/protocol_controller.rs b/client/network/src/protocol_controller.rs index 9a77881c63320..5b421e1485d69 100644 --- a/client/network/src/protocol_controller.rs +++ b/client/network/src/protocol_controller.rs @@ -658,9 +658,7 @@ impl ProtocolController { /// disconnected, `Ok(false)` if it wasn't found, `Err(PeerId)`, if the peer found, but not in /// connected state. fn drop_reserved_peer(&mut self, peer_id: &PeerId) -> Result { - let Some(state) = self.reserved_nodes.get_mut(peer_id) else { - return Ok(false) - }; + let Some(state) = self.reserved_nodes.get_mut(peer_id) else { return Ok(false) }; if let PeerState::Connected(direction) = state { trace!( @@ -678,9 +676,7 @@ impl ProtocolController { /// Try dropping the peer as a regular peer. Return `true` if the peer was found and /// disconnected, `false` if it wasn't found. fn drop_regular_peer(&mut self, peer_id: &PeerId) -> bool { - let Some(direction) = self.nodes.remove(peer_id) else { - return false - }; + let Some(direction) = self.nodes.remove(peer_id) else { return false }; trace!( target: LOG_TARGET, diff --git a/client/rpc-spec-v2/src/chain_head/chain_head.rs b/client/rpc-spec-v2/src/chain_head/chain_head.rs index bb3599c0e4ae5..a61406b8d53b8 100644 --- a/client/rpc-spec-v2/src/chain_head/chain_head.rs +++ b/client/rpc-spec-v2/src/chain_head/chain_head.rs @@ -162,7 +162,8 @@ where }, }; // Keep track of the subscription. - let Some(rx_stop) = self.subscriptions.insert_subscription(sub_id.clone(), with_runtime) else { + let Some(rx_stop) = self.subscriptions.insert_subscription(sub_id.clone(), with_runtime) + else { // Inserting the subscription can only fail if the JsonRPSee // generated a duplicate subscription ID. debug!(target: LOG_TARGET, "[follow][id={:?}] Subscription already accepted", sub_id); diff --git a/client/rpc-spec-v2/src/chain_head/chain_head_follow.rs b/client/rpc-spec-v2/src/chain_head/chain_head_follow.rs index cb6af8bd590b3..799978be532ae 100644 --- a/client/rpc-spec-v2/src/chain_head/chain_head_follow.rs +++ b/client/rpc-spec-v2/src/chain_head/chain_head_follow.rs @@ -339,9 +339,7 @@ where let mut events = Vec::new(); // Nothing to be done if no finalized hashes are provided. - let Some(first_hash) = finalized_block_hashes.get(0) else { - return Ok(Default::default()) - }; + let Some(first_hash) = finalized_block_hashes.get(0) else { return Ok(Default::default()) }; // Find the parent header. let Some(first_header) = self.client.header(*first_hash)? else { diff --git a/client/rpc-spec-v2/src/chain_head/subscription/inner.rs b/client/rpc-spec-v2/src/chain_head/subscription/inner.rs index adab64a01c875..be8b8f46a2844 100644 --- a/client/rpc-spec-v2/src/chain_head/subscription/inner.rs +++ b/client/rpc-spec-v2/src/chain_head/subscription/inner.rs @@ -328,9 +328,7 @@ impl> SubscriptionsInner { /// Remove the subscription ID with associated pinned blocks. pub fn remove_subscription(&mut self, sub_id: &str) { - let Some(mut sub) = self.subs.remove(sub_id) else { - return - }; + let Some(mut sub) = self.subs.remove(sub_id) else { return }; // The `Stop` event can be generated only once. sub.stop(); diff --git a/client/service/src/lib.rs b/client/service/src/lib.rs index c987c2471907d..0961967f9ca20 100644 --- a/client/service/src/lib.rs +++ b/client/service/src/lib.rs @@ -237,7 +237,7 @@ pub async fn build_system_rpc_future< // Answer incoming RPC requests. let Some(req) = rpc_rx.next().await else { debug!("RPC requests stream has terminated, shutting down the system RPC future."); - return; + return }; match req { diff --git a/client/statement-store/Cargo.toml b/client/statement-store/Cargo.toml index bb2d7aa2feaa5..8668dbfa8ba03 100644 --- a/client/statement-store/Cargo.toml +++ b/client/statement-store/Cargo.toml @@ -24,6 +24,7 @@ sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } sp-core = { version = "21.0.0", path = "../../primitives/core" } sp-runtime = { version = "24.0.0", path = "../../primitives/runtime" } sc-client-api = { version = "4.0.0-dev", path = "../api" } +sc-keystore = { version = "4.0.0-dev", path = "../../client/keystore" } [dev-dependencies] tempfile = "3.1.0" diff --git a/client/statement-store/src/lib.rs b/client/statement-store/src/lib.rs index 3b42641d9c5ab..da0af08b45402 100644 --- a/client/statement-store/src/lib.rs +++ b/client/statement-store/src/lib.rs @@ -54,9 +54,10 @@ pub use sp_statement_store::{Error, StatementStore, MAX_TOPICS}; use metrics::MetricsLink as PrometheusMetrics; use parking_lot::RwLock; use prometheus_endpoint::Registry as PrometheusRegistry; +use sc_keystore::LocalKeystore; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; -use sp_core::{hexdisplay::HexDisplay, traits::SpawnNamed, Decode, Encode}; +use sp_core::{crypto::UncheckedFrom, hexdisplay::HexDisplay, traits::SpawnNamed, Decode, Encode}; use sp_runtime::traits::Block as BlockT; use sp_statement_store::{ runtime_api::{ @@ -201,6 +202,7 @@ pub struct Store { + Send + Sync, >, + keystore: Arc, // Used for testing time_override: Option, metrics: PrometheusMetrics, @@ -479,6 +481,7 @@ impl Store { path: &std::path::Path, options: Options, client: Arc, + keystore: Arc, prometheus: Option<&PrometheusRegistry>, task_spawner: &dyn SpawnNamed, ) -> Result> @@ -493,7 +496,7 @@ impl Store { + 'static, Client::Api: ValidateStatement, { - let store = Arc::new(Self::new(path, options, client, prometheus)?); + let store = Arc::new(Self::new(path, options, client, keystore, prometheus)?); // Perform periodic statement store maintenance let worker_store = store.clone(); @@ -518,6 +521,7 @@ impl Store { path: &std::path::Path, options: Options, client: Arc, + keystore: Arc, prometheus: Option<&PrometheusRegistry>, ) -> Result where @@ -566,6 +570,7 @@ impl Store { db, index: RwLock::new(Index::new(options)), validate_fn, + keystore, time_override: None, metrics: PrometheusMetrics::new(prometheus), }; @@ -768,7 +773,45 @@ impl StatementStore for Store { /// Return the decrypted data of all known statements whose decryption key is identified as /// `dest`. The key must be available to the client. fn posted_clear(&self, match_all_topics: &[Topic], dest: [u8; 32]) -> Result>> { - self.collect_statements(Some(dest), match_all_topics, |statement| statement.into_data()) + self.collect_statements(Some(dest), match_all_topics, |statement| { + if let (Some(key), Some(_)) = (statement.decryption_key(), statement.data()) { + let public: sp_core::ed25519::Public = UncheckedFrom::unchecked_from(key); + let public: sp_statement_store::ed25519::Public = public.into(); + match self.keystore.key_pair::(&public) { + Err(e) => { + log::debug!( + target: LOG_TARGET, + "Keystore error: {:?}, for statement {:?}", + e, + HexDisplay::from(&statement.hash()) + ); + None + }, + Ok(None) => { + log::debug!( + target: LOG_TARGET, + "Keystore is missing key for statement {:?}", + HexDisplay::from(&statement.hash()) + ); + None + }, + Ok(Some(pair)) => match statement.decrypt_private(&pair.into_inner()) { + Ok(r) => r, + Err(e) => { + log::debug!( + target: LOG_TARGET, + "Decryption error: {:?}, for statement {:?}", + e, + HexDisplay::from(&statement.hash()) + ); + None + }, + }, + } + } else { + None + } + }) } /// Submit a statement to the store. Validates the statement and returns validation result. @@ -887,6 +930,7 @@ impl StatementStore for Store { #[cfg(test)] mod tests { use crate::Store; + use sc_keystore::Keystore; use sp_core::Pair; use sp_statement_store::{ runtime_api::{InvalidStatement, ValidStatement, ValidateStatement}, @@ -916,6 +960,7 @@ mod tests { RuntimeApi { _inner: self.clone() }.into() } } + sp_api::mock_impl_runtime_apis! { impl ValidateStatement for RuntimeApi { fn validate_statement( @@ -983,7 +1028,8 @@ mod tests { let client = std::sync::Arc::new(TestClient); let mut path: std::path::PathBuf = temp_dir.path().into(); path.push("db"); - let store = Store::new(&path, Default::default(), client, None).unwrap(); + let keystore = std::sync::Arc::new(sc_keystore::LocalKeystore::in_memory()); + let store = Store::new(&path, Default::default(), client, keystore, None).unwrap(); (store, temp_dir) // return order is important. Store must be dropped before TempDir } @@ -1086,12 +1132,13 @@ mod tests { assert_eq!(store.statements().unwrap().len(), 3); assert_eq!(store.broadcasts(&[]).unwrap().len(), 3); assert_eq!(store.statement(&statement1.hash()).unwrap(), Some(statement1.clone())); + let keystore = store.keystore.clone(); drop(store); let client = std::sync::Arc::new(TestClient); let mut path: std::path::PathBuf = temp.path().into(); path.push("db"); - let store = Store::new(&path, Default::default(), client, None).unwrap(); + let store = Store::new(&path, Default::default(), client, keystore, None).unwrap(); assert_eq!(store.statements().unwrap().len(), 3); assert_eq!(store.broadcasts(&[]).unwrap().len(), 3); assert_eq!(store.statement(&statement1.hash()).unwrap(), Some(statement1)); @@ -1196,7 +1243,6 @@ mod tests { statement(2, 4, None, 1000).hash(), statement(3, 4, Some(3), 300).hash(), statement(3, 5, None, 500).hash(), - //statement(4, 6, None, 100).hash(), ]; expected_statements.sort(); let mut statements: Vec<_> = @@ -1220,13 +1266,31 @@ mod tests { store.set_time(DEFAULT_PURGE_AFTER_SEC + 1); store.maintain(); assert_eq!(store.index.read().expired.len(), 0); + let keystore = store.keystore.clone(); drop(store); let client = std::sync::Arc::new(TestClient); let mut path: std::path::PathBuf = temp.path().into(); path.push("db"); - let store = Store::new(&path, Default::default(), client, None).unwrap(); + let store = Store::new(&path, Default::default(), client, keystore, None).unwrap(); assert_eq!(store.statements().unwrap().len(), 0); assert_eq!(store.index.read().expired.len(), 0); } + + #[test] + fn posted_clear_decrypts() { + let (store, _temp) = test_store(); + let public = store + .keystore + .ed25519_generate_new(sp_core::crypto::key_types::STATEMENT, None) + .unwrap(); + let statement1 = statement(1, 1, None, 100); + let mut statement2 = statement(1, 2, None, 0); + let plain = b"The most valuable secret".to_vec(); + statement2.encrypt(&plain, &public).unwrap(); + store.submit(statement1, StatementSource::Network); + store.submit(statement2, StatementSource::Network); + let posted_clear = store.posted_clear(&[], public.into()).unwrap(); + assert_eq!(posted_clear, vec![plain]); + } } diff --git a/frame/glutton/src/lib.rs b/frame/glutton/src/lib.rs index ae3e4f87f0e80..838bd9b67d296 100644 --- a/frame/glutton/src/lib.rs +++ b/frame/glutton/src/lib.rs @@ -271,9 +271,7 @@ pub mod pallet { /// /// Tries to come as close to the limit as possible. pub(crate) fn waste_at_most_proof_size(meter: &mut WeightMeter) { - let Ok(n) = Self::calculate_proof_size_iters(&meter) else { - return; - }; + let Ok(n) = Self::calculate_proof_size_iters(&meter) else { return }; meter.defensive_saturating_accrue(T::WeightInfo::waste_proof_size_some(n)); @@ -303,9 +301,7 @@ pub mod pallet { /// /// Tries to come as close to the limit as possible. pub(crate) fn waste_at_most_ref_time(meter: &mut WeightMeter) { - let Ok(n) = Self::calculate_ref_time_iters(&meter) else { - return; - }; + let Ok(n) = Self::calculate_ref_time_iters(&meter) else { return }; meter.defensive_saturating_accrue(T::WeightInfo::waste_ref_time_iter(n)); let clobber = Self::waste_ref_time_iter(vec![0u8; 64], n); diff --git a/frame/support/procedural/src/benchmark.rs b/frame/support/procedural/src/benchmark.rs index 18d672b9b0508..9f28e7129d2e1 100644 --- a/frame/support/procedural/src/benchmark.rs +++ b/frame/support/procedural/src/benchmark.rs @@ -166,11 +166,11 @@ fn ensure_valid_return_type(item_fn: &ItemFn) -> Result<()> { if let ReturnType::Type(_, typ) = &item_fn.sig.output { let non_unit = |span| return Err(Error::new(span, "expected `()`")); let Type::Path(TypePath { path, qself: _ }) = &**typ else { - return Err(Error::new( + return Err(Error::new( typ.span(), "Only `Result<(), BenchmarkError>` or a blank return type is allowed on benchmark function definitions", )) - }; + }; let seg = path .segments .last() @@ -780,7 +780,7 @@ fn expand_benchmark( let call_name = match *expr_call.func { Expr::Path(expr_path) => { // normal function call - let Some(segment) = expr_path.path.segments.last() else { return call_err(); }; + let Some(segment) = expr_path.path.segments.last() else { return call_err() }; segment.ident.to_string() }, Expr::Infer(_) => { diff --git a/frame/support/procedural/src/construct_runtime/expand/outer_enums.rs b/frame/support/procedural/src/construct_runtime/expand/outer_enums.rs index 544f63be2bfa1..b78360d5fc052 100644 --- a/frame/support/procedural/src/construct_runtime/expand/outer_enums.rs +++ b/frame/support/procedural/src/construct_runtime/expand/outer_enums.rs @@ -100,9 +100,7 @@ pub fn expand_outer_enum( let enum_name_ident = Ident::new(enum_ty.struct_name(), Span::call_site()); for pallet_decl in pallet_decls { - let Some(pallet_entry) = pallet_decl.find_part(enum_name_str) else { - continue - }; + let Some(pallet_entry) = pallet_decl.find_part(enum_name_str) else { continue }; let path = &pallet_decl.path; let pallet_name = &pallet_decl.name; diff --git a/primitives/api/proc-macro/src/runtime_metadata.rs b/primitives/api/proc-macro/src/runtime_metadata.rs index d027e86fac4ef..41849401291e6 100644 --- a/primitives/api/proc-macro/src/runtime_metadata.rs +++ b/primitives/api/proc-macro/src/runtime_metadata.rs @@ -88,9 +88,7 @@ pub fn generate_decl_runtime_metadata(decl: &ItemTrait) -> TokenStream2 { let mut where_clause = Vec::new(); for item in &decl.items { // Collect metadata for methods only. - let syn::TraitItem::Fn(method) = item else { - continue - }; + let syn::TraitItem::Fn(method) = item else { continue }; // Collect metadata only for the latest methods. let is_changed_in = @@ -103,9 +101,7 @@ pub fn generate_decl_runtime_metadata(decl: &ItemTrait) -> TokenStream2 { let signature = &method.sig; for input in &signature.inputs { // Exclude `self` from metadata collection. - let syn::FnArg::Typed(typed) = input else { - continue - }; + let syn::FnArg::Typed(typed) = input else { continue }; let pat = &typed.pat; let name = quote!(#pat).to_string(); @@ -153,9 +149,7 @@ pub fn generate_decl_runtime_metadata(decl: &ItemTrait) -> TokenStream2 { // The trait generics where already extended with `Block: BlockT`. let mut generics = decl.generics.clone(); for generic_param in generics.params.iter_mut() { - let syn::GenericParam::Type(ty) = generic_param else { - continue - }; + let syn::GenericParam::Type(ty) = generic_param else { continue }; // Default type parameters are not allowed in functions. ty.eq_token = None; diff --git a/primitives/api/proc-macro/src/utils.rs b/primitives/api/proc-macro/src/utils.rs index 7b580ee6f099e..c9389154bbf40 100644 --- a/primitives/api/proc-macro/src/utils.rs +++ b/primitives/api/proc-macro/src/utils.rs @@ -266,9 +266,7 @@ pub fn get_doc_literals(attrs: &[syn::Attribute]) -> Vec { attrs .iter() .filter_map(|attr| { - let syn::Meta::NameValue(meta) = &attr.meta else { - return None - }; + let syn::Meta::NameValue(meta) = &attr.meta else { return None }; let Ok(lit) = syn::parse2::(meta.value.to_token_stream()) else { unreachable!("non-lit doc attribute values do not exist"); }; diff --git a/primitives/application-crypto/src/lib.rs b/primitives/application-crypto/src/lib.rs index 46f59719f9c29..95a25c11a717d 100644 --- a/primitives/application-crypto/src/lib.rs +++ b/primitives/application-crypto/src/lib.rs @@ -179,6 +179,13 @@ macro_rules! app_crypto_pair { impl $crate::AppPair for Pair { type Generic = $pair; } + + impl Pair { + /// Convert into wrapped generic key pair type. + pub fn into_inner(self) -> $pair { + self.0 + } + } }; } diff --git a/primitives/arithmetic/fuzzer/src/multiply_by_rational_with_rounding.rs b/primitives/arithmetic/fuzzer/src/multiply_by_rational_with_rounding.rs index e9a3208a738ef..5f3f675c971f2 100644 --- a/primitives/arithmetic/fuzzer/src/multiply_by_rational_with_rounding.rs +++ b/primitives/arithmetic/fuzzer/src/multiply_by_rational_with_rounding.rs @@ -52,9 +52,7 @@ fn check(f: N, n: N, d: N, r: Rounding) where N: MultiplyRational + Into + Copy + core::fmt::Debug, { - let Some(got) = f.multiply_rational(n, d, r) else { - return; - }; + let Some(got) = f.multiply_rational(n, d, r) else { return }; let (ae, be, ce) = (Fraction::from(f.into()), Fraction::from(n.into()), Fraction::from(d.into())); diff --git a/primitives/blockchain/src/backend.rs b/primitives/blockchain/src/backend.rs index e9278be1d5d3c..8208f9128e714 100644 --- a/primitives/blockchain/src/backend.rs +++ b/primitives/blockchain/src/backend.rs @@ -196,9 +196,7 @@ pub trait Backend: base_hash: Block::Hash, import_lock: &RwLock<()>, ) -> Result> { - let Some(base_header) = self.header(base_hash)? else { - return Ok(None) - }; + let Some(base_header) = self.header(base_hash)? else { return Ok(None) }; let leaves = { // ensure no blocks are imported during this code block. diff --git a/primitives/core/Cargo.toml b/primitives/core/Cargo.toml index f0da73e8ec789..f02489a09f05e 100644 --- a/primitives/core/Cargo.toml +++ b/primitives/core/Cargo.toml @@ -57,7 +57,6 @@ sp-runtime-interface = { version = "17.0.0", default-features = false, path = ". w3f-bls = { version = "0.1.3", default-features = false, optional = true} [dev-dependencies] -rand = "0.8.5" criterion = "0.4.0" serde_json = "1.0" sp-core-hashing-proc-macro = { version = "9.0.0", path = "./hashing/proc-macro" } diff --git a/primitives/core/src/ed25519.rs b/primitives/core/src/ed25519.rs index 9d948a5bcea66..d46f2b5043d61 100644 --- a/primitives/core/src/ed25519.rs +++ b/primitives/core/src/ed25519.rs @@ -422,12 +422,8 @@ impl TraitPair for Pair { /// /// Returns true if the signature is good. fn verify>(sig: &Self::Signature, message: M, public: &Self::Public) -> bool { - let Ok(public) = VerificationKey::try_from(public.as_slice()) else { - return false - }; - let Ok(signature) = ed25519_zebra::Signature::try_from(sig.as_ref()) else { - return false - }; + let Ok(public) = VerificationKey::try_from(public.as_slice()) else { return false }; + let Ok(signature) = ed25519_zebra::Signature::try_from(sig.as_ref()) else { return false }; public.verify(&signature, message.as_ref()).is_ok() } diff --git a/primitives/core/src/sr25519.rs b/primitives/core/src/sr25519.rs index 1c040f6ccf7be..bcd64ed1cc3cf 100644 --- a/primitives/core/src/sr25519.rs +++ b/primitives/core/src/sr25519.rs @@ -505,12 +505,8 @@ impl TraitPair for Pair { } fn verify>(sig: &Self::Signature, message: M, pubkey: &Self::Public) -> bool { - let Ok(signature) = schnorrkel::Signature::from_bytes(sig.as_ref()) else { - return false - }; - let Ok(public) = PublicKey::from_bytes(pubkey.as_ref()) else { - return false - }; + let Ok(signature) = schnorrkel::Signature::from_bytes(sig.as_ref()) else { return false }; + let Ok(public) = PublicKey::from_bytes(pubkey.as_ref()) else { return false }; public.verify_simple(SIGNING_CTX, message.as_ref(), &signature).is_ok() } diff --git a/primitives/io/src/lib.rs b/primitives/io/src/lib.rs index 750b5d5924637..bd20ee0c917aa 100644 --- a/primitives/io/src/lib.rs +++ b/primitives/io/src/lib.rs @@ -776,9 +776,7 @@ pub trait Crypto { return false }; - let Ok(sig) = ed25519_dalek::Signature::from_bytes(&sig.0) else { - return false - }; + let Ok(sig) = ed25519_dalek::Signature::from_bytes(&sig.0) else { return false }; public_key.verify(msg, &sig).is_ok() } else { diff --git a/primitives/statement-store/Cargo.toml b/primitives/statement-store/Cargo.toml index c0e1a494ab23a..02ee6f4c15521 100644 --- a/primitives/statement-store/Cargo.toml +++ b/primitives/statement-store/Cargo.toml @@ -24,6 +24,15 @@ sp-runtime-interface = { version = "17.0.0", default-features = false, path = ". sp-externalities = { version = "0.19.0", default-features = false, path = "../externalities" } thiserror = { version = "1.0", optional = true } +# ECIES dependencies +ed25519-dalek = { version = "1.0", optional = true } +x25519-dalek = { version = "2.0.0-pre.1", optional = true } +curve25519-dalek = { version = "3.2", optional = true } +aes-gcm = { version = "0.10", optional = true } +hkdf = { version = "0.12.0", optional = true } +sha2 = { version = "0.10.0", optional = true } +rand = { version = "0.8.5", features = ["small_rng"], optional = true } + [features] default = ["std"] std = [ @@ -36,6 +45,14 @@ std = [ "sp-api/std", "sp-application-crypto/std", "thiserror", + + "ed25519-dalek", + "x25519-dalek", + "curve25519-dalek", + "aes-gcm", + "hkdf", + "sha2", + "rand", ] serde = [ "scale-info/serde", diff --git a/primitives/statement-store/src/ecies.rs b/primitives/statement-store/src/ecies.rs new file mode 100644 index 0000000000000..4afd583e03c80 --- /dev/null +++ b/primitives/statement-store/src/ecies.rs @@ -0,0 +1,174 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// tag::description[] +//! ECIES encryption scheme using x25519 key exchange and AEAD. +// end::description[] + +use aes_gcm::{aead::Aead, AeadCore, KeyInit}; +use rand::rngs::OsRng; +use sha2::Digest; +use sp_core::crypto::Pair; + +/// x25519 secret key. +pub type SecretKey = x25519_dalek::StaticSecret; +/// x25519 public key. +pub type PublicKey = x25519_dalek::PublicKey; + +/// Encryption or decryption error. +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// Generic AES encryption error. + #[error("Encryption error")] + Encryption, + /// Generic AES decryption error. + #[error("Decryption error")] + Decryption, + /// Error reading key data. Not enough data in the buffer. + #[error("Bad cypher text")] + BadData, +} + +const NONCE_LEN: usize = 12; +const PK_LEN: usize = 32; +const AES_KEY_LEN: usize = 32; + +fn aes_encrypt(key: &[u8; AES_KEY_LEN], nonce: &[u8], plaintext: &[u8]) -> Result, Error> { + let enc = aes_gcm::Aes256Gcm::new(key.into()); + + enc.encrypt(nonce.into(), aes_gcm::aead::Payload { msg: plaintext, aad: b"" }) + .map_err(|_| Error::Encryption) +} + +fn aes_decrypt(key: &[u8; AES_KEY_LEN], nonce: &[u8], ciphertext: &[u8]) -> Result, Error> { + let dec = aes_gcm::Aes256Gcm::new(key.into()); + dec.decrypt(nonce.into(), aes_gcm::aead::Payload { msg: ciphertext, aad: b"" }) + .map_err(|_| Error::Decryption) +} + +fn kdf(shared_secret: &[u8]) -> [u8; AES_KEY_LEN] { + let hkdf = hkdf::Hkdf::::new(None, shared_secret); + let mut aes_key = [0u8; AES_KEY_LEN]; + hkdf.expand(b"", &mut aes_key) + .expect("There's always enough data for derivation. qed."); + aes_key +} + +/// Encrypt `plaintext` with the given public x25519 public key. Decryption can be performed with +/// the matching secret key. +pub fn encrypt_x25519(pk: &PublicKey, plaintext: &[u8]) -> Result, Error> { + let ephemeral_sk = x25519_dalek::StaticSecret::new(OsRng); + let ephemeral_pk = x25519_dalek::PublicKey::from(&ephemeral_sk); + + let mut shared_secret = ephemeral_sk.diffie_hellman(pk).to_bytes().to_vec(); + shared_secret.extend_from_slice(ephemeral_pk.as_bytes()); + + let aes_key = kdf(&shared_secret); + + let nonce = aes_gcm::Aes256Gcm::generate_nonce(OsRng); + let ciphertext = aes_encrypt(&aes_key, &nonce, plaintext)?; + + let mut out = Vec::with_capacity(ciphertext.len() + PK_LEN + NONCE_LEN); + out.extend_from_slice(ephemeral_pk.as_bytes()); + out.extend_from_slice(nonce.as_slice()); + out.extend_from_slice(ciphertext.as_slice()); + + Ok(out) +} + +/// Encrypt `plaintext` with the given ed25519 public key. Decryption can be performed with the +/// matching secret key. +pub fn encrypt_ed25519(pk: &sp_core::ed25519::Public, plaintext: &[u8]) -> Result, Error> { + let ed25519 = curve25519_dalek::edwards::CompressedEdwardsY(pk.0); + let x25519 = ed25519.decompress().ok_or(Error::BadData)?.to_montgomery(); + let montgomery = x25519_dalek::PublicKey::from(x25519.to_bytes()); + encrypt_x25519(&montgomery, plaintext) +} + +/// Decrypt with the given x25519 secret key. +pub fn decrypt_x25519(sk: &SecretKey, encrypted: &[u8]) -> Result, Error> { + if encrypted.len() < PK_LEN + NONCE_LEN { + return Err(Error::BadData) + } + let mut ephemeral_pk: [u8; PK_LEN] = Default::default(); + ephemeral_pk.copy_from_slice(&encrypted[0..PK_LEN]); + let ephemeral_pk = PublicKey::from(ephemeral_pk); + + let mut shared_secret = sk.diffie_hellman(&ephemeral_pk).to_bytes().to_vec(); + shared_secret.extend_from_slice(ephemeral_pk.as_bytes()); + + let aes_key = kdf(&shared_secret); + + let nonce = &encrypted[PK_LEN..PK_LEN + NONCE_LEN]; + aes_decrypt(&aes_key, &nonce, &encrypted[PK_LEN + NONCE_LEN..]) +} + +/// Decrypt with the given ed25519 key pair. +pub fn decrypt_ed25519(pair: &sp_core::ed25519::Pair, encrypted: &[u8]) -> Result, Error> { + let raw = pair.to_raw_vec(); + let hash: [u8; 32] = sha2::Sha512::digest(&raw).as_slice()[..32] + .try_into() + .map_err(|_| Error::Decryption)?; + let secret = x25519_dalek::StaticSecret::from(hash); + decrypt_x25519(&secret, encrypted) +} + +#[cfg(test)] +mod test { + use super::*; + use rand::rngs::OsRng; + use sp_core::crypto::Pair; + + #[test] + fn basic_x25519_encryption() { + let sk = SecretKey::new(OsRng); + let pk = PublicKey::from(&sk); + + let plain_message = b"An important secret message"; + let encrypted = encrypt_x25519(&pk, plain_message).unwrap(); + + let decrypted = decrypt_x25519(&sk, &encrypted).unwrap(); + assert_eq!(plain_message, decrypted.as_slice()); + } + + #[test] + fn basic_ed25519_encryption() { + let (pair, _) = sp_core::ed25519::Pair::generate(); + let pk = pair.into(); + + let plain_message = b"An important secret message"; + let encrypted = encrypt_ed25519(&pk, plain_message).unwrap(); + + let decrypted = decrypt_ed25519(&pair, &encrypted).unwrap(); + assert_eq!(plain_message, decrypted.as_slice()); + } + + #[test] + fn fails_on_bad_data() { + let sk = SecretKey::new(OsRng); + let pk = PublicKey::from(&sk); + + let plain_message = b"An important secret message"; + let encrypted = encrypt_x25519(&pk, plain_message).unwrap(); + + assert_eq!(decrypt_x25519(&sk, &[]), Err(Error::BadData)); + assert_eq!( + decrypt_x25519(&sk, &encrypted[0..super::PK_LEN + super::NONCE_LEN - 1]), + Err(Error::BadData) + ); + } +} diff --git a/primitives/statement-store/src/lib.rs b/primitives/statement-store/src/lib.rs index e5c642d24e2b3..67e7a7b3896b5 100644 --- a/primitives/statement-store/src/lib.rs +++ b/primitives/statement-store/src/lib.rs @@ -49,6 +49,8 @@ pub use store_api::{ Error, NetworkPriority, Result, StatementSource, StatementStore, SubmitResult, }; +#[cfg(feature = "std")] +mod ecies; pub mod runtime_api; #[cfg(feature = "std")] mod store_api; @@ -61,12 +63,17 @@ mod sr25519 { pub type Public = app_sr25519::Public; } -mod ed25519 { +/// Statement-store specific ed25519 crypto primitives. +pub mod ed25519 { mod app_ed25519 { use sp_application_crypto::{app_crypto, ed25519, key_types::STATEMENT}; app_crypto!(ed25519, STATEMENT); } + /// Statement-store specific ed25519 public key. pub type Public = app_ed25519::Public; + /// Statement-store specific ed25519 key pair. + #[cfg(feature = "std")] + pub type Pair = app_ed25519::Pair; } mod ecdsa { @@ -507,6 +514,28 @@ impl Statement { } output } + + /// Encrypt give data with given key and store both in the statements. + #[cfg(feature = "std")] + pub fn encrypt( + &mut self, + data: &[u8], + key: &sp_core::ed25519::Public, + ) -> core::result::Result<(), ecies::Error> { + let encrypted = ecies::encrypt_ed25519(key, data)?; + self.data = Some(encrypted); + self.decryption_key = Some((*key).into()); + Ok(()) + } + + /// Decrypt data (if any) with the given private key. + #[cfg(feature = "std")] + pub fn decrypt_private( + &self, + key: &sp_core::ed25519::Pair, + ) -> core::result::Result>, ecies::Error> { + self.data.as_ref().map(|d| ecies::decrypt_ed25519(key, d)).transpose() + } } #[cfg(test)] @@ -615,4 +644,18 @@ mod test { statement.remove_proof(); assert_eq!(statement.verify_signature(), SignatureVerificationResult::NoSignature); } + + #[test] + fn encrypt_decrypt() { + let mut statement = Statement::new(); + let (pair, _) = sp_core::ed25519::Pair::generate(); + let plain = b"test data".to_vec(); + + //let sr25519_kp = sp_core::sr25519::Pair::from_string("//Alice", None).unwrap(); + statement.encrypt(&plain, &pair.public()).unwrap(); + assert_ne!(plain.as_slice(), statement.data().unwrap().as_slice()); + + let decrypted = statement.decrypt_private(&pair).unwrap(); + assert_eq!(decrypted, Some(plain)); + } } diff --git a/utils/wasm-builder/src/lib.rs b/utils/wasm-builder/src/lib.rs index 8405b5a0bda9e..c9011f97be711 100644 --- a/utils/wasm-builder/src/lib.rs +++ b/utils/wasm-builder/src/lib.rs @@ -222,7 +222,7 @@ fn get_rustup_command() -> Option { continue } - let Some(cargo_version) = cmd.version() else { continue; }; + let Some(cargo_version) = cmd.version() else { continue }; versions.push((cargo_version, rustup_version.to_string())); } From 696d09b3d1da1b2045fe46200df1d9f6d6d9d829 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Silva?= <123550+andresilva@users.noreply.github.com> Date: Tue, 18 Jul 2023 06:56:40 +0100 Subject: [PATCH 39/39] client: fix invalid node name pattern regex (#14593) * client: fix invalid name pattern regex * Update client/cli/src/commands/run_cmd.rs Co-authored-by: Oliver Tale-Yazdi * client: test node name is non-empty * client: add more tests to is_node_name_valid --------- Co-authored-by: Oliver Tale-Yazdi --- client/cli/src/commands/run_cmd.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/client/cli/src/commands/run_cmd.rs b/client/cli/src/commands/run_cmd.rs index 2942cfac4c7a3..5dda488b13330 100644 --- a/client/cli/src/commands/run_cmd.rs +++ b/client/cli/src/commands/run_cmd.rs @@ -394,6 +394,11 @@ impl CliConfiguration for RunCmd { /// Check whether a node name is considered as valid. pub fn is_node_name_valid(_name: &str) -> std::result::Result<(), &str> { let name = _name.to_string(); + + if name.is_empty() { + return Err("Node name cannot be empty") + } + if name.chars().count() >= crate::NODE_NAME_MAX_LENGTH { return Err("Node name too long") } @@ -404,7 +409,7 @@ pub fn is_node_name_valid(_name: &str) -> std::result::Result<(), &str> { return Err("Node name should not contain invalid chars such as '.' and '@'") } - let invalid_patterns = r"^https?:\/\/"; + let invalid_patterns = r"^https?:"; let re = Regex::new(invalid_patterns).unwrap(); if re.is_match(&name) { return Err("Node name should not contain urls") @@ -498,15 +503,23 @@ mod tests { #[test] fn tests_node_name_bad() { + assert!(is_node_name_valid("").is_err()); assert!(is_node_name_valid( "very very long names are really not very cool for the ui at all, really they're not" ) .is_err()); assert!(is_node_name_valid("Dots.not.Ok").is_err()); - assert!(is_node_name_valid("http://visit.me").is_err()); - assert!(is_node_name_valid("https://visit.me").is_err()); + // NOTE: the urls below don't include a domain otherwise + // they'd get filtered for including a `.` + assert!(is_node_name_valid("http://visitme").is_err()); + assert!(is_node_name_valid("http:/visitme").is_err()); + assert!(is_node_name_valid("http:visitme").is_err()); + assert!(is_node_name_valid("https://visitme").is_err()); + assert!(is_node_name_valid("https:/visitme").is_err()); + assert!(is_node_name_valid("https:visitme").is_err()); assert!(is_node_name_valid("www.visit.me").is_err()); assert!(is_node_name_valid("www.visit").is_err()); + assert!(is_node_name_valid("hello\\world").is_err()); assert!(is_node_name_valid("visit.www").is_err()); assert!(is_node_name_valid("email@domain").is_err()); }