diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 9df4c0b618661..e6f26cbfd5cf7 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -41,7 +41,7 @@ workflow: - if: $CI_COMMIT_TAG - if: $CI_COMMIT_BRANCH -variables: &default-vars +variables: GIT_STRATEGY: fetch GIT_DEPTH: 100 CARGO_INCREMENTAL: 0 @@ -278,8 +278,6 @@ rusty-cachier-notify: PR_NUM: "${PR_NUM}" trigger: project: "parity/infrastructure/ci_cd/pipeline-stopper" - # remove branch, when pipeline-stopper for polakdot is updated to the same branch - branch: "as-improve" # need to copy jobs this way because otherwise gitlab will wait # for all 3 jobs to finish instead of cancelling if one fails diff --git a/Cargo.lock b/Cargo.lock index 4d55345acd369..1362df697a20b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -112,6 +112,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "698b65a961a9d730fb45b6b0327e20207810c9f61ee421b082b27ba003f49e2b" +[[package]] +name = "array-bytes" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a913633b0c922e6b745072795f50d90ebea78ba31a57e2ac8c2fc7b50950949" + [[package]] name = "arrayref" version = "0.3.6" @@ -446,12 +452,12 @@ dependencies = [ name = "beefy-gadget" version = "4.0.0-dev" dependencies = [ + "array-bytes", "async-trait", "beefy-primitives", "fnv", "futures", "futures-timer", - "hex", "log", "parity-scale-codec", "parking_lot 0.12.1", @@ -513,10 +519,9 @@ dependencies = [ name = "beefy-merkle-tree" version = "4.0.0-dev" dependencies = [ + "array-bytes", "beefy-primitives", "env_logger", - "hex", - "hex-literal", "log", "sp-api", "tiny-keccak", @@ -526,8 +531,7 @@ dependencies = [ name = "beefy-primitives" version = "4.0.0-dev" dependencies = [ - "hex", - "hex-literal", + "array-bytes", "parity-scale-codec", "scale-info", "sp-api", @@ -1148,11 +1152,11 @@ dependencies = [ [[package]] name = "cranelift-bforest" -version = "0.87.1" +version = "0.88.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f91425bea5a5ac6d76b788477064944a7e21f0e240fd93f6f368a774a3efdd1" +checksum = "b27bbd3e6c422cf6282b047bcdd51ecd9ca9f3497a3be0132ffa08e509b824b0" dependencies = [ - "cranelift-entity 0.87.1", + "cranelift-entity 0.88.0", ] [[package]] @@ -1174,14 +1178,16 @@ dependencies = [ [[package]] name = "cranelift-codegen" -version = "0.87.1" +version = "0.88.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b83b4bbf7bc96db77b7b5b5e41fafc4001536e9f0cbfd702ed7d4d8f848dc06" +checksum = "872f5d4557a411b087bd731df6347c142ae1004e6467a144a7e33662e5715a01" dependencies = [ - "cranelift-bforest 0.87.1", - "cranelift-codegen-meta 0.87.1", - "cranelift-codegen-shared 0.87.1", - "cranelift-entity 0.87.1", + "arrayvec 0.7.2", + "bumpalo", + "cranelift-bforest 0.88.0", + "cranelift-codegen-meta 0.88.0", + "cranelift-codegen-shared 0.88.0", + "cranelift-entity 0.88.0", "cranelift-isle", "gimli 0.26.1", "log", @@ -1202,11 +1208,11 @@ dependencies = [ [[package]] name = "cranelift-codegen-meta" -version = "0.87.1" +version = "0.88.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da02e8fff048c381b313a3dfef4deb2343976fb6d7acc8e7d9c86d4c93e3fa06" +checksum = "21b49fdebb29c62c1fc4da1eeebd609e9d530ecde24a9876def546275f73a244" dependencies = [ - "cranelift-codegen-shared 0.87.1", + "cranelift-codegen-shared 0.88.0", ] [[package]] @@ -1217,9 +1223,9 @@ checksum = "9dabb5fe66e04d4652e434195b45ae65b5c8172d520247b8f66d8df42b2b45dc" [[package]] name = "cranelift-codegen-shared" -version = "0.87.1" +version = "0.88.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9abc2a06e8fc29e36660ebbc9e2503e18a051057072acbb1e75e7f7cf19cb95e" +checksum = "5fc0c091e2db055d4d7f6b7cec2d2ead286bcfaea3357c6a52c2a2613a8cb5ac" [[package]] name = "cranelift-entity" @@ -1229,9 +1235,9 @@ checksum = "3329733e4d4b8e91c809efcaa4faee80bf66f20164e3dd16d707346bd3494799" [[package]] name = "cranelift-entity" -version = "0.87.1" +version = "0.88.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aeced7874890fc25d85cacc5e626c4d67931c7c25aad1c2ad521684744c1ff5c" +checksum = "354a9597be87996c9b278655e68b8447f65dd907256855ad773864edee8d985c" dependencies = [ "serde", ] @@ -1250,11 +1256,11 @@ dependencies = [ [[package]] name = "cranelift-frontend" -version = "0.87.1" +version = "0.88.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc1d301ccad6fce05d9c9793d433d225fafdd57661b98d268d8d162e9291ff2e" +checksum = "0cd8dd3fb8b82c772f4172e87ae1677b971676fffa7c4e3398e3047e650a266b" dependencies = [ - "cranelift-codegen 0.87.1", + "cranelift-codegen 0.88.0", "log", "smallvec", "target-lexicon", @@ -1262,34 +1268,34 @@ dependencies = [ [[package]] name = "cranelift-isle" -version = "0.87.1" +version = "0.88.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd7b100db19320848986b4df1da19501dbddeb706a799f502222f72f889b0fab" +checksum = "b82527802b1f7d8da288adc28f1dc97ea52943f5871c041213f7b5035ac698a7" [[package]] name = "cranelift-native" -version = "0.87.1" +version = "0.88.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7be18d8b976cddc822e52343f328b7593d26dd2f1aeadd90da071596a210d524" +checksum = "c30ba8b910f1be023af0c39109cb28a8809734942a6b3eecbf2de8993052ea5e" dependencies = [ - "cranelift-codegen 0.87.1", + "cranelift-codegen 0.88.0", "libc", "target-lexicon", ] [[package]] name = "cranelift-wasm" -version = "0.87.1" +version = "0.88.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f9e48bb632a2e189b38a9fa89fa5a6eea687a5a4c613bbef7c2b7522c3ad0e0" +checksum = "776a8916d201894aca9637a20814f1e11abc62acd5cfbe0b4eb2e63922756971" dependencies = [ - "cranelift-codegen 0.87.1", - "cranelift-entity 0.87.1", - "cranelift-frontend 0.87.1", + "cranelift-codegen 0.88.0", + "cranelift-entity 0.88.0", + "cranelift-frontend 0.88.0", "itertools", "log", "smallvec", - "wasmparser 0.88.0", + "wasmparser 0.89.1", "wasmtime-types", ] @@ -2111,9 +2117,9 @@ dependencies = [ name = "frame-benchmarking" version = "4.0.0-dev" dependencies = [ + "array-bytes", "frame-support", "frame-system", - "hex-literal", "linregress", "log", "parity-scale-codec", @@ -2137,6 +2143,7 @@ name = "frame-benchmarking-cli" version = "4.0.0-dev" dependencies = [ "Inflector", + "array-bytes", "chrono", "clap 3.1.18", "comfy-table", @@ -2146,7 +2153,6 @@ dependencies = [ "gethostname", "handlebars", "hash-db", - "hex", "itertools", "kvdb", "lazy_static", @@ -2237,10 +2243,10 @@ dependencies = [ name = "frame-executive" version = "4.0.0-dev" dependencies = [ + "array-bytes", "frame-support", "frame-system", "frame-try-runtime", - "hex-literal", "pallet-balances", "pallet-transaction-payment", "parity-scale-codec", @@ -2841,12 +2847,6 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" -[[package]] -name = "hex-literal" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ebdb29d2ea9ed0083cd8cece49bbd968021bd99b0849edb4a9a7ee0fdf6a4e0" - [[package]] name = "hex_fmt" version = "0.3.0" @@ -3342,7 +3342,6 @@ dependencies = [ "frame-system-benchmarking", "frame-system-rpc-runtime-api", "frame-try-runtime", - "hex-literal", "log", "node-primitives", "pallet-alliance", @@ -3364,6 +3363,7 @@ dependencies = [ "pallet-election-provider-multi-phase", "pallet-election-provider-support-benchmarking", "pallet-elections-phragmen", + "pallet-fast-unstake", "pallet-gilt", "pallet-grandpa", "pallet-identity", @@ -4612,12 +4612,12 @@ dependencies = [ name = "node-bench" version = "0.9.0-dev" dependencies = [ + "array-bytes", "clap 3.1.18", "derive_more", "fs_extra", "futures", "hash-db", - "hex", "kitchensink-runtime", "kvdb", "kvdb-rocksdb", @@ -4649,6 +4649,7 @@ dependencies = [ name = "node-cli" version = "3.0.0-dev" dependencies = [ + "array-bytes", "assert_cmd", "async-std", "clap 3.1.18", @@ -4658,7 +4659,6 @@ dependencies = [ "frame-system", "frame-system-rpc-runtime-api", "futures", - "hex-literal", "jsonrpsee", "kitchensink-runtime", "log", @@ -4811,6 +4811,7 @@ dependencies = [ "sc-finality-grandpa-rpc", "sc-rpc", "sc-rpc-api", + "sc-rpc-spec-v2", "sc-sync-state-rpc", "sc-transaction-pool-api", "sp-api", @@ -4886,7 +4887,6 @@ dependencies = [ "frame-system-benchmarking", "frame-system-rpc-runtime-api", "frame-try-runtime", - "hex-literal", "pallet-aura", "pallet-balances", "pallet-grandpa", @@ -5155,11 +5155,10 @@ dependencies = [ name = "pallet-alliance" version = "4.0.0-dev" dependencies = [ + "array-bytes", "frame-benchmarking", "frame-support", "frame-system", - "hex", - "hex-literal", "log", "pallet-balances", "pallet-collective", @@ -5390,12 +5389,11 @@ dependencies = [ name = "pallet-beefy-mmr" version = "4.0.0-dev" dependencies = [ + "array-bytes", "beefy-merkle-tree", "beefy-primitives", "frame-support", "frame-system", - "hex", - "hex-literal", "log", "pallet-beefy", "pallet-mmr", @@ -5467,13 +5465,13 @@ dependencies = [ name = "pallet-contracts" version = "4.0.0-dev" dependencies = [ + "array-bytes", "assert_matches", "bitflags", "env_logger", "frame-benchmarking", "frame-support", "frame-system", - "hex-literal", "impl-trait-for-tuples", "log", "pallet-balances", @@ -5696,6 +5694,31 @@ dependencies = [ "sp-tasks", ] +[[package]] +name = "pallet-fast-unstake" +version = "4.0.0-dev" +dependencies = [ + "frame-benchmarking", + "frame-election-provider-support", + "frame-support", + "frame-system", + "log", + "pallet-balances", + "pallet-nomination-pools", + "pallet-staking", + "pallet-staking-reward-curve", + "pallet-timestamp", + "parity-scale-codec", + "scale-info", + "sp-core", + "sp-io", + "sp-runtime", + "sp-staking", + "sp-std", + "sp-tracing", + "substrate-test-utils", +] + [[package]] name = "pallet-gilt" version = "4.0.0-dev" @@ -5834,12 +5857,12 @@ dependencies = [ name = "pallet-mmr" version = "4.0.0-dev" dependencies = [ + "array-bytes", "ckb-merkle-mountain-range", "env_logger", "frame-benchmarking", "frame-support", "frame-system", - "hex-literal", "itertools", "parity-scale-codec", "scale-info", @@ -6427,10 +6450,10 @@ dependencies = [ name = "pallet-transaction-storage" version = "4.0.0-dev" dependencies = [ + "array-bytes", "frame-benchmarking", "frame-support", "frame-system", - "hex-literal", "log", "pallet-balances", "parity-scale-codec", @@ -7871,11 +7894,11 @@ dependencies = [ name = "sc-cli" version = "0.10.0-dev" dependencies = [ + "array-bytes", "chrono", "clap 3.1.18", "fdlimit", "futures", - "hex", "libp2p", "log", "names", @@ -8217,9 +8240,9 @@ dependencies = [ name = "sc-executor" version = "0.10.0-dev" dependencies = [ + "array-bytes", "criterion", "env_logger", - "hex-literal", "lazy_static", "lru", "num_cpus", @@ -8313,6 +8336,7 @@ name = "sc-finality-grandpa" version = "0.10.0-dev" dependencies = [ "ahash", + "array-bytes", "assert_matches", "async-trait", "dyn-clone", @@ -8320,7 +8344,6 @@ dependencies = [ "fork-tree", "futures", "futures-timer", - "hex", "log", "parity-scale-codec", "parking_lot 0.12.1", @@ -8401,8 +8424,8 @@ dependencies = [ name = "sc-keystore" version = "4.0.0-dev" dependencies = [ + "array-bytes", "async-trait", - "hex", "parking_lot 0.12.1", "serde_json", "sp-application-crypto", @@ -8416,6 +8439,7 @@ dependencies = [ name = "sc-network" version = "0.10.0-dev" dependencies = [ + "array-bytes", "assert_matches", "async-std", "async-trait", @@ -8428,7 +8452,6 @@ dependencies = [ "fork-tree", "futures", "futures-timer", - "hex", "ip_network", "libp2p", "linked-hash-map", @@ -8539,8 +8562,8 @@ dependencies = [ name = "sc-network-light" version = "0.10.0-dev" dependencies = [ + "array-bytes", "futures", - "hex", "libp2p", "log", "parity-scale-codec", @@ -8559,9 +8582,9 @@ dependencies = [ name = "sc-network-sync" version = "0.10.0-dev" dependencies = [ + "array-bytes", "fork-tree", "futures", - "hex", "libp2p", "log", "lru", @@ -8621,11 +8644,11 @@ dependencies = [ name = "sc-offchain" version = "4.0.0-dev" dependencies = [ + "array-bytes", "bytes", "fnv", "futures", "futures-timer", - "hex", "hyper", "hyper-rustls", "lazy_static", @@ -8749,6 +8772,17 @@ dependencies = [ "tokio", ] +[[package]] +name = "sc-rpc-spec-v2" +version = "0.10.0-dev" +dependencies = [ + "hex", + "jsonrpsee", + "sc-chain-spec", + "serde_json", + "tokio", +] + [[package]] name = "sc-runtime-test" version = "2.0.0" @@ -8838,10 +8872,9 @@ dependencies = [ name = "sc-service-test" version = "2.0.0" dependencies = [ + "array-bytes", "fdlimit", "futures", - "hex", - "hex-literal", "log", "parity-scale-codec", "parking_lot 0.12.1", @@ -8982,11 +9015,11 @@ dependencies = [ name = "sc-transaction-pool" version = "4.0.0-dev" dependencies = [ + "array-bytes", "assert_matches", "criterion", "futures", "futures-timer", - "hex", "linked-hash-map", "log", "parity-scale-codec", @@ -9724,6 +9757,7 @@ dependencies = [ name = "sp-core" version = "6.0.0" dependencies = [ + "array-bytes", "base58", "bitflags", "blake2", @@ -9734,8 +9768,6 @@ dependencies = [ "futures", "hash-db", "hash256-std-hasher", - "hex", - "hex-literal", "impl-serde", "lazy_static", "libsecp256k1", @@ -9916,7 +9948,7 @@ dependencies = [ name = "sp-mmr-primitives" version = "4.0.0-dev" dependencies = [ - "hex-literal", + "array-bytes", "log", "parity-scale-codec", "serde", @@ -10134,9 +10166,9 @@ dependencies = [ name = "sp-state-machine" version = "0.12.0" dependencies = [ + "array-bytes", "assert_matches", "hash-db", - "hex-literal", "log", "num-traits", "parity-scale-codec", @@ -10251,10 +10283,10 @@ name = "sp-trie" version = "6.0.0" dependencies = [ "ahash", + "array-bytes", "criterion", "hash-db", "hashbrown 0.12.3", - "hex-literal", "lazy_static", "lru", "memory-db", @@ -10491,6 +10523,8 @@ dependencies = [ "sc-rpc-api", "scale-info", "serde", + "sp-core", + "sp-runtime", "sp-storage", "tokio", ] @@ -10557,9 +10591,9 @@ dependencies = [ name = "substrate-test-client" version = "2.0.1" dependencies = [ + "array-bytes", "async-trait", "futures", - "hex", "parity-scale-codec", "sc-client-api", "sc-client-db", @@ -11829,18 +11863,18 @@ checksum = "52144d4c78e5cf8b055ceab8e5fa22814ce4315d6002ad32cfd914f37c12fd65" [[package]] name = "wasmparser" -version = "0.88.0" +version = "0.89.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb8cf7dd82407fe68161bedcd57fde15596f32ebf6e9b3bdbf3ae1da20e38e5e" +checksum = "ab5d3e08b13876f96dd55608d03cd4883a0545884932d5adf11925876c96daef" dependencies = [ "indexmap", ] [[package]] name = "wasmtime" -version = "0.40.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a020a3f6587fa7a7d98a021156177735ebb07212a6239a85ab5f14b2f728508f" +checksum = "8a10dc9784d8c3a33c970e3939180424955f08af2e7f20368ec02685a0e8f065" dependencies = [ "anyhow", "bincode", @@ -11855,7 +11889,7 @@ dependencies = [ "rayon", "serde", "target-lexicon", - "wasmparser 0.88.0", + "wasmparser 0.89.1", "wasmtime-cache", "wasmtime-cranelift", "wasmtime-environ", @@ -11866,18 +11900,18 @@ dependencies = [ [[package]] name = "wasmtime-asm-macros" -version = "0.40.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fed4ada1fdd4d9a2aa37be652abcc31ae3188ad0efcefb4571ef4f785be2d777" +checksum = "ee4dbdc6daf68528cad1275ac91e3f51848ce9824385facc94c759f529decdf8" dependencies = [ "cfg-if 1.0.0", ] [[package]] name = "wasmtime-cache" -version = "0.40.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d96a03a5732ef39b83943d9d72de8ac2d58623d3bfaaea4d9a92aea5fcd9acf5" +checksum = "9f507f3fa1ee1b2f9a83644e2514242b1dfe580782c0eb042f1ef70255bc4ffe" dependencies = [ "anyhow", "base64", @@ -11895,14 +11929,14 @@ dependencies = [ [[package]] name = "wasmtime-cranelift" -version = "0.40.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fc59c28fe895112db09e262fb9c483f9e7b82c78a82a6ded69567ccc0e9795b" +checksum = "8f03cf79d982fc68e94ba0bea6a300a3b94621c4eb9705eece0a4f06b235a3b5" dependencies = [ "anyhow", - "cranelift-codegen 0.87.1", - "cranelift-entity 0.87.1", - "cranelift-frontend 0.87.1", + "cranelift-codegen 0.88.0", + "cranelift-entity 0.88.0", + "cranelift-frontend 0.88.0", "cranelift-native", "cranelift-wasm", "gimli 0.26.1", @@ -11910,18 +11944,18 @@ dependencies = [ "object 0.29.0", "target-lexicon", "thiserror", - "wasmparser 0.88.0", + "wasmparser 0.89.1", "wasmtime-environ", ] [[package]] name = "wasmtime-environ" -version = "0.40.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11086e573d2635a45ac0d44697a8e4586e058cf1b190f76bea466ca2ec36c30a" +checksum = "5c587c62e91c5499df62012b87b88890d0eb470b2ffecc5964e9da967b70c77c" dependencies = [ "anyhow", - "cranelift-entity 0.87.1", + "cranelift-entity 0.88.0", "gimli 0.26.1", "indexmap", "log", @@ -11929,15 +11963,15 @@ dependencies = [ "serde", "target-lexicon", "thiserror", - "wasmparser 0.88.0", + "wasmparser 0.89.1", "wasmtime-types", ] [[package]] name = "wasmtime-jit" -version = "0.40.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5444a78b74144718633f8642eccd7c4858f4c6f0c98ae6a3668998adf177ba2" +checksum = "047839b5dabeae5424a078c19b8cc897e5943a7fadc69e3d888b9c9a897666b3" dependencies = [ "addr2line", "anyhow", @@ -11960,9 +11994,9 @@ dependencies = [ [[package]] name = "wasmtime-jit-debug" -version = "0.40.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2bf6a667d2a29b2b0ed42bcf7564f00c595d92c24acb4d241c7c4d950b1910c" +checksum = "b299569abf6f99b7b8e020afaf84a700e8636c6a42e242069267322cd5818235" dependencies = [ "object 0.29.0", "once_cell", @@ -11971,9 +12005,9 @@ dependencies = [ [[package]] name = "wasmtime-runtime" -version = "0.40.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee064ce7b563cc201cdf3bb1cc4b233f386d8c57a96e55f4c4afe6103f4bd6a1" +checksum = "ae79e0515160bd5abee5df50a16c4eb8db9f71b530fc988ae1d9ce34dcb8dd01" dependencies = [ "anyhow", "cc", @@ -11996,14 +12030,14 @@ dependencies = [ [[package]] name = "wasmtime-types" -version = "0.40.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01e104bd9e625181d53ead85910bbc0863aa5f0c6ef96836fe9a5cc65da11b69" +checksum = "790cf43ee8e2d5dad1780af30f00d7a972b74725fb1e4f90c28d62733819b185" dependencies = [ - "cranelift-entity 0.87.1", + "cranelift-entity 0.88.0", "serde", "thiserror", - "wasmparser 0.88.0", + "wasmparser 0.89.1", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 4dbf65dc7e1fe..018355df6c9fd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,6 +55,7 @@ members = [ "client/rpc", "client/rpc-api", "client/rpc-servers", + "client/rpc-spec-v2", "client/service", "client/service/test", "client/state-db", @@ -89,6 +90,7 @@ members = [ "frame/contracts/rpc/runtime-api", "frame/conviction-voting", "frame/democracy", + "frame/fast-unstake", "frame/try-runtime", "frame/election-provider-multi-phase", "frame/election-provider-support", diff --git a/bin/node-template/pallets/template/src/mock.rs b/bin/node-template/pallets/template/src/mock.rs index 3289ec2da4952..989681fa59a00 100644 --- a/bin/node-template/pallets/template/src/mock.rs +++ b/bin/node-template/pallets/template/src/mock.rs @@ -27,7 +27,7 @@ impl system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = u64; diff --git a/bin/node-template/pallets/template/src/tests.rs b/bin/node-template/pallets/template/src/tests.rs index 2205658601721..527aec8ed00c0 100644 --- a/bin/node-template/pallets/template/src/tests.rs +++ b/bin/node-template/pallets/template/src/tests.rs @@ -5,7 +5,7 @@ use frame_support::{assert_noop, assert_ok}; fn it_works_for_default_value() { new_test_ext().execute_with(|| { // Dispatch a signed extrinsic. - assert_ok!(TemplateModule::do_something(Origin::signed(1), 42)); + assert_ok!(TemplateModule::do_something(RuntimeOrigin::signed(1), 42)); // Read pallet storage and assert an expected result. assert_eq!(TemplateModule::something(), Some(42)); }); @@ -15,6 +15,9 @@ fn it_works_for_default_value() { fn correct_error_for_none_value() { new_test_ext().execute_with(|| { // Ensure the expected error is thrown when no value is present. - assert_noop!(TemplateModule::cause_error(Origin::signed(1)), Error::::NoneValue); + assert_noop!( + TemplateModule::cause_error(RuntimeOrigin::signed(1)), + Error::::NoneValue + ); }); } diff --git a/bin/node-template/runtime/Cargo.toml b/bin/node-template/runtime/Cargo.toml index c6c4b2ea911ec..45ab4939e311c 100644 --- a/bin/node-template/runtime/Cargo.toml +++ b/bin/node-template/runtime/Cargo.toml @@ -46,7 +46,6 @@ pallet-transaction-payment-rpc-runtime-api = { version = "4.0.0-dev", default-fe # Used for runtime benchmarking frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../../../frame/benchmarking", optional = true } frame-system-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../../../frame/system/benchmarking", optional = true } -hex-literal = { version = "0.3.4", optional = true } # Local Dependencies pallet-template = { version = "4.0.0-dev", default-features = false, path = "../pallets/template" } @@ -93,7 +92,6 @@ runtime-benchmarks = [ "frame-support/runtime-benchmarks", "frame-system-benchmarking/runtime-benchmarks", "frame-system/runtime-benchmarks", - "hex-literal", "pallet-balances/runtime-benchmarks", "pallet-grandpa/runtime-benchmarks", "pallet-template/runtime-benchmarks", diff --git a/bin/node-template/runtime/src/lib.rs b/bin/node-template/runtime/src/lib.rs index c309b27682080..f801068b10fda 100644 --- a/bin/node-template/runtime/src/lib.rs +++ b/bin/node-template/runtime/src/lib.rs @@ -174,7 +174,7 @@ impl frame_system::Config for Runtime { /// The ubiquitous event type. type RuntimeEvent = RuntimeEvent; /// The ubiquitous origin type. - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; /// Maximum number of block number to block hash mappings to keep (oldest pruned first). type BlockHashCount = BlockHashCount; /// The weight of database operations that the runtime can invoke. diff --git a/bin/node/bench/Cargo.toml b/bin/node/bench/Cargo.toml index cca20d14b40f1..42953da837100 100644 --- a/bin/node/bench/Cargo.toml +++ b/bin/node/bench/Cargo.toml @@ -11,6 +11,7 @@ repository = "https://github.com/paritytech/substrate/" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +array-bytes = "4.1" clap = { version = "3.1.18", features = ["derive"] } log = "0.4.17" node-primitives = { version = "2.0.0", path = "../primitives" } @@ -34,7 +35,6 @@ sp-tracing = { version = "5.0.0", path = "../../../primitives/tracing" } hash-db = "0.15.2" tempfile = "3.1.0" fs_extra = "1" -hex = "0.4.0" rand = { version = "0.7.2", features = ["small_rng"] } lazy_static = "1.4.0" parity-util-mem = { version = "0.12.0", default-features = false, features = ["primitive-types"] } diff --git a/bin/node/bench/src/generator.rs b/bin/node/bench/src/generator.rs index 863928c719429..76bd3a3240c51 100644 --- a/bin/node/bench/src/generator.rs +++ b/bin/node/bench/src/generator.rs @@ -37,8 +37,10 @@ pub fn generate_trie( let (db, overlay) = { let mut overlay = HashMap::new(); overlay.insert( - hex::decode("03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314") - .expect("null key is valid"), + array_bytes::hex2bytes( + "03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314", + ) + .expect("null key is valid"), Some(vec![0]), ); let mut trie = SimpleTrie { db, overlay: &mut overlay }; diff --git a/bin/node/cli/Cargo.toml b/bin/node/cli/Cargo.toml index a435945168e0d..edb434e3c04e3 100644 --- a/bin/node/cli/Cargo.toml +++ b/bin/node/cli/Cargo.toml @@ -34,12 +34,12 @@ crate-type = ["cdylib", "rlib"] [dependencies] # third-party dependencies +array-bytes = "4.1" clap = { version = "3.1.18", features = ["derive"], optional = true } codec = { package = "parity-scale-codec", version = "3.0.0" } serde = { version = "1.0.136", features = ["derive"] } jsonrpsee = { version = "0.15.1", features = ["server"] } futures = "0.3.21" -hex-literal = "0.3.4" log = "0.4.17" rand = "0.8" diff --git a/bin/node/cli/src/chain_spec.rs b/bin/node/cli/src/chain_spec.rs index 77e2f73dd6e18..8d74f2bde0f44 100644 --- a/bin/node/cli/src/chain_spec.rs +++ b/bin/node/cli/src/chain_spec.rs @@ -19,7 +19,6 @@ //! Substrate chain configurations. use grandpa_primitives::AuthorityId as GrandpaId; -use hex_literal::hex; use kitchensink_runtime::{ constants::currency::*, wasm_binary_unwrap, AuthorityDiscoveryConfig, BabeConfig, BalancesConfig, Block, CouncilConfig, DemocracyConfig, ElectionsConfig, GrandpaConfig, @@ -98,84 +97,83 @@ fn staging_testnet_config_genesis() -> GenesisConfig { )> = vec![ ( // 5Fbsd6WXDGiLTxunqeK5BATNiocfCqu9bS1yArVjCgeBLkVy - hex!["9c7a2ee14e565db0c69f78c7b4cd839fbf52b607d867e9e9c5a79042898a0d12"].into(), + array_bytes::hex_n_into_unchecked("9c7a2ee14e565db0c69f78c7b4cd839fbf52b607d867e9e9c5a79042898a0d12"), // 5EnCiV7wSHeNhjW3FSUwiJNkcc2SBkPLn5Nj93FmbLtBjQUq - hex!["781ead1e2fa9ccb74b44c19d29cb2a7a4b5be3972927ae98cd3877523976a276"].into(), + array_bytes::hex_n_into_unchecked("781ead1e2fa9ccb74b44c19d29cb2a7a4b5be3972927ae98cd3877523976a276"), // 5Fb9ayurnxnaXj56CjmyQLBiadfRCqUbL2VWNbbe1nZU6wiC - hex!["9becad03e6dcac03cee07edebca5475314861492cdfc96a2144a67bbe9699332"] + array_bytes::hex2array_unchecked("9becad03e6dcac03cee07edebca5475314861492cdfc96a2144a67bbe9699332") .unchecked_into(), // 5EZaeQ8djPcq9pheJUhgerXQZt9YaHnMJpiHMRhwQeinqUW8 - hex!["6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"] + array_bytes::hex2array_unchecked("6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106") .unchecked_into(), // 5EZaeQ8djPcq9pheJUhgerXQZt9YaHnMJpiHMRhwQeinqUW8 - hex!["6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"] + array_bytes::hex2array_unchecked("6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106") .unchecked_into(), // 5EZaeQ8djPcq9pheJUhgerXQZt9YaHnMJpiHMRhwQeinqUW8 - hex!["6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"] + array_bytes::hex2array_unchecked("6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106") .unchecked_into(), ), ( // 5ERawXCzCWkjVq3xz1W5KGNtVx2VdefvZ62Bw1FEuZW4Vny2 - hex!["68655684472b743e456907b398d3a44c113f189e56d1bbfd55e889e295dfde78"].into(), + array_bytes::hex_n_into_unchecked("68655684472b743e456907b398d3a44c113f189e56d1bbfd55e889e295dfde78"), // 5Gc4vr42hH1uDZc93Nayk5G7i687bAQdHHc9unLuyeawHipF - hex!["c8dc79e36b29395413399edaec3e20fcca7205fb19776ed8ddb25d6f427ec40e"].into(), + array_bytes::hex_n_into_unchecked("c8dc79e36b29395413399edaec3e20fcca7205fb19776ed8ddb25d6f427ec40e"), // 5EockCXN6YkiNCDjpqqnbcqd4ad35nU4RmA1ikM4YeRN4WcE - hex!["7932cff431e748892fa48e10c63c17d30f80ca42e4de3921e641249cd7fa3c2f"] + array_bytes::hex2array_unchecked("7932cff431e748892fa48e10c63c17d30f80ca42e4de3921e641249cd7fa3c2f") .unchecked_into(), // 5DhLtiaQd1L1LU9jaNeeu9HJkP6eyg3BwXA7iNMzKm7qqruQ - hex!["482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e"] + array_bytes::hex2array_unchecked("482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e") .unchecked_into(), // 5DhLtiaQd1L1LU9jaNeeu9HJkP6eyg3BwXA7iNMzKm7qqruQ - hex!["482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e"] + array_bytes::hex2array_unchecked("482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e") .unchecked_into(), // 5DhLtiaQd1L1LU9jaNeeu9HJkP6eyg3BwXA7iNMzKm7qqruQ - hex!["482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e"] + array_bytes::hex2array_unchecked("482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e") .unchecked_into(), ), ( // 5DyVtKWPidondEu8iHZgi6Ffv9yrJJ1NDNLom3X9cTDi98qp - hex!["547ff0ab649283a7ae01dbc2eb73932eba2fb09075e9485ff369082a2ff38d65"].into(), + array_bytes::hex_n_into_unchecked("547ff0ab649283a7ae01dbc2eb73932eba2fb09075e9485ff369082a2ff38d65"), // 5FeD54vGVNpFX3PndHPXJ2MDakc462vBCD5mgtWRnWYCpZU9 - hex!["9e42241d7cd91d001773b0b616d523dd80e13c6c2cab860b1234ef1b9ffc1526"].into(), + array_bytes::hex_n_into_unchecked("9e42241d7cd91d001773b0b616d523dd80e13c6c2cab860b1234ef1b9ffc1526"), // 5E1jLYfLdUQKrFrtqoKgFrRvxM3oQPMbf6DfcsrugZZ5Bn8d - hex!["5633b70b80a6c8bb16270f82cca6d56b27ed7b76c8fd5af2986a25a4788ce440"] + array_bytes::hex2array_unchecked("5633b70b80a6c8bb16270f82cca6d56b27ed7b76c8fd5af2986a25a4788ce440") .unchecked_into(), // 5DhKqkHRkndJu8vq7pi2Q5S3DfftWJHGxbEUNH43b46qNspH - hex!["482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a"] + array_bytes::hex2array_unchecked("482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a") .unchecked_into(), // 5DhKqkHRkndJu8vq7pi2Q5S3DfftWJHGxbEUNH43b46qNspH - hex!["482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a"] + array_bytes::hex2array_unchecked("482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a") .unchecked_into(), // 5DhKqkHRkndJu8vq7pi2Q5S3DfftWJHGxbEUNH43b46qNspH - hex!["482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a"] + array_bytes::hex2array_unchecked("482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a") .unchecked_into(), ), ( // 5HYZnKWe5FVZQ33ZRJK1rG3WaLMztxWrrNDb1JRwaHHVWyP9 - hex!["f26cdb14b5aec7b2789fd5ca80f979cef3761897ae1f37ffb3e154cbcc1c2663"].into(), + array_bytes::hex_n_into_unchecked("f26cdb14b5aec7b2789fd5ca80f979cef3761897ae1f37ffb3e154cbcc1c2663"), // 5EPQdAQ39WQNLCRjWsCk5jErsCitHiY5ZmjfWzzbXDoAoYbn - hex!["66bc1e5d275da50b72b15de072a2468a5ad414919ca9054d2695767cf650012f"].into(), + array_bytes::hex_n_into_unchecked("66bc1e5d275da50b72b15de072a2468a5ad414919ca9054d2695767cf650012f"), // 5DMa31Hd5u1dwoRKgC4uvqyrdK45RHv3CpwvpUC1EzuwDit4 - hex!["3919132b851ef0fd2dae42a7e734fe547af5a6b809006100f48944d7fae8e8ef"] + array_bytes::hex2array_unchecked("3919132b851ef0fd2dae42a7e734fe547af5a6b809006100f48944d7fae8e8ef") .unchecked_into(), // 5C4vDQxA8LTck2xJEy4Yg1hM9qjDt4LvTQaMo4Y8ne43aU6x - hex!["00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378"] + array_bytes::hex2array_unchecked("00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378") .unchecked_into(), // 5C4vDQxA8LTck2xJEy4Yg1hM9qjDt4LvTQaMo4Y8ne43aU6x - hex!["00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378"] + array_bytes::hex2array_unchecked("00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378") .unchecked_into(), // 5C4vDQxA8LTck2xJEy4Yg1hM9qjDt4LvTQaMo4Y8ne43aU6x - hex!["00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378"] + array_bytes::hex2array_unchecked("00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378") .unchecked_into(), ), ]; // generated with secret: subkey inspect "$secret"/fir - let root_key: AccountId = hex![ + let root_key: AccountId = array_bytes::hex_n_into_unchecked( // 5Ff3iXP75ruzroPWRP2FYBHWnmGGBSb63857BgnzCoXNxfPo - "9ee5e5bdc0ec239eb164f865ecc345ce4c88e76ee002e0f7e318097347471809" - ] - .into(); + "9ee5e5bdc0ec239eb164f865ecc345ce4c88e76ee002e0f7e318097347471809", + ); let endowed_accounts: Vec = vec![root_key.clone()]; diff --git a/bin/node/cli/src/service.rs b/bin/node/cli/src/service.rs index c058e22fa7a97..f2b4feb58075f 100644 --- a/bin/node/cli/src/service.rs +++ b/bin/node/cli/src/service.rs @@ -587,7 +587,7 @@ mod tests { RuntimeAppPublic, }; use sp_timestamp; - use std::{borrow::Cow, sync::Arc}; + use std::sync::Arc; type AccountPublic = ::Signer; @@ -733,9 +733,9 @@ mod tests { let mut params = BlockImportParams::new(BlockOrigin::File, new_header); params.post_digests.push(item); params.body = Some(new_body); - params.intermediates.insert( - Cow::from(INTERMEDIATE_KEY), - Box::new(BabeIntermediate:: { epoch_descriptor }) as Box<_>, + params.insert_intermediate( + INTERMEDIATE_KEY, + BabeIntermediate:: { epoch_descriptor }, ); params.fork_choice = Some(ForkChoiceStrategy::LongestChain); diff --git a/bin/node/rpc/Cargo.toml b/bin/node/rpc/Cargo.toml index 851eb2cfc5104..0b69ae27010fa 100644 --- a/bin/node/rpc/Cargo.toml +++ b/bin/node/rpc/Cargo.toml @@ -26,6 +26,7 @@ sc-finality-grandpa = { version = "0.10.0-dev", path = "../../../client/finality sc-finality-grandpa-rpc = { version = "0.10.0-dev", path = "../../../client/finality-grandpa/rpc" } sc-rpc = { version = "4.0.0-dev", path = "../../../client/rpc" } sc-rpc-api = { version = "0.10.0-dev", path = "../../../client/rpc-api" } +sc-rpc-spec-v2 = { version = "0.10.0-dev", path = "../../../client/rpc-spec-v2" } sc-sync-state-rpc = { version = "0.10.0-dev", path = "../../../client/sync-state-rpc" } sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../../client/transaction-pool/api" } sp-api = { version = "4.0.0-dev", path = "../../../primitives/api" } diff --git a/bin/node/rpc/src/lib.rs b/bin/node/rpc/src/lib.rs index 1c8b9cce1a744..0e6b04087fa63 100644 --- a/bin/node/rpc/src/lib.rs +++ b/bin/node/rpc/src/lib.rs @@ -124,6 +124,7 @@ where use sc_consensus_babe_rpc::{Babe, BabeApiServer}; use sc_finality_grandpa_rpc::{Grandpa, GrandpaApiServer}; use sc_rpc::dev::{Dev, DevApiServer}; + use sc_rpc_spec_v2::chain_spec::{ChainSpec, ChainSpecApiServer}; use sc_sync_state_rpc::{SyncState, SyncStateApiServer}; use substrate_frame_rpc_system::{System, SystemApiServer}; use substrate_state_trie_migration_rpc::{StateMigration, StateMigrationApiServer}; @@ -140,6 +141,11 @@ where finality_provider, } = grandpa; + let chain_name = chain_spec.name().to_string(); + let genesis_hash = client.block_hash(0).ok().flatten().expect("Genesis block exists; qed"); + let properties = chain_spec.properties(); + io.merge(ChainSpec::new(chain_name, genesis_hash, properties).into_rpc())?; + io.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?; // Making synchronous calls in light client freezes the browser currently, // more context: https://github.com/paritytech/substrate/pull/3480 diff --git a/bin/node/runtime/Cargo.toml b/bin/node/runtime/Cargo.toml index 6a81c16780240..e722024231651 100644 --- a/bin/node/runtime/Cargo.toml +++ b/bin/node/runtime/Cargo.toml @@ -21,7 +21,6 @@ codec = { package = "parity-scale-codec", version = "3.0.0", default-features = ] } scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } static_assertions = "1.1.0" -hex-literal = { version = "0.3.4", optional = true } log = { version = "0.4.17", default-features = false } # primitives @@ -69,6 +68,7 @@ pallet-democracy = { version = "4.0.0-dev", default-features = false, path = ".. pallet-election-provider-multi-phase = { version = "4.0.0-dev", default-features = false, path = "../../../frame/election-provider-multi-phase" } pallet-election-provider-support-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../../../frame/election-provider-support/benchmarking", optional = true } pallet-elections-phragmen = { version = "5.0.0-dev", default-features = false, path = "../../../frame/elections-phragmen" } +pallet-fast-unstake = { version = "4.0.0-dev", default-features = false, path = "../../../frame/fast-unstake" } pallet-gilt = { version = "4.0.0-dev", default-features = false, path = "../../../frame/gilt" } pallet-grandpa = { version = "4.0.0-dev", default-features = false, path = "../../../frame/grandpa" } pallet-im-online = { version = "4.0.0-dev", default-features = false, path = "../../../frame/im-online" } @@ -143,6 +143,7 @@ std = [ "pallet-conviction-voting/std", "pallet-democracy/std", "pallet-elections-phragmen/std", + "pallet-fast-unstake/std", "frame-executive/std", "pallet-gilt/std", "pallet-grandpa/std", @@ -221,6 +222,7 @@ runtime-benchmarks = [ "pallet-election-provider-multi-phase/runtime-benchmarks", "pallet-election-provider-support-benchmarking/runtime-benchmarks", "pallet-elections-phragmen/runtime-benchmarks", + "pallet-fast-unstake/runtime-benchmarks", "pallet-gilt/runtime-benchmarks", "pallet-grandpa/runtime-benchmarks", "pallet-identity/runtime-benchmarks", @@ -252,7 +254,6 @@ runtime-benchmarks = [ "pallet-vesting/runtime-benchmarks", "pallet-whitelist/runtime-benchmarks", "frame-system-benchmarking/runtime-benchmarks", - "hex-literal", ] try-runtime = [ "frame-try-runtime", @@ -274,6 +275,7 @@ try-runtime = [ "pallet-democracy/try-runtime", "pallet-election-provider-multi-phase/try-runtime", "pallet-elections-phragmen/try-runtime", + "pallet-fast-unstake/try-runtime", "pallet-gilt/try-runtime", "pallet-grandpa/try-runtime", "pallet-im-online/try-runtime", diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 8b150dca849f0..8ed5f1c847f5e 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -205,7 +205,7 @@ impl frame_system::Config for Runtime { type BlockWeights = RuntimeBlockWeights; type BlockLength = RuntimeBlockLength; type DbWeight = RocksDbWeight; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = Index; type BlockNumber = BlockNumber; @@ -346,7 +346,7 @@ parameter_types! { impl pallet_scheduler::Config for Runtime { type RuntimeEvent = RuntimeEvent; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type PalletsOrigin = OriginCaller; type RuntimeCall = RuntimeCall; type MaximumWeight = MaximumSchedulerWeight; @@ -535,6 +535,7 @@ parameter_types! { pub const MaxNominatorRewardedPerValidator: u32 = 256; pub const OffendingValidatorsThreshold: Perbill = Perbill::from_percent(17); pub OffchainRepeat: BlockNumber = 5; + pub HistoryDepth: u32 = 84; } pub struct StakingBenchmarkingConfig; @@ -572,11 +573,19 @@ impl pallet_staking::Config for Runtime { // This a placeholder, to be introduced in the next PR as an instance of bags-list type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; + type HistoryDepth = HistoryDepth; type OnStakerSlash = NominationPools; type WeightInfo = pallet_staking::weights::SubstrateWeight; type BenchmarkingConfig = StakingBenchmarkingConfig; } +impl pallet_fast_unstake::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type SlashPerEra = ConstU128<{ DOLLARS }>; + type ControlOrigin = frame_system::EnsureRoot; + type WeightInfo = (); +} + parameter_types! { // phase durations. 1/4 of the last session for each. pub const SignedPhase: u32 = EPOCH_DURATION_IN_BLOCKS / 4; @@ -796,7 +805,7 @@ parameter_types! { pub struct TracksInfo; impl pallet_referenda::TracksInfo for TracksInfo { type Id = u16; - type Origin = ::PalletsOrigin; + type RuntimeOrigin = ::PalletsOrigin; fn tracks() -> &'static [(Self::Id, pallet_referenda::TrackInfo)] { static DATA: [(u16, pallet_referenda::TrackInfo); 1] = [( 0u16, @@ -822,7 +831,7 @@ impl pallet_referenda::TracksInfo for TracksInfo { )]; &DATA[..] } - fn track_for(id: &Self::Origin) -> Result { + fn track_for(id: &Self::RuntimeOrigin) -> Result { if let Ok(system_origin) = frame_system::RawOrigin::try_from(id.clone()) { match system_origin { frame_system::RawOrigin::Root => Ok(0), @@ -957,7 +966,7 @@ parameter_types! { type CouncilCollective = pallet_collective::Instance1; impl pallet_collective::Config for Runtime { - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Proposal = RuntimeCall; type RuntimeEvent = RuntimeEvent; type MotionDuration = CouncilMotionDuration; @@ -1014,7 +1023,7 @@ parameter_types! { type TechnicalCollective = pallet_collective::Instance2; impl pallet_collective::Config for Runtime { - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Proposal = RuntimeCall; type RuntimeEvent = RuntimeEvent; type MotionDuration = TechnicalMotionDuration; @@ -1536,7 +1545,7 @@ parameter_types! { type AllianceCollective = pallet_collective::Instance3; impl pallet_collective::Config for Runtime { - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Proposal = RuntimeCall; type RuntimeEvent = RuntimeEvent; type MotionDuration = AllianceMotionDuration; @@ -1653,6 +1662,7 @@ construct_runtime!( NominationPools: pallet_nomination_pools, RankedPolls: pallet_referenda::, RankedCollective: pallet_ranked_collective, + FastUnstake: pallet_fast_unstake, } ); @@ -1704,6 +1714,7 @@ pub type Executive = frame_executive::Executive< type Migrations = ( pallet_nomination_pools::migration::v2::MigrateToV2, pallet_alliance::migration::Migration, + pallet_contracts::Migration, ); /// MMR helper types. @@ -1738,6 +1749,7 @@ mod benches { [pallet_election_provider_multi_phase, ElectionProviderMultiPhase] [pallet_election_provider_support_benchmarking, EPSBench::] [pallet_elections_phragmen, Elections] + [pallet_fast_unstake, FastUnstake] [pallet_gilt, Gilt] [pallet_grandpa, Grandpa] [pallet_identity, Identity] diff --git a/client/beefy/Cargo.toml b/client/beefy/Cargo.toml index 5cc2952e26ba5..47a3be859cbbb 100644 --- a/client/beefy/Cargo.toml +++ b/client/beefy/Cargo.toml @@ -9,12 +9,12 @@ description = "BEEFY Client gadget for substrate" homepage = "https://substrate.io" [dependencies] +array-bytes = "4.1" async-trait = "0.1.57" codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive"] } fnv = "1.0.6" futures = "0.3" futures-timer = "3.0.1" -hex = "0.4.2" log = "0.4" parking_lot = "0.12.1" thiserror = "1.0" diff --git a/client/beefy/src/lib.rs b/client/beefy/src/lib.rs index cdb7fca10320d..41eeec43d64bd 100644 --- a/client/beefy/src/lib.rs +++ b/client/beefy/src/lib.rs @@ -69,9 +69,10 @@ pub(crate) mod beefy_protocol_name { genesis_hash: &Hash, chain_spec: &Box, ) -> ProtocolName { + let genesis_hash = genesis_hash.as_ref(); let chain_prefix = match chain_spec.fork_id() { - Some(fork_id) => format!("/{}/{}", hex::encode(genesis_hash), fork_id), - None => format!("/{}", hex::encode(genesis_hash)), + Some(fork_id) => format!("/{}/{}", array_bytes::bytes2hex("", genesis_hash), fork_id), + None => format!("/{}", array_bytes::bytes2hex("", genesis_hash)), }; format!("{}{}", chain_prefix, NAME).into() } diff --git a/client/beefy/src/tests.rs b/client/beefy/src/tests.rs index e0058e5238d6a..26c85592ecb85 100644 --- a/client/beefy/src/tests.rs +++ b/client/beefy/src/tests.rs @@ -99,7 +99,7 @@ fn beefy_protocol_name() { // Create protocol name using random genesis hash. let genesis_hash = H256::random(); - let expected = format!("/{}/beefy/1", hex::encode(genesis_hash)); + let expected = format!("/{}/beefy/1", array_bytes::bytes2hex("", genesis_hash.as_ref())); let proto_name = beefy_protocol_name::standard_name(&genesis_hash, &chain_spec); assert_eq!(proto_name.to_string(), expected); diff --git a/client/cli/Cargo.toml b/client/cli/Cargo.toml index 50d110d40eabd..e5cd6167596c0 100644 --- a/client/cli/Cargo.toml +++ b/client/cli/Cargo.toml @@ -13,11 +13,11 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] +array-bytes = "4.1" chrono = "0.4.10" clap = { version = "3.1.18", features = ["derive"] } fdlimit = "0.2.1" futures = "0.3.21" -hex = "0.4.2" libp2p = "0.46.1" log = "0.4.17" names = { version = "0.13.0", default-features = false } diff --git a/client/cli/src/commands/generate_node_key.rs b/client/cli/src/commands/generate_node_key.rs index 6b2f12531458c..3afd99d60a123 100644 --- a/client/cli/src/commands/generate_node_key.rs +++ b/client/cli/src/commands/generate_node_key.rs @@ -57,7 +57,7 @@ impl GenerateNodeKeyCmd { let file_data = if self.bin { secret.as_ref().to_owned() } else { - hex::encode(secret.as_ref()).into_bytes() + array_bytes::bytes2hex("", secret.as_ref()).into_bytes() }; match &self.file { @@ -85,6 +85,6 @@ mod tests { assert!(generate.run().is_ok()); let mut buf = String::new(); assert!(file.read_to_string(&mut buf).is_ok()); - assert!(hex::decode(buf).is_ok()); + assert!(array_bytes::hex2bytes(&buf).is_ok()); } } diff --git a/client/cli/src/commands/inspect_key.rs b/client/cli/src/commands/inspect_key.rs index 14bb059503df9..59f105dc52a5c 100644 --- a/client/cli/src/commands/inspect_key.rs +++ b/client/cli/src/commands/inspect_key.rs @@ -127,7 +127,7 @@ fn expect_public_from_phrase( ) -> Result<(), Error> { let secret_uri = SecretUri::from_str(suri).map_err(|e| format!("{:?}", e))?; let expected_public = if let Some(public) = expect_public.strip_prefix("0x") { - let hex_public = hex::decode(&public) + let hex_public = array_bytes::hex2bytes(public) .map_err(|_| format!("Invalid expected public key hex: `{}`", expect_public))?; Pair::Public::try_from(&hex_public) .map_err(|_| format!("Invalid expected public key: `{}`", expect_public))? @@ -208,7 +208,7 @@ mod tests { .expect("Valid") .0 .public(); - let valid_public_hex = format!("0x{}", hex::encode(valid_public.as_slice())); + let valid_public_hex = array_bytes::bytes2hex("0x", valid_public.as_slice()); let valid_accountid = format!("{}", valid_public.into_account()); // It should fail with the invalid public key @@ -226,7 +226,7 @@ mod tests { .0 .public(); let valid_public_hex_with_password = - format!("0x{}", hex::encode(&valid_public_with_password.as_slice())); + array_bytes::bytes2hex("0x", valid_public_with_password.as_slice()); let valid_accountid_with_password = format!("{}", &valid_public_with_password.into_account()); @@ -248,7 +248,7 @@ mod tests { .0 .public(); let valid_public_hex_with_password_and_derivation = - format!("0x{}", hex::encode(&valid_public_with_password_and_derivation.as_slice())); + array_bytes::bytes2hex("0x", valid_public_with_password_and_derivation.as_slice()); // They should still be valid, because we check the base secret key. check_cmd(&seed_with_password_and_derivation, &valid_public_hex_with_password, true); diff --git a/client/cli/src/commands/inspect_node_key.rs b/client/cli/src/commands/inspect_node_key.rs index e1617c1d085df..a9dff9c760d33 100644 --- a/client/cli/src/commands/inspect_node_key.rs +++ b/client/cli/src/commands/inspect_node_key.rs @@ -66,7 +66,8 @@ impl InspectNodeKeyCmd { if !self.bin { // With hex input, give to the user a bit of tolerance about whitespaces let keyhex = String::from_utf8_lossy(&file_data); - file_data = hex::decode(keyhex.trim()).map_err(|_| "failed to decode secret as hex")?; + file_data = array_bytes::hex2bytes(keyhex.trim()) + .map_err(|_| "failed to decode secret as hex")?; } let secret = diff --git a/client/cli/src/commands/sign.rs b/client/cli/src/commands/sign.rs index e0a5fce353ef4..7d93390326717 100644 --- a/client/cli/src/commands/sign.rs +++ b/client/cli/src/commands/sign.rs @@ -70,7 +70,7 @@ fn sign( message: Vec, ) -> error::Result { let pair = utils::pair_from_suri::

(suri, password)?; - Ok(hex::encode(pair.sign(&message))) + Ok(array_bytes::bytes2hex("", pair.sign(&message).as_ref())) } #[cfg(test)] diff --git a/client/cli/src/commands/utils.rs b/client/cli/src/commands/utils.rs index 95849065471b4..1ce2b23221691 100644 --- a/client/cli/src/commands/utils.rs +++ b/client/cli/src/commands/utils.rs @@ -203,7 +203,7 @@ where Pair: sp_core::Pair, Pair::Public: Into, { - let public = decode_hex(public_str)?; + let public = array_bytes::hex2bytes(public_str)?; let public_key = Pair::Public::try_from(&public) .map_err(|_| "Failed to construct public key from given hex")?; @@ -273,26 +273,17 @@ where format!("0x{}", HexDisplay::from(&public_key.into().into_account().as_ref())) } -/// helper method for decoding hex -pub fn decode_hex>(message: T) -> Result, Error> { - let mut message = message.as_ref(); - if message[..2] == [b'0', b'x'] { - message = &message[2..] - } - Ok(hex::decode(message)?) -} - /// checks if message is Some, otherwise reads message from stdin and optionally decodes hex pub fn read_message(msg: Option<&String>, should_decode: bool) -> Result, Error> { let mut message = vec![]; match msg { Some(m) => { - message = decode_hex(m)?; + message = array_bytes::hex2bytes(m.as_str())?; }, None => { std::io::stdin().lock().read_to_end(&mut message)?; if should_decode { - message = decode_hex(&message)?; + message = array_bytes::hex2bytes(array_bytes::hex_bytes2hex_str(&message)?)?; } }, } diff --git a/client/cli/src/commands/vanity.rs b/client/cli/src/commands/vanity.rs index 6a1bf77f6c8b0..289dc1705c3a3 100644 --- a/client/cli/src/commands/vanity.rs +++ b/client/cli/src/commands/vanity.rs @@ -178,7 +178,7 @@ mod tests { #[test] fn test_generation_with_single_char() { let seed = generate_key::("ab", default_ss58_version()).unwrap(); - assert!(sr25519::Pair::from_seed_slice(&hex::decode(&seed[2..]).unwrap()) + assert!(sr25519::Pair::from_seed_slice(&array_bytes::hex2bytes_unchecked(&seed)) .unwrap() .public() .to_ss58check() @@ -190,7 +190,7 @@ mod tests { let seed = generate_key::("ab", Ss58AddressFormatRegistry::PolkadotAccount.into()) .unwrap(); - assert!(sr25519::Pair::from_seed_slice(&hex::decode(&seed[2..]).unwrap()) + assert!(sr25519::Pair::from_seed_slice(&array_bytes::hex2bytes_unchecked(&seed)) .unwrap() .public() .to_ss58check_with_version(Ss58AddressFormatRegistry::PolkadotAccount.into()) diff --git a/client/cli/src/commands/verify.rs b/client/cli/src/commands/verify.rs index b004a948a7a48..6389cdbde2c17 100644 --- a/client/cli/src/commands/verify.rs +++ b/client/cli/src/commands/verify.rs @@ -55,7 +55,7 @@ impl VerifyCmd { /// Run the command pub fn run(&self) -> error::Result<()> { let message = utils::read_message(self.message.as_ref(), self.hex)?; - let sig_data = utils::decode_hex(&self.sig)?; + let sig_data = array_bytes::hex2bytes(&self.sig)?; let uri = utils::read_uri(self.uri.as_ref())?; let uri = if let Some(uri) = uri.strip_prefix("0x") { uri } else { &uri }; @@ -71,7 +71,7 @@ where let signature = Pair::Signature::try_from(&sig_data).map_err(|_| error::Error::SignatureFormatInvalid)?; - let pubkey = if let Ok(pubkey_vec) = hex::decode(uri) { + let pubkey = if let Ok(pubkey_vec) = array_bytes::hex2bytes(uri) { Pair::Public::from_slice(pubkey_vec.as_slice()) .map_err(|_| error::Error::KeyFormatInvalid)? } else { diff --git a/client/cli/src/error.rs b/client/cli/src/error.rs index f38a95e0115f1..a0f843e73bf53 100644 --- a/client/cli/src/error.rs +++ b/client/cli/src/error.rs @@ -69,8 +69,8 @@ pub enum Error { #[error("Key storage issue encountered")] KeyStorage(#[from] sc_keystore::Error), - #[error("Invalid hexadecimal string data")] - HexDataConversion(#[from] hex::FromHexError), + #[error("Invalid hexadecimal string data, {0:?}")] + HexDataConversion(array_bytes::Error), /// Application specific error chain sequence forwarder. #[error(transparent)] @@ -97,3 +97,9 @@ impl From for Error { Error::InvalidUri(e) } } + +impl From for Error { + fn from(e: array_bytes::Error) -> Error { + Error::HexDataConversion(e) + } +} diff --git a/client/cli/src/params/node_key_params.rs b/client/cli/src/params/node_key_params.rs index d51b6143ed393..00ce9e8027aab 100644 --- a/client/cli/src/params/node_key_params.rs +++ b/client/cli/src/params/node_key_params.rs @@ -176,7 +176,7 @@ mod tests { let file = tmp.path().join("mysecret").to_path_buf(); let key = ed25519::SecretKey::generate(); - fs::write(&file, hex::encode(key.as_ref())).expect("Writes secret key"); + fs::write(&file, array_bytes::bytes2hex("", key.as_ref())).expect("Writes secret key"); check_key(file.clone(), &key); fs::write(&file, &key).expect("Writes secret key"); diff --git a/client/consensus/babe/src/lib.rs b/client/consensus/babe/src/lib.rs index eca6654f6e4dc..aef4785b7bb81 100644 --- a/client/consensus/babe/src/lib.rs +++ b/client/consensus/babe/src/lib.rs @@ -67,7 +67,6 @@ #![warn(missing_docs)] use std::{ - borrow::Cow, collections::{HashMap, HashSet}, future::Future, pin::Pin, @@ -857,10 +856,8 @@ where import_block.body = Some(body); import_block.state_action = StateAction::ApplyChanges(sc_consensus::StorageChanges::Changes(storage_changes)); - import_block.intermediates.insert( - Cow::from(INTERMEDIATE_KEY), - Box::new(BabeIntermediate:: { epoch_descriptor }) as Box<_>, - ); + import_block + .insert_intermediate(INTERMEDIATE_KEY, BabeIntermediate:: { epoch_descriptor }); Ok(import_block) } @@ -1272,9 +1269,9 @@ where block.header = pre_header; block.post_digests.push(verified_info.seal); - block.intermediates.insert( - Cow::from(INTERMEDIATE_KEY), - Box::new(BabeIntermediate:: { epoch_descriptor }) as Box<_>, + block.insert_intermediate( + INTERMEDIATE_KEY, + BabeIntermediate:: { epoch_descriptor }, ); block.post_hash = Some(hash); @@ -1426,7 +1423,7 @@ where match self.client.status(BlockId::Hash(hash)) { Ok(sp_blockchain::BlockStatus::InChain) => { // When re-importing existing block strip away intermediates. - let _ = block.take_intermediate::>(INTERMEDIATE_KEY); + let _ = block.remove_intermediate::>(INTERMEDIATE_KEY); block.fork_choice = Some(ForkChoiceStrategy::Custom(false)); return self.inner.import_block(block, new_cache).await.map_err(Into::into) }, @@ -1495,7 +1492,7 @@ where }; let intermediate = - block.take_intermediate::>(INTERMEDIATE_KEY)?; + block.remove_intermediate::>(INTERMEDIATE_KEY)?; let epoch_descriptor = intermediate.epoch_descriptor; let first_in_epoch = parent_slot < epoch_descriptor.start_slot(); diff --git a/client/consensus/babe/src/tests.rs b/client/consensus/babe/src/tests.rs index ab3805138482c..a3467e0020200 100644 --- a/client/consensus/babe/src/tests.rs +++ b/client/consensus/babe/src/tests.rs @@ -642,10 +642,8 @@ fn propose_and_import_block( let mut import = BlockImportParams::new(BlockOrigin::Own, block.header); import.post_digests.push(seal); import.body = Some(block.extrinsics); - import.intermediates.insert( - Cow::from(INTERMEDIATE_KEY), - Box::new(BabeIntermediate:: { epoch_descriptor }) as Box<_>, - ); + import + .insert_intermediate(INTERMEDIATE_KEY, BabeIntermediate:: { epoch_descriptor }); import.fork_choice = Some(ForkChoiceStrategy::LongestChain); let import_result = block_on(block_import.import_block(import, Default::default())).unwrap(); diff --git a/client/consensus/common/src/block_import.rs b/client/consensus/common/src/block_import.rs index b8fc815cc5c5c..f888176addd2d 100644 --- a/client/consensus/common/src/block_import.rs +++ b/client/consensus/common/src/block_import.rs @@ -294,18 +294,23 @@ impl BlockImportParams { } } - /// Take intermediate by given key, and remove it from the processing list. - pub fn take_intermediate(&mut self, key: &[u8]) -> Result, Error> { + /// Insert intermediate by given key. + pub fn insert_intermediate(&mut self, key: &'static [u8], value: T) { + self.intermediates.insert(Cow::from(key), Box::new(value)); + } + + /// Remove and return intermediate by given key. + pub fn remove_intermediate(&mut self, key: &[u8]) -> Result { let (k, v) = self.intermediates.remove_entry(key).ok_or(Error::NoIntermediate)?; - v.downcast::().map_err(|v| { + v.downcast::().map(|v| *v).map_err(|v| { self.intermediates.insert(k, v); Error::InvalidIntermediate }) } /// Get a reference to a given intermediate. - pub fn intermediate(&self, key: &[u8]) -> Result<&T, Error> { + pub fn get_intermediate(&self, key: &[u8]) -> Result<&T, Error> { self.intermediates .get(key) .ok_or(Error::NoIntermediate)? @@ -314,7 +319,7 @@ impl BlockImportParams { } /// Get a mutable reference to a given intermediate. - pub fn intermediate_mut(&mut self, key: &[u8]) -> Result<&mut T, Error> { + pub fn get_intermediate_mut(&mut self, key: &[u8]) -> Result<&mut T, Error> { self.intermediates .get_mut(key) .ok_or(Error::NoIntermediate)? diff --git a/client/consensus/common/src/import_queue.rs b/client/consensus/common/src/import_queue.rs index c71e21ccd4b00..3741fa99663cd 100644 --- a/client/consensus/common/src/import_queue.rs +++ b/client/consensus/common/src/import_queue.rs @@ -62,8 +62,8 @@ pub type BoxBlockImport = pub type BoxJustificationImport = Box + Send + Sync>; -/// Maps to the Origin used by the network. -pub type Origin = libp2p::PeerId; +/// Maps to the RuntimeOrigin used by the network. +pub type RuntimeOrigin = libp2p::PeerId; /// Block data used by the queue. #[derive(Debug, PartialEq, Eq, Clone)] @@ -79,7 +79,7 @@ pub struct IncomingBlock { /// Justification(s) if requested. pub justifications: Option, /// The peer, we received this from - pub origin: Option, + pub origin: Option, /// Allow importing the block skipping state verification if parent state is missing. pub allow_missing_state: bool, /// Skip block execution and state verification. @@ -112,7 +112,7 @@ pub trait ImportQueue: Send { /// Import block justifications. fn import_justifications( &mut self, - who: Origin, + who: RuntimeOrigin, hash: B::Hash, number: NumberFor, justifications: Justifications, @@ -140,7 +140,7 @@ pub trait Link: Send { /// Justification import result. fn justification_imported( &mut self, - _who: Origin, + _who: RuntimeOrigin, _hash: &B::Hash, _number: NumberFor, _success: bool, @@ -155,9 +155,9 @@ pub trait Link: Send { #[derive(Debug, PartialEq)] pub enum BlockImportStatus { /// Imported known block. - ImportedKnown(N, Option), + ImportedKnown(N, Option), /// Imported unknown block. - ImportedUnknown(N, ImportedAux, Option), + ImportedUnknown(N, ImportedAux, Option), } impl BlockImportStatus { @@ -175,15 +175,15 @@ impl BlockImportStatus { pub enum BlockImportError { /// Block missed header, can't be imported #[error("block is missing a header (origin = {0:?})")] - IncompleteHeader(Option), + IncompleteHeader(Option), /// Block verification failed, can't be imported #[error("block verification failed (origin = {0:?}): {1}")] - VerificationFailed(Option, String), + VerificationFailed(Option, String), /// Block is known to be Bad #[error("bad block (origin = {0:?})")] - BadBlock(Option), + BadBlock(Option), /// Parent state is missing. #[error("block is missing parent state")] diff --git a/client/consensus/common/src/import_queue/basic_queue.rs b/client/consensus/common/src/import_queue/basic_queue.rs index 84ccba990e599..0e607159b75c3 100644 --- a/client/consensus/common/src/import_queue/basic_queue.rs +++ b/client/consensus/common/src/import_queue/basic_queue.rs @@ -34,7 +34,7 @@ use crate::{ import_queue::{ buffered_link::{self, BufferedLinkReceiver, BufferedLinkSender}, import_single_block_metered, BlockImportError, BlockImportStatus, BoxBlockImport, - BoxJustificationImport, ImportQueue, IncomingBlock, Link, Origin, Verifier, + BoxJustificationImport, ImportQueue, IncomingBlock, Link, RuntimeOrigin, Verifier, }, metrics::Metrics, }; @@ -120,7 +120,7 @@ impl ImportQueue for BasicQueue fn import_justifications( &mut self, - who: Origin, + who: RuntimeOrigin, hash: B::Hash, number: NumberFor, justifications: Justifications, @@ -152,7 +152,7 @@ mod worker_messages { pub struct ImportBlocks(pub BlockOrigin, pub Vec>); pub struct ImportJustification( - pub Origin, + pub RuntimeOrigin, pub B::Hash, pub NumberFor, pub Justification, @@ -289,7 +289,7 @@ impl BlockImportWorker { async fn import_justification( &mut self, - who: Origin, + who: RuntimeOrigin, hash: B::Hash, number: NumberFor, justification: Justification, @@ -530,7 +530,7 @@ mod tests { fn justification_imported( &mut self, - _who: Origin, + _who: RuntimeOrigin, hash: &Hash, _number: BlockNumber, _success: bool, diff --git a/client/consensus/common/src/import_queue/buffered_link.rs b/client/consensus/common/src/import_queue/buffered_link.rs index d3d91f5bd31c5..5d418dddf0853 100644 --- a/client/consensus/common/src/import_queue/buffered_link.rs +++ b/client/consensus/common/src/import_queue/buffered_link.rs @@ -38,7 +38,7 @@ //! }); //! ``` -use crate::import_queue::{Link, Origin}; +use crate::import_queue::{Link, RuntimeOrigin}; use futures::prelude::*; use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver, TracingUnboundedSender}; use sp_runtime::traits::{Block as BlockT, NumberFor}; @@ -82,7 +82,7 @@ impl Clone for BufferedLinkSender { /// Internal buffered message. enum BlockImportWorkerMsg { BlocksProcessed(usize, usize, Vec<(BlockImportResult, B::Hash)>), - JustificationImported(Origin, B::Hash, NumberFor, bool), + JustificationImported(RuntimeOrigin, B::Hash, NumberFor, bool), RequestJustification(B::Hash, NumberFor), } @@ -100,7 +100,7 @@ impl Link for BufferedLinkSender { fn justification_imported( &mut self, - who: Origin, + who: RuntimeOrigin, hash: &B::Hash, number: NumberFor, success: bool, diff --git a/client/consensus/manual-seal/src/consensus/babe.rs b/client/consensus/manual-seal/src/consensus/babe.rs index 300a96695c90a..206f5163a13cd 100644 --- a/client/consensus/manual-seal/src/consensus/babe.rs +++ b/client/consensus/manual-seal/src/consensus/babe.rs @@ -30,7 +30,7 @@ use sc_consensus_epochs::{ descendent_query, EpochHeader, SharedEpochChanges, ViableEpochDescriptor, }; use sp_keystore::SyncCryptoStorePtr; -use std::{borrow::Cow, marker::PhantomData, sync::Arc}; +use std::{marker::PhantomData, sync::Arc}; use sc_consensus::{BlockImportParams, ForkChoiceStrategy, Verifier}; use sp_api::{ProvideRuntimeApi, TransactionFor}; @@ -125,10 +125,8 @@ where // drop the lock drop(epoch_changes); - import_params.intermediates.insert( - Cow::from(INTERMEDIATE_KEY), - Box::new(BabeIntermediate:: { epoch_descriptor }) as Box<_>, - ); + import_params + .insert_intermediate(INTERMEDIATE_KEY, BabeIntermediate:: { epoch_descriptor }); Ok((import_params, None)) } @@ -315,10 +313,7 @@ where }; } - params.intermediates.insert( - Cow::from(INTERMEDIATE_KEY), - Box::new(BabeIntermediate:: { epoch_descriptor }) as Box<_>, - ); + params.insert_intermediate(INTERMEDIATE_KEY, BabeIntermediate:: { epoch_descriptor }); Ok(()) } diff --git a/client/consensus/pow/src/lib.rs b/client/consensus/pow/src/lib.rs index 9b3ef501d2396..dcf069d617bab 100644 --- a/client/consensus/pow/src/lib.rs +++ b/client/consensus/pow/src/lib.rs @@ -65,10 +65,7 @@ use sp_runtime::{ traits::{Block as BlockT, Header as HeaderT}, RuntimeString, }; -use std::{ - borrow::Cow, cmp::Ordering, collections::HashMap, marker::PhantomData, sync::Arc, - time::Duration, -}; +use std::{cmp::Ordering, collections::HashMap, marker::PhantomData, sync::Arc, time::Duration}; #[derive(Debug, thiserror::Error)] pub enum Error { @@ -358,8 +355,8 @@ where let inner_seal = fetch_seal::(block.post_digests.last(), block.header.hash())?; - let intermediate = - block.take_intermediate::>(INTERMEDIATE_KEY)?; + let intermediate = block + .remove_intermediate::>(INTERMEDIATE_KEY)?; let difficulty = match intermediate.difficulty { Some(difficulty) => difficulty, @@ -455,9 +452,7 @@ where let intermediate = PowIntermediate:: { difficulty: None }; block.header = checked_header; block.post_digests.push(seal); - block - .intermediates - .insert(Cow::from(INTERMEDIATE_KEY), Box::new(intermediate) as Box<_>); + block.insert_intermediate(INTERMEDIATE_KEY, intermediate); block.post_hash = Some(hash); Ok((block, None)) diff --git a/client/consensus/pow/src/worker.rs b/client/consensus/pow/src/worker.rs index 750e78cd9a038..a00da6e7022fb 100644 --- a/client/consensus/pow/src/worker.rs +++ b/client/consensus/pow/src/worker.rs @@ -32,7 +32,6 @@ use sp_runtime::{ DigestItem, }; use std::{ - borrow::Cow, collections::HashMap, pin::Pin, sync::{ @@ -212,10 +211,7 @@ where let intermediate = PowIntermediate:: { difficulty: Some(build.metadata.difficulty), }; - - import_block - .intermediates - .insert(Cow::from(INTERMEDIATE_KEY), Box::new(intermediate) as Box<_>); + import_block.insert_intermediate(INTERMEDIATE_KEY, intermediate); let header = import_block.post_header(); let mut block_import = self.block_import.lock(); diff --git a/client/executor/Cargo.toml b/client/executor/Cargo.toml index 2fe7e822b36c3..264db0e89b1c8 100644 --- a/client/executor/Cargo.toml +++ b/client/executor/Cargo.toml @@ -37,8 +37,8 @@ sp-version = { version = "5.0.0", path = "../../primitives/version" } sp-wasm-interface = { version = "6.0.0", path = "../../primitives/wasm-interface" } [dev-dependencies] +array-bytes = "4.1" wat = "1.0" -hex-literal = "0.3.4" sc-runtime-test = { version = "2.0.0", path = "runtime-test" } substrate-test-runtime = { version = "2.0.0", path = "../../test-utils/runtime" } sp-state-machine = { version = "0.12.0", path = "../../primitives/state-machine" } diff --git a/client/executor/src/integration_tests/mod.rs b/client/executor/src/integration_tests/mod.rs index 25280f856f2a5..9ffb7f502f5c6 100644 --- a/client/executor/src/integration_tests/mod.rs +++ b/client/executor/src/integration_tests/mod.rs @@ -21,7 +21,6 @@ mod linux; mod sandbox; use codec::{Decode, Encode}; -use hex_literal::hex; use sc_executor_common::{error::Error, runtime_blob::RuntimeBlob, wasm_runtime::WasmModule}; use sc_runtime_test::wasm_binary_unwrap; use sp_core::{ @@ -391,16 +390,18 @@ fn sha2_256_should_work(wasm_method: WasmExecutionMethod) { let mut ext = ext.ext(); assert_eq!( call_in_wasm("test_sha2_256", &[0], wasm_method, &mut ext,).unwrap(), - hex!("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") - .to_vec() - .encode(), + array_bytes::hex2bytes_unchecked( + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + ) + .encode(), ); assert_eq!( call_in_wasm("test_sha2_256", &b"Hello world!".to_vec().encode(), wasm_method, &mut ext,) .unwrap(), - hex!("c0535e4be2b79ffd93291305436bf889314e4a3faec05ecffcbb7df31ad9e51a") - .to_vec() - .encode(), + array_bytes::hex2bytes_unchecked( + "c0535e4be2b79ffd93291305436bf889314e4a3faec05ecffcbb7df31ad9e51a" + ) + .encode(), ); } @@ -410,16 +411,18 @@ fn twox_256_should_work(wasm_method: WasmExecutionMethod) { let mut ext = ext.ext(); assert_eq!( call_in_wasm("test_twox_256", &[0], wasm_method, &mut ext,).unwrap(), - hex!("99e9d85137db46ef4bbea33613baafd56f963c64b1f3685a4eb4abd67ff6203a") - .to_vec() - .encode(), + array_bytes::hex2bytes_unchecked( + "99e9d85137db46ef4bbea33613baafd56f963c64b1f3685a4eb4abd67ff6203a" + ) + .encode(), ); assert_eq!( call_in_wasm("test_twox_256", &b"Hello world!".to_vec().encode(), wasm_method, &mut ext,) .unwrap(), - hex!("b27dfd7f223f177f2a13647b533599af0c07f68bda23d96d059da2b451a35a74") - .to_vec() - .encode(), + array_bytes::hex2bytes_unchecked( + "b27dfd7f223f177f2a13647b533599af0c07f68bda23d96d059da2b451a35a74" + ) + .encode(), ); } @@ -429,12 +432,12 @@ fn twox_128_should_work(wasm_method: WasmExecutionMethod) { let mut ext = ext.ext(); assert_eq!( call_in_wasm("test_twox_128", &[0], wasm_method, &mut ext,).unwrap(), - hex!("99e9d85137db46ef4bbea33613baafd5").to_vec().encode(), + array_bytes::hex2bytes_unchecked("99e9d85137db46ef4bbea33613baafd5").encode(), ); assert_eq!( call_in_wasm("test_twox_128", &b"Hello world!".to_vec().encode(), wasm_method, &mut ext,) .unwrap(), - hex!("b27dfd7f223f177f2a13647b533599af").to_vec().encode(), + array_bytes::hex2bytes_unchecked("b27dfd7f223f177f2a13647b533599af").encode(), ); } @@ -704,7 +707,7 @@ fn parallel_execution(wasm_method: WasmExecutionMethod) { &[0], ) .unwrap(), - hex!("99e9d85137db46ef4bbea33613baafd5").to_vec().encode(), + array_bytes::hex2bytes_unchecked("99e9d85137db46ef4bbea33613baafd5").encode() ); }) }) diff --git a/client/executor/wasmtime/Cargo.toml b/client/executor/wasmtime/Cargo.toml index 94ad25bdc948c..fc6d5db14aa1d 100644 --- a/client/executor/wasmtime/Cargo.toml +++ b/client/executor/wasmtime/Cargo.toml @@ -21,7 +21,7 @@ parity-wasm = "0.45" # When bumping wasmtime do not forget to also bump rustix # to exactly the same version as used by wasmtime! -wasmtime = { version = "0.40.1", default-features = false, features = [ +wasmtime = { version = "1.0.0", default-features = false, features = [ "cache", "cranelift", "jitdump", @@ -35,7 +35,8 @@ sp-runtime-interface = { version = "6.0.0", path = "../../../primitives/runtime- sp-sandbox = { version = "0.10.0-dev", path = "../../../primitives/sandbox" } sp-wasm-interface = { version = "6.0.0", features = ["wasmtime"], path = "../../../primitives/wasm-interface" } -# Here we include the rustix crate used by wasmtime just to enable its 'use-libc' flag. +# Here we include the rustix crate in the exactly same semver-compatible version as used by +# wasmtime and enable its 'use-libc' flag. # # By default rustix directly calls the appropriate syscalls completely bypassing libc; # this doesn't have any actual benefits for us besides making it harder to debug memory diff --git a/client/finality-grandpa/Cargo.toml b/client/finality-grandpa/Cargo.toml index 5950b108ca4ab..83c6051946aff 100644 --- a/client/finality-grandpa/Cargo.toml +++ b/client/finality-grandpa/Cargo.toml @@ -15,12 +15,12 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] ahash = "0.7.6" +array-bytes = "4.1" async-trait = "0.1.57" dyn-clone = "1.0" finality-grandpa = { version = "0.16.0", features = ["derive-codec"] } futures = "0.3.21" futures-timer = "3.0.1" -hex = "0.4.2" log = "0.4.17" parity-scale-codec = { version = "3.0.0", features = ["derive"] } parking_lot = "0.12.1" diff --git a/client/finality-grandpa/src/communication/mod.rs b/client/finality-grandpa/src/communication/mod.rs index d211c10ae62be..12cb2601f4c26 100644 --- a/client/finality-grandpa/src/communication/mod.rs +++ b/client/finality-grandpa/src/communication/mod.rs @@ -83,9 +83,10 @@ pub mod grandpa_protocol_name { genesis_hash: &Hash, chain_spec: &Box, ) -> ProtocolName { + let genesis_hash = genesis_hash.as_ref(); let chain_prefix = match chain_spec.fork_id() { - Some(fork_id) => format!("/{}/{}", hex::encode(genesis_hash), fork_id), - None => format!("/{}", hex::encode(genesis_hash)), + Some(fork_id) => format!("/{}/{}", array_bytes::bytes2hex("", genesis_hash), fork_id), + None => format!("/{}", array_bytes::bytes2hex("", genesis_hash)), }; format!("{}{}", chain_prefix, NAME).into() } diff --git a/client/finality-grandpa/src/communication/tests.rs b/client/finality-grandpa/src/communication/tests.rs index 1f607e8d68c02..b73f6cdecdd4f 100644 --- a/client/finality-grandpa/src/communication/tests.rs +++ b/client/finality-grandpa/src/communication/tests.rs @@ -646,7 +646,7 @@ fn grandpa_protocol_name() { // Create protocol name using random genesis hash. let genesis_hash = sp_core::H256::random(); - let expected = format!("/{}/grandpa/1", hex::encode(genesis_hash)); + let expected = format!("/{}/grandpa/1", array_bytes::bytes2hex("", genesis_hash.as_ref())); let proto_name = grandpa_protocol_name::standard_name(&genesis_hash, &chain_spec); assert_eq!(proto_name.to_string(), expected); diff --git a/client/keystore/Cargo.toml b/client/keystore/Cargo.toml index 9b7afba759c60..ff963f9d446f6 100644 --- a/client/keystore/Cargo.toml +++ b/client/keystore/Cargo.toml @@ -14,8 +14,8 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] +array-bytes = "4.1" async-trait = "0.1.57" -hex = "0.4.0" parking_lot = "0.12.1" serde_json = "1.0.85" thiserror = "1.0" diff --git a/client/keystore/src/local.rs b/client/keystore/src/local.rs index 19be6715ffe3f..54ff6a5b164a8 100644 --- a/client/keystore/src/local.rs +++ b/client/keystore/src/local.rs @@ -512,8 +512,8 @@ impl KeystoreInner { /// Returns `None` if the keystore only exists in-memory and there isn't any path to provide. fn key_file_path(&self, public: &[u8], key_type: KeyTypeId) -> Option { let mut buf = self.path.as_ref()?.clone(); - let key_type = hex::encode(key_type.0); - let key = hex::encode(public); + let key_type = array_bytes::bytes2hex("", &key_type.0); + let key = array_bytes::bytes2hex("", public); buf.push(key_type + key.as_str()); Some(buf) } @@ -534,7 +534,7 @@ impl KeystoreInner { // skip directories and non-unicode file names (hex is unicode) if let Some(name) = path.file_name().and_then(|n| n.to_str()) { - match hex::decode(name) { + match array_bytes::hex2bytes(name) { Ok(ref hex) if hex.len() > 4 => { if hex[0..4] != id.0 { continue @@ -739,7 +739,7 @@ mod tests { let temp_dir = TempDir::new().unwrap(); let store = LocalKeystore::open(temp_dir.path(), None).unwrap(); - let file_name = temp_dir.path().join(hex::encode(&SR25519.0[..2])); + let file_name = temp_dir.path().join(array_bytes::bytes2hex("", &SR25519.0[..2])); fs::write(file_name, "test").expect("Invalid file is written"); assert!(SyncCryptoStore::sr25519_public_keys(&store, SR25519).is_empty()); diff --git a/client/network/Cargo.toml b/client/network/Cargo.toml index ae115220d6843..e96749df40aa2 100644 --- a/client/network/Cargo.toml +++ b/client/network/Cargo.toml @@ -14,6 +14,7 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] +array-bytes = "4.1" async-trait = "0.1" asynchronous-codec = "0.6" bitflags = "1.3.2" @@ -24,7 +25,6 @@ either = "1.5.3" fnv = "1.0.6" futures = "0.3.21" futures-timer = "3.0.2" -hex = "0.4.0" ip_network = "0.4.1" libp2p = "0.46.1" linked_hash_set = "0.1.3" diff --git a/client/network/common/src/sync.rs b/client/network/common/src/sync.rs index 2ee8f8c51814b..020b2c9efa4c7 100644 --- a/client/network/common/src/sync.rs +++ b/client/network/common/src/sync.rs @@ -96,6 +96,8 @@ pub enum OnBlockData { Import(BlockOrigin, Vec>), /// A new block request needs to be made to the given peer. Request(PeerId, BlockRequest), + /// Continue processing events. + Continue, } /// Result of [`ChainSync::on_block_justification`]. diff --git a/client/network/common/src/sync/warp.rs b/client/network/common/src/sync/warp.rs index 339a4c33a7eeb..c9b9037542388 100644 --- a/client/network/common/src/sync/warp.rs +++ b/client/network/common/src/sync/warp.rs @@ -64,6 +64,8 @@ pub enum WarpSyncPhase { AwaitingPeers, /// Downloading and verifying grandpa warp proofs. DownloadingWarpProofs, + /// Downloading target block. + DownloadingTargetBlock, /// Downloading state data. DownloadingState, /// Importing state. @@ -77,6 +79,7 @@ impl fmt::Display for WarpSyncPhase { match self { Self::AwaitingPeers => write!(f, "Waiting for peers"), Self::DownloadingWarpProofs => write!(f, "Downloading finality proofs"), + Self::DownloadingTargetBlock => write!(f, "Downloading target block"), Self::DownloadingState => write!(f, "Downloading state"), Self::ImportingState => write!(f, "Importing state"), Self::DownloadingBlocks(n) => write!(f, "Downloading block history (#{})", n), diff --git a/client/network/light/Cargo.toml b/client/network/light/Cargo.toml index c1a0fb4759320..c2a77c3b577ba 100644 --- a/client/network/light/Cargo.toml +++ b/client/network/light/Cargo.toml @@ -17,11 +17,11 @@ targets = ["x86_64-unknown-linux-gnu"] prost-build = "0.10" [dependencies] +array-bytes = "4.1" codec = { package = "parity-scale-codec", version = "3.0.0", features = [ "derive", ] } futures = "0.3.21" -hex = "0.4.0" libp2p = "0.46.1" log = "0.4.16" prost = "0.10" diff --git a/client/network/light/src/light_client_requests.rs b/client/network/light/src/light_client_requests.rs index b58426cf15992..61b549d0f0984 100644 --- a/client/network/light/src/light_client_requests.rs +++ b/client/network/light/src/light_client_requests.rs @@ -27,10 +27,11 @@ use std::time::Duration; /// Generate the light client protocol name from the genesis hash and fork id. fn generate_protocol_name>(genesis_hash: Hash, fork_id: Option<&str>) -> String { + let genesis_hash = genesis_hash.as_ref(); if let Some(fork_id) = fork_id { - format!("/{}/{}/light/2", hex::encode(genesis_hash), fork_id) + format!("/{}/{}/light/2", array_bytes::bytes2hex("", genesis_hash), fork_id) } else { - format!("/{}/light/2", hex::encode(genesis_hash)) + format!("/{}/light/2", array_bytes::bytes2hex("", genesis_hash)) } } diff --git a/client/network/src/behaviour.rs b/client/network/src/behaviour.rs index 88571647fb0e3..14962c837aa10 100644 --- a/client/network/src/behaviour.rs +++ b/client/network/src/behaviour.rs @@ -37,7 +37,7 @@ use libp2p::{ }; use log::debug; -use sc_consensus::import_queue::{IncomingBlock, Origin}; +use sc_consensus::import_queue::{IncomingBlock, RuntimeOrigin}; use sc_network_common::{ config::ProtocolId, protocol::{ @@ -103,7 +103,7 @@ where /// Event generated by `Behaviour`. pub enum BehaviourOut { BlockImport(BlockOrigin, Vec>), - JustificationImport(Origin, B::Hash, NumberFor, Justifications), + JustificationImport(RuntimeOrigin, B::Hash, NumberFor, Justifications), /// Started a random iterative Kademlia discovery query. RandomKademliaStarted(ProtocolId), diff --git a/client/network/src/config.rs b/client/network/src/config.rs index d7ca8b48a7c88..202a628884d79 100644 --- a/client/network/src/config.rs +++ b/client/network/src/config.rs @@ -585,7 +585,7 @@ impl NodeKeyConfig { f, |mut b| match String::from_utf8(b.to_vec()).ok().and_then(|s| { if s.len() == 64 { - hex::decode(&s).ok() + array_bytes::hex2bytes(&s).ok() } else { None } diff --git a/client/network/src/protocol.rs b/client/network/src/protocol.rs index 9bcf363cd0692..c7a3cf4b2160f 100644 --- a/client/network/src/protocol.rs +++ b/client/network/src/protocol.rs @@ -41,7 +41,9 @@ use message::{ use notifications::{Notifications, NotificationsOut}; use prometheus_endpoint::{register, Gauge, GaugeVec, Opts, PrometheusError, Registry, U64}; use sc_client_api::HeaderBackend; -use sc_consensus::import_queue::{BlockImportError, BlockImportStatus, IncomingBlock, Origin}; +use sc_consensus::import_queue::{ + BlockImportError, BlockImportStatus, IncomingBlock, RuntimeOrigin, +}; use sc_network_common::{ config::ProtocolId, protocol::ProtocolName, @@ -367,10 +369,15 @@ where let block_announces_protocol = { let genesis_hash = chain.hash(0u32.into()).ok().flatten().expect("Genesis block exists; qed"); + let genesis_hash = genesis_hash.as_ref(); if let Some(fork_id) = fork_id { - format!("/{}/{}/block-announces/1", hex::encode(genesis_hash), fork_id) + format!( + "/{}/{}/block-announces/1", + array_bytes::bytes2hex("", genesis_hash), + fork_id + ) } else { - format!("/{}/block-announces/1", hex::encode(genesis_hash)) + format!("/{}/block-announces/1", array_bytes::bytes2hex("", genesis_hash)) } }; @@ -627,6 +634,7 @@ where CustomMessageOutcome::BlockImport(origin, blocks), Ok(OnBlockData::Request(peer, req)) => prepare_block_request(self.chain_sync.as_ref(), &mut self.peers, peer, req), + Ok(OnBlockData::Continue) => CustomMessageOutcome::None, Err(BadPeer(id, repu)) => { self.behaviour.disconnect_peer(&id, HARDCODED_PEERSETS_SYNC); self.peerset_handle.report_peer(id, repu); @@ -974,6 +982,7 @@ where CustomMessageOutcome::BlockImport(origin, blocks), Ok(OnBlockData::Request(peer, req)) => prepare_block_request(self.chain_sync.as_ref(), &mut self.peers, peer, req), + Ok(OnBlockData::Continue) => CustomMessageOutcome::None, Err(BadPeer(id, repu)) => { self.behaviour.disconnect_peer(&id, HARDCODED_PEERSETS_SYNC); self.peerset_handle.report_peer(id, repu); @@ -1255,7 +1264,7 @@ fn prepare_warp_sync_request( #[must_use] pub enum CustomMessageOutcome { BlockImport(BlockOrigin, Vec>), - JustificationImport(Origin, B::Hash, NumberFor, Justifications), + JustificationImport(RuntimeOrigin, B::Hash, NumberFor, Justifications), /// Notification protocols have been opened with a remote. NotificationStreamOpened { remote: PeerId, diff --git a/client/network/src/transactions.rs b/client/network/src/transactions.rs index 1cf532f33ddc6..da4547aefeab3 100644 --- a/client/network/src/transactions.rs +++ b/client/network/src/transactions.rs @@ -143,10 +143,11 @@ impl TransactionsHandlerPrototype { genesis_hash: Hash, fork_id: Option, ) -> Self { + let genesis_hash = genesis_hash.as_ref(); let protocol_name = if let Some(fork_id) = fork_id { - format!("/{}/{}/transactions/1", hex::encode(genesis_hash), fork_id) + format!("/{}/{}/transactions/1", array_bytes::bytes2hex("", genesis_hash), fork_id) } else { - format!("/{}/transactions/1", hex::encode(genesis_hash)) + format!("/{}/transactions/1", array_bytes::bytes2hex("", genesis_hash)) }; let legacy_protocol_name = format!("/{}/transactions/1", protocol_id.as_ref()); diff --git a/client/network/sync/Cargo.toml b/client/network/sync/Cargo.toml index 7c8f8adafd214..269214aeff3f7 100644 --- a/client/network/sync/Cargo.toml +++ b/client/network/sync/Cargo.toml @@ -17,11 +17,11 @@ targets = ["x86_64-unknown-linux-gnu"] prost-build = "0.10" [dependencies] +array-bytes = "4.1" codec = { package = "parity-scale-codec", version = "3.0.0", features = [ "derive", ] } futures = "0.3.21" -hex = "0.4.0" libp2p = "0.46.1" log = "0.4.17" lru = "0.7.5" diff --git a/client/network/sync/src/block_request_handler.rs b/client/network/sync/src/block_request_handler.rs index cc61be2b57256..a6b39591e7945 100644 --- a/client/network/sync/src/block_request_handler.rs +++ b/client/network/sync/src/block_request_handler.rs @@ -80,10 +80,11 @@ pub fn generate_protocol_config>( /// Generate the block protocol name from the genesis hash and fork id. fn generate_protocol_name>(genesis_hash: Hash, fork_id: Option<&str>) -> String { + let genesis_hash = genesis_hash.as_ref(); if let Some(fork_id) = fork_id { - format!("/{}/{}/sync/2", hex::encode(genesis_hash), fork_id) + format!("/{}/{}/sync/2", array_bytes::bytes2hex("", genesis_hash), fork_id) } else { - format!("/{}/sync/2", hex::encode(genesis_hash)) + format!("/{}/sync/2", array_bytes::bytes2hex("", genesis_hash)) } } diff --git a/client/network/sync/src/lib.rs b/client/network/sync/src/lib.rs index aae5f4de353fe..6ad4a8fbbdcc5 100644 --- a/client/network/sync/src/lib.rs +++ b/client/network/sync/src/lib.rs @@ -80,6 +80,7 @@ use std::{ pin::Pin, sync::Arc, }; +use warp::TargetBlockImportResult; mod extra_requests; @@ -315,6 +316,8 @@ pub enum PeerSyncState { DownloadingState, /// Downloading warp proof. DownloadingWarpProof, + /// Downloading warp sync target block. + DownloadingWarpTargetBlock, /// Actively downloading block history after warp sync. DownloadingGap(NumberFor), } @@ -659,10 +662,11 @@ where } fn block_requests(&mut self) -> Box)> + '_> { - if self.allowed_requests.is_empty() || - self.state_sync.is_some() || - self.mode == SyncMode::Warp - { + if self.mode == SyncMode::Warp { + return Box::new(std::iter::once(self.warp_target_block_request()).flatten()) + } + + if self.allowed_requests.is_empty() || self.state_sync.is_some() { return Box::new(std::iter::empty()) } @@ -824,7 +828,7 @@ where // Only one pending state request is allowed. return None } - if let Some(request) = sync.next_warp_poof_request() { + if let Some(request) = sync.next_warp_proof_request() { let mut targets: Vec<_> = self.peers.values().map(|p| p.best_number).collect(); if !targets.is_empty() { targets.sort(); @@ -1031,6 +1035,40 @@ where Vec::new() } }, + PeerSyncState::DownloadingWarpTargetBlock => { + peer.state = PeerSyncState::Available; + if let Some(warp_sync) = &mut self.warp_sync { + if blocks.len() == 1 { + validate_blocks::(&blocks, who, Some(request))?; + match warp_sync.import_target_block( + blocks.pop().expect("`blocks` len checked above."), + ) { + TargetBlockImportResult::Success => + return Ok(OnBlockData::Continue), + TargetBlockImportResult::BadResponse => + return Err(BadPeer(*who, rep::VERIFICATION_FAIL)), + } + } else if blocks.is_empty() { + debug!(target: "sync", "Empty block response from {}", who); + return Err(BadPeer(*who, rep::NO_BLOCK)) + } else { + debug!( + target: "sync", + "Too many blocks ({}) in warp target block response from {}", + blocks.len(), + who, + ); + return Err(BadPeer(*who, rep::NOT_REQUESTED)) + } + } else { + debug!( + target: "sync", + "Logic error: we think we are downloading warp target block from {}, but no warp sync is happening.", + who, + ); + return Ok(OnBlockData::Continue) + } + }, PeerSyncState::Available | PeerSyncState::DownloadingJustification(..) | PeerSyncState::DownloadingState | @@ -1112,14 +1150,14 @@ where }; match import_result { - state::ImportResult::Import(hash, header, state) => { + state::ImportResult::Import(hash, header, state, body, justifications) => { let origin = BlockOrigin::NetworkInitialSync; let block = IncomingBlock { hash, header: Some(header), - body: None, + body, indexed_body: None, - justifications: None, + justifications, origin: None, allow_missing_state: true, import_existing: true, @@ -1399,8 +1437,13 @@ where number, hash, ); - self.state_sync = - Some(StateSync::new(self.client.clone(), header, *skip_proofs)); + self.state_sync = Some(StateSync::new( + self.client.clone(), + header, + None, + None, + *skip_proofs, + )); self.allowed_requests.set_all(); } } @@ -2163,6 +2206,33 @@ where }) .collect() } + + /// Generate block request for downloading of the target block body during warp sync. + fn warp_target_block_request(&mut self) -> Option<(&PeerId, BlockRequest)> { + if let Some(sync) = &self.warp_sync { + if self.allowed_requests.is_empty() || + sync.is_complete() || + self.peers + .iter() + .any(|(_, peer)| peer.state == PeerSyncState::DownloadingWarpTargetBlock) + { + // Only one pending warp target block request is allowed. + return None + } + if let Some((target_number, request)) = sync.next_target_block_request() { + // Find a random peer that has a block with the target number. + for (id, peer) in self.peers.iter_mut() { + if peer.state.is_available() && peer.best_number >= target_number { + trace!(target: "sync", "New warp target block request for {}", id); + peer.state = PeerSyncState::DownloadingWarpTargetBlock; + self.allowed_requests.clear(); + return Some((id, request)) + } + } + } + } + None + } } // This is purely during a backwards compatible transitionary period and should be removed diff --git a/client/network/sync/src/state.rs b/client/network/sync/src/state.rs index e70d3b6b33a28..9f64b52334c8a 100644 --- a/client/network/sync/src/state.rs +++ b/client/network/sync/src/state.rs @@ -26,7 +26,10 @@ use sc_consensus::ImportedState; use sc_network_common::sync::StateDownloadProgress; use smallvec::SmallVec; use sp_core::storage::well_known_keys; -use sp_runtime::traits::{Block as BlockT, Header, NumberFor}; +use sp_runtime::{ + traits::{Block as BlockT, Header, NumberFor}, + Justifications, +}; use std::{collections::HashMap, sync::Arc}; /// State sync state machine. Accumulates partial state data until it @@ -35,6 +38,8 @@ pub struct StateSync { target_block: B::Hash, target_header: B::Header, target_root: B::Hash, + target_body: Option>, + target_justifications: Option, last_key: SmallVec<[Vec; 2]>, state: HashMap, (Vec<(Vec, Vec)>, Vec>)>, complete: bool, @@ -46,7 +51,7 @@ pub struct StateSync { /// Import state chunk result. pub enum ImportResult { /// State is complete and ready for import. - Import(B::Hash, B::Header, ImportedState), + Import(B::Hash, B::Header, ImportedState, Option>, Option), /// Continue downloading. Continue, /// Bad state chunk. @@ -59,12 +64,20 @@ where Client: ProofProvider + Send + Sync + 'static, { /// Create a new instance. - pub fn new(client: Arc, target: B::Header, skip_proof: bool) -> Self { + pub fn new( + client: Arc, + target_header: B::Header, + target_body: Option>, + target_justifications: Option, + skip_proof: bool, + ) -> Self { Self { client, - target_block: target.hash(), - target_root: *target.state_root(), - target_header: target, + target_block: target_header.hash(), + target_root: *target_header.state_root(), + target_header, + target_body, + target_justifications, last_key: SmallVec::default(), state: HashMap::default(), complete: false, @@ -213,6 +226,8 @@ where block: self.target_block, state: std::mem::take(&mut self.state).into(), }, + self.target_body.clone(), + self.target_justifications.clone(), ) } else { ImportResult::Continue diff --git a/client/network/sync/src/state_request_handler.rs b/client/network/sync/src/state_request_handler.rs index 6cf6482a44f8b..abbbcad2e378f 100644 --- a/client/network/sync/src/state_request_handler.rs +++ b/client/network/sync/src/state_request_handler.rs @@ -69,10 +69,11 @@ pub fn generate_protocol_config>( /// Generate the state protocol name from the genesis hash and fork id. fn generate_protocol_name>(genesis_hash: Hash, fork_id: Option<&str>) -> String { + let genesis_hash = genesis_hash.as_ref(); if let Some(fork_id) = fork_id { - format!("/{}/{}/state/2", hex::encode(genesis_hash), fork_id) + format!("/{}/{}/state/2", array_bytes::bytes2hex("", genesis_hash), fork_id) } else { - format!("/{}/state/2", hex::encode(genesis_hash)) + format!("/{}/state/2", array_bytes::bytes2hex("", genesis_hash)) } } diff --git a/client/network/sync/src/warp.rs b/client/network/sync/src/warp.rs index f3fad6c1b7fdb..4f2a71d98613e 100644 --- a/client/network/sync/src/warp.rs +++ b/client/network/sync/src/warp.rs @@ -23,17 +23,21 @@ use crate::{ state::{ImportResult, StateSync}, }; use sc_client_api::ProofProvider; -use sc_network_common::sync::warp::{ - EncodedProof, VerificationResult, WarpProofRequest, WarpSyncPhase, WarpSyncProgress, - WarpSyncProvider, +use sc_network_common::sync::{ + message::{BlockAttributes, BlockData, BlockRequest, Direction, FromBlock}, + warp::{ + EncodedProof, VerificationResult, WarpProofRequest, WarpSyncPhase, WarpSyncProgress, + WarpSyncProvider, + }, }; use sp_blockchain::HeaderBackend; use sp_finality_grandpa::{AuthorityList, SetId}; -use sp_runtime::traits::{Block as BlockT, NumberFor, Zero}; +use sp_runtime::traits::{Block as BlockT, Header, NumberFor, Zero}; use std::sync::Arc; enum Phase { WarpProof { set_id: SetId, authorities: AuthorityList, last_hash: B::Hash }, + TargetBlock(B::Header), State(StateSync), } @@ -45,6 +49,14 @@ pub enum WarpProofImportResult { BadResponse, } +/// Import target block result. +pub enum TargetBlockImportResult { + /// Import was successful. + Success, + /// Invalid block. + BadResponse, +} + /// Warp sync state machine. Accumulates warp proofs and state. pub struct WarpSync { phase: Phase, @@ -72,7 +84,7 @@ where /// Validate and import a state response. pub fn import_state(&mut self, response: StateResponse) -> ImportResult { match &mut self.phase { - Phase::WarpProof { .. } => { + Phase::WarpProof { .. } | Phase::TargetBlock(_) => { log::debug!(target: "sync", "Unexpected state response"); ImportResult::BadResponse }, @@ -83,7 +95,7 @@ where /// Validate and import a warp proof response. pub fn import_warp_proof(&mut self, response: EncodedProof) -> WarpProofImportResult { match &mut self.phase { - Phase::State(_) => { + Phase::State(_) | Phase::TargetBlock(_) => { log::debug!(target: "sync", "Unexpected warp proof response"); WarpProofImportResult::BadResponse }, @@ -104,8 +116,7 @@ where Ok(VerificationResult::Complete(new_set_id, _, header)) => { log::debug!(target: "sync", "Verified complete proof, set_id={:?}", new_set_id); self.total_proof_bytes += response.0.len() as u64; - let state_sync = StateSync::new(self.client.clone(), header, false); - self.phase = Phase::State(state_sync); + self.phase = Phase::TargetBlock(header); WarpProofImportResult::Success }, } @@ -113,35 +124,100 @@ where } } + /// Import the target block body. + pub fn import_target_block(&mut self, block: BlockData) -> TargetBlockImportResult { + match &mut self.phase { + Phase::WarpProof { .. } | Phase::State(_) => { + log::debug!(target: "sync", "Unexpected target block response"); + TargetBlockImportResult::BadResponse + }, + Phase::TargetBlock(header) => + if let Some(block_header) = &block.header { + if block_header == header { + if block.body.is_some() { + let state_sync = StateSync::new( + self.client.clone(), + header.clone(), + block.body, + block.justifications, + false, + ); + self.phase = Phase::State(state_sync); + TargetBlockImportResult::Success + } else { + log::debug!( + target: "sync", + "Importing target block failed: missing body.", + ); + TargetBlockImportResult::BadResponse + } + } else { + log::debug!( + target: "sync", + "Importing target block failed: different header.", + ); + TargetBlockImportResult::BadResponse + } + } else { + log::debug!(target: "sync", "Importing target block failed: missing header."); + TargetBlockImportResult::BadResponse + }, + } + } + /// Produce next state request. pub fn next_state_request(&self) -> Option { match &self.phase { Phase::WarpProof { .. } => None, + Phase::TargetBlock(_) => None, Phase::State(sync) => Some(sync.next_request()), } } /// Produce next warp proof request. - pub fn next_warp_poof_request(&self) -> Option> { + pub fn next_warp_proof_request(&self) -> Option> { match &self.phase { - Phase::State(_) => None, Phase::WarpProof { last_hash, .. } => Some(WarpProofRequest { begin: *last_hash }), + Phase::TargetBlock(_) => None, + Phase::State(_) => None, + } + } + + /// Produce next target block request. + pub fn next_target_block_request(&self) -> Option<(NumberFor, BlockRequest)> { + match &self.phase { + Phase::WarpProof { .. } => None, + Phase::TargetBlock(header) => { + let request = BlockRequest:: { + id: 0, + fields: BlockAttributes::HEADER | + BlockAttributes::BODY | BlockAttributes::JUSTIFICATION, + from: FromBlock::Hash(header.hash()), + to: Some(header.hash()), + direction: Direction::Ascending, + max: Some(1), + }; + Some((*header.number(), request)) + }, + Phase::State(_) => None, } } /// Return target block hash if it is known. pub fn target_block_hash(&self) -> Option { match &self.phase { - Phase::State(s) => Some(s.target()), Phase::WarpProof { .. } => None, + Phase::TargetBlock(_) => None, + Phase::State(s) => Some(s.target()), } } /// Return target block number if it is known. pub fn target_block_number(&self) -> Option> { match &self.phase { - Phase::State(s) => Some(s.target_block_num()), Phase::WarpProof { .. } => None, + Phase::TargetBlock(header) => Some(*header.number()), + Phase::State(s) => Some(s.target_block_num()), } } @@ -149,6 +225,7 @@ where pub fn is_complete(&self) -> bool { match &self.phase { Phase::WarpProof { .. } => false, + Phase::TargetBlock(_) => false, Phase::State(sync) => sync.is_complete(), } } @@ -160,6 +237,10 @@ where phase: WarpSyncPhase::DownloadingWarpProofs, total_bytes: self.total_proof_bytes, }, + Phase::TargetBlock(_) => WarpSyncProgress { + phase: WarpSyncPhase::DownloadingTargetBlock, + total_bytes: self.total_proof_bytes, + }, Phase::State(sync) => WarpSyncProgress { phase: if self.is_complete() { WarpSyncPhase::ImportingState diff --git a/client/network/sync/src/warp_request_handler.rs b/client/network/sync/src/warp_request_handler.rs index 394bc68449099..e675bf45cad91 100644 --- a/client/network/sync/src/warp_request_handler.rs +++ b/client/network/sync/src/warp_request_handler.rs @@ -54,10 +54,11 @@ pub fn generate_request_response_config>( /// Generate the grandpa warp sync protocol name from the genesi hash and fork id. fn generate_protocol_name>(genesis_hash: Hash, fork_id: Option<&str>) -> String { + let genesis_hash = genesis_hash.as_ref(); if let Some(fork_id) = fork_id { - format!("/{}/{}/sync/warp", hex::encode(genesis_hash), fork_id) + format!("/{}/{}/sync/warp", array_bytes::bytes2hex("", genesis_hash), fork_id) } else { - format!("/{}/sync/warp", hex::encode(genesis_hash)) + format!("/{}/sync/warp", array_bytes::bytes2hex("", genesis_hash)) } } diff --git a/client/network/test/src/lib.rs b/client/network/test/src/lib.rs index 5a29e587ceff5..e78b91a4e04ee 100644 --- a/client/network/test/src/lib.rs +++ b/client/network/test/src/lib.rs @@ -69,7 +69,7 @@ use sc_network_sync::{ use sc_service::client::Client; use sp_blockchain::{ well_known_cache_keys::{self, Id as CacheKeyId}, - HeaderBackend, Info as BlockchainInfo, Result as ClientResult, + Backend as BlockchainBackend, HeaderBackend, Info as BlockchainInfo, Result as ClientResult, }; use sp_consensus::{ block_validation::{BlockAnnounceValidator, DefaultBlockAnnounceValidator}, @@ -540,6 +540,13 @@ where .map(|backend| backend.blockchain().header(BlockId::hash(*hash)).unwrap().is_some()) .unwrap_or(false) } + + pub fn has_body(&self, hash: &H256) -> bool { + self.backend + .as_ref() + .map(|backend| backend.blockchain().body(BlockId::hash(*hash)).unwrap().is_some()) + .unwrap_or(false) + } } pub trait BlockImportAdapterFull: diff --git a/client/network/test/src/sync.rs b/client/network/test/src/sync.rs index c0778767b75af..6115e0e3b2c86 100644 --- a/client/network/test/src/sync.rs +++ b/client/network/test/src/sync.rs @@ -1192,7 +1192,7 @@ fn warp_sync() { ..Default::default() }); let gap_end = net.peer(0).push_blocks(63, false); - net.peer(0).push_blocks(1, false); + let target = net.peer(0).push_blocks(1, false); net.peer(1).push_blocks(64, false); net.peer(2).push_blocks(64, false); // Wait for peer 1 to sync state. @@ -1203,7 +1203,7 @@ fn warp_sync() { // Wait for peer 1 download block history block_on(futures::future::poll_fn::<(), _>(|cx| { net.poll(cx); - if net.peer(3).has_block(&gap_end) { + if net.peer(3).has_body(&gap_end) && net.peer(3).has_body(&target) { Poll::Ready(()) } else { Poll::Pending diff --git a/client/offchain/Cargo.toml b/client/offchain/Cargo.toml index ff97f29961155..5ebb21406efbf 100644 --- a/client/offchain/Cargo.toml +++ b/client/offchain/Cargo.toml @@ -13,12 +13,12 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] +array-bytes = "4.1" bytes = "1.1" codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive"] } fnv = "1.0.6" futures = "0.3.21" futures-timer = "3.0.2" -hex = "0.4" hyper = { version = "0.14.16", features = ["stream", "http2"] } hyper-rustls = { version = "0.23.0", features = ["http2"] } libp2p = { version = "0.46.1", default-features = false } diff --git a/client/offchain/src/api.rs b/client/offchain/src/api.rs index 6d6c52c989c34..7d3dd8302f343 100644 --- a/client/offchain/src/api.rs +++ b/client/offchain/src/api.rs @@ -79,8 +79,8 @@ impl offchain::DbExternalities for Db { tracing::debug!( target: "offchain-worker::storage", ?kind, - key = ?hex::encode(key), - value = ?hex::encode(value), + key = ?array_bytes::bytes2hex("", key), + value = ?array_bytes::bytes2hex("", value), "Write", ); match kind { @@ -93,7 +93,7 @@ impl offchain::DbExternalities for Db { tracing::debug!( target: "offchain-worker::storage", ?kind, - key = ?hex::encode(key), + key = ?array_bytes::bytes2hex("", key), "Clear", ); match kind { @@ -112,9 +112,9 @@ impl offchain::DbExternalities for Db { tracing::debug!( target: "offchain-worker::storage", ?kind, - key = ?hex::encode(key), - new_value = ?hex::encode(new_value), - old_value = ?old_value.as_ref().map(hex::encode), + 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 { @@ -132,8 +132,8 @@ impl offchain::DbExternalities for Db { tracing::debug!( target: "offchain-worker::storage", ?kind, - key = ?hex::encode(key), - result = ?result.as_ref().map(hex::encode), + key = ?array_bytes::bytes2hex("", key), + result = ?result.as_ref().map(|s| array_bytes::bytes2hex("", s)), "Read", ); result diff --git a/client/rpc-servers/src/lib.rs b/client/rpc-servers/src/lib.rs index 68b4aa6767348..0e2aca0dcc829 100644 --- a/client/rpc-servers/src/lib.rs +++ b/client/rpc-servers/src/lib.rs @@ -203,7 +203,6 @@ fn build_rpc_api(mut rpc_api: RpcModule) -> RpcModu rpc_api .register_method("rpc_methods", move |_, _| { Ok(serde_json::json!({ - "version": 1, "methods": available_methods, })) }) diff --git a/client/rpc-spec-v2/Cargo.toml b/client/rpc-spec-v2/Cargo.toml new file mode 100644 index 0000000000000..12dec7464e6d0 --- /dev/null +++ b/client/rpc-spec-v2/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "sc-rpc-spec-v2" +version = "0.10.0-dev" +authors = ["Parity Technologies "] +edition = "2021" +license = "GPL-3.0-or-later WITH Classpath-exception-2.0" +homepage = "https://substrate.io" +repository = "https://github.com/paritytech/substrate/" +description = "Substrate RPC interface v2." +readme = "README.md" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +jsonrpsee = { version = "0.15.1", features = ["server", "macros"] } +# Internal chain structures for "chain_spec". +sc-chain-spec = { version = "4.0.0-dev", path = "../chain-spec" } +hex = "0.4" + +[dev-dependencies] +serde_json = "1.0" +tokio = { version = "1.17.0", features = ["macros"] } diff --git a/client/rpc-spec-v2/README.md b/client/rpc-spec-v2/README.md new file mode 100644 index 0000000000000..e860e0c2334da --- /dev/null +++ b/client/rpc-spec-v2/README.md @@ -0,0 +1,5 @@ +Substrate RPC interfaces. + +A collection of RPC methods and subscriptions supported by all substrate clients. + +License: GPL-3.0-or-later WITH Classpath-exception-2.0 \ No newline at end of file diff --git a/client/rpc-spec-v2/src/chain_spec/api.rs b/client/rpc-spec-v2/src/chain_spec/api.rs new file mode 100644 index 0000000000000..dfe2d76de6501 --- /dev/null +++ b/client/rpc-spec-v2/src/chain_spec/api.rs @@ -0,0 +1,53 @@ +// This file is part of Substrate. + +// Copyright (C) 2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +//! API trait of the chain spec. + +use jsonrpsee::{core::RpcResult, proc_macros::rpc}; +use sc_chain_spec::Properties; + +#[rpc(client, server)] +pub trait ChainSpecApi { + /// Get the chain name, as present in the chain specification. + /// + /// # Unstable + /// + /// This method is unstable and subject to change in the future. + #[method(name = "chainSpec_unstable_chainName")] + fn chain_spec_unstable_chain_name(&self) -> RpcResult; + + /// Get the chain's genesis hash. + /// + /// # Unstable + /// + /// This method is unstable and subject to change in the future. + #[method(name = "chainSpec_unstable_genesisHash")] + fn chain_spec_unstable_genesis_hash(&self) -> RpcResult; + + /// Get the properties of the chain, as present in the chain specification. + /// + /// # Note + /// + /// The json whitespaces are not guaranteed to persist. + /// + /// # Unstable + /// + /// This method is unstable and subject to change in the future. + #[method(name = "chainSpec_unstable_properties")] + fn chain_spec_unstable_properties(&self) -> RpcResult; +} diff --git a/client/rpc-spec-v2/src/chain_spec/chain_spec.rs b/client/rpc-spec-v2/src/chain_spec/chain_spec.rs new file mode 100644 index 0000000000000..90d05f1d9d41d --- /dev/null +++ b/client/rpc-spec-v2/src/chain_spec/chain_spec.rs @@ -0,0 +1,60 @@ +// This file is part of Substrate. + +// Copyright (C) 2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +//! API implementation for the specification of a chain. + +use crate::chain_spec::api::ChainSpecApiServer; +use jsonrpsee::core::RpcResult; +use sc_chain_spec::Properties; + +/// An API for chain spec RPC calls. +pub struct ChainSpec { + /// The name of the chain. + name: String, + /// The hexadecimal encoded hash of the genesis block. + genesis_hash: String, + /// Chain properties. + properties: Properties, +} + +impl ChainSpec { + /// Creates a new [`ChainSpec`]. + pub fn new>( + name: String, + genesis_hash: Hash, + properties: Properties, + ) -> Self { + let genesis_hash = format!("0x{}", hex::encode(genesis_hash)); + + Self { name, properties, genesis_hash } + } +} + +impl ChainSpecApiServer for ChainSpec { + fn chain_spec_unstable_chain_name(&self) -> RpcResult { + Ok(self.name.clone()) + } + + fn chain_spec_unstable_genesis_hash(&self) -> RpcResult { + Ok(self.genesis_hash.clone()) + } + + fn chain_spec_unstable_properties(&self) -> RpcResult { + Ok(self.properties.clone()) + } +} diff --git a/client/rpc-spec-v2/src/chain_spec/mod.rs b/client/rpc-spec-v2/src/chain_spec/mod.rs new file mode 100644 index 0000000000000..cd4fcf246f603 --- /dev/null +++ b/client/rpc-spec-v2/src/chain_spec/mod.rs @@ -0,0 +1,38 @@ +// This file is part of Substrate. + +// Copyright (C) 2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +//! Substrate chain specification API. +//! +//! The *chain spec* (short for *chain specification*) allows inspecting the content of +//! the specification of the chain that a JSON-RPC server is targeting. +//! +//! The values returned by the API are guaranteed to never change during the lifetime of the +//! JSON-RPC server. +//! +//! # Note +//! +//! Methods are prefixed by `chainSpec`. + +#[cfg(test)] +mod tests; + +pub mod api; +pub mod chain_spec; + +pub use api::ChainSpecApiServer; +pub use chain_spec::ChainSpec; diff --git a/client/rpc-spec-v2/src/chain_spec/tests.rs b/client/rpc-spec-v2/src/chain_spec/tests.rs new file mode 100644 index 0000000000000..6c078b2974e98 --- /dev/null +++ b/client/rpc-spec-v2/src/chain_spec/tests.rs @@ -0,0 +1,61 @@ +// This file is part of Substrate. + +// Copyright (C) 2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +use super::*; +use jsonrpsee::{types::EmptyParams, RpcModule}; +use sc_chain_spec::Properties; + +const CHAIN_NAME: &'static str = "TEST_CHAIN_NAME"; +const CHAIN_GENESIS: [u8; 32] = [0; 32]; +const CHAIN_PROPERTIES: &'static str = r#"{"three": "123", "one": 1, "two": 12}"#; + +fn api() -> RpcModule { + ChainSpec::new( + CHAIN_NAME.to_string(), + CHAIN_GENESIS, + serde_json::from_str(CHAIN_PROPERTIES).unwrap(), + ) + .into_rpc() +} + +#[tokio::test] +async fn chain_spec_chain_name_works() { + let name = api() + .call::<_, String>("chainSpec_unstable_chainName", EmptyParams::new()) + .await + .unwrap(); + assert_eq!(name, CHAIN_NAME); +} + +#[tokio::test] +async fn chain_spec_genesis_hash_works() { + let genesis = api() + .call::<_, String>("chainSpec_unstable_genesisHash", EmptyParams::new()) + .await + .unwrap(); + assert_eq!(genesis, format!("0x{}", hex::encode(CHAIN_GENESIS))); +} + +#[tokio::test] +async fn chain_spec_properties_works() { + let properties = api() + .call::<_, Properties>("chainSpec_unstable_properties", EmptyParams::new()) + .await + .unwrap(); + assert_eq!(properties, serde_json::from_str(CHAIN_PROPERTIES).unwrap()); +} diff --git a/client/rpc-spec-v2/src/lib.rs b/client/rpc-spec-v2/src/lib.rs new file mode 100644 index 0000000000000..297fda13172d6 --- /dev/null +++ b/client/rpc-spec-v2/src/lib.rs @@ -0,0 +1,26 @@ +// This file is part of Substrate. + +// Copyright (C) 2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +//! Substrate JSON-RPC interface v2. +//! +//! Specification [document](https://paritytech.github.io/json-rpc-interface-spec/). + +#![warn(missing_docs)] +#![deny(unused_crate_dependencies)] + +pub mod chain_spec; diff --git a/client/rpc/src/dev/tests.rs b/client/rpc/src/dev/tests.rs index f3b18690d0972..816f3cdfe6025 100644 --- a/client/rpc/src/dev/tests.rs +++ b/client/rpc/src/dev/tests.rs @@ -43,8 +43,8 @@ async fn block_stats_work() { .await .unwrap(), Some(BlockStats { - witness_len: 597, - witness_compact_len: 500, + witness_len: 630, + witness_compact_len: 534, block_len: 99, num_extrinsics: 0, }), diff --git a/client/service/test/Cargo.toml b/client/service/test/Cargo.toml index 92df5381c202b..1f934a6e5355f 100644 --- a/client/service/test/Cargo.toml +++ b/client/service/test/Cargo.toml @@ -12,10 +12,9 @@ repository = "https://github.com/paritytech/substrate/" targets = ["x86_64-unknown-linux-gnu"] [dependencies] +array-bytes = "4.1" fdlimit = "0.2.1" futures = "0.3.21" -hex = "0.4" -hex-literal = "0.3.4" log = "0.4.17" parity-scale-codec = "3.0.0" parking_lot = "0.12.1" diff --git a/client/service/test/src/client/mod.rs b/client/service/test/src/client/mod.rs index f02b1321d2922..2ab1415f8ca31 100644 --- a/client/service/test/src/client/mod.rs +++ b/client/service/test/src/client/mod.rs @@ -17,7 +17,6 @@ // along with this program. If not, see . use futures::executor::block_on; -use hex_literal::hex; use parity_scale_codec::{Decode, Encode, Joiner}; use sc_block_builder::BlockBuilderProvider; use sc_client_api::{ @@ -155,7 +154,9 @@ fn block1(genesis_hash: Hash, backend: &InMemoryBackend) -> (Vec = client @@ -1604,25 +1605,29 @@ fn storage_keys_iter_prefix_and_start_key_works() { .collect(); assert_eq!( res, - [child_root.clone(), hex!("3a636f6465").to_vec(), hex!("3a686561707061676573").to_vec(),] + [ + child_root.clone(), + array_bytes::hex2bytes_unchecked("3a636f6465"), + array_bytes::hex2bytes_unchecked("3a686561707061676573"), + ] ); let res: Vec<_> = client .storage_keys_iter( &BlockId::Number(0), Some(&prefix), - Some(&StorageKey(hex!("3a636f6465").to_vec())), + Some(&StorageKey(array_bytes::hex2bytes_unchecked("3a636f6465"))), ) .unwrap() .map(|x| x.0) .collect(); - assert_eq!(res, [hex!("3a686561707061676573").to_vec()]); + assert_eq!(res, [array_bytes::hex2bytes_unchecked("3a686561707061676573")]); let res: Vec<_> = client .storage_keys_iter( &BlockId::Number(0), Some(&prefix), - Some(&StorageKey(hex!("3a686561707061676573").to_vec())), + Some(&StorageKey(array_bytes::hex2bytes_unchecked("3a686561707061676573"))), ) .unwrap() .map(|x| x.0) @@ -1653,13 +1658,13 @@ fn storage_keys_iter_prefix_and_start_key_works() { fn storage_keys_iter_works() { let client = substrate_test_runtime_client::new(); - let prefix = StorageKey(hex!("").to_vec()); + let prefix = StorageKey(array_bytes::hex2bytes_unchecked("")); let res: Vec<_> = client .storage_keys_iter(&BlockId::Number(0), Some(&prefix), None) .unwrap() - .take(8) - .map(|x| hex::encode(&x.0)) + .take(9) + .map(|x| array_bytes::bytes2hex("", &x.0)) .collect(); assert_eq!( res, @@ -1670,6 +1675,7 @@ fn storage_keys_iter_works() { "1a560ecfd2a62c2b8521ef149d0804eb621050e3988ed97dca55f0d7c3e6aa34", "1d66850d32002979d67dd29dc583af5b2ae2a1f71c1f35ad90fff122be7a3824", "237498b98d8803334286e9f0483ef513098dd3c1c22ca21c4dc155b4ef6cc204", + "26aa394eea5630e07c48ae0c9558cef75e0621c4869aa60c02be9adcc98a0d1d", "29b9db10ec5bf7907d8f74b5e60aa8140c4fbdd8127a1ee5600cb98e5ec01729", "3a636f6465", ] @@ -1679,11 +1685,11 @@ fn storage_keys_iter_works() { .storage_keys_iter( &BlockId::Number(0), Some(&prefix), - Some(&StorageKey(hex!("3a636f6465").to_vec())), + Some(&StorageKey(array_bytes::hex2bytes_unchecked("3a636f6465"))), ) .unwrap() .take(7) - .map(|x| hex::encode(&x.0)) + .map(|x| array_bytes::bytes2hex("", &x.0)) .collect(); assert_eq!( res, @@ -1694,7 +1700,7 @@ fn storage_keys_iter_works() { "5c2d5fda66373dabf970e4fb13d277ce91c5233473321129d32b5a8085fa8133", "6644b9b8bc315888ac8e41a7968dc2b4141a5403c58acdf70b7e8f7e07bf5081", "66484000ed3f75c95fc7b03f39c20ca1e1011e5999278247d3b2f5e3c3273808", - "79c07e2b1d2e2abfd4855b936617eeff5e0621c4869aa60c02be9adcc98a0d1d", + "7d5007603a7f5dd729d51d93cf695d6465789443bb967c0d1fe270e388c96eaa", ] ); @@ -1702,22 +1708,22 @@ fn storage_keys_iter_works() { .storage_keys_iter( &BlockId::Number(0), Some(&prefix), - Some(&StorageKey( - hex!("79c07e2b1d2e2abfd4855b936617eeff5e0621c4869aa60c02be9adcc98a0d1d").to_vec(), - )), + Some(&StorageKey(array_bytes::hex2bytes_unchecked( + "7d5007603a7f5dd729d51d93cf695d6465789443bb967c0d1fe270e388c96eaa", + ))), ) .unwrap() .take(5) - .map(|x| hex::encode(x.0)) + .map(|x| array_bytes::bytes2hex("", &x.0)) .collect(); assert_eq!( res, [ - "7d5007603a7f5dd729d51d93cf695d6465789443bb967c0d1fe270e388c96eaa", "811ecfaadcf5f2ee1d67393247e2f71a1662d433e8ce7ff89fb0d4aa9561820b", "a93d74caa7ec34ea1b04ce1e5c090245f867d333f0f88278a451e45299654dc5", "a9ee1403384afbfc13f13be91ff70bfac057436212e53b9733914382ac942892", "cf722c0832b5231d35e29f319ff27389f5032bfc7bfc3ba5ed7839f2042fb99f", + "e3b47b6c84c0493481f97c5197d2554f", ] ); } diff --git a/client/transaction-pool/Cargo.toml b/client/transaction-pool/Cargo.toml index 56860d94a9e02..5e005f5523ae8 100644 --- a/client/transaction-pool/Cargo.toml +++ b/client/transaction-pool/Cargo.toml @@ -34,9 +34,9 @@ sp-tracing = { version = "5.0.0", path = "../../primitives/tracing" } sp-transaction-pool = { version = "4.0.0-dev", path = "../../primitives/transaction-pool" } [dev-dependencies] +array-bytes = "4.1" assert_matches = "1.3.0" criterion = "0.3" -hex = "0.4" sc-block-builder = { version = "0.10.0-dev", path = "../block-builder" } sp-consensus = { version = "0.10.0-dev", path = "../../primitives/consensus/common" } substrate-test-runtime = { version = "2.0.0", path = "../../test-utils/runtime" } diff --git a/client/transaction-pool/tests/pool.rs b/client/transaction-pool/tests/pool.rs index 17c2cfa8a1e06..f04a27cf81e1d 100644 --- a/client/transaction-pool/tests/pool.rs +++ b/client/transaction-pool/tests/pool.rs @@ -880,7 +880,7 @@ fn should_not_accept_old_signatures() { // generated with schnorrkel 0.1.1 from `_bytes` let old_singature = sp_core::sr25519::Signature::try_from( - &hex::decode( + &array_bytes::hex2bytes( "c427eb672e8c441c86d31f1a81b22b43102058e9ce237cabe9897ea5099ffd426\ cd1c6a1f4f2869c3df57901d36bedcb295657adb3a4355add86ed234eb83108", ) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index c867a245739ff..25f8e582c78fc 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -360,7 +360,7 @@ Runtime ------- * Introduce stacked filtering (#6273) -* Allow "anonymous" proxied accounts (#6236) +* Allow "pure" proxied accounts (#6236) * Allow over-weight collective proposals to be closed (#6163) * Fix Election when ForceNone V1 (#6166) diff --git a/docs/Upgrading-2.0-to-3.0.md b/docs/Upgrading-2.0-to-3.0.md index 210023c3aec5a..7540e0d5b5b8c 100644 --- a/docs/Upgrading-2.0-to-3.0.md +++ b/docs/Upgrading-2.0-to-3.0.md @@ -147,7 +147,7 @@ And update the overall definition for weights on frame and a few related types a + type BlockWeights = RuntimeBlockWeights; + type BlockLength = RuntimeBlockLength; + type DbWeight = RocksDbWeight; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = Index; @@ -171,25 +198,19 @@ impl frame_system::Trait for Runtime { diff --git a/frame/alliance/Cargo.toml b/frame/alliance/Cargo.toml index 24e047091009b..399822a2215f5 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] -hex = { version = "0.4", default-features = false, features = ["alloc"], optional = true } +array-bytes = { version = "4.1", optional = true } sha2 = { version = "0.10.1", default-features = false, optional = true } log = { version = "0.4.14", default-features = false } @@ -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] -hex-literal = "0.3.1" +array-bytes = "4.1" sha2 = "0.10.1" pallet-balances = { version = "4.0.0-dev", path = "../balances" } pallet-collective = { version = "4.0.0-dev", path = "../collective" } @@ -55,7 +55,7 @@ std = [ "pallet-identity/std", ] runtime-benchmarks = [ - "hex", + "array-bytes", "sha2", "frame-benchmarking/runtime-benchmarks", "sp-runtime/runtime-benchmarks", diff --git a/frame/alliance/src/lib.rs b/frame/alliance/src/lib.rs index 9d320c4215a70..82c7e21dba3af 100644 --- a/frame/alliance/src/lib.rs +++ b/frame/alliance/src/lib.rs @@ -245,7 +245,7 @@ pub mod pallet { /// The outer call dispatch type. type Proposal: Parameter - + Dispatchable + + Dispatchable + From> + From> + GetDispatchInfo @@ -253,13 +253,13 @@ pub mod pallet { + IsType<::RuntimeCall>; /// Origin for admin-level operations, like setting the Alliance's rules. - type AdminOrigin: EnsureOrigin; + type AdminOrigin: EnsureOrigin; /// Origin that manages entry and forcible discharge from the Alliance. - type MembershipManager: EnsureOrigin; + type MembershipManager: EnsureOrigin; /// Origin for making announcements and adding/removing unscrupulous items. - type AnnouncementOrigin: EnsureOrigin; + type AnnouncementOrigin: EnsureOrigin; /// The currency used for deposits. type Currency: ReservableCurrency; diff --git a/frame/alliance/src/mock.rs b/frame/alliance/src/mock.rs index 42c97876d40b0..196e0003b537f 100644 --- a/frame/alliance/src/mock.rs +++ b/frame/alliance/src/mock.rs @@ -47,7 +47,7 @@ impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); type BlockLength = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = BlockNumber; @@ -95,7 +95,7 @@ parameter_types! { } type AllianceCollective = pallet_collective::Instance1; impl pallet_collective::Config for Test { - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Proposal = RuntimeCall; type RuntimeEvent = RuntimeEvent; type MotionDuration = MotionDuration; @@ -283,7 +283,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| { - assert_ok!(Identity::add_registrar(Origin::signed(1), 1)); + assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), 1)); let info = IdentityInfo { additional: BoundedVec::default(), @@ -296,58 +296,58 @@ pub fn new_test_ext() -> sp_io::TestExternalities { image: Data::default(), twitter: Data::default(), }; - assert_ok!(Identity::set_identity(Origin::signed(1), Box::new(info.clone()))); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(1), Box::new(info.clone()))); assert_ok!(Identity::provide_judgement( - Origin::signed(1), + RuntimeOrigin::signed(1), 0, 1, Judgement::KnownGood, BlakeTwo256::hash_of(&info) )); - assert_ok!(Identity::set_identity(Origin::signed(2), Box::new(info.clone()))); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(2), Box::new(info.clone()))); assert_ok!(Identity::provide_judgement( - Origin::signed(1), + RuntimeOrigin::signed(1), 0, 2, Judgement::KnownGood, BlakeTwo256::hash_of(&info) )); - assert_ok!(Identity::set_identity(Origin::signed(3), Box::new(info.clone()))); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(3), Box::new(info.clone()))); assert_ok!(Identity::provide_judgement( - Origin::signed(1), + RuntimeOrigin::signed(1), 0, 3, Judgement::KnownGood, BlakeTwo256::hash_of(&info) )); - assert_ok!(Identity::set_identity(Origin::signed(4), Box::new(info.clone()))); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(4), Box::new(info.clone()))); assert_ok!(Identity::provide_judgement( - Origin::signed(1), + RuntimeOrigin::signed(1), 0, 4, Judgement::KnownGood, BlakeTwo256::hash_of(&info) )); - assert_ok!(Identity::set_identity(Origin::signed(5), Box::new(info.clone()))); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(5), Box::new(info.clone()))); assert_ok!(Identity::provide_judgement( - Origin::signed(1), + RuntimeOrigin::signed(1), 0, 5, Judgement::KnownGood, BlakeTwo256::hash_of(&info) )); - assert_ok!(Identity::set_identity(Origin::signed(6), Box::new(info.clone()))); - assert_ok!(Identity::set_identity(Origin::signed(8), Box::new(info.clone()))); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(6), Box::new(info.clone()))); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(8), Box::new(info.clone()))); assert_ok!(Identity::provide_judgement( - Origin::signed(1), + RuntimeOrigin::signed(1), 0, 8, Judgement::KnownGood, BlakeTwo256::hash_of(&info) )); - assert_ok!(Identity::set_identity(Origin::signed(9), Box::new(info.clone()))); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(9), Box::new(info.clone()))); assert_ok!(Identity::provide_judgement( - Origin::signed(1), + RuntimeOrigin::signed(1), 0, 9, Judgement::KnownGood, @@ -356,11 +356,11 @@ pub fn new_test_ext() -> sp_io::TestExternalities { // Joining before init should fail. assert_noop!( - Alliance::join_alliance(Origin::signed(1)), + Alliance::join_alliance(RuntimeOrigin::signed(1)), Error::::AllianceNotYetInitialized ); - assert_ok!(Alliance::init_members(Origin::root(), vec![1, 2], vec![3], vec![])); + assert_ok!(Alliance::init_members(RuntimeOrigin::root(), vec![1, 2], vec![3], vec![])); System::set_block_number(1); }); diff --git a/frame/alliance/src/tests.rs b/frame/alliance/src/tests.rs index 79fd33965edb5..c55826768c695 100644 --- a/frame/alliance/src/tests.rs +++ b/frame/alliance/src/tests.rs @@ -30,28 +30,31 @@ fn init_members_works() { new_test_ext().execute_with(|| { // alliance must be reset first, no witness data assert_noop!( - Alliance::init_members(Origin::root(), vec![8], vec![], vec![],), + Alliance::init_members(RuntimeOrigin::root(), vec![8], vec![], vec![],), Error::::AllianceAlreadyInitialized, ); // give a retirement notice to check later a retiring member not removed - assert_ok!(Alliance::give_retirement_notice(Origin::signed(2))); + assert_ok!(Alliance::give_retirement_notice(RuntimeOrigin::signed(2))); assert!(Alliance::is_member_of(&2, MemberRole::Retiring)); // disband the Alliance to init new - assert_ok!(Alliance::disband(Origin::root(), DisbandWitness::new(2, 0))); + assert_ok!(Alliance::disband(RuntimeOrigin::root(), DisbandWitness::new(2, 0))); // fails without root - assert_noop!(Alliance::init_members(Origin::signed(1), vec![], vec![], vec![]), BadOrigin); + assert_noop!( + Alliance::init_members(RuntimeOrigin::signed(1), vec![], vec![], vec![]), + BadOrigin + ); // founders missing, other members given assert_noop!( - Alliance::init_members(Origin::root(), vec![], vec![4], vec![2],), + Alliance::init_members(RuntimeOrigin::root(), vec![], vec![4], vec![2],), Error::::FoundersMissing, ); // success call - assert_ok!(Alliance::init_members(Origin::root(), vec![8, 5], vec![4], vec![2],)); + assert_ok!(Alliance::init_members(RuntimeOrigin::root(), vec![8, 5], vec![4], vec![2],)); // assert new set of voting members assert_eq!(Alliance::voting_members_sorted(), vec![4, 5, 8]); @@ -78,36 +81,36 @@ fn disband_works() { assert_eq!(Alliance::voting_members_sorted(), vec![1, 2, 3]); // give a retirement notice to check later a retiring member not removed - assert_ok!(Alliance::give_retirement_notice(Origin::signed(2))); + assert_ok!(Alliance::give_retirement_notice(RuntimeOrigin::signed(2))); assert!(Alliance::is_member_of(&2, MemberRole::Retiring)); // join alliance and reserve funds assert_eq!(Balances::free_balance(9), 40); - assert_ok!(Alliance::join_alliance(Origin::signed(9))); + assert_ok!(Alliance::join_alliance(RuntimeOrigin::signed(9))); assert_eq!(Alliance::deposit_of(9), Some(25)); assert_eq!(Balances::free_balance(9), 15); assert!(Alliance::is_member_of(&9, MemberRole::Ally)); // fails without root - assert_noop!(Alliance::disband(Origin::signed(1), Default::default()), BadOrigin); + assert_noop!(Alliance::disband(RuntimeOrigin::signed(1), Default::default()), BadOrigin); // bad witness data checks assert_noop!( - Alliance::disband(Origin::root(), Default::default(),), + Alliance::disband(RuntimeOrigin::root(), Default::default(),), Error::::BadWitness ); assert_noop!( - Alliance::disband(Origin::root(), DisbandWitness::new(1, 1)), + Alliance::disband(RuntimeOrigin::root(), DisbandWitness::new(1, 1)), Error::::BadWitness, ); assert_noop!( - Alliance::disband(Origin::root(), DisbandWitness::new(2, 0)), + Alliance::disband(RuntimeOrigin::root(), DisbandWitness::new(2, 0)), Error::::BadWitness, ); // success call - assert_ok!(Alliance::disband(Origin::root(), DisbandWitness::new(2, 1))); + assert_ok!(Alliance::disband(RuntimeOrigin::root(), DisbandWitness::new(2, 1))); // assert members disband assert!(!Alliance::is_member(&1)); @@ -125,7 +128,7 @@ fn disband_works() { // the Alliance must be set first assert_noop!( - Alliance::disband(Origin::root(), DisbandWitness::new(100, 100)), + Alliance::disband(RuntimeOrigin::root(), DisbandWitness::new(100, 100)), Error::::AllianceNotYetInitialized, ); }) @@ -138,12 +141,17 @@ fn propose_works() { // only voting member can propose proposal, 4 is ally not have vote rights assert_noop!( - Alliance::propose(Origin::signed(4), 3, Box::new(proposal.clone()), proposal_len), + Alliance::propose( + RuntimeOrigin::signed(4), + 3, + Box::new(proposal.clone()), + proposal_len + ), Error::::NoVotingRights ); assert_ok!(Alliance::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len @@ -171,12 +179,12 @@ fn vote_works() { new_test_ext().execute_with(|| { let (proposal, proposal_len, hash) = make_remark_proposal(42); assert_ok!(Alliance::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len )); - assert_ok!(Alliance::vote(Origin::signed(2), hash, 0, true)); + assert_ok!(Alliance::vote(RuntimeOrigin::signed(2), hash, 0, true)); let record = |event| EventRecord { phase: Phase::Initialization, event, topics: vec![] }; assert_eq!( @@ -205,21 +213,21 @@ fn veto_works() { new_test_ext().execute_with(|| { let (proposal, proposal_len, hash) = make_remark_proposal(42); assert_ok!(Alliance::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len )); // only set_rule/elevate_ally can be veto assert_noop!( - Alliance::veto(Origin::signed(1), hash), + Alliance::veto(RuntimeOrigin::signed(1), hash), Error::::NotVetoableProposal ); let cid = test_cid(); let (vetoable_proposal, vetoable_proposal_len, vetoable_hash) = make_set_rule_proposal(cid); assert_ok!(Alliance::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(vetoable_proposal.clone()), vetoable_proposal_len @@ -227,11 +235,11 @@ fn veto_works() { // only founder have veto rights, 3 is fellow assert_noop!( - Alliance::veto(Origin::signed(3), vetoable_hash), + Alliance::veto(RuntimeOrigin::signed(3), vetoable_hash), Error::::NotFounder ); - assert_ok!(Alliance::veto(Origin::signed(2), vetoable_hash)); + assert_ok!(Alliance::veto(RuntimeOrigin::signed(2), vetoable_hash)); let record = |event| EventRecord { phase: Phase::Initialization, event, topics: vec![] }; assert_eq!( System::events(), @@ -262,15 +270,21 @@ fn close_works() { let (proposal, proposal_len, hash) = make_remark_proposal(42); let proposal_weight = proposal.get_dispatch_info().weight; assert_ok!(Alliance::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len )); - assert_ok!(Alliance::vote(Origin::signed(1), hash, 0, true)); - assert_ok!(Alliance::vote(Origin::signed(2), hash, 0, true)); - assert_ok!(Alliance::vote(Origin::signed(3), hash, 0, true)); - assert_ok!(Alliance::close(Origin::signed(1), hash, 0, proposal_weight, proposal_len)); + assert_ok!(Alliance::vote(RuntimeOrigin::signed(1), hash, 0, true)); + assert_ok!(Alliance::vote(RuntimeOrigin::signed(2), hash, 0, true)); + assert_ok!(Alliance::vote(RuntimeOrigin::signed(3), hash, 0, true)); + assert_ok!(Alliance::close( + RuntimeOrigin::signed(1), + hash, + 0, + proposal_weight, + proposal_len + )); let record = |event| EventRecord { phase: Phase::Initialization, event, topics: vec![] }; assert_eq!( @@ -324,7 +338,7 @@ fn close_works() { fn set_rule_works() { new_test_ext().execute_with(|| { let cid = test_cid(); - assert_ok!(Alliance::set_rule(Origin::signed(1), cid.clone())); + assert_ok!(Alliance::set_rule(RuntimeOrigin::signed(1), cid.clone())); assert_eq!(Alliance::rule(), Some(cid.clone())); System::assert_last_event(mock::RuntimeEvent::Alliance(crate::Event::NewRuleSet { @@ -338,9 +352,9 @@ fn announce_works() { new_test_ext().execute_with(|| { let cid = test_cid(); - assert_noop!(Alliance::announce(Origin::signed(2), cid.clone()), BadOrigin); + assert_noop!(Alliance::announce(RuntimeOrigin::signed(2), cid.clone()), BadOrigin); - assert_ok!(Alliance::announce(Origin::signed(3), cid.clone())); + assert_ok!(Alliance::announce(RuntimeOrigin::signed(3), cid.clone())); assert_eq!(Alliance::announcements(), vec![cid.clone()]); System::assert_last_event(mock::RuntimeEvent::Alliance(crate::Event::Announced { @@ -353,7 +367,7 @@ fn announce_works() { fn remove_announcement_works() { new_test_ext().execute_with(|| { let cid = test_cid(); - assert_ok!(Alliance::announce(Origin::signed(3), cid.clone())); + assert_ok!(Alliance::announce(RuntimeOrigin::signed(3), cid.clone())); assert_eq!(Alliance::announcements(), vec![cid.clone()]); System::assert_last_event(mock::RuntimeEvent::Alliance(crate::Event::Announced { announcement: cid.clone(), @@ -361,7 +375,7 @@ fn remove_announcement_works() { System::set_block_number(2); - assert_ok!(Alliance::remove_announcement(Origin::signed(3), cid.clone())); + assert_ok!(Alliance::remove_announcement(RuntimeOrigin::signed(3), cid.clone())); assert_eq!(Alliance::announcements(), vec![]); System::assert_last_event(mock::RuntimeEvent::Alliance( crate::Event::AnnouncementRemoved { announcement: cid }, @@ -373,46 +387,52 @@ fn remove_announcement_works() { fn join_alliance_works() { new_test_ext().execute_with(|| { // check already member - assert_noop!(Alliance::join_alliance(Origin::signed(1)), Error::::AlreadyMember); + assert_noop!( + Alliance::join_alliance(RuntimeOrigin::signed(1)), + Error::::AlreadyMember + ); // check already listed as unscrupulous assert_ok!(Alliance::add_unscrupulous_items( - Origin::signed(3), + RuntimeOrigin::signed(3), vec![UnscrupulousItem::AccountId(4)] )); assert_noop!( - Alliance::join_alliance(Origin::signed(4)), + Alliance::join_alliance(RuntimeOrigin::signed(4)), Error::::AccountNonGrata ); assert_ok!(Alliance::remove_unscrupulous_items( - Origin::signed(3), + RuntimeOrigin::signed(3), vec![UnscrupulousItem::AccountId(4)] )); // check deposit funds assert_noop!( - Alliance::join_alliance(Origin::signed(5)), + Alliance::join_alliance(RuntimeOrigin::signed(5)), Error::::InsufficientFunds ); // success to submit - assert_ok!(Alliance::join_alliance(Origin::signed(4))); + assert_ok!(Alliance::join_alliance(RuntimeOrigin::signed(4))); assert_eq!(Alliance::deposit_of(4), Some(25)); assert_eq!(Alliance::members(MemberRole::Ally), vec![4]); // check already member - assert_noop!(Alliance::join_alliance(Origin::signed(4)), Error::::AlreadyMember); + assert_noop!( + Alliance::join_alliance(RuntimeOrigin::signed(4)), + Error::::AlreadyMember + ); // check missing identity judgement #[cfg(not(feature = "runtime-benchmarks"))] assert_noop!( - Alliance::join_alliance(Origin::signed(6)), + Alliance::join_alliance(RuntimeOrigin::signed(6)), Error::::WithoutGoodIdentityJudgement ); // check missing identity info #[cfg(not(feature = "runtime-benchmarks"))] assert_noop!( - Alliance::join_alliance(Origin::signed(7)), + Alliance::join_alliance(RuntimeOrigin::signed(7)), Error::::WithoutIdentityDisplayAndWebsite ); }); @@ -423,51 +443,51 @@ fn nominate_ally_works() { new_test_ext().execute_with(|| { // check already member assert_noop!( - Alliance::nominate_ally(Origin::signed(1), 2), + Alliance::nominate_ally(RuntimeOrigin::signed(1), 2), Error::::AlreadyMember ); // only voting member(founder/fellow) have nominate right assert_noop!( - Alliance::nominate_ally(Origin::signed(5), 4), + Alliance::nominate_ally(RuntimeOrigin::signed(5), 4), Error::::NoVotingRights ); // check already listed as unscrupulous assert_ok!(Alliance::add_unscrupulous_items( - Origin::signed(3), + RuntimeOrigin::signed(3), vec![UnscrupulousItem::AccountId(4)] )); assert_noop!( - Alliance::nominate_ally(Origin::signed(1), 4), + Alliance::nominate_ally(RuntimeOrigin::signed(1), 4), Error::::AccountNonGrata ); assert_ok!(Alliance::remove_unscrupulous_items( - Origin::signed(3), + RuntimeOrigin::signed(3), vec![UnscrupulousItem::AccountId(4)] )); // success to nominate - assert_ok!(Alliance::nominate_ally(Origin::signed(1), 4)); + assert_ok!(Alliance::nominate_ally(RuntimeOrigin::signed(1), 4)); assert_eq!(Alliance::deposit_of(4), None); assert_eq!(Alliance::members(MemberRole::Ally), vec![4]); // check already member assert_noop!( - Alliance::nominate_ally(Origin::signed(1), 4), + Alliance::nominate_ally(RuntimeOrigin::signed(1), 4), Error::::AlreadyMember ); // check missing identity judgement #[cfg(not(feature = "runtime-benchmarks"))] assert_noop!( - Alliance::join_alliance(Origin::signed(6)), + Alliance::join_alliance(RuntimeOrigin::signed(6)), Error::::WithoutGoodIdentityJudgement ); // check missing identity info #[cfg(not(feature = "runtime-benchmarks"))] assert_noop!( - Alliance::join_alliance(Origin::signed(7)), + Alliance::join_alliance(RuntimeOrigin::signed(7)), Error::::WithoutIdentityDisplayAndWebsite ); }); @@ -476,13 +496,16 @@ fn nominate_ally_works() { #[test] fn elevate_ally_works() { new_test_ext().execute_with(|| { - assert_noop!(Alliance::elevate_ally(Origin::signed(2), 4), Error::::NotAlly); + assert_noop!( + Alliance::elevate_ally(RuntimeOrigin::signed(2), 4), + Error::::NotAlly + ); - assert_ok!(Alliance::join_alliance(Origin::signed(4))); + assert_ok!(Alliance::join_alliance(RuntimeOrigin::signed(4))); assert_eq!(Alliance::members(MemberRole::Ally), vec![4]); assert_eq!(Alliance::members(MemberRole::Fellow), vec![3]); - assert_ok!(Alliance::elevate_ally(Origin::signed(2), 4)); + assert_ok!(Alliance::elevate_ally(RuntimeOrigin::signed(2), 4)); assert_eq!(Alliance::members(MemberRole::Ally), Vec::::new()); assert_eq!(Alliance::members(MemberRole::Fellow), vec![3, 4]); }); @@ -492,12 +515,12 @@ fn elevate_ally_works() { fn give_retirement_notice_work() { new_test_ext().execute_with(|| { assert_noop!( - Alliance::give_retirement_notice(Origin::signed(4)), + Alliance::give_retirement_notice(RuntimeOrigin::signed(4)), Error::::NotMember ); assert_eq!(Alliance::members(MemberRole::Fellow), vec![3]); - assert_ok!(Alliance::give_retirement_notice(Origin::signed(3))); + assert_ok!(Alliance::give_retirement_notice(RuntimeOrigin::signed(3))); assert_eq!(Alliance::members(MemberRole::Fellow), Vec::::new()); assert_eq!(Alliance::members(MemberRole::Retiring), vec![3]); System::assert_last_event(mock::RuntimeEvent::Alliance( @@ -505,7 +528,7 @@ fn give_retirement_notice_work() { )); assert_noop!( - Alliance::give_retirement_notice(Origin::signed(3)), + Alliance::give_retirement_notice(RuntimeOrigin::signed(3)), Error::::AlreadyRetiring ); }); @@ -515,23 +538,23 @@ fn give_retirement_notice_work() { fn retire_works() { new_test_ext().execute_with(|| { assert_noop!( - Alliance::retire(Origin::signed(2)), + Alliance::retire(RuntimeOrigin::signed(2)), Error::::RetirementNoticeNotGiven ); assert_noop!( - Alliance::retire(Origin::signed(4)), + Alliance::retire(RuntimeOrigin::signed(4)), Error::::RetirementNoticeNotGiven ); assert_eq!(Alliance::members(MemberRole::Fellow), vec![3]); - assert_ok!(Alliance::give_retirement_notice(Origin::signed(3))); + assert_ok!(Alliance::give_retirement_notice(RuntimeOrigin::signed(3))); assert_noop!( - Alliance::retire(Origin::signed(3)), + Alliance::retire(RuntimeOrigin::signed(3)), Error::::RetirementPeriodNotPassed ); System::set_block_number(System::block_number() + RetirementPeriod::get()); - assert_ok!(Alliance::retire(Origin::signed(3))); + assert_ok!(Alliance::retire(RuntimeOrigin::signed(3))); assert_eq!(Alliance::members(MemberRole::Fellow), Vec::::new()); System::assert_last_event(mock::RuntimeEvent::Alliance(crate::Event::MemberRetired { member: (3), @@ -541,11 +564,11 @@ fn retire_works() { // Move time on: System::set_block_number(System::block_number() + RetirementPeriod::get()); - assert_powerless(Origin::signed(3)); + assert_powerless(RuntimeOrigin::signed(3)); }); } -fn assert_powerless(user: Origin) { +fn assert_powerless(user: RuntimeOrigin) { //vote / veto with a valid propsal let cid = test_cid(); let (proposal, _, _) = make_kick_member_proposal(42); @@ -578,13 +601,16 @@ fn assert_powerless(user: Origin) { #[test] fn kick_member_works() { new_test_ext().execute_with(|| { - assert_noop!(Alliance::kick_member(Origin::signed(4), 4), BadOrigin); + assert_noop!(Alliance::kick_member(RuntimeOrigin::signed(4), 4), BadOrigin); - assert_noop!(Alliance::kick_member(Origin::signed(2), 4), Error::::NotMember); + assert_noop!( + Alliance::kick_member(RuntimeOrigin::signed(2), 4), + Error::::NotMember + ); >::insert(2, 25); assert_eq!(Alliance::members(MemberRole::Founder), vec![1, 2]); - assert_ok!(Alliance::kick_member(Origin::signed(2), 2)); + assert_ok!(Alliance::kick_member(RuntimeOrigin::signed(2), 2)); assert_eq!(Alliance::members(MemberRole::Founder), vec![1]); assert_eq!(>::get(2), None); System::assert_last_event(mock::RuntimeEvent::Alliance(crate::Event::MemberKicked { @@ -597,10 +623,10 @@ fn kick_member_works() { #[test] fn add_unscrupulous_items_works() { new_test_ext().execute_with(|| { - assert_noop!(Alliance::add_unscrupulous_items(Origin::signed(2), vec![]), BadOrigin); + assert_noop!(Alliance::add_unscrupulous_items(RuntimeOrigin::signed(2), vec![]), BadOrigin); assert_ok!(Alliance::add_unscrupulous_items( - Origin::signed(3), + RuntimeOrigin::signed(3), vec![ UnscrupulousItem::AccountId(3), UnscrupulousItem::Website("abc".as_bytes().to_vec().try_into().unwrap()) @@ -611,7 +637,7 @@ fn add_unscrupulous_items_works() { assert_noop!( Alliance::add_unscrupulous_items( - Origin::signed(3), + RuntimeOrigin::signed(3), vec![UnscrupulousItem::AccountId(3)] ), Error::::AlreadyUnscrupulous @@ -622,23 +648,26 @@ fn add_unscrupulous_items_works() { #[test] fn remove_unscrupulous_items_works() { new_test_ext().execute_with(|| { - assert_noop!(Alliance::remove_unscrupulous_items(Origin::signed(2), vec![]), BadOrigin); + assert_noop!( + Alliance::remove_unscrupulous_items(RuntimeOrigin::signed(2), vec![]), + BadOrigin + ); assert_noop!( Alliance::remove_unscrupulous_items( - Origin::signed(3), + RuntimeOrigin::signed(3), vec![UnscrupulousItem::AccountId(3)] ), Error::::NotListedAsUnscrupulous ); assert_ok!(Alliance::add_unscrupulous_items( - Origin::signed(3), + RuntimeOrigin::signed(3), vec![UnscrupulousItem::AccountId(3)] )); assert_eq!(Alliance::unscrupulous_accounts(), vec![3]); assert_ok!(Alliance::remove_unscrupulous_items( - Origin::signed(3), + RuntimeOrigin::signed(3), vec![UnscrupulousItem::AccountId(3)] )); assert_eq!(Alliance::unscrupulous_accounts(), Vec::::new()); diff --git a/frame/assets/src/lib.rs b/frame/assets/src/lib.rs index fbb4a3ea1568b..28743f917d323 100644 --- a/frame/assets/src/lib.rs +++ b/frame/assets/src/lib.rs @@ -208,7 +208,7 @@ pub mod pallet { /// The origin which may forcibly create or destroy an asset or otherwise alter privileged /// attributes. - type ForceOrigin: EnsureOrigin; + type ForceOrigin: EnsureOrigin; /// The basic amount of funds that must be reserved for an asset. #[pallet::constant] diff --git a/frame/assets/src/mock.rs b/frame/assets/src/mock.rs index 9344e5920d205..1f105eb6b4fbc 100644 --- a/frame/assets/src/mock.rs +++ b/frame/assets/src/mock.rs @@ -49,7 +49,7 @@ impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); type BlockLength = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = u64; diff --git a/frame/assets/src/tests.rs b/frame/assets/src/tests.rs index 598b6049b3d57..48cfad45a49fc 100644 --- a/frame/assets/src/tests.rs +++ b/frame/assets/src/tests.rs @@ -26,10 +26,10 @@ use sp_runtime::{traits::ConvertInto, TokenError}; #[test] fn basic_minting_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); assert_eq!(Assets::balance(0, 1), 100); - assert_ok!(Assets::mint(Origin::signed(1), 0, 2, 100)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 2, 100)); assert_eq!(Assets::balance(0, 2), 100); }); } @@ -37,46 +37,46 @@ fn basic_minting_should_work() { #[test] fn minting_too_many_insufficient_assets_fails() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, false, 1)); - assert_ok!(Assets::force_create(Origin::root(), 1, 1, false, 1)); - assert_ok!(Assets::force_create(Origin::root(), 2, 1, false, 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, false, 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 1, 1, false, 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 2, 1, false, 1)); Balances::make_free_balance_be(&1, 100); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); - assert_ok!(Assets::mint(Origin::signed(1), 1, 1, 100)); - assert_noop!(Assets::mint(Origin::signed(1), 2, 1, 100), TokenError::CannotCreate); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 1, 1, 100)); + assert_noop!(Assets::mint(RuntimeOrigin::signed(1), 2, 1, 100), TokenError::CannotCreate); Balances::make_free_balance_be(&2, 1); - assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 100)); - assert_ok!(Assets::mint(Origin::signed(1), 2, 1, 100)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 100)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 2, 1, 100)); }); } #[test] fn minting_insufficient_asset_with_deposit_should_work_when_consumers_exhausted() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, false, 1)); - assert_ok!(Assets::force_create(Origin::root(), 1, 1, false, 1)); - assert_ok!(Assets::force_create(Origin::root(), 2, 1, false, 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, false, 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 1, 1, false, 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 2, 1, false, 1)); Balances::make_free_balance_be(&1, 100); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); - assert_ok!(Assets::mint(Origin::signed(1), 1, 1, 100)); - assert_noop!(Assets::mint(Origin::signed(1), 2, 1, 100), TokenError::CannotCreate); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 1, 1, 100)); + assert_noop!(Assets::mint(RuntimeOrigin::signed(1), 2, 1, 100), TokenError::CannotCreate); - assert_ok!(Assets::touch(Origin::signed(1), 2)); + assert_ok!(Assets::touch(RuntimeOrigin::signed(1), 2)); assert_eq!(Balances::reserved_balance(&1), 10); - assert_ok!(Assets::mint(Origin::signed(1), 2, 1, 100)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 2, 1, 100)); }); } #[test] fn minting_insufficient_assets_with_deposit_without_consumer_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, false, 1)); - assert_noop!(Assets::mint(Origin::signed(1), 0, 1, 100), TokenError::CannotCreate); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, false, 1)); + assert_noop!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100), TokenError::CannotCreate); Balances::make_free_balance_be(&1, 100); - assert_ok!(Assets::touch(Origin::signed(1), 0)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::touch(RuntimeOrigin::signed(1), 0)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); assert_eq!(Balances::reserved_balance(&1), 10); assert_eq!(System::consumers(&1), 0); }); @@ -85,11 +85,11 @@ fn minting_insufficient_assets_with_deposit_without_consumer_should_work() { #[test] fn refunding_asset_deposit_with_burn_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, false, 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, false, 1)); Balances::make_free_balance_be(&1, 100); - assert_ok!(Assets::touch(Origin::signed(1), 0)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); - assert_ok!(Assets::refund(Origin::signed(1), 0, true)); + assert_ok!(Assets::touch(RuntimeOrigin::signed(1), 0)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); + assert_ok!(Assets::refund(RuntimeOrigin::signed(1), 0, true)); assert_eq!(Balances::reserved_balance(&1), 0); assert_eq!(Assets::balance(1, 0), 0); }); @@ -98,28 +98,28 @@ fn refunding_asset_deposit_with_burn_should_work() { #[test] fn refunding_asset_deposit_with_burn_disallowed_should_fail() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, false, 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, false, 1)); Balances::make_free_balance_be(&1, 100); - assert_ok!(Assets::touch(Origin::signed(1), 0)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); - assert_noop!(Assets::refund(Origin::signed(1), 0, false), Error::::WouldBurn); + assert_ok!(Assets::touch(RuntimeOrigin::signed(1), 0)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); + assert_noop!(Assets::refund(RuntimeOrigin::signed(1), 0, false), Error::::WouldBurn); }); } #[test] fn refunding_asset_deposit_without_burn_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, false, 1)); - assert_noop!(Assets::mint(Origin::signed(1), 0, 1, 100), TokenError::CannotCreate); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, false, 1)); + assert_noop!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100), TokenError::CannotCreate); Balances::make_free_balance_be(&1, 100); - assert_ok!(Assets::touch(Origin::signed(1), 0)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::touch(RuntimeOrigin::signed(1), 0)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); Balances::make_free_balance_be(&2, 100); - assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 100)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 100)); assert_eq!(Assets::balance(0, 2), 100); assert_eq!(Assets::balance(0, 1), 0); assert_eq!(Balances::reserved_balance(&1), 10); - assert_ok!(Assets::refund(Origin::signed(1), 0, false)); + assert_ok!(Assets::refund(RuntimeOrigin::signed(1), 0, false)); assert_eq!(Balances::reserved_balance(&1), 0); assert_eq!(Assets::balance(1, 0), 0); }); @@ -129,11 +129,11 @@ fn refunding_asset_deposit_without_burn_should_work() { #[test] fn refunding_calls_died_hook() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, false, 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, false, 1)); Balances::make_free_balance_be(&1, 100); - assert_ok!(Assets::touch(Origin::signed(1), 0)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); - assert_ok!(Assets::refund(Origin::signed(1), 0, true)); + assert_ok!(Assets::touch(RuntimeOrigin::signed(1), 0)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); + assert_ok!(Assets::refund(RuntimeOrigin::signed(1), 0, true)); assert_eq!(Asset::::get(0).unwrap().accounts, 0); assert_eq!(hooks(), vec![Hook::Died(0, 1)]); @@ -144,17 +144,20 @@ fn refunding_calls_died_hook() { fn approval_lifecycle_works() { new_test_ext().execute_with(|| { // can't approve non-existent token - assert_noop!(Assets::approve_transfer(Origin::signed(1), 0, 2, 50), Error::::Unknown); + assert_noop!( + Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 2, 50), + Error::::Unknown + ); // so we create it :) - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); Balances::make_free_balance_be(&1, 1); - assert_ok!(Assets::approve_transfer(Origin::signed(1), 0, 2, 50)); + assert_ok!(Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 2, 50)); assert_eq!(Asset::::get(0).unwrap().approvals, 1); assert_eq!(Balances::reserved_balance(&1), 1); - assert_ok!(Assets::transfer_approved(Origin::signed(2), 0, 1, 3, 40)); + assert_ok!(Assets::transfer_approved(RuntimeOrigin::signed(2), 0, 1, 3, 40)); assert_eq!(Asset::::get(0).unwrap().approvals, 1); - assert_ok!(Assets::cancel_approval(Origin::signed(1), 0, 2)); + assert_ok!(Assets::cancel_approval(RuntimeOrigin::signed(1), 0, 2)); assert_eq!(Asset::::get(0).unwrap().approvals, 0); assert_eq!(Assets::balance(0, 1), 60); assert_eq!(Assets::balance(0, 3), 40); @@ -166,17 +169,20 @@ fn approval_lifecycle_works() { fn transfer_approved_all_funds() { new_test_ext().execute_with(|| { // can't approve non-existent token - assert_noop!(Assets::approve_transfer(Origin::signed(1), 0, 2, 50), Error::::Unknown); + assert_noop!( + Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 2, 50), + Error::::Unknown + ); // so we create it :) - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); Balances::make_free_balance_be(&1, 1); - assert_ok!(Assets::approve_transfer(Origin::signed(1), 0, 2, 50)); + assert_ok!(Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 2, 50)); assert_eq!(Asset::::get(0).unwrap().approvals, 1); assert_eq!(Balances::reserved_balance(&1), 1); // transfer the full amount, which should trigger auto-cleanup - assert_ok!(Assets::transfer_approved(Origin::signed(2), 0, 1, 3, 50)); + assert_ok!(Assets::transfer_approved(RuntimeOrigin::signed(2), 0, 1, 3, 50)); assert_eq!(Asset::::get(0).unwrap().approvals, 0); assert_eq!(Assets::balance(0, 1), 50); assert_eq!(Assets::balance(0, 3), 50); @@ -187,20 +193,20 @@ fn transfer_approved_all_funds() { #[test] fn approval_deposits_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); let e = BalancesError::::InsufficientBalance; - assert_noop!(Assets::approve_transfer(Origin::signed(1), 0, 2, 50), e); + assert_noop!(Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 2, 50), e); Balances::make_free_balance_be(&1, 1); - assert_ok!(Assets::approve_transfer(Origin::signed(1), 0, 2, 50)); + assert_ok!(Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 2, 50)); assert_eq!(Balances::reserved_balance(&1), 1); - assert_ok!(Assets::transfer_approved(Origin::signed(2), 0, 1, 3, 50)); + assert_ok!(Assets::transfer_approved(RuntimeOrigin::signed(2), 0, 1, 3, 50)); assert_eq!(Balances::reserved_balance(&1), 0); - assert_ok!(Assets::approve_transfer(Origin::signed(1), 0, 2, 50)); - assert_ok!(Assets::cancel_approval(Origin::signed(1), 0, 2)); + assert_ok!(Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 2, 50)); + assert_ok!(Assets::cancel_approval(RuntimeOrigin::signed(1), 0, 2)); assert_eq!(Balances::reserved_balance(&1), 0); }); } @@ -208,72 +214,84 @@ fn approval_deposits_work() { #[test] fn cannot_transfer_more_than_approved() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); Balances::make_free_balance_be(&1, 1); - assert_ok!(Assets::approve_transfer(Origin::signed(1), 0, 2, 50)); + assert_ok!(Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 2, 50)); let e = Error::::Unapproved; - assert_noop!(Assets::transfer_approved(Origin::signed(2), 0, 1, 3, 51), e); + assert_noop!(Assets::transfer_approved(RuntimeOrigin::signed(2), 0, 1, 3, 51), e); }); } #[test] fn cannot_transfer_more_than_exists() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); Balances::make_free_balance_be(&1, 1); - assert_ok!(Assets::approve_transfer(Origin::signed(1), 0, 2, 101)); + assert_ok!(Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 2, 101)); let e = Error::::BalanceLow; - assert_noop!(Assets::transfer_approved(Origin::signed(2), 0, 1, 3, 101), e); + assert_noop!(Assets::transfer_approved(RuntimeOrigin::signed(2), 0, 1, 3, 101), e); }); } #[test] fn cancel_approval_works() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); Balances::make_free_balance_be(&1, 1); - assert_ok!(Assets::approve_transfer(Origin::signed(1), 0, 2, 50)); + assert_ok!(Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 2, 50)); assert_eq!(Asset::::get(0).unwrap().approvals, 1); - assert_noop!(Assets::cancel_approval(Origin::signed(1), 1, 2), Error::::Unknown); - assert_noop!(Assets::cancel_approval(Origin::signed(2), 0, 2), Error::::Unknown); - assert_noop!(Assets::cancel_approval(Origin::signed(1), 0, 3), Error::::Unknown); + assert_noop!( + Assets::cancel_approval(RuntimeOrigin::signed(1), 1, 2), + Error::::Unknown + ); + assert_noop!( + Assets::cancel_approval(RuntimeOrigin::signed(2), 0, 2), + Error::::Unknown + ); + assert_noop!( + Assets::cancel_approval(RuntimeOrigin::signed(1), 0, 3), + Error::::Unknown + ); assert_eq!(Asset::::get(0).unwrap().approvals, 1); - assert_ok!(Assets::cancel_approval(Origin::signed(1), 0, 2)); + assert_ok!(Assets::cancel_approval(RuntimeOrigin::signed(1), 0, 2)); assert_eq!(Asset::::get(0).unwrap().approvals, 0); - assert_noop!(Assets::cancel_approval(Origin::signed(1), 0, 2), Error::::Unknown); + assert_noop!( + Assets::cancel_approval(RuntimeOrigin::signed(1), 0, 2), + Error::::Unknown + ); }); } #[test] fn force_cancel_approval_works() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); Balances::make_free_balance_be(&1, 1); - assert_ok!(Assets::approve_transfer(Origin::signed(1), 0, 2, 50)); + assert_ok!(Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 2, 50)); assert_eq!(Asset::::get(0).unwrap().approvals, 1); let e = Error::::NoPermission; - assert_noop!(Assets::force_cancel_approval(Origin::signed(2), 0, 1, 2), e); + assert_noop!(Assets::force_cancel_approval(RuntimeOrigin::signed(2), 0, 1, 2), e); assert_noop!( - Assets::force_cancel_approval(Origin::signed(1), 1, 1, 2), + Assets::force_cancel_approval(RuntimeOrigin::signed(1), 1, 1, 2), Error::::Unknown ); assert_noop!( - Assets::force_cancel_approval(Origin::signed(1), 0, 2, 2), + Assets::force_cancel_approval(RuntimeOrigin::signed(1), 0, 2, 2), Error::::Unknown ); assert_noop!( - Assets::force_cancel_approval(Origin::signed(1), 0, 1, 3), + Assets::force_cancel_approval(RuntimeOrigin::signed(1), 0, 1, 3), Error::::Unknown ); assert_eq!(Asset::::get(0).unwrap().approvals, 1); - assert_ok!(Assets::force_cancel_approval(Origin::signed(1), 0, 1, 2)); + assert_ok!(Assets::force_cancel_approval(RuntimeOrigin::signed(1), 0, 1, 2)); assert_eq!(Asset::::get(0).unwrap().approvals, 0); assert_noop!( - Assets::force_cancel_approval(Origin::signed(1), 0, 1, 2), + Assets::force_cancel_approval(RuntimeOrigin::signed(1), 0, 1, 2), Error::::Unknown ); }); @@ -283,42 +301,42 @@ fn force_cancel_approval_works() { fn lifecycle_should_work() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&1, 100); - assert_ok!(Assets::create(Origin::signed(1), 0, 1, 1)); + assert_ok!(Assets::create(RuntimeOrigin::signed(1), 0, 1, 1)); assert_eq!(Balances::reserved_balance(&1), 1); assert!(Asset::::contains_key(0)); - assert_ok!(Assets::set_metadata(Origin::signed(1), 0, vec![0], vec![0], 12)); + assert_ok!(Assets::set_metadata(RuntimeOrigin::signed(1), 0, vec![0], vec![0], 12)); assert_eq!(Balances::reserved_balance(&1), 4); assert!(Metadata::::contains_key(0)); Balances::make_free_balance_be(&10, 100); - assert_ok!(Assets::mint(Origin::signed(1), 0, 10, 100)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 10, 100)); Balances::make_free_balance_be(&20, 100); - assert_ok!(Assets::mint(Origin::signed(1), 0, 20, 100)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 20, 100)); assert_eq!(Account::::iter_prefix(0).count(), 2); let w = Asset::::get(0).unwrap().destroy_witness(); - assert_ok!(Assets::destroy(Origin::signed(1), 0, w)); + assert_ok!(Assets::destroy(RuntimeOrigin::signed(1), 0, w)); assert_eq!(Balances::reserved_balance(&1), 0); assert!(!Asset::::contains_key(0)); assert!(!Metadata::::contains_key(0)); assert_eq!(Account::::iter_prefix(0).count(), 0); - assert_ok!(Assets::create(Origin::signed(1), 0, 1, 1)); + assert_ok!(Assets::create(RuntimeOrigin::signed(1), 0, 1, 1)); assert_eq!(Balances::reserved_balance(&1), 1); assert!(Asset::::contains_key(0)); - assert_ok!(Assets::set_metadata(Origin::signed(1), 0, vec![0], vec![0], 12)); + assert_ok!(Assets::set_metadata(RuntimeOrigin::signed(1), 0, vec![0], vec![0], 12)); assert_eq!(Balances::reserved_balance(&1), 4); assert!(Metadata::::contains_key(0)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 10, 100)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 20, 100)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 10, 100)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 20, 100)); assert_eq!(Account::::iter_prefix(0).count(), 2); let w = Asset::::get(0).unwrap().destroy_witness(); - assert_ok!(Assets::destroy(Origin::root(), 0, w)); + assert_ok!(Assets::destroy(RuntimeOrigin::root(), 0, w)); assert_eq!(Balances::reserved_balance(&1), 0); assert!(!Asset::::contains_key(0)); @@ -331,15 +349,15 @@ fn lifecycle_should_work() { fn destroy_with_bad_witness_should_not_work() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&1, 100); - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); let mut w = Asset::::get(0).unwrap().destroy_witness(); - assert_ok!(Assets::mint(Origin::signed(1), 0, 10, 100)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 10, 100)); // witness too low - assert_noop!(Assets::destroy(Origin::signed(1), 0, w), Error::::BadWitness); + assert_noop!(Assets::destroy(RuntimeOrigin::signed(1), 0, w), Error::::BadWitness); // witness too high is okay though w.accounts += 2; w.sufficients += 2; - assert_ok!(Assets::destroy(Origin::signed(1), 0, w)); + assert_ok!(Assets::destroy(RuntimeOrigin::signed(1), 0, w)); }); } @@ -347,15 +365,15 @@ fn destroy_with_bad_witness_should_not_work() { fn destroy_should_refund_approvals() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&1, 100); - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 10, 100)); - assert_ok!(Assets::approve_transfer(Origin::signed(1), 0, 2, 50)); - assert_ok!(Assets::approve_transfer(Origin::signed(1), 0, 3, 50)); - assert_ok!(Assets::approve_transfer(Origin::signed(1), 0, 4, 50)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 10, 100)); + assert_ok!(Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 2, 50)); + assert_ok!(Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 3, 50)); + assert_ok!(Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 4, 50)); assert_eq!(Balances::reserved_balance(&1), 3); let w = Asset::::get(0).unwrap().destroy_witness(); - assert_ok!(Assets::destroy(Origin::signed(1), 0, w)); + assert_ok!(Assets::destroy(RuntimeOrigin::signed(1), 0, w)); assert_eq!(Balances::reserved_balance(&1), 0); // all approvals are removed @@ -366,69 +384,72 @@ fn destroy_should_refund_approvals() { #[test] fn non_providing_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, false, 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, false, 1)); Balances::make_free_balance_be(&0, 100); - assert_ok!(Assets::mint(Origin::signed(1), 0, 0, 100)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 0, 100)); // Cannot mint into account 2 since it doesn't (yet) exist... - assert_noop!(Assets::mint(Origin::signed(1), 0, 1, 100), TokenError::CannotCreate); + assert_noop!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100), TokenError::CannotCreate); // ...or transfer... - assert_noop!(Assets::transfer(Origin::signed(0), 0, 1, 50), TokenError::CannotCreate); + assert_noop!( + Assets::transfer(RuntimeOrigin::signed(0), 0, 1, 50), + TokenError::CannotCreate + ); // ...or force-transfer assert_noop!( - Assets::force_transfer(Origin::signed(1), 0, 0, 1, 50), + Assets::force_transfer(RuntimeOrigin::signed(1), 0, 0, 1, 50), TokenError::CannotCreate ); Balances::make_free_balance_be(&1, 100); Balances::make_free_balance_be(&2, 100); - assert_ok!(Assets::transfer(Origin::signed(0), 0, 1, 25)); - assert_ok!(Assets::force_transfer(Origin::signed(1), 0, 0, 2, 25)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(0), 0, 1, 25)); + assert_ok!(Assets::force_transfer(RuntimeOrigin::signed(1), 0, 0, 2, 25)); }); } #[test] fn min_balance_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 10)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 10)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); assert_eq!(Asset::::get(0).unwrap().accounts, 1); // Cannot create a new account with a balance that is below minimum... - assert_noop!(Assets::mint(Origin::signed(1), 0, 2, 9), TokenError::BelowMinimum); - assert_noop!(Assets::transfer(Origin::signed(1), 0, 2, 9), TokenError::BelowMinimum); + assert_noop!(Assets::mint(RuntimeOrigin::signed(1), 0, 2, 9), TokenError::BelowMinimum); + assert_noop!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 9), TokenError::BelowMinimum); assert_noop!( - Assets::force_transfer(Origin::signed(1), 0, 1, 2, 9), + Assets::force_transfer(RuntimeOrigin::signed(1), 0, 1, 2, 9), TokenError::BelowMinimum ); // When deducting from an account to below minimum, it should be reaped. // Death by `transfer`. - assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 91)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 91)); assert!(Assets::maybe_balance(0, 1).is_none()); assert_eq!(Assets::balance(0, 2), 100); assert_eq!(Asset::::get(0).unwrap().accounts, 1); assert_eq!(take_hooks(), vec![Hook::Died(0, 1)]); // Death by `force_transfer`. - assert_ok!(Assets::force_transfer(Origin::signed(1), 0, 2, 1, 91)); + assert_ok!(Assets::force_transfer(RuntimeOrigin::signed(1), 0, 2, 1, 91)); assert!(Assets::maybe_balance(0, 2).is_none()); assert_eq!(Assets::balance(0, 1), 100); assert_eq!(Asset::::get(0).unwrap().accounts, 1); assert_eq!(take_hooks(), vec![Hook::Died(0, 2)]); // Death by `burn`. - assert_ok!(Assets::burn(Origin::signed(1), 0, 1, 91)); + assert_ok!(Assets::burn(RuntimeOrigin::signed(1), 0, 1, 91)); assert!(Assets::maybe_balance(0, 1).is_none()); assert_eq!(Asset::::get(0).unwrap().accounts, 0); assert_eq!(take_hooks(), vec![Hook::Died(0, 1)]); // Death by `transfer_approved`. - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); Balances::make_free_balance_be(&1, 1); - assert_ok!(Assets::approve_transfer(Origin::signed(1), 0, 2, 100)); - assert_ok!(Assets::transfer_approved(Origin::signed(2), 0, 1, 3, 91)); + assert_ok!(Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 2, 100)); + assert_ok!(Assets::transfer_approved(RuntimeOrigin::signed(2), 0, 1, 3, 91)); assert_eq!(take_hooks(), vec![Hook::Died(0, 1)]); }); } @@ -436,17 +457,17 @@ fn min_balance_should_work() { #[test] fn querying_total_supply_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); assert_eq!(Assets::balance(0, 1), 100); - assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 50)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 50)); assert_eq!(Assets::balance(0, 1), 50); assert_eq!(Assets::balance(0, 2), 50); - assert_ok!(Assets::transfer(Origin::signed(2), 0, 3, 31)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(2), 0, 3, 31)); assert_eq!(Assets::balance(0, 1), 50); assert_eq!(Assets::balance(0, 2), 19); assert_eq!(Assets::balance(0, 3), 31); - assert_ok!(Assets::burn(Origin::signed(1), 0, 3, u64::MAX)); + assert_ok!(Assets::burn(RuntimeOrigin::signed(1), 0, 3, u64::MAX)); assert_eq!(Assets::total_supply(0), 69); }); } @@ -454,10 +475,10 @@ fn querying_total_supply_should_work() { #[test] fn transferring_amount_below_available_balance_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); assert_eq!(Assets::balance(0, 1), 100); - assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 50)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 50)); assert_eq!(Assets::balance(0, 1), 50); assert_eq!(Assets::balance(0, 2), 50); }); @@ -466,14 +487,14 @@ fn transferring_amount_below_available_balance_should_work() { #[test] fn transferring_enough_to_kill_source_when_keep_alive_should_fail() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 10)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 10)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); assert_eq!(Assets::balance(0, 1), 100); assert_noop!( - Assets::transfer_keep_alive(Origin::signed(1), 0, 2, 91), + Assets::transfer_keep_alive(RuntimeOrigin::signed(1), 0, 2, 91), Error::::BalanceLow ); - assert_ok!(Assets::transfer_keep_alive(Origin::signed(1), 0, 2, 90)); + assert_ok!(Assets::transfer_keep_alive(RuntimeOrigin::signed(1), 0, 2, 90)); assert_eq!(Assets::balance(0, 1), 10); assert_eq!(Assets::balance(0, 2), 90); assert!(hooks().is_empty()); @@ -483,26 +504,26 @@ fn transferring_enough_to_kill_source_when_keep_alive_should_fail() { #[test] fn transferring_frozen_user_should_not_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); assert_eq!(Assets::balance(0, 1), 100); - assert_ok!(Assets::freeze(Origin::signed(1), 0, 1)); - assert_noop!(Assets::transfer(Origin::signed(1), 0, 2, 50), Error::::Frozen); - assert_ok!(Assets::thaw(Origin::signed(1), 0, 1)); - assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 50)); + assert_ok!(Assets::freeze(RuntimeOrigin::signed(1), 0, 1)); + assert_noop!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 50), Error::::Frozen); + assert_ok!(Assets::thaw(RuntimeOrigin::signed(1), 0, 1)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 50)); }); } #[test] fn transferring_frozen_asset_should_not_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); assert_eq!(Assets::balance(0, 1), 100); - assert_ok!(Assets::freeze_asset(Origin::signed(1), 0)); - assert_noop!(Assets::transfer(Origin::signed(1), 0, 2, 50), Error::::Frozen); - assert_ok!(Assets::thaw_asset(Origin::signed(1), 0)); - assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 50)); + assert_ok!(Assets::freeze_asset(RuntimeOrigin::signed(1), 0)); + assert_noop!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 50), Error::::Frozen); + assert_ok!(Assets::thaw_asset(RuntimeOrigin::signed(1), 0)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 50)); }); } @@ -510,36 +531,48 @@ fn transferring_frozen_asset_should_not_work() { fn approve_transfer_frozen_asset_should_not_work() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&1, 100); - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); assert_eq!(Assets::balance(0, 1), 100); - assert_ok!(Assets::freeze_asset(Origin::signed(1), 0)); - assert_noop!(Assets::approve_transfer(Origin::signed(1), 0, 2, 50), Error::::Frozen); - assert_ok!(Assets::thaw_asset(Origin::signed(1), 0)); - assert_ok!(Assets::approve_transfer(Origin::signed(1), 0, 2, 50)); + assert_ok!(Assets::freeze_asset(RuntimeOrigin::signed(1), 0)); + assert_noop!( + Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 2, 50), + Error::::Frozen + ); + assert_ok!(Assets::thaw_asset(RuntimeOrigin::signed(1), 0)); + assert_ok!(Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 2, 50)); }); } #[test] fn origin_guards_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); + assert_noop!( + Assets::transfer_ownership(RuntimeOrigin::signed(2), 0, 2), + Error::::NoPermission + ); + assert_noop!( + Assets::set_team(RuntimeOrigin::signed(2), 0, 2, 2, 2), + Error::::NoPermission + ); + assert_noop!(Assets::freeze(RuntimeOrigin::signed(2), 0, 1), Error::::NoPermission); + assert_noop!(Assets::thaw(RuntimeOrigin::signed(2), 0, 2), Error::::NoPermission); + assert_noop!( + Assets::mint(RuntimeOrigin::signed(2), 0, 2, 100), + Error::::NoPermission + ); assert_noop!( - Assets::transfer_ownership(Origin::signed(2), 0, 2), + Assets::burn(RuntimeOrigin::signed(2), 0, 1, 100), Error::::NoPermission ); - assert_noop!(Assets::set_team(Origin::signed(2), 0, 2, 2, 2), Error::::NoPermission); - assert_noop!(Assets::freeze(Origin::signed(2), 0, 1), Error::::NoPermission); - assert_noop!(Assets::thaw(Origin::signed(2), 0, 2), Error::::NoPermission); - assert_noop!(Assets::mint(Origin::signed(2), 0, 2, 100), Error::::NoPermission); - assert_noop!(Assets::burn(Origin::signed(2), 0, 1, 100), Error::::NoPermission); assert_noop!( - Assets::force_transfer(Origin::signed(2), 0, 1, 2, 100), + Assets::force_transfer(RuntimeOrigin::signed(2), 0, 1, 2, 100), Error::::NoPermission ); let w = Asset::::get(0).unwrap().destroy_witness(); - assert_noop!(Assets::destroy(Origin::signed(2), 0, w), Error::::NoPermission); + assert_noop!(Assets::destroy(RuntimeOrigin::signed(2), 0, w), Error::::NoPermission); }); } @@ -548,22 +581,28 @@ fn transfer_owner_should_work() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&1, 100); Balances::make_free_balance_be(&2, 100); - assert_ok!(Assets::create(Origin::signed(1), 0, 1, 1)); + assert_ok!(Assets::create(RuntimeOrigin::signed(1), 0, 1, 1)); assert_eq!(Balances::reserved_balance(&1), 1); - assert_ok!(Assets::transfer_ownership(Origin::signed(1), 0, 2)); + assert_ok!(Assets::transfer_ownership(RuntimeOrigin::signed(1), 0, 2)); assert_eq!(Balances::reserved_balance(&2), 1); assert_eq!(Balances::reserved_balance(&1), 0); assert_noop!( - Assets::transfer_ownership(Origin::signed(1), 0, 1), + Assets::transfer_ownership(RuntimeOrigin::signed(1), 0, 1), Error::::NoPermission ); // Set metadata now and make sure that deposit gets transferred back. - assert_ok!(Assets::set_metadata(Origin::signed(2), 0, vec![0u8; 10], vec![0u8; 10], 12)); - assert_ok!(Assets::transfer_ownership(Origin::signed(2), 0, 1)); + assert_ok!(Assets::set_metadata( + RuntimeOrigin::signed(2), + 0, + vec![0u8; 10], + vec![0u8; 10], + 12 + )); + assert_ok!(Assets::transfer_ownership(RuntimeOrigin::signed(2), 0, 1)); assert_eq!(Balances::reserved_balance(&1), 22); assert_eq!(Balances::reserved_balance(&2), 0); }); @@ -572,27 +611,27 @@ fn transfer_owner_should_work() { #[test] fn set_team_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::set_team(Origin::signed(1), 0, 2, 3, 4)); - - assert_ok!(Assets::mint(Origin::signed(2), 0, 2, 100)); - assert_ok!(Assets::freeze(Origin::signed(4), 0, 2)); - assert_ok!(Assets::thaw(Origin::signed(3), 0, 2)); - assert_ok!(Assets::force_transfer(Origin::signed(3), 0, 2, 3, 100)); - assert_ok!(Assets::burn(Origin::signed(3), 0, 3, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::set_team(RuntimeOrigin::signed(1), 0, 2, 3, 4)); + + assert_ok!(Assets::mint(RuntimeOrigin::signed(2), 0, 2, 100)); + assert_ok!(Assets::freeze(RuntimeOrigin::signed(4), 0, 2)); + assert_ok!(Assets::thaw(RuntimeOrigin::signed(3), 0, 2)); + assert_ok!(Assets::force_transfer(RuntimeOrigin::signed(3), 0, 2, 3, 100)); + assert_ok!(Assets::burn(RuntimeOrigin::signed(3), 0, 3, 100)); }); } #[test] fn transferring_to_frozen_account_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 2, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 2, 100)); assert_eq!(Assets::balance(0, 1), 100); assert_eq!(Assets::balance(0, 2), 100); - assert_ok!(Assets::freeze(Origin::signed(1), 0, 2)); - assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 50)); + assert_ok!(Assets::freeze(RuntimeOrigin::signed(1), 0, 2)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 50)); assert_eq!(Assets::balance(0, 2), 150); }); } @@ -600,26 +639,32 @@ fn transferring_to_frozen_account_should_work() { #[test] fn transferring_amount_more_than_available_balance_should_not_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); assert_eq!(Assets::balance(0, 1), 100); - assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 50)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 50)); assert_eq!(Assets::balance(0, 1), 50); assert_eq!(Assets::balance(0, 2), 50); - assert_ok!(Assets::burn(Origin::signed(1), 0, 1, u64::MAX)); + assert_ok!(Assets::burn(RuntimeOrigin::signed(1), 0, 1, u64::MAX)); assert_eq!(Assets::balance(0, 1), 0); - assert_noop!(Assets::transfer(Origin::signed(1), 0, 1, 50), Error::::NoAccount); - assert_noop!(Assets::transfer(Origin::signed(2), 0, 1, 51), Error::::BalanceLow); + assert_noop!( + Assets::transfer(RuntimeOrigin::signed(1), 0, 1, 50), + Error::::NoAccount + ); + assert_noop!( + Assets::transfer(RuntimeOrigin::signed(2), 0, 1, 51), + Error::::BalanceLow + ); }); } #[test] fn transferring_less_than_one_unit_is_fine() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); assert_eq!(Assets::balance(0, 1), 100); - assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 0)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 0)); // `ForceCreated` and `Issued` but no `Transferred` event. assert_eq!(System::events().len(), 2); }); @@ -628,20 +673,23 @@ fn transferring_less_than_one_unit_is_fine() { #[test] fn transferring_more_units_than_total_supply_should_not_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); assert_eq!(Assets::balance(0, 1), 100); - assert_noop!(Assets::transfer(Origin::signed(1), 0, 2, 101), Error::::BalanceLow); + assert_noop!( + Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 101), + Error::::BalanceLow + ); }); } #[test] fn burning_asset_balance_with_positive_balance_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); assert_eq!(Assets::balance(0, 1), 100); - assert_ok!(Assets::burn(Origin::signed(1), 0, 1, u64::MAX)); + assert_ok!(Assets::burn(RuntimeOrigin::signed(1), 0, 1, u64::MAX)); assert_eq!(Assets::balance(0, 1), 0); }); } @@ -649,10 +697,13 @@ fn burning_asset_balance_with_positive_balance_should_work() { #[test] fn burning_asset_balance_with_zero_balance_does_nothing() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); assert_eq!(Assets::balance(0, 2), 0); - assert_noop!(Assets::burn(Origin::signed(1), 0, 2, u64::MAX), Error::::NoAccount); + assert_noop!( + Assets::burn(RuntimeOrigin::signed(1), 0, 2, u64::MAX), + Error::::NoAccount + ); assert_eq!(Assets::balance(0, 2), 0); assert_eq!(Assets::total_supply(0), 100); }); @@ -663,48 +714,69 @@ fn set_metadata_should_work() { new_test_ext().execute_with(|| { // Cannot add metadata to unknown asset assert_noop!( - Assets::set_metadata(Origin::signed(1), 0, vec![0u8; 10], vec![0u8; 10], 12), + Assets::set_metadata(RuntimeOrigin::signed(1), 0, vec![0u8; 10], vec![0u8; 10], 12), Error::::Unknown, ); - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); // Cannot add metadata to unowned asset assert_noop!( - Assets::set_metadata(Origin::signed(2), 0, vec![0u8; 10], vec![0u8; 10], 12), + Assets::set_metadata(RuntimeOrigin::signed(2), 0, vec![0u8; 10], vec![0u8; 10], 12), Error::::NoPermission, ); // Cannot add oversized metadata assert_noop!( - Assets::set_metadata(Origin::signed(1), 0, vec![0u8; 100], vec![0u8; 10], 12), + Assets::set_metadata(RuntimeOrigin::signed(1), 0, vec![0u8; 100], vec![0u8; 10], 12), Error::::BadMetadata, ); assert_noop!( - Assets::set_metadata(Origin::signed(1), 0, vec![0u8; 10], vec![0u8; 100], 12), + Assets::set_metadata(RuntimeOrigin::signed(1), 0, vec![0u8; 10], vec![0u8; 100], 12), Error::::BadMetadata, ); // Successfully add metadata and take deposit Balances::make_free_balance_be(&1, 30); - assert_ok!(Assets::set_metadata(Origin::signed(1), 0, vec![0u8; 10], vec![0u8; 10], 12)); + assert_ok!(Assets::set_metadata( + RuntimeOrigin::signed(1), + 0, + vec![0u8; 10], + vec![0u8; 10], + 12 + )); assert_eq!(Balances::free_balance(&1), 9); // Update deposit - assert_ok!(Assets::set_metadata(Origin::signed(1), 0, vec![0u8; 10], vec![0u8; 5], 12)); + assert_ok!(Assets::set_metadata( + RuntimeOrigin::signed(1), + 0, + vec![0u8; 10], + vec![0u8; 5], + 12 + )); assert_eq!(Balances::free_balance(&1), 14); - assert_ok!(Assets::set_metadata(Origin::signed(1), 0, vec![0u8; 10], vec![0u8; 15], 12)); + assert_ok!(Assets::set_metadata( + RuntimeOrigin::signed(1), + 0, + vec![0u8; 10], + vec![0u8; 15], + 12 + )); assert_eq!(Balances::free_balance(&1), 4); // Cannot over-reserve assert_noop!( - Assets::set_metadata(Origin::signed(1), 0, vec![0u8; 20], vec![0u8; 20], 12), + Assets::set_metadata(RuntimeOrigin::signed(1), 0, vec![0u8; 20], vec![0u8; 20], 12), BalancesError::::InsufficientBalance, ); // Clear Metadata assert!(Metadata::::contains_key(0)); - assert_noop!(Assets::clear_metadata(Origin::signed(2), 0), Error::::NoPermission); - assert_noop!(Assets::clear_metadata(Origin::signed(1), 1), Error::::Unknown); - assert_ok!(Assets::clear_metadata(Origin::signed(1), 0)); + assert_noop!( + Assets::clear_metadata(RuntimeOrigin::signed(2), 0), + Error::::NoPermission + ); + assert_noop!(Assets::clear_metadata(RuntimeOrigin::signed(1), 1), Error::::Unknown); + assert_ok!(Assets::clear_metadata(RuntimeOrigin::signed(1), 0)); assert!(!Metadata::::contains_key(0)); }); } @@ -713,13 +785,13 @@ fn set_metadata_should_work() { #[test] fn destroy_calls_died_hooks() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 50)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 50)); // Create account 1 and 2. - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 2, 100)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 2, 100)); // Destroy the asset. let w = Asset::::get(0).unwrap().destroy_witness(); - assert_ok!(Assets::destroy(Origin::signed(1), 0, w)); + assert_ok!(Assets::destroy(RuntimeOrigin::signed(1), 0, w)); // Asset is gone and accounts 1 and 2 died. assert!(Asset::::get(0).is_none()); @@ -730,36 +802,39 @@ fn destroy_calls_died_hooks() { #[test] fn freezer_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 10)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 10)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); assert_eq!(Assets::balance(0, 1), 100); // freeze 50 of it. set_frozen_balance(0, 1, 50); - assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 20)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 20)); // cannot transfer another 21 away as this would take the non-frozen balance (30) to below // the minimum balance (10). - assert_noop!(Assets::transfer(Origin::signed(1), 0, 2, 21), Error::::BalanceLow); + assert_noop!( + Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 21), + Error::::BalanceLow + ); // create an approved transfer... Balances::make_free_balance_be(&1, 100); - assert_ok!(Assets::approve_transfer(Origin::signed(1), 0, 2, 50)); + assert_ok!(Assets::approve_transfer(RuntimeOrigin::signed(1), 0, 2, 50)); let e = Error::::BalanceLow; // ...but that wont work either: - assert_noop!(Assets::transfer_approved(Origin::signed(2), 0, 1, 2, 21), e); + assert_noop!(Assets::transfer_approved(RuntimeOrigin::signed(2), 0, 1, 2, 21), e); // a force transfer won't work also. let e = Error::::BalanceLow; - assert_noop!(Assets::force_transfer(Origin::signed(1), 0, 1, 2, 21), e); + assert_noop!(Assets::force_transfer(RuntimeOrigin::signed(1), 0, 1, 2, 21), e); // reduce it to only 49 frozen... set_frozen_balance(0, 1, 49); // ...and it's all good: - assert_ok!(Assets::force_transfer(Origin::signed(1), 0, 1, 2, 21)); + assert_ok!(Assets::force_transfer(RuntimeOrigin::signed(1), 0, 1, 2, 21)); // and if we clear it, we can remove the account completely. clear_frozen_balance(0, 1); - assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 50)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 50)); assert_eq!(hooks(), vec![Hook::Died(0, 1)]); }); } @@ -769,7 +844,7 @@ fn imbalances_should_work() { use frame_support::traits::tokens::fungibles::Balanced; new_test_ext().execute_with(|| { - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); let imb = Assets::issue(0, 100); assert_eq!(Assets::total_supply(0), 100); @@ -792,9 +867,9 @@ fn imbalances_should_work() { fn force_metadata_should_work() { new_test_ext().execute_with(|| { // force set metadata works - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); assert_ok!(Assets::force_set_metadata( - Origin::root(), + RuntimeOrigin::root(), 0, vec![0u8; 10], vec![0u8; 10], @@ -806,7 +881,7 @@ fn force_metadata_should_work() { // overwrites existing metadata let asset_original_metadata = Metadata::::get(0); assert_ok!(Assets::force_set_metadata( - Origin::root(), + RuntimeOrigin::root(), 0, vec![1u8; 10], vec![1u8; 10], @@ -817,7 +892,14 @@ fn force_metadata_should_work() { // attempt to set metadata for non-existent asset class assert_noop!( - Assets::force_set_metadata(Origin::root(), 1, vec![0u8; 10], vec![0u8; 10], 8, false), + Assets::force_set_metadata( + RuntimeOrigin::root(), + 1, + vec![0u8; 10], + vec![0u8; 10], + 8, + false + ), Error::::Unknown ); @@ -825,7 +907,7 @@ fn force_metadata_should_work() { let limit = 50usize; assert_noop!( Assets::force_set_metadata( - Origin::root(), + RuntimeOrigin::root(), 0, vec![0u8; limit + 1], vec![0u8; 10], @@ -836,7 +918,7 @@ fn force_metadata_should_work() { ); assert_noop!( Assets::force_set_metadata( - Origin::root(), + RuntimeOrigin::root(), 0, vec![0u8; 10], vec![0u8; limit + 1], @@ -848,11 +930,14 @@ fn force_metadata_should_work() { // force clear metadata works assert!(Metadata::::contains_key(0)); - assert_ok!(Assets::force_clear_metadata(Origin::root(), 0)); + assert_ok!(Assets::force_clear_metadata(RuntimeOrigin::root(), 0)); assert!(!Metadata::::contains_key(0)); // Error handles clearing non-existent asset class - assert_noop!(Assets::force_clear_metadata(Origin::root(), 1), Error::::Unknown); + assert_noop!( + Assets::force_clear_metadata(RuntimeOrigin::root(), 1), + Error::::Unknown + ); }); } @@ -861,34 +946,57 @@ fn force_asset_status_should_work() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&1, 10); Balances::make_free_balance_be(&2, 10); - assert_ok!(Assets::create(Origin::signed(1), 0, 1, 30)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 50)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 2, 150)); + assert_ok!(Assets::create(RuntimeOrigin::signed(1), 0, 1, 30)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 50)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 2, 150)); // force asset status to change min_balance > balance - assert_ok!(Assets::force_asset_status(Origin::root(), 0, 1, 1, 1, 1, 100, true, false)); + assert_ok!(Assets::force_asset_status( + RuntimeOrigin::root(), + 0, + 1, + 1, + 1, + 1, + 100, + true, + false + )); assert_eq!(Assets::balance(0, 1), 50); // account can recieve assets for balance < min_balance - assert_ok!(Assets::transfer(Origin::signed(2), 0, 1, 1)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(2), 0, 1, 1)); assert_eq!(Assets::balance(0, 1), 51); // account on outbound transfer will cleanup for balance < min_balance - assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 1)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, 1)); assert_eq!(Assets::balance(0, 1), 0); // won't create new account with balance below min_balance - assert_noop!(Assets::transfer(Origin::signed(2), 0, 3, 50), TokenError::BelowMinimum); + assert_noop!( + Assets::transfer(RuntimeOrigin::signed(2), 0, 3, 50), + TokenError::BelowMinimum + ); // force asset status will not execute for non-existent class assert_noop!( - Assets::force_asset_status(Origin::root(), 1, 1, 1, 1, 1, 90, true, false), + Assets::force_asset_status(RuntimeOrigin::root(), 1, 1, 1, 1, 1, 90, true, false), Error::::Unknown ); // account drains to completion when funds dip below min_balance - assert_ok!(Assets::force_asset_status(Origin::root(), 0, 1, 1, 1, 1, 110, true, false)); - assert_ok!(Assets::transfer(Origin::signed(2), 0, 1, 110)); + assert_ok!(Assets::force_asset_status( + RuntimeOrigin::root(), + 0, + 1, + 1, + 1, + 1, + 110, + true, + false + )); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(2), 0, 1, 110)); assert_eq!(Assets::balance(0, 1), 200); assert_eq!(Assets::balance(0, 2), 0); assert_eq!(Assets::total_supply(0), 200); @@ -901,9 +1009,9 @@ fn balance_conversion_should_work() { use frame_support::traits::tokens::BalanceConversion; let id = 42; - assert_ok!(Assets::force_create(Origin::root(), id, 1, true, 10)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), id, 1, true, 10)); let not_sufficient = 23; - assert_ok!(Assets::force_create(Origin::root(), not_sufficient, 1, false, 10)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), not_sufficient, 1, false, 10)); assert_eq!( BalanceToAssetBalance::::to_asset_balance(100, 1234), @@ -938,9 +1046,9 @@ fn assets_from_genesis_should_exist() { fn querying_name_symbol_and_decimals_should_work() { new_test_ext().execute_with(|| { use frame_support::traits::tokens::fungibles::metadata::Inspect; - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); assert_ok!(Assets::force_set_metadata( - Origin::root(), + RuntimeOrigin::root(), 0, vec![0u8; 10], vec![1u8; 10], @@ -957,8 +1065,8 @@ fn querying_name_symbol_and_decimals_should_work() { fn querying_allowance_should_work() { new_test_ext().execute_with(|| { use frame_support::traits::tokens::fungibles::approvals::{Inspect, Mutate}; - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, 100)); Balances::make_free_balance_be(&1, 1); assert_ok!(Assets::approve(0, &1, &2, 50)); assert_eq!(Assets::allowance(0, &1, &2), 50); @@ -972,9 +1080,9 @@ fn querying_allowance_should_work() { fn transfer_large_asset() { new_test_ext().execute_with(|| { let amount = u64::pow(2, 63) + 2; - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); - assert_ok!(Assets::mint(Origin::signed(1), 0, 1, amount)); - assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, amount - 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); + assert_ok!(Assets::mint(RuntimeOrigin::signed(1), 0, 1, amount)); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(1), 0, 2, amount - 1)); }) } @@ -982,9 +1090,9 @@ fn transfer_large_asset() { fn querying_roles_should_work() { new_test_ext().execute_with(|| { use frame_support::traits::tokens::fungibles::roles::Inspect; - assert_ok!(Assets::force_create(Origin::root(), 0, 1, true, 1)); + assert_ok!(Assets::force_create(RuntimeOrigin::root(), 0, 1, true, 1)); assert_ok!(Assets::set_team( - Origin::signed(1), + RuntimeOrigin::signed(1), 0, // Issuer 2, diff --git a/frame/atomic-swap/src/tests.rs b/frame/atomic-swap/src/tests.rs index d3d8b37d82794..5ad63dfce55b4 100644 --- a/frame/atomic-swap/src/tests.rs +++ b/frame/atomic-swap/src/tests.rs @@ -37,7 +37,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = H256; @@ -100,7 +100,7 @@ fn two_party_successful_swap() { // A creates the swap on chain1. chain1.execute_with(|| { AtomicSwap::create_swap( - Origin::signed(A), + RuntimeOrigin::signed(A), B, hashed_proof, BalanceSwapAction::new(50), @@ -115,7 +115,7 @@ fn two_party_successful_swap() { // B creates the swap on chain2. chain2.execute_with(|| { AtomicSwap::create_swap( - Origin::signed(B), + RuntimeOrigin::signed(B), A, hashed_proof, BalanceSwapAction::new(75), @@ -129,8 +129,12 @@ fn two_party_successful_swap() { // A reveals the proof and claims the swap on chain2. chain2.execute_with(|| { - AtomicSwap::claim_swap(Origin::signed(A), proof.to_vec(), BalanceSwapAction::new(75)) - .unwrap(); + AtomicSwap::claim_swap( + RuntimeOrigin::signed(A), + proof.to_vec(), + BalanceSwapAction::new(75), + ) + .unwrap(); assert_eq!(Balances::free_balance(A), 100 + 75); assert_eq!(Balances::free_balance(B), 200 - 75); @@ -138,8 +142,12 @@ fn two_party_successful_swap() { // B use the revealed proof to claim the swap on chain1. chain1.execute_with(|| { - AtomicSwap::claim_swap(Origin::signed(B), proof.to_vec(), BalanceSwapAction::new(50)) - .unwrap(); + AtomicSwap::claim_swap( + RuntimeOrigin::signed(B), + proof.to_vec(), + BalanceSwapAction::new(50), + ) + .unwrap(); assert_eq!(Balances::free_balance(A), 100 - 50); assert_eq!(Balances::free_balance(B), 200 + 50); diff --git a/frame/aura/src/mock.rs b/frame/aura/src/mock.rs index 673190c95f2e1..07fa9aa680e80 100644 --- a/frame/aura/src/mock.rs +++ b/frame/aura/src/mock.rs @@ -56,7 +56,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; diff --git a/frame/authority-discovery/src/lib.rs b/frame/authority-discovery/src/lib.rs index 3505f20a05929..b642a9ac283f2 100644 --- a/frame/authority-discovery/src/lib.rs +++ b/frame/authority-discovery/src/lib.rs @@ -235,7 +235,7 @@ mod tests { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index 3f484ef24eec0..c08e773abe3a7 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -468,7 +468,7 @@ mod tests { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; @@ -738,7 +738,7 @@ mod tests { System::reset_events(); System::initialize(¤t_depth, &parent_hash, &Default::default()); Authorship::on_initialize(current_depth); - Authorship::set_uncles(Origin::none(), uncles).unwrap(); + Authorship::set_uncles(RuntimeOrigin::none(), uncles).unwrap(); Authorship::on_finalize(current_depth); max_item_count = std::cmp::max(max_item_count, ::Uncles::get().len()); diff --git a/frame/babe/src/mock.rs b/frame/babe/src/mock.rs index fb251457db9ca..46aeabe743fe2 100644 --- a/frame/babe/src/mock.rs +++ b/frame/babe/src/mock.rs @@ -74,7 +74,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; @@ -204,6 +204,7 @@ impl pallet_staking::Config for Test { type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; + type HistoryDepth = ConstU32<84>; type OnStakerSlash = (); type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; type WeightInfo = (); diff --git a/frame/babe/src/tests.rs b/frame/babe/src/tests.rs index 1015ada7f0185..8d2a9b326cd0f 100644 --- a/frame/babe/src/tests.rs +++ b/frame/babe/src/tests.rs @@ -289,7 +289,7 @@ fn can_enact_next_config() { assert_eq!(NextEpochConfig::::get(), Some(next_config.clone())); Babe::plan_config_change( - Origin::root(), + RuntimeOrigin::root(), NextConfigDescriptor::V1 { c: next_next_config.c, allowed_slots: next_next_config.allowed_slots, @@ -323,15 +323,15 @@ fn only_root_can_enact_config_change() { let next_config = NextConfigDescriptor::V1 { c: (1, 4), allowed_slots: AllowedSlots::PrimarySlots }; - let res = Babe::plan_config_change(Origin::none(), next_config.clone()); + let res = Babe::plan_config_change(RuntimeOrigin::none(), next_config.clone()); assert_noop!(res, DispatchError::BadOrigin); - let res = Babe::plan_config_change(Origin::signed(1), next_config.clone()); + let res = Babe::plan_config_change(RuntimeOrigin::signed(1), next_config.clone()); assert_noop!(res, DispatchError::BadOrigin); - let res = Babe::plan_config_change(Origin::root(), next_config); + let res = Babe::plan_config_change(RuntimeOrigin::root(), next_config); assert!(res.is_ok()); }); @@ -464,7 +464,7 @@ fn report_equivocation_current_session_works() { // report the equivocation Babe::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof), key_owner_proof, ) @@ -536,7 +536,7 @@ fn report_equivocation_old_session_works() { // report the equivocation Babe::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof), key_owner_proof, ) @@ -588,7 +588,7 @@ fn report_equivocation_invalid_key_owner_proof() { key_owner_proof.session = 0; assert_err!( Babe::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof.clone()), key_owner_proof ), @@ -608,7 +608,7 @@ fn report_equivocation_invalid_key_owner_proof() { assert_err!( Babe::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof), key_owner_proof, ), @@ -642,7 +642,7 @@ fn report_equivocation_invalid_equivocation_proof() { let assert_invalid_equivocation = |equivocation_proof| { assert_err!( Babe::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof), key_owner_proof.clone(), ), @@ -784,7 +784,7 @@ fn report_equivocation_validate_unsigned_prevents_duplicates() { // we submit the report Babe::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof), key_owner_proof, ) @@ -857,7 +857,7 @@ fn valid_equivocation_reports_dont_pay_fees() { // report the equivocation. let post_info = Babe::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof.clone()), key_owner_proof.clone(), ) @@ -871,7 +871,7 @@ fn valid_equivocation_reports_dont_pay_fees() { // report the equivocation again which is invalid now since it is // duplicate. let post_info = Babe::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof), key_owner_proof, ) diff --git a/frame/bags-list/src/mock.rs b/frame/bags-list/src/mock.rs index f6bde63b3867c..8cc96a988e72a 100644 --- a/frame/bags-list/src/mock.rs +++ b/frame/bags-list/src/mock.rs @@ -49,7 +49,7 @@ impl frame_election_provider_support::ScoreProvider for StakingMock { impl frame_system::Config for Runtime { type SS58Prefix = (); type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; diff --git a/frame/bags-list/src/tests.rs b/frame/bags-list/src/tests.rs index 01c1642f882c1..63a395ed0d65a 100644 --- a/frame/bags-list/src/tests.rs +++ b/frame/bags-list/src/tests.rs @@ -37,7 +37,7 @@ mod pallet { // when increasing score to the level of non-existent bag assert_eq!(List::::get_score(&42).unwrap(), 20); StakingMock::set_score_of(&42, 2_000); - assert_ok!(BagsList::rebag(Origin::signed(0), 42)); + assert_ok!(BagsList::rebag(RuntimeOrigin::signed(0), 42)); assert_eq!(List::::get_score(&42).unwrap(), 2_000); // then a new bag is created and the id moves into it @@ -48,7 +48,7 @@ mod pallet { // when decreasing score within the range of the current bag StakingMock::set_score_of(&42, 1_001); - assert_ok!(BagsList::rebag(Origin::signed(0), 42)); + assert_ok!(BagsList::rebag(RuntimeOrigin::signed(0), 42)); // then the id does not move assert_eq!( @@ -60,7 +60,7 @@ mod pallet { // when reducing score to the level of a non-existent bag StakingMock::set_score_of(&42, 30); - assert_ok!(BagsList::rebag(Origin::signed(0), 42)); + assert_ok!(BagsList::rebag(RuntimeOrigin::signed(0), 42)); // then a new bag is created and the id moves into it assert_eq!( @@ -71,7 +71,7 @@ mod pallet { // when increasing score to the level of a pre-existing bag StakingMock::set_score_of(&42, 500); - assert_ok!(BagsList::rebag(Origin::signed(0), 42)); + assert_ok!(BagsList::rebag(RuntimeOrigin::signed(0), 42)); // then the id moves into that bag assert_eq!( @@ -92,7 +92,7 @@ mod pallet { // when StakingMock::set_score_of(&4, 10); - assert_ok!(BagsList::rebag(Origin::signed(0), 4)); + assert_ok!(BagsList::rebag(RuntimeOrigin::signed(0), 4)); // then assert_eq!(List::::get_bags(), vec![(10, vec![1, 4]), (1_000, vec![2, 3])]); @@ -100,7 +100,7 @@ mod pallet { // when StakingMock::set_score_of(&3, 10); - assert_ok!(BagsList::rebag(Origin::signed(0), 3)); + assert_ok!(BagsList::rebag(RuntimeOrigin::signed(0), 3)); // then assert_eq!(List::::get_bags(), vec![(10, vec![1, 4, 3]), (1_000, vec![2])]); @@ -111,7 +111,7 @@ mod pallet { // when StakingMock::set_score_of(&2, 10); - assert_ok!(BagsList::rebag(Origin::signed(0), 2)); + assert_ok!(BagsList::rebag(RuntimeOrigin::signed(0), 2)); // then assert_eq!(List::::get_bags(), vec![(10, vec![1, 4, 3, 2])]); @@ -126,7 +126,7 @@ mod pallet { ExtBuilder::default().build_and_execute(|| { // when StakingMock::set_score_of(&2, 10); - assert_ok!(BagsList::rebag(Origin::signed(0), 2)); + assert_ok!(BagsList::rebag(RuntimeOrigin::signed(0), 2)); // then assert_eq!(List::::get_bags(), vec![(10, vec![1, 2]), (1_000, vec![3, 4])]); @@ -134,7 +134,7 @@ mod pallet { // when StakingMock::set_score_of(&3, 10); - assert_ok!(BagsList::rebag(Origin::signed(0), 3)); + assert_ok!(BagsList::rebag(RuntimeOrigin::signed(0), 3)); // then assert_eq!(List::::get_bags(), vec![(10, vec![1, 2, 3]), (1_000, vec![4])]); @@ -142,7 +142,7 @@ mod pallet { // when StakingMock::set_score_of(&4, 10); - assert_ok!(BagsList::rebag(Origin::signed(0), 4)); + assert_ok!(BagsList::rebag(RuntimeOrigin::signed(0), 4)); // then assert_eq!(List::::get_bags(), vec![(10, vec![1, 2, 3, 4])]); @@ -159,12 +159,15 @@ mod pallet { assert!(!node_3.is_misplaced(500)); // then calling rebag on account 3 with score 500 is a noop - assert_storage_noop!(assert_eq!(BagsList::rebag(Origin::signed(0), 3), Ok(()))); + assert_storage_noop!(assert_eq!(BagsList::rebag(RuntimeOrigin::signed(0), 3), Ok(()))); // when account 42 is not in the list assert!(!BagsList::contains(&42)); // then rebag-ing account 42 is an error - assert_storage_noop!(assert!(matches!(BagsList::rebag(Origin::signed(0), 42), Err(_)))); + assert_storage_noop!(assert!(matches!( + BagsList::rebag(RuntimeOrigin::signed(0), 42), + Err(_) + ))); }); } @@ -200,7 +203,7 @@ mod pallet { ); // any rebag is noop. - assert_storage_noop!(assert_eq!(BagsList::rebag(Origin::signed(0), 1), Ok(()))); + assert_storage_noop!(assert_eq!(BagsList::rebag(RuntimeOrigin::signed(0), 1), Ok(()))); }) } @@ -214,7 +217,7 @@ mod pallet { assert_eq!(List::::get_bags(), vec![(20, vec![10, 11])]); // when - assert_ok!(BagsList::put_in_front_of(Origin::signed(11), 10)); + assert_ok!(BagsList::put_in_front_of(RuntimeOrigin::signed(11), 10)); // then assert_eq!(List::::get_bags(), vec![(20, vec![11, 10])]); @@ -231,7 +234,7 @@ mod pallet { assert_eq!(List::::get_bags(), vec![(20, vec![11, 10])]); // when - assert_ok!(BagsList::put_in_front_of(Origin::signed(11), 10)); + assert_ok!(BagsList::put_in_front_of(RuntimeOrigin::signed(11), 10)); // then assert_eq!(List::::get_bags(), vec![(20, vec![11, 10])]); @@ -247,7 +250,7 @@ mod pallet { StakingMock::set_score_of(&3, 999); // when - assert_ok!(BagsList::put_in_front_of(Origin::signed(4), 3)); + assert_ok!(BagsList::put_in_front_of(RuntimeOrigin::signed(4), 3)); // then assert_eq!(List::::get_bags(), vec![(10, vec![1]), (1_000, vec![2, 4, 3, 5])]); @@ -268,7 +271,7 @@ mod pallet { StakingMock::set_score_of(&5, 999); // when - assert_ok!(BagsList::put_in_front_of(Origin::signed(3), 5)); + assert_ok!(BagsList::put_in_front_of(RuntimeOrigin::signed(3), 5)); // then assert_eq!( @@ -287,7 +290,7 @@ mod pallet { StakingMock::set_score_of(&2, 999); // when - assert_ok!(BagsList::put_in_front_of(Origin::signed(3), 2)); + assert_ok!(BagsList::put_in_front_of(RuntimeOrigin::signed(3), 2)); // then assert_eq!(List::::get_bags(), vec![(10, vec![1]), (1_000, vec![3, 2, 4])]); @@ -303,7 +306,7 @@ mod pallet { StakingMock::set_score_of(&3, 999); // when - assert_ok!(BagsList::put_in_front_of(Origin::signed(4), 3)); + assert_ok!(BagsList::put_in_front_of(RuntimeOrigin::signed(4), 3)); // then assert_eq!(List::::get_bags(), vec![(10, vec![1]), (1_000, vec![2, 4, 3])]); @@ -319,7 +322,7 @@ mod pallet { StakingMock::set_score_of(&2, 999); // when - assert_ok!(BagsList::put_in_front_of(Origin::signed(5), 2)); + assert_ok!(BagsList::put_in_front_of(RuntimeOrigin::signed(5), 2)); // then assert_eq!(List::::get_bags(), vec![(10, vec![1]), (1_000, vec![5, 2, 3, 4])]); @@ -335,7 +338,7 @@ mod pallet { StakingMock::set_score_of(&4, 999); // when - BagsList::put_in_front_of(Origin::signed(2), 4).unwrap(); + BagsList::put_in_front_of(RuntimeOrigin::signed(2), 4).unwrap(); // then assert_eq!(List::::get_bags(), vec![(10, vec![1]), (1_000, vec![3, 2, 4, 5])]); @@ -349,7 +352,7 @@ mod pallet { assert_eq!(List::::get_bags(), vec![(10, vec![1]), (1_000, vec![2, 3, 4, 5])]); // when - BagsList::put_in_front_of(Origin::signed(3), 5).unwrap(); + BagsList::put_in_front_of(RuntimeOrigin::signed(3), 5).unwrap(); // then assert_eq!(List::::get_bags(), vec![(10, vec![1]), (1_000, vec![2, 4, 3, 5])]); @@ -365,7 +368,7 @@ mod pallet { StakingMock::set_score_of(&4, 999); // when - BagsList::put_in_front_of(Origin::signed(2), 4).unwrap(); + BagsList::put_in_front_of(RuntimeOrigin::signed(2), 4).unwrap(); // then assert_eq!(List::::get_bags(), vec![(10, vec![1]), (1_000, vec![3, 2, 4])]); @@ -382,7 +385,7 @@ mod pallet { // then assert_noop!( - BagsList::put_in_front_of(Origin::signed(3), 2), + BagsList::put_in_front_of(RuntimeOrigin::signed(3), 2), crate::pallet::Error::::List(ListError::NotHeavier) ); }); @@ -396,7 +399,7 @@ mod pallet { // then assert_noop!( - BagsList::put_in_front_of(Origin::signed(3), 4), + BagsList::put_in_front_of(RuntimeOrigin::signed(3), 4), crate::pallet::Error::::List(ListError::NotHeavier) ); }); @@ -413,7 +416,7 @@ mod pallet { // then assert_noop!( - BagsList::put_in_front_of(Origin::signed(5), 4), + BagsList::put_in_front_of(RuntimeOrigin::signed(5), 4), crate::pallet::Error::::List(ListError::NodeNotFound) ); }); @@ -427,7 +430,7 @@ mod pallet { // then assert_noop!( - BagsList::put_in_front_of(Origin::signed(4), 5), + BagsList::put_in_front_of(RuntimeOrigin::signed(4), 5), crate::pallet::Error::::List(ListError::NodeNotFound) ); }); @@ -441,7 +444,7 @@ mod pallet { // then assert_noop!( - BagsList::put_in_front_of(Origin::signed(4), 1), + BagsList::put_in_front_of(RuntimeOrigin::signed(4), 1), crate::pallet::Error::::List(ListError::NotInSameBag) ); }); diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 82d6f87dbde1a..4014efdd26e4e 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -185,7 +185,7 @@ use sp_runtime::{ AtLeast32BitUnsigned, Bounded, CheckedAdd, CheckedSub, MaybeSerializeDeserialize, Saturating, StaticLookup, Zero, }, - ArithmeticError, DispatchError, RuntimeDebug, + ArithmeticError, DispatchError, FixedPointOperand, RuntimeDebug, }; use sp_std::{cmp, fmt::Debug, mem, ops::BitOr, prelude::*, result}; pub use weights::WeightInfo; @@ -212,7 +212,8 @@ pub mod pallet { + MaybeSerializeDeserialize + Debug + MaxEncodedLen - + TypeInfo; + + TypeInfo + + FixedPointOperand; /// Handler for the unbalanced reduction when removing a dust account. type DustRemoval: OnUnbalanced>; diff --git a/frame/balances/src/tests.rs b/frame/balances/src/tests.rs index 9c641f6b38a22..faf53e16cb028 100644 --- a/frame/balances/src/tests.rs +++ b/frame/balances/src/tests.rs @@ -825,7 +825,7 @@ macro_rules! decl_tests { /* User has no reference counter, so they can die in these scenarios */ // SCENARIO: Slash would not kill account. - assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 0)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 1_000, 0)); // Slashed completed in full assert_eq!(Balances::slash(&1, 900), (NegativeImbalance::new(900), 0)); // Account is still alive @@ -833,35 +833,35 @@ macro_rules! decl_tests { System::assert_last_event(RuntimeEvent::Balances(crate::Event::Slashed { who: 1, amount: 900 })); // SCENARIO: Slash will kill account because not enough balance left. - assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 0)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 1_000, 0)); // Slashed completed in full assert_eq!(Balances::slash(&1, 950), (NegativeImbalance::new(950), 0)); // Account is killed assert!(!System::account_exists(&1)); // SCENARIO: Over-slash will kill account, and report missing slash amount. - assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 0)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 1_000, 0)); // Slashed full free_balance, and reports 300 not slashed assert_eq!(Balances::slash(&1, 1_300), (NegativeImbalance::new(1000), 300)); // Account is dead assert!(!System::account_exists(&1)); // SCENARIO: Over-slash can take from reserved, but keep alive. - assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 400)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 1_000, 400)); // Slashed full free_balance and 300 of reserved balance assert_eq!(Balances::slash(&1, 1_300), (NegativeImbalance::new(1300), 0)); // Account is still alive assert!(System::account_exists(&1)); // SCENARIO: Over-slash can take from reserved, and kill. - assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 350)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 1_000, 350)); // Slashed full free_balance and 300 of reserved balance assert_eq!(Balances::slash(&1, 1_300), (NegativeImbalance::new(1300), 0)); // Account is dead because 50 reserved balance is not enough to keep alive assert!(!System::account_exists(&1)); // SCENARIO: Over-slash can take as much as possible from reserved, kill, and report missing amount. - assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 250)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 1_000, 250)); // Slashed full free_balance and 300 of reserved balance assert_eq!(Balances::slash(&1, 1_300), (NegativeImbalance::new(1250), 50)); // Account is super dead @@ -870,7 +870,7 @@ macro_rules! decl_tests { /* User will now have a reference counter on them, keeping them alive in these scenarios */ // SCENARIO: Slash would not kill account. - assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 0)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 1_000, 0)); assert_ok!(System::inc_consumers(&1)); // <-- Reference counter added here is enough for all tests // Slashed completed in full assert_eq!(Balances::slash(&1, 900), (NegativeImbalance::new(900), 0)); @@ -878,35 +878,35 @@ macro_rules! decl_tests { assert!(System::account_exists(&1)); // SCENARIO: Slash will take as much as possible without killing account. - assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 0)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 1_000, 0)); // Slashed completed in full assert_eq!(Balances::slash(&1, 950), (NegativeImbalance::new(900), 50)); // Account is still alive assert!(System::account_exists(&1)); // SCENARIO: Over-slash will not kill account, and report missing slash amount. - assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 0)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 1_000, 0)); // Slashed full free_balance minus ED, and reports 400 not slashed assert_eq!(Balances::slash(&1, 1_300), (NegativeImbalance::new(900), 400)); // Account is still alive assert!(System::account_exists(&1)); // SCENARIO: Over-slash can take from reserved, but keep alive. - assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 400)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 1_000, 400)); // Slashed full free_balance and 300 of reserved balance assert_eq!(Balances::slash(&1, 1_300), (NegativeImbalance::new(1300), 0)); // Account is still alive assert!(System::account_exists(&1)); // SCENARIO: Over-slash can take from reserved, but keep alive. - assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 350)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 1_000, 350)); // Slashed full free_balance and 250 of reserved balance to leave ED assert_eq!(Balances::slash(&1, 1_300), (NegativeImbalance::new(1250), 50)); // Account is still alive assert!(System::account_exists(&1)); // SCENARIO: Over-slash can take as much as possible from reserved and report missing amount. - assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 250)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 1_000, 250)); // Slashed full free_balance and 300 of reserved balance assert_eq!(Balances::slash(&1, 1_300), (NegativeImbalance::new(1150), 150)); // Account is still alive @@ -926,28 +926,28 @@ macro_rules! decl_tests { /* User has no reference counter, so they can die in these scenarios */ // SCENARIO: Slash would not kill account. - assert_ok!(Balances::set_balance(Origin::root(), 1, 50, 1_000)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 50, 1_000)); // Slashed completed in full assert_eq!(Balances::slash_reserved(&1, 900), (NegativeImbalance::new(900), 0)); // Account is still alive assert!(System::account_exists(&1)); // SCENARIO: Slash would kill account. - assert_ok!(Balances::set_balance(Origin::root(), 1, 50, 1_000)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 50, 1_000)); // Slashed completed in full assert_eq!(Balances::slash_reserved(&1, 1_000), (NegativeImbalance::new(1_000), 0)); // Account is dead assert!(!System::account_exists(&1)); // SCENARIO: Over-slash would kill account, and reports left over slash. - assert_ok!(Balances::set_balance(Origin::root(), 1, 50, 1_000)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 50, 1_000)); // Slashed completed in full assert_eq!(Balances::slash_reserved(&1, 1_300), (NegativeImbalance::new(1_000), 300)); // Account is dead assert!(!System::account_exists(&1)); // SCENARIO: Over-slash does not take from free balance. - assert_ok!(Balances::set_balance(Origin::root(), 1, 300, 1_000)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 300, 1_000)); // Slashed completed in full assert_eq!(Balances::slash_reserved(&1, 1_300), (NegativeImbalance::new(1_000), 300)); // Account is alive because of free balance @@ -956,7 +956,7 @@ macro_rules! decl_tests { /* User has a reference counter, so they cannot die */ // SCENARIO: Slash would not kill account. - assert_ok!(Balances::set_balance(Origin::root(), 1, 50, 1_000)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 50, 1_000)); assert_ok!(System::inc_consumers(&1)); // <-- Reference counter added here is enough for all tests // Slashed completed in full assert_eq!(Balances::slash_reserved(&1, 900), (NegativeImbalance::new(900), 0)); @@ -964,21 +964,21 @@ macro_rules! decl_tests { assert!(System::account_exists(&1)); // SCENARIO: Slash as much as possible without killing. - assert_ok!(Balances::set_balance(Origin::root(), 1, 50, 1_000)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 50, 1_000)); // Slashed as much as possible assert_eq!(Balances::slash_reserved(&1, 1_000), (NegativeImbalance::new(950), 50)); // Account is still alive assert!(System::account_exists(&1)); // SCENARIO: Over-slash reports correctly, where reserved is needed to keep alive. - assert_ok!(Balances::set_balance(Origin::root(), 1, 50, 1_000)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 50, 1_000)); // Slashed as much as possible assert_eq!(Balances::slash_reserved(&1, 1_300), (NegativeImbalance::new(950), 350)); // Account is still alive assert!(System::account_exists(&1)); // SCENARIO: Over-slash reports correctly, where full reserved is removed. - assert_ok!(Balances::set_balance(Origin::root(), 1, 200, 1_000)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 200, 1_000)); // Slashed as much as possible assert_eq!(Balances::slash_reserved(&1, 1_300), (NegativeImbalance::new(1_000), 300)); // Account is still alive @@ -1018,7 +1018,7 @@ macro_rules! decl_tests { .existential_deposit(100) .build() .execute_with(|| { - assert_ok!(Balances::set_balance(Origin::root(), 1, 100, 100)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 100, 100)); assert_ok!(Balances::transfer_keep_alive(Some(1).into(), 2, 100)); assert_eq!(Balances::total_balance(&1), 100); assert_eq!(Balances::total_balance(&2), 100); @@ -1032,32 +1032,32 @@ macro_rules! decl_tests { .build() .execute_with(|| { // setup - assert_ok!(Balances::set_balance(Origin::root(), 1, 200, 0)); - assert_ok!(Balances::set_balance(Origin::root(), 2, 0, 0)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 200, 0)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 2, 0, 0)); // transfer all and allow death assert_ok!(Balances::transfer_all(Some(1).into(), 2, false)); assert_eq!(Balances::total_balance(&1), 0); assert_eq!(Balances::total_balance(&2), 200); // setup - assert_ok!(Balances::set_balance(Origin::root(), 1, 200, 0)); - assert_ok!(Balances::set_balance(Origin::root(), 2, 0, 0)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 200, 0)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 2, 0, 0)); // transfer all and keep alive assert_ok!(Balances::transfer_all(Some(1).into(), 2, true)); assert_eq!(Balances::total_balance(&1), 100); assert_eq!(Balances::total_balance(&2), 100); // setup - assert_ok!(Balances::set_balance(Origin::root(), 1, 200, 10)); - assert_ok!(Balances::set_balance(Origin::root(), 2, 0, 0)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 200, 10)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 2, 0, 0)); // transfer all and allow death w/ reserved assert_ok!(Balances::transfer_all(Some(1).into(), 2, false)); assert_eq!(Balances::total_balance(&1), 0); assert_eq!(Balances::total_balance(&2), 200); // setup - assert_ok!(Balances::set_balance(Origin::root(), 1, 200, 10)); - assert_ok!(Balances::set_balance(Origin::root(), 2, 0, 0)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1, 200, 10)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 2, 0, 0)); // transfer all and keep alive w/ reserved assert_ok!(Balances::transfer_all(Some(1).into(), 2, true)); assert_eq!(Balances::total_balance(&1), 100); @@ -1281,7 +1281,7 @@ macro_rules! decl_tests { let _ = Balances::deposit_creating(&1, 111); assert_ok!(frame_system::Pallet::::inc_consumers(&1)); assert_noop!( - Balances::set_balance(Origin::root(), 1, 0, 0), + Balances::set_balance(RuntimeOrigin::root(), 1, 0, 0), DispatchError::ConsumerRemaining, ); }); @@ -1291,7 +1291,7 @@ macro_rules! decl_tests { fn set_balance_handles_total_issuance() { <$ext_builder>::default().build().execute_with(|| { let old_total_issuance = Balances::total_issuance(); - assert_ok!(Balances::set_balance(Origin::root(), 1337, 69, 42)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 1337, 69, 42)); assert_eq!(Balances::total_issuance(), old_total_issuance + 69 + 42); assert_eq!(Balances::total_balance(&1337), 69 + 42); assert_eq!(Balances::free_balance(&1337), 69); diff --git a/frame/balances/src/tests_composite.rs b/frame/balances/src/tests_composite.rs index 1276a812c7861..1e38d611773d4 100644 --- a/frame/balances/src/tests_composite.rs +++ b/frame/balances/src/tests_composite.rs @@ -55,7 +55,7 @@ impl frame_system::Config for Test { type BlockWeights = BlockWeights; type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; diff --git a/frame/balances/src/tests_local.rs b/frame/balances/src/tests_local.rs index b391b03ed6b6a..e080eafb66067 100644 --- a/frame/balances/src/tests_local.rs +++ b/frame/balances/src/tests_local.rs @@ -56,7 +56,7 @@ impl frame_system::Config for Test { type BlockWeights = BlockWeights; type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; diff --git a/frame/balances/src/tests_reentrancy.rs b/frame/balances/src/tests_reentrancy.rs index 6fda1697dcfeb..fa2eb0e488e7d 100644 --- a/frame/balances/src/tests_reentrancy.rs +++ b/frame/balances/src/tests_reentrancy.rs @@ -59,7 +59,7 @@ impl frame_system::Config for Test { type BlockWeights = BlockWeights; type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; diff --git a/frame/beefy-mmr/Cargo.toml b/frame/beefy-mmr/Cargo.toml index e8366943c85b0..62fabd387a167 100644 --- a/frame/beefy-mmr/Cargo.toml +++ b/frame/beefy-mmr/Cargo.toml @@ -9,8 +9,8 @@ repository = "https://github.com/paritytech/substrate" homepage = "https://substrate.io" [dependencies] +array-bytes = { version = "4.1", optional = true } codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } -hex = { version = "0.4", optional = true } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } serde = { version = "1.0.136", optional = true } @@ -27,18 +27,18 @@ sp-runtime = { version = "6.0.0", default-features = false, path = "../../primit sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } [dev-dependencies] -hex-literal = "0.3" +array-bytes = "4.1" sp-staking = { version = "4.0.0-dev", path = "../../primitives/staking" } [features] default = ["std"] std = [ + "array-bytes", "beefy-merkle-tree/std", "beefy-primitives/std", "codec/std", "frame-support/std", "frame-system/std", - "hex", "log/std", "pallet-beefy/std", "pallet-mmr/std", diff --git a/frame/beefy-mmr/primitives/Cargo.toml b/frame/beefy-mmr/primitives/Cargo.toml index f30a418def042..1aa2573c7f680 100644 --- a/frame/beefy-mmr/primitives/Cargo.toml +++ b/frame/beefy-mmr/primitives/Cargo.toml @@ -9,7 +9,7 @@ description = "A no-std/Substrate compatible library to construct binary merkle homepage = "https://substrate.io" [dependencies] -hex = { version = "0.4", default-features = false, optional = true } +array-bytes = { version = "4.1", optional = true } log = { version = "0.4", default-features = false, optional = true } tiny-keccak = { version = "2.0.2", features = ["keccak"], optional = true } @@ -17,12 +17,11 @@ beefy-primitives = { version = "4.0.0-dev", default-features = false, path = ".. sp-api = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/api" } [dev-dependencies] +array-bytes = "4.1" env_logger = "0.9" -hex = "0.4" -hex-literal = "0.3" [features] -debug = ["hex", "hex/std", "log"] +debug = ["array-bytes", "log"] default = ["debug", "keccak", "std"] keccak = ["tiny-keccak"] std = [ diff --git a/frame/beefy-mmr/primitives/src/lib.rs b/frame/beefy-mmr/primitives/src/lib.rs index 664fd18199dd0..38831d7914715 100644 --- a/frame/beefy-mmr/primitives/src/lib.rs +++ b/frame/beefy-mmr/primitives/src/lib.rs @@ -235,7 +235,11 @@ where #[cfg(feature = "debug")] log::debug!( "[merkle_proof] Proof: {:?}", - collect_proof.proof.iter().map(hex::encode).collect::>() + collect_proof + .proof + .iter() + .map(|s| array_bytes::bytes2hex("", s)) + .collect::>() ); MerkleProof { root, proof: collect_proof.proof, number_of_leaves, leaf_index, leaf } @@ -308,10 +312,10 @@ where #[cfg(feature = "debug")] log::debug!( "[verify_proof]: (a, b) {:?}, {:?} => {:?} ({:?}) hash", - hex::encode(a), - hex::encode(b), - hex::encode(hash), - hex::encode(combined) + array_bytes::bytes2hex("", &a), + array_bytes::bytes2hex("", &b), + array_bytes::bytes2hex("", &hash), + array_bytes::bytes2hex("", &combined) ); position /= 2; width = ((width - 1) / 2) + 1; @@ -348,7 +352,11 @@ where visitor.visit(index, &a, &b); #[cfg(feature = "debug")] - log::debug!(" {:?}\n {:?}", a.as_ref().map(hex::encode), b.as_ref().map(hex::encode)); + log::debug!( + " {:?}\n {:?}", + a.as_ref().map(|s| array_bytes::bytes2hex("", s)), + b.as_ref().map(|s| array_bytes::bytes2hex("", s)) + ); index += 2; match (a, b) { @@ -369,7 +377,7 @@ where #[cfg(feature = "debug")] log::debug!( "[merkelize_row] Next: {:?}", - next.iter().map(hex::encode).collect::>() + next.iter().map(|s| array_bytes::bytes2hex("", s)).collect::>() ); return Err(next) }, @@ -395,7 +403,6 @@ sp_api::decl_runtime_apis! { #[cfg(test)] mod tests { use super::*; - use hex_literal::hex; #[test] fn should_generate_empty_root() { @@ -408,7 +415,7 @@ mod tests { // then assert_eq!( - hex::encode(&out), + array_bytes::bytes2hex("", &out), "0000000000000000000000000000000000000000000000000000000000000000" ); } @@ -417,14 +424,16 @@ mod tests { fn should_generate_single_root() { // given let _ = env_logger::try_init(); - let data = vec![hex!("E04CC55ebEE1cBCE552f250e85c57B70B2E2625b")]; + let data = vec![array_bytes::hex2array_unchecked::<20>( + "E04CC55ebEE1cBCE552f250e85c57B70B2E2625b", + )]; // when let out = merkle_root::(data); // then assert_eq!( - hex::encode(&out), + array_bytes::bytes2hex("", &out), "aeb47a269393297f4b0a3c9c9cfd00c7a4195255274cf39d83dabc2fcc9ff3d7" ); } @@ -434,8 +443,8 @@ mod tests { // given let _ = env_logger::try_init(); let data = vec![ - hex!("E04CC55ebEE1cBCE552f250e85c57B70B2E2625b"), - hex!("25451A4de12dcCc2D166922fA938E900fCc4ED24"), + array_bytes::hex2array_unchecked::<20>("E04CC55ebEE1cBCE552f250e85c57B70B2E2625b"), + array_bytes::hex2array_unchecked::<20>("25451A4de12dcCc2D166922fA938E900fCc4ED24"), ]; // when @@ -443,7 +452,7 @@ mod tests { // then assert_eq!( - hex::encode(&out), + array_bytes::bytes2hex("", &out), "697ea2a8fe5b03468548a7a413424a6292ab44a82a6f5cc594c3fa7dda7ce402" ); } @@ -452,7 +461,7 @@ mod tests { fn should_generate_root_complex() { let _ = env_logger::try_init(); let test = |root, data| { - assert_eq!(hex::encode(&merkle_root::(data)), root); + assert_eq!(array_bytes::bytes2hex("", &merkle_root::(data)), root); }; test( @@ -511,11 +520,19 @@ mod tests { )); // then - assert_eq!(hex::encode(proof0.root), hex::encode(proof1.root)); - assert_eq!(hex::encode(proof2.root), hex::encode(proof1.root)); + assert_eq!( + array_bytes::bytes2hex("", &proof0.root), + array_bytes::bytes2hex("", &proof1.root) + ); + assert_eq!( + array_bytes::bytes2hex("", &proof2.root), + array_bytes::bytes2hex("", &proof1.root) + ); assert!(!verify_proof::( - &hex!("fb3b3be94be9e983ba5e094c9c51a7d96a4fa2e5d8e891df00ca89ba05bb1239"), + &array_bytes::hex2array_unchecked( + "fb3b3be94be9e983ba5e094c9c51a7d96a4fa2e5d8e891df00ca89ba05bb1239" + ), proof0.proof, data.len(), proof0.leaf_index, @@ -779,17 +796,19 @@ mod tests { "0xA4cDc98593CE52d01Fe5Ca47CB3dA5320e0D7592", "0xc26B34D375533fFc4c5276282Fa5D660F3d8cbcB", ]; - let root = hex!("72b0acd7c302a84f1f6b6cefe0ba7194b7398afb440e1b44a9dbbe270394ca53"); + let root = array_bytes::hex2array_unchecked( + "72b0acd7c302a84f1f6b6cefe0ba7194b7398afb440e1b44a9dbbe270394ca53", + ); let data = addresses .into_iter() - .map(|address| hex::decode(&address[2..]).unwrap()) + .map(|address| array_bytes::hex2bytes_unchecked(&address)) .collect::>(); for l in 0..data.len() { // when let proof = merkle_proof::(data.clone(), l); - assert_eq!(hex::encode(&proof.root), hex::encode(&root)); + assert_eq!(array_bytes::bytes2hex("", &proof.root), array_bytes::bytes2hex("", &root)); assert_eq!(proof.leaf_index, l); assert_eq!(&proof.leaf, &data[l]); @@ -810,14 +829,25 @@ mod tests { MerkleProof { root, proof: vec![ - hex!("340bcb1d49b2d82802ddbcf5b85043edb3427b65d09d7f758fbc76932ad2da2f"), - hex!("ba0580e5bd530bc93d61276df7969fb5b4ae8f1864b4a28c280249575198ff1f"), - hex!("d02609d2bbdb28aa25f58b85afec937d5a4c85d37925bce6d0cf802f9d76ba79"), - hex!("ae3f8991955ed884613b0a5f40295902eea0e0abe5858fc520b72959bc016d4e"), + array_bytes::hex2array_unchecked( + "340bcb1d49b2d82802ddbcf5b85043edb3427b65d09d7f758fbc76932ad2da2f" + ), + array_bytes::hex2array_unchecked( + "ba0580e5bd530bc93d61276df7969fb5b4ae8f1864b4a28c280249575198ff1f" + ), + array_bytes::hex2array_unchecked( + "d02609d2bbdb28aa25f58b85afec937d5a4c85d37925bce6d0cf802f9d76ba79" + ), + array_bytes::hex2array_unchecked( + "ae3f8991955ed884613b0a5f40295902eea0e0abe5858fc520b72959bc016d4e" + ), ], number_of_leaves: data.len(), leaf_index: data.len() - 1, - leaf: hex!("c26B34D375533fFc4c5276282Fa5D660F3d8cbcB").to_vec(), + leaf: array_bytes::hex2array_unchecked::<20>( + "c26B34D375533fFc4c5276282Fa5D660F3d8cbcB" + ) + .to_vec(), } ); } diff --git a/frame/beefy-mmr/src/mock.rs b/frame/beefy-mmr/src/mock.rs index 792b775b77998..602d0aa5fe1a6 100644 --- a/frame/beefy-mmr/src/mock.rs +++ b/frame/beefy-mmr/src/mock.rs @@ -67,7 +67,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = H256; diff --git a/frame/beefy-mmr/src/tests.rs b/frame/beefy-mmr/src/tests.rs index eaa50004ae848..b9851d9eef6cb 100644 --- a/frame/beefy-mmr/src/tests.rs +++ b/frame/beefy-mmr/src/tests.rs @@ -22,7 +22,6 @@ use beefy_primitives::{ ValidatorSet, }; use codec::{Decode, Encode}; -use hex_literal::hex; use sp_core::H256; use sp_io::TestExternalities; @@ -70,9 +69,9 @@ fn should_contain_mmr_digest() { beefy_log(ConsensusLog::AuthoritiesChange( ValidatorSet::new(vec![mock_beefy_id(1), mock_beefy_id(2)], 1).unwrap() )), - beefy_log(ConsensusLog::MmrRoot( - hex!("95803defe6ea9f41e7ec6afa497064f21bfded027d8812efacbdf984e630cbdc").into() - )) + beefy_log(ConsensusLog::MmrRoot(array_bytes::hex_n_into_unchecked( + "95803defe6ea9f41e7ec6afa497064f21bfded027d8812efacbdf984e630cbdc" + ))) ] ); @@ -85,15 +84,15 @@ fn should_contain_mmr_digest() { beefy_log(ConsensusLog::AuthoritiesChange( ValidatorSet::new(vec![mock_beefy_id(1), mock_beefy_id(2)], 1).unwrap() )), - beefy_log(ConsensusLog::MmrRoot( - hex!("95803defe6ea9f41e7ec6afa497064f21bfded027d8812efacbdf984e630cbdc").into() - )), + beefy_log(ConsensusLog::MmrRoot(array_bytes::hex_n_into_unchecked( + "95803defe6ea9f41e7ec6afa497064f21bfded027d8812efacbdf984e630cbdc" + ))), beefy_log(ConsensusLog::AuthoritiesChange( ValidatorSet::new(vec![mock_beefy_id(3), mock_beefy_id(4)], 2).unwrap() )), - beefy_log(ConsensusLog::MmrRoot( - hex!("a73271a0974f1e67d6e9b8dd58e506177a2e556519a330796721e98279a753e2").into() - )), + beefy_log(ConsensusLog::MmrRoot(array_bytes::hex_n_into_unchecked( + "a73271a0974f1e67d6e9b8dd58e506177a2e556519a330796721e98279a753e2" + ))), ] ); }); @@ -120,11 +119,13 @@ fn should_contain_valid_leaf_data() { beefy_next_authority_set: BeefyNextAuthoritySet { id: 2, len: 2, - root: hex!("9c6b2c1b0d0b25a008e6c882cc7b415f309965c72ad2b944ac0931048ca31cd5") - .into(), + root: array_bytes::hex_n_into_unchecked( + "9c6b2c1b0d0b25a008e6c882cc7b415f309965c72ad2b944ac0931048ca31cd5" + ) }, - leaf_extra: hex!("55b8e9e1cc9f0db7776fac0ca66318ef8acfb8ec26db11e373120583e07ee648") - .to_vec(), + leaf_extra: array_bytes::hex2bytes_unchecked( + "55b8e9e1cc9f0db7776fac0ca66318ef8acfb8ec26db11e373120583e07ee648" + ) } ); @@ -143,11 +144,13 @@ fn should_contain_valid_leaf_data() { beefy_next_authority_set: BeefyNextAuthoritySet { id: 3, len: 2, - root: hex!("9c6b2c1b0d0b25a008e6c882cc7b415f309965c72ad2b944ac0931048ca31cd5") - .into(), + root: array_bytes::hex_n_into_unchecked( + "9c6b2c1b0d0b25a008e6c882cc7b415f309965c72ad2b944ac0931048ca31cd5" + ) }, - leaf_extra: hex!("55b8e9e1cc9f0db7776fac0ca66318ef8acfb8ec26db11e373120583e07ee648") - .to_vec() + leaf_extra: array_bytes::hex2bytes_unchecked( + "55b8e9e1cc9f0db7776fac0ca66318ef8acfb8ec26db11e373120583e07ee648" + ) } ); } @@ -161,8 +164,9 @@ fn should_update_authorities() { // check current authority set assert_eq!(0, auth_set.id); assert_eq!(2, auth_set.len); - let want: H256 = - hex!("176e73f1bf656478b728e28dd1a7733c98621b8acf830bff585949763dca7a96").into(); + let want = array_bytes::hex_n_into_unchecked::( + "176e73f1bf656478b728e28dd1a7733c98621b8acf830bff585949763dca7a96", + ); assert_eq!(want, auth_set.root); // next authority set should have same validators but different id @@ -180,8 +184,9 @@ fn should_update_authorities() { assert_eq!(1, auth_set.id); // check next auth set assert_eq!(2, next_auth_set.id); - let want: H256 = - hex!("9c6b2c1b0d0b25a008e6c882cc7b415f309965c72ad2b944ac0931048ca31cd5").into(); + let want = array_bytes::hex_n_into_unchecked::( + "9c6b2c1b0d0b25a008e6c882cc7b415f309965c72ad2b944ac0931048ca31cd5", + ); assert_eq!(2, next_auth_set.len); assert_eq!(want, next_auth_set.root); @@ -195,8 +200,9 @@ fn should_update_authorities() { assert_eq!(2, auth_set.id); // check next auth set assert_eq!(3, next_auth_set.id); - let want: H256 = - hex!("9c6b2c1b0d0b25a008e6c882cc7b415f309965c72ad2b944ac0931048ca31cd5").into(); + let want = array_bytes::hex_n_into_unchecked::( + "9c6b2c1b0d0b25a008e6c882cc7b415f309965c72ad2b944ac0931048ca31cd5", + ); assert_eq!(2, next_auth_set.len); assert_eq!(want, next_auth_set.root); }); diff --git a/frame/beefy/src/mock.rs b/frame/beefy/src/mock.rs index 7c4cd1af01533..ad3a672333dd5 100644 --- a/frame/beefy/src/mock.rs +++ b/frame/beefy/src/mock.rs @@ -62,7 +62,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = H256; diff --git a/frame/benchmarking/Cargo.toml b/frame/benchmarking/Cargo.toml index 49603915ca6da..61aa2b9b900c6 100644 --- a/frame/benchmarking/Cargo.toml +++ b/frame/benchmarking/Cargo.toml @@ -31,7 +31,7 @@ sp-std = { version = "4.0.0", default-features = false, path = "../../primitives sp-storage = { version = "6.0.0", default-features = false, path = "../../primitives/storage" } [dev-dependencies] -hex-literal = "0.3.4" +array-bytes = "4.1" rusty-fork = { version = "0.3.0", default-features = false } sp-keystore = { version = "0.12.0", path = "../../primitives/keystore" } diff --git a/frame/benchmarking/README.md b/frame/benchmarking/README.md index 6316cd5903c8b..76673c5f69b33 100644 --- a/frame/benchmarking/README.md +++ b/frame/benchmarking/README.md @@ -185,7 +185,7 @@ Then you can run a benchmark like so: ``` This will output a file `pallet_name.rs` which implements the `WeightInfo` trait you should include -in your pallet. Each blockchain should generate their own benchmark file with their custom +in your pallet. Double colons `::` will be replaced with a `_` in the output name if you specify a directory. Each blockchain should generate their own benchmark file with their custom implementation of the `WeightInfo` trait. This means that you will be able to use these modular Substrate pallets while still keeping your network safe for your specific configuration and requirements. diff --git a/frame/benchmarking/src/baseline.rs b/frame/benchmarking/src/baseline.rs index 38aa7b261cb01..6a310330cafb1 100644 --- a/frame/benchmarking/src/baseline.rs +++ b/frame/benchmarking/src/baseline.rs @@ -176,7 +176,7 @@ pub mod mock { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; diff --git a/frame/benchmarking/src/lib.rs b/frame/benchmarking/src/lib.rs index d96ed4dd17b6e..a221eccb82c85 100644 --- a/frame/benchmarking/src/lib.rs +++ b/frame/benchmarking/src/lib.rs @@ -112,14 +112,14 @@ macro_rules! whitelist { /// foo { /// let caller = account::(b"caller", 0, benchmarks_seed); /// let l in 1 .. MAX_LENGTH => initialize_l(l); -/// }: _(Origin::Signed(caller), vec![0u8; l]) +/// }: _(RuntimeOrigin::Signed(caller), vec![0u8; l]) /// /// // second dispatchable: bar; this is a root dispatchable and accepts a `u8` vector of size /// // `l`. /// // In this case, we explicitly name the call using `bar` instead of `_`. /// bar { /// let l in 1 .. MAX_LENGTH => initialize_l(l); -/// }: bar(Origin::Root, vec![0u8; l]) +/// }: bar(RuntimeOrigin::Root, vec![0u8; l]) /// /// // third dispatchable: baz; this is a user dispatchable. It isn't dependent on length like the /// // other two but has its own complexity `c` that needs setting up. It uses `caller` (in the @@ -128,20 +128,20 @@ macro_rules! whitelist { /// baz1 { /// let caller = account::(b"caller", 0, benchmarks_seed); /// let c = 0 .. 10 => setup_c(&caller, c); -/// }: baz(Origin::Signed(caller)) +/// }: baz(RuntimeOrigin::Signed(caller)) /// /// // this is a second benchmark of the baz dispatchable with a different setup. /// baz2 { /// let caller = account::(b"caller", 0, benchmarks_seed); /// let c = 0 .. 10 => setup_c_in_some_other_way(&caller, c); -/// }: baz(Origin::Signed(caller)) +/// }: baz(RuntimeOrigin::Signed(caller)) /// /// // You may optionally specify the origin type if it can't be determined automatically like /// // this. /// baz3 { /// let caller = account::(b"caller", 0, benchmarks_seed); /// let l in 1 .. MAX_LENGTH => initialize_l(l); -/// }: baz(Origin::Signed(caller), vec![0u8; l]) +/// }: baz(RuntimeOrigin::Signed(caller), vec![0u8; l]) /// /// // this is benchmarking some code that is not a dispatchable. /// populate_a_set { @@ -617,7 +617,7 @@ macro_rules! to_origin { $origin.into() }; ($origin:expr, $origin_type:ty) => { - <::Origin as From<$origin_type>>::from($origin) + <::RuntimeOrigin as From<$origin_type>>::from($origin) }; } @@ -1695,13 +1695,13 @@ pub fn show_benchmark_debug_info( /// use frame_benchmarking::TrackedStorageKey; /// let whitelist: Vec = vec![ /// // Block Number -/// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), +/// array_bytes::hex_into_unchecked("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac"), /// // Total Issuance -/// hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(), +/// array_bytes::hex_into_unchecked("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80"), /// // Execution Phase -/// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), +/// array_bytes::hex_into_unchecked("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a"), /// // Event Count -/// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), +/// array_bytes::hex_into_unchecked("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850"), /// ]; /// ``` /// diff --git a/frame/benchmarking/src/tests.rs b/frame/benchmarking/src/tests.rs index fd7e0cce03c22..88a7d6d0286b2 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -36,7 +36,7 @@ mod pallet_test { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - pub struct Pallet(_); + pub struct Pallet(PhantomData); #[pallet::config] pub trait Config: frame_system::Config { @@ -46,21 +46,21 @@ mod pallet_test { } #[pallet::storage] - #[pallet::getter(fn heartbeat_after)] + #[pallet::getter(fn value)] pub(crate) type Value = StorageValue<_, u32, OptionQuery>; #[pallet::call] impl Pallet { #[pallet::weight(0)] pub fn set_value(origin: OriginFor, n: u32) -> DispatchResult { - let _sender = frame_system::ensure_signed(origin)?; + let _sender = ensure_signed(origin)?; Value::::put(n); Ok(()) } #[pallet::weight(0)] pub fn dummy(origin: OriginFor, _n: u32) -> DispatchResult { - let _sender = frame_system::ensure_none(origin)?; + let _sender = ensure_none(origin)?; Ok(()) } @@ -90,7 +90,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = H256; @@ -148,7 +148,7 @@ mod benchmarks { crate::benchmarks! { where_clause { where - crate::tests::Origin: From::AccountId>>, + crate::tests::RuntimeOrigin: From::AccountId>>, } set_value { diff --git a/frame/benchmarking/src/tests_instance.rs b/frame/benchmarking/src/tests_instance.rs index 7617696a949cf..7e1cd48840687 100644 --- a/frame/benchmarking/src/tests_instance.rs +++ b/frame/benchmarking/src/tests_instance.rs @@ -28,48 +28,52 @@ use sp_runtime::{ }; use sp_std::prelude::*; +#[frame_support::pallet] mod pallet_test { - use frame_support::pallet_prelude::Get; + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; - frame_support::decl_storage! { - trait Store for Module, I: Instance = DefaultInstance> as Test where - ::OtherEvent: Into<>::RuntimeEvent> - { - pub Value get(fn value): Option; - } - } - - frame_support::decl_module! { - pub struct Module, I: Instance = DefaultInstance> for enum Call where - origin: T::Origin, ::OtherEvent: Into<>::RuntimeEvent> - { - #[weight = 0] - fn set_value(origin, n: u32) -> frame_support::dispatch::DispatchResult { - let _sender = frame_system::ensure_signed(origin)?; - Value::::put(n); - Ok(()) - } - - #[weight = 0] - fn dummy(origin, _n: u32) -> frame_support::dispatch::DispatchResult { - let _sender = frame_system::ensure_none(origin)?; - Ok(()) - } - } - } + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(PhantomData<(T, I)>); pub trait OtherConfig { type OtherEvent; } - pub trait Config: frame_system::Config + OtherConfig - where - Self::OtherEvent: Into<>::RuntimeEvent>, - { - type RuntimeEvent; + #[pallet::config] + pub trait Config: frame_system::Config + OtherConfig { + type RuntimeEvent: From> + + IsType<::RuntimeEvent>; type LowerBound: Get; type UpperBound: Get; } + + #[pallet::storage] + #[pallet::getter(fn value)] + pub(crate) type Value, I: 'static = ()> = StorageValue<_, u32, OptionQuery>; + + #[pallet::event] + pub enum Event, I: 'static = ()> {} + + #[pallet::call] + impl, I: 'static> Pallet + where + ::OtherEvent: Into<>::RuntimeEvent>, + { + #[pallet::weight(0)] + pub fn set_value(origin: OriginFor, n: u32) -> DispatchResult { + let _sender = ensure_signed(origin)?; + Value::::put(n); + Ok(()) + } + + #[pallet::weight(0)] + pub fn dummy(origin: OriginFor, _n: u32) -> DispatchResult { + let _sender = ensure_none(origin)?; + Ok(()) + } + } } type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -82,7 +86,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Config, Storage, Event}, - TestPallet: pallet_test::{Pallet, Call, Storage}, + TestPallet: pallet_test::{Pallet, Call, Storage, Event}, } ); @@ -90,18 +94,18 @@ impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); type BlockLength = (); - type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; 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 RuntimeEvent = RuntimeEvent; type BlockHashCount = (); + type DbWeight = (); type Version = (); type PalletInfo = PalletInfo; type AccountData = (); @@ -110,7 +114,7 @@ impl frame_system::Config for Test { type SystemWeightInfo = (); type SS58Prefix = (); type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; + type MaxConsumers = ConstU32<16>; } impl pallet_test::Config for Test { @@ -130,15 +134,14 @@ fn new_test_ext() -> sp_io::TestExternalities { mod benchmarks { use super::pallet_test::{self, Value}; use crate::account; - use frame_support::{ensure, StorageValue}; + use frame_support::ensure; use frame_system::RawOrigin; use sp_std::prelude::*; // Additional used internally by the benchmark macro. use super::pallet_test::{Call, Config, Pallet}; - use frame_support::traits::Instance; - crate::benchmarks_instance! { + crate::benchmarks_instance_pallet! { where_clause { where ::OtherEvent: Clone @@ -151,7 +154,7 @@ mod benchmarks { let caller = account::("caller", 0, 0); }: _ (RawOrigin::Signed(caller), b.into()) verify { - assert_eq!(Value::::get(), Some(b)); + assert_eq!(Value::::get(), Some(b)); } other_name { diff --git a/frame/bounties/src/benchmarking.rs b/frame/bounties/src/benchmarking.rs index 9dc920f6cca28..6ccd587cebc10 100644 --- a/frame/bounties/src/benchmarking.rs +++ b/frame/bounties/src/benchmarking.rs @@ -98,7 +98,7 @@ benchmarks_instance_pallet! { Bounties::::propose_bounty(RawOrigin::Signed(caller).into(), value, reason)?; let bounty_id = BountyCount::::get() - 1; let approve_origin = T::ApproveOrigin::successful_origin(); - }: _(approve_origin, bounty_id) + }: _(approve_origin, bounty_id) propose_curator { setup_pot_account::(); @@ -110,7 +110,7 @@ benchmarks_instance_pallet! { Bounties::::approve_bounty(approve_origin, bounty_id)?; Treasury::::on_initialize(T::BlockNumber::zero()); let approve_origin = T::ApproveOrigin::successful_origin(); - }: _(approve_origin, bounty_id, curator_lookup, fee) + }: _(approve_origin, bounty_id, curator_lookup, fee) // Worst case when curator is inactive and any sender unassigns the curator. unassign_curator { @@ -171,7 +171,7 @@ benchmarks_instance_pallet! { Bounties::::propose_bounty(RawOrigin::Signed(caller).into(), value, reason)?; let bounty_id = BountyCount::::get() - 1; let approve_origin = T::ApproveOrigin::successful_origin(); - }: close_bounty(approve_origin, bounty_id) + }: close_bounty(approve_origin, bounty_id) close_bounty_active { setup_pot_account::(); @@ -179,7 +179,7 @@ benchmarks_instance_pallet! { Treasury::::on_initialize(T::BlockNumber::zero()); let bounty_id = BountyCount::::get() - 1; let approve_origin = T::ApproveOrigin::successful_origin(); - }: close_bounty(approve_origin, bounty_id) + }: close_bounty(approve_origin, bounty_id) verify { assert_last_event::(Event::BountyCanceled { index: bounty_id }.into()) } diff --git a/frame/bounties/src/tests.rs b/frame/bounties/src/tests.rs index f1d794eb89dbe..68aa56ccdde7f 100644 --- a/frame/bounties/src/tests.rs +++ b/frame/bounties/src/tests.rs @@ -68,7 +68,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; @@ -229,7 +229,7 @@ fn minting_works() { #[test] fn spend_proposal_takes_min_deposit() { new_test_ext().execute_with(|| { - assert_ok!(Treasury::propose_spend(Origin::signed(0), 1, 3)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 1, 3)); assert_eq!(Balances::free_balance(0), 99); assert_eq!(Balances::reserved_balance(0), 1); }); @@ -238,7 +238,7 @@ fn spend_proposal_takes_min_deposit() { #[test] fn spend_proposal_takes_proportional_deposit() { new_test_ext().execute_with(|| { - assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3)); assert_eq!(Balances::free_balance(0), 95); assert_eq!(Balances::reserved_balance(0), 5); }); @@ -248,7 +248,7 @@ fn spend_proposal_takes_proportional_deposit() { fn spend_proposal_fails_when_proposer_poor() { new_test_ext().execute_with(|| { assert_noop!( - Treasury::propose_spend(Origin::signed(2), 100, 3), + Treasury::propose_spend(RuntimeOrigin::signed(2), 100, 3), TreasuryError::InsufficientProposersBalance, ); }); @@ -259,8 +259,8 @@ fn accepted_spend_proposal_ignored_outside_spend_period() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); - assert_ok!(Treasury::approve_proposal(Origin::root(), 0)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3)); + assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 0)); >::on_initialize(1); assert_eq!(Balances::free_balance(3), 0); @@ -286,8 +286,8 @@ fn rejected_spend_proposal_ignored_on_spend_period() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); - assert_ok!(Treasury::reject_proposal(Origin::root(), 0)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3)); + assert_ok!(Treasury::reject_proposal(RuntimeOrigin::root(), 0)); >::on_initialize(2); assert_eq!(Balances::free_balance(3), 0); @@ -300,9 +300,12 @@ fn reject_already_rejected_spend_proposal_fails() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); - assert_ok!(Treasury::reject_proposal(Origin::root(), 0)); - assert_noop!(Treasury::reject_proposal(Origin::root(), 0), TreasuryError::InvalidIndex); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3)); + assert_ok!(Treasury::reject_proposal(RuntimeOrigin::root(), 0)); + assert_noop!( + Treasury::reject_proposal(RuntimeOrigin::root(), 0), + TreasuryError::InvalidIndex + ); }); } @@ -310,7 +313,7 @@ fn reject_already_rejected_spend_proposal_fails() { fn reject_non_existent_spend_proposal_fails() { new_test_ext().execute_with(|| { assert_noop!( - Treasury::reject_proposal(Origin::root(), 0), + Treasury::reject_proposal(RuntimeOrigin::root(), 0), pallet_treasury::Error::::InvalidIndex ); }); @@ -319,7 +322,10 @@ fn reject_non_existent_spend_proposal_fails() { #[test] fn accept_non_existent_spend_proposal_fails() { new_test_ext().execute_with(|| { - assert_noop!(Treasury::approve_proposal(Origin::root(), 0), TreasuryError::InvalidIndex); + assert_noop!( + Treasury::approve_proposal(RuntimeOrigin::root(), 0), + TreasuryError::InvalidIndex + ); }); } @@ -328,9 +334,12 @@ fn accept_already_rejected_spend_proposal_fails() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); - assert_ok!(Treasury::reject_proposal(Origin::root(), 0)); - assert_noop!(Treasury::approve_proposal(Origin::root(), 0), TreasuryError::InvalidIndex); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3)); + assert_ok!(Treasury::reject_proposal(RuntimeOrigin::root(), 0)); + assert_noop!( + Treasury::approve_proposal(RuntimeOrigin::root(), 0), + TreasuryError::InvalidIndex + ); }); } @@ -340,8 +349,8 @@ fn accepted_spend_proposal_enacted_on_spend_period() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); - assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); - assert_ok!(Treasury::approve_proposal(Origin::root(), 0)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3)); + assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 0)); >::on_initialize(2); assert_eq!(Balances::free_balance(3), 100); @@ -355,8 +364,8 @@ fn pot_underflow_should_not_diminish() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); - assert_ok!(Treasury::propose_spend(Origin::signed(0), 150, 3)); - assert_ok!(Treasury::approve_proposal(Origin::root(), 0)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 150, 3)); + assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 0)); >::on_initialize(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed @@ -377,14 +386,14 @@ fn treasury_account_doesnt_get_deleted() { assert_eq!(Treasury::pot(), 100); let treasury_balance = Balances::free_balance(&Treasury::account_id()); - assert_ok!(Treasury::propose_spend(Origin::signed(0), treasury_balance, 3)); - assert_ok!(Treasury::approve_proposal(Origin::root(), 0)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), treasury_balance, 3)); + assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 0)); >::on_initialize(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed - assert_ok!(Treasury::propose_spend(Origin::signed(0), Treasury::pot(), 3)); - assert_ok!(Treasury::approve_proposal(Origin::root(), 1)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), Treasury::pot(), 3)); + assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 1)); >::on_initialize(4); assert_eq!(Treasury::pot(), 0); // Pot is emptied @@ -407,10 +416,10 @@ fn inexistent_account_works() { assert_eq!(Balances::free_balance(Treasury::account_id()), 0); // Account does not exist assert_eq!(Treasury::pot(), 0); // Pot is empty - assert_ok!(Treasury::propose_spend(Origin::signed(0), 99, 3)); - assert_ok!(Treasury::approve_proposal(Origin::root(), 0)); - assert_ok!(Treasury::propose_spend(Origin::signed(0), 1, 3)); - assert_ok!(Treasury::approve_proposal(Origin::root(), 1)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 99, 3)); + assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 0)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 1, 3)); + assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 1)); >::on_initialize(2); assert_eq!(Treasury::pot(), 0); // Pot hasn't changed assert_eq!(Balances::free_balance(3), 0); // Balance of `3` hasn't changed @@ -434,7 +443,7 @@ fn propose_bounty_works() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 10, b"1234567890".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 10, b"1234567890".to_vec())); assert_eq!(last_event(), BountiesEvent::BountyProposed { index: 0 }); @@ -469,17 +478,21 @@ fn propose_bounty_validation_works() { assert_eq!(Treasury::pot(), 100); assert_noop!( - Bounties::propose_bounty(Origin::signed(1), 0, [0; 17_000].to_vec()), + Bounties::propose_bounty(RuntimeOrigin::signed(1), 0, [0; 17_000].to_vec()), Error::::ReasonTooBig ); assert_noop!( - Bounties::propose_bounty(Origin::signed(1), 10, b"12345678901234567890".to_vec()), + Bounties::propose_bounty( + RuntimeOrigin::signed(1), + 10, + b"12345678901234567890".to_vec() + ), Error::::InsufficientProposersBalance ); assert_noop!( - Bounties::propose_bounty(Origin::signed(1), 0, b"12345678901234567890".to_vec()), + Bounties::propose_bounty(RuntimeOrigin::signed(1), 0, b"12345678901234567890".to_vec()), Error::::InvalidValue ); }); @@ -490,11 +503,11 @@ fn close_bounty_works() { new_test_ext().execute_with(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_noop!(Bounties::close_bounty(Origin::root(), 0), Error::::InvalidIndex); + assert_noop!(Bounties::close_bounty(RuntimeOrigin::root(), 0), Error::::InvalidIndex); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 10, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 10, b"12345".to_vec())); - assert_ok!(Bounties::close_bounty(Origin::root(), 0)); + assert_ok!(Bounties::close_bounty(RuntimeOrigin::root(), 0)); let deposit: u64 = 80 + 5; @@ -515,11 +528,14 @@ fn approve_bounty_works() { new_test_ext().execute_with(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_noop!(Bounties::approve_bounty(Origin::root(), 0), Error::::InvalidIndex); + assert_noop!( + Bounties::approve_bounty(RuntimeOrigin::root(), 0), + Error::::InvalidIndex + ); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); let deposit: u64 = 80 + 5; @@ -536,7 +552,10 @@ fn approve_bounty_works() { ); assert_eq!(Bounties::bounty_approvals(), vec![0]); - assert_noop!(Bounties::close_bounty(Origin::root(), 0), Error::::UnexpectedStatus); + assert_noop!( + Bounties::close_bounty(RuntimeOrigin::root(), 0), + Error::::UnexpectedStatus + ); // deposit not returned yet assert_eq!(Balances::reserved_balance(0), deposit); @@ -572,24 +591,24 @@ fn assign_curator_works() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_noop!( - Bounties::propose_curator(Origin::root(), 0, 4, 4), + Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 4), Error::::InvalidIndex ); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); assert_noop!( - Bounties::propose_curator(Origin::root(), 0, 4, 50), + Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 50), Error::::InvalidFee ); let fee = 4; - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, fee)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, fee)); assert_eq!( Bounties::bounties(0).unwrap(), @@ -603,15 +622,18 @@ fn assign_curator_works() { } ); - assert_noop!(Bounties::accept_curator(Origin::signed(1), 0), Error::::RequireCurator); assert_noop!( - Bounties::accept_curator(Origin::signed(4), 0), + Bounties::accept_curator(RuntimeOrigin::signed(1), 0), + Error::::RequireCurator + ); + assert_noop!( + Bounties::accept_curator(RuntimeOrigin::signed(4), 0), pallet_balances::Error::::InsufficientBalance ); Balances::make_free_balance_be(&4, 10); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); let expected_deposit = Bounties::calculate_curator_deposit(&fee); @@ -637,18 +659,18 @@ fn unassign_curator_works() { new_test_ext().execute_with(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); let fee = 4; - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, fee)); - assert_noop!(Bounties::unassign_curator(Origin::signed(1), 0), BadOrigin); - assert_ok!(Bounties::unassign_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, fee)); + assert_noop!(Bounties::unassign_curator(RuntimeOrigin::signed(1), 0), BadOrigin); + assert_ok!(Bounties::unassign_curator(RuntimeOrigin::signed(4), 0)); assert_eq!( Bounties::bounties(0).unwrap(), @@ -662,11 +684,11 @@ fn unassign_curator_works() { } ); - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, fee)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, fee)); Balances::make_free_balance_be(&4, 10); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); let expected_deposit = Bounties::calculate_curator_deposit(&fee); - assert_ok!(Bounties::unassign_curator(Origin::root(), 0)); + assert_ok!(Bounties::unassign_curator(RuntimeOrigin::root(), 0)); assert_eq!( Bounties::bounties(0).unwrap(), @@ -691,26 +713,26 @@ fn award_and_claim_bounty_works() { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); Balances::make_free_balance_be(&4, 10); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); let fee = 4; - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, fee)); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, fee)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); let expected_deposit = Bounties::calculate_curator_deposit(&fee); assert_eq!(Balances::free_balance(4), 10 - expected_deposit); assert_noop!( - Bounties::award_bounty(Origin::signed(1), 0, 3), + Bounties::award_bounty(RuntimeOrigin::signed(1), 0, 3), Error::::RequireCurator ); - assert_ok!(Bounties::award_bounty(Origin::signed(4), 0, 3)); + assert_ok!(Bounties::award_bounty(RuntimeOrigin::signed(4), 0, 3)); assert_eq!( Bounties::bounties(0).unwrap(), @@ -724,14 +746,18 @@ fn award_and_claim_bounty_works() { } ); - assert_noop!(Bounties::claim_bounty(Origin::signed(1), 0), Error::::Premature); + assert_noop!(Bounties::claim_bounty(RuntimeOrigin::signed(1), 0), Error::::Premature); System::set_block_number(5); >::on_initialize(5); - assert_ok!(Balances::transfer(Origin::signed(0), Bounties::bounty_account_id(0), 10)); + assert_ok!(Balances::transfer( + RuntimeOrigin::signed(0), + Bounties::bounty_account_id(0), + 10 + )); - assert_ok!(Bounties::claim_bounty(Origin::signed(1), 0)); + assert_ok!(Bounties::claim_bounty(RuntimeOrigin::signed(1), 0)); assert_eq!( last_event(), @@ -754,17 +780,17 @@ fn claim_handles_high_fee() { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); Balances::make_free_balance_be(&4, 30); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, 49)); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 49)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); - assert_ok!(Bounties::award_bounty(Origin::signed(4), 0, 3)); + assert_ok!(Bounties::award_bounty(RuntimeOrigin::signed(4), 0, 3)); System::set_block_number(5); >::on_initialize(5); @@ -773,7 +799,7 @@ fn claim_handles_high_fee() { let res = Balances::slash(&Bounties::bounty_account_id(0), 10); assert_eq!(res.0.peek(), 10); - assert_ok!(Bounties::claim_bounty(Origin::signed(1), 0)); + assert_ok!(Bounties::claim_bounty(RuntimeOrigin::signed(1), 0)); assert_eq!( last_event(), @@ -796,14 +822,18 @@ fn cancel_and_refund() { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); - assert_ok!(Balances::transfer(Origin::signed(0), Bounties::bounty_account_id(0), 10)); + assert_ok!(Balances::transfer( + RuntimeOrigin::signed(0), + Bounties::bounty_account_id(0), + 10 + )); assert_eq!( Bounties::bounties(0).unwrap(), @@ -819,9 +849,9 @@ fn cancel_and_refund() { assert_eq!(Balances::free_balance(Bounties::bounty_account_id(0)), 60); - assert_noop!(Bounties::close_bounty(Origin::signed(0), 0), BadOrigin); + assert_noop!(Bounties::close_bounty(RuntimeOrigin::signed(0), 0), BadOrigin); - assert_ok!(Bounties::close_bounty(Origin::root(), 0)); + assert_ok!(Bounties::close_bounty(RuntimeOrigin::root(), 0)); // `- 25 + 10` assert_eq!(Treasury::pot(), 85); @@ -833,27 +863,30 @@ fn award_and_cancel() { new_test_ext().execute_with(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 0, 10)); - assert_ok!(Bounties::accept_curator(Origin::signed(0), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 0, 10)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(0), 0)); assert_eq!(Balances::free_balance(0), 95); assert_eq!(Balances::reserved_balance(0), 5); - assert_ok!(Bounties::award_bounty(Origin::signed(0), 0, 3)); + assert_ok!(Bounties::award_bounty(RuntimeOrigin::signed(0), 0, 3)); // Cannot close bounty directly when payout is happening... - assert_noop!(Bounties::close_bounty(Origin::root(), 0), Error::::PendingPayout); + assert_noop!( + Bounties::close_bounty(RuntimeOrigin::root(), 0), + Error::::PendingPayout + ); // Instead unassign the curator to slash them and then close. - assert_ok!(Bounties::unassign_curator(Origin::root(), 0)); - assert_ok!(Bounties::close_bounty(Origin::root(), 0)); + assert_ok!(Bounties::unassign_curator(RuntimeOrigin::root(), 0)); + assert_ok!(Bounties::close_bounty(RuntimeOrigin::root(), 0)); assert_eq!(last_event(), BountiesEvent::BountyCanceled { index: 0 }); @@ -873,15 +906,15 @@ fn expire_and_unassign() { new_test_ext().execute_with(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 1, 10)); - assert_ok!(Bounties::accept_curator(Origin::signed(1), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 1, 10)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(1), 0)); assert_eq!(Balances::free_balance(1), 93); assert_eq!(Balances::reserved_balance(1), 5); @@ -889,12 +922,15 @@ fn expire_and_unassign() { System::set_block_number(22); >::on_initialize(22); - assert_noop!(Bounties::unassign_curator(Origin::signed(0), 0), Error::::Premature); + assert_noop!( + Bounties::unassign_curator(RuntimeOrigin::signed(0), 0), + Error::::Premature + ); System::set_block_number(23); >::on_initialize(23); - assert_ok!(Bounties::unassign_curator(Origin::signed(0), 0)); + assert_ok!(Bounties::unassign_curator(RuntimeOrigin::signed(0), 0)); assert_eq!( Bounties::bounties(0).unwrap(), @@ -919,20 +955,20 @@ fn extend_expiry() { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); Balances::make_free_balance_be(&4, 10); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); assert_noop!( - Bounties::extend_bounty_expiry(Origin::signed(1), 0, Vec::new()), + Bounties::extend_bounty_expiry(RuntimeOrigin::signed(1), 0, Vec::new()), Error::::UnexpectedStatus ); System::set_block_number(2); >::on_initialize(2); - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, 10)); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 10)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); assert_eq!(Balances::free_balance(4), 5); assert_eq!(Balances::reserved_balance(4), 5); @@ -941,10 +977,10 @@ fn extend_expiry() { >::on_initialize(10); assert_noop!( - Bounties::extend_bounty_expiry(Origin::signed(0), 0, Vec::new()), + Bounties::extend_bounty_expiry(RuntimeOrigin::signed(0), 0, Vec::new()), Error::::RequireCurator ); - assert_ok!(Bounties::extend_bounty_expiry(Origin::signed(4), 0, Vec::new())); + assert_ok!(Bounties::extend_bounty_expiry(RuntimeOrigin::signed(4), 0, Vec::new())); assert_eq!( Bounties::bounties(0).unwrap(), @@ -958,7 +994,7 @@ fn extend_expiry() { } ); - assert_ok!(Bounties::extend_bounty_expiry(Origin::signed(4), 0, Vec::new())); + assert_ok!(Bounties::extend_bounty_expiry(RuntimeOrigin::signed(4), 0, Vec::new())); assert_eq!( Bounties::bounties(0).unwrap(), @@ -975,8 +1011,11 @@ fn extend_expiry() { System::set_block_number(25); >::on_initialize(25); - assert_noop!(Bounties::unassign_curator(Origin::signed(0), 0), Error::::Premature); - assert_ok!(Bounties::unassign_curator(Origin::signed(4), 0)); + assert_noop!( + Bounties::unassign_curator(RuntimeOrigin::signed(0), 0), + Error::::Premature + ); + assert_ok!(Bounties::unassign_curator(RuntimeOrigin::signed(4), 0)); assert_eq!(Balances::free_balance(4), 10); // not slashed assert_eq!(Balances::reserved_balance(4), 0); @@ -1049,14 +1088,14 @@ fn unassign_curator_self() { new_test_ext().execute_with(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 1, 10)); - assert_ok!(Bounties::accept_curator(Origin::signed(1), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 1, 10)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(1), 0)); assert_eq!(Balances::free_balance(1), 93); assert_eq!(Balances::reserved_balance(1), 5); @@ -1064,7 +1103,7 @@ fn unassign_curator_self() { System::set_block_number(8); >::on_initialize(8); - assert_ok!(Bounties::unassign_curator(Origin::signed(1), 0)); + assert_ok!(Bounties::unassign_curator(RuntimeOrigin::signed(1), 0)); assert_eq!( Bounties::bounties(0).unwrap(), @@ -1097,14 +1136,14 @@ fn accept_curator_handles_different_deposit_calculations() { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); Balances::make_free_balance_be(&user, 100); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), value, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), bounty_index)); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), value, b"12345".to_vec())); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), bounty_index)); System::set_block_number(2); >::on_initialize(2); - assert_ok!(Bounties::propose_curator(Origin::root(), bounty_index, user, fee)); - assert_ok!(Bounties::accept_curator(Origin::signed(user), bounty_index)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), bounty_index, user, fee)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(user), bounty_index)); let expected_deposit = CuratorDepositMultiplier::get() * fee; assert_eq!(Balances::free_balance(&user), 100 - expected_deposit); @@ -1119,14 +1158,14 @@ fn accept_curator_handles_different_deposit_calculations() { Balances::make_free_balance_be(&Treasury::account_id(), 101); Balances::make_free_balance_be(&user, 100); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), value, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), bounty_index)); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), value, b"12345".to_vec())); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), bounty_index)); System::set_block_number(4); >::on_initialize(4); - assert_ok!(Bounties::propose_curator(Origin::root(), bounty_index, user, fee)); - assert_ok!(Bounties::accept_curator(Origin::signed(user), bounty_index)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), bounty_index, user, fee)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(user), bounty_index)); let expected_deposit = CuratorDepositMin::get(); assert_eq!(Balances::free_balance(&user), 100 - expected_deposit); @@ -1143,14 +1182,14 @@ fn accept_curator_handles_different_deposit_calculations() { Balances::make_free_balance_be(&user, starting_balance); Balances::make_free_balance_be(&0, starting_balance); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), value, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), bounty_index)); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), value, b"12345".to_vec())); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), bounty_index)); System::set_block_number(6); >::on_initialize(6); - assert_ok!(Bounties::propose_curator(Origin::root(), bounty_index, user, fee)); - assert_ok!(Bounties::accept_curator(Origin::signed(user), bounty_index)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), bounty_index, user, fee)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(user), bounty_index)); let expected_deposit = CuratorDepositMax::get(); assert_eq!(Balances::free_balance(&user), starting_balance - expected_deposit); @@ -1170,8 +1209,8 @@ fn approve_bounty_works_second_instance() { assert_eq!(Balances::free_balance(&Treasury::account_id()), 101); assert_eq!(Balances::free_balance(&Treasury1::account_id()), 201); - assert_ok!(Bounties1::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties1::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties1::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties1::approve_bounty(RuntimeOrigin::root(), 0)); >::on_initialize(2); >::on_initialize(2); diff --git a/frame/child-bounties/src/tests.rs b/frame/child-bounties/src/tests.rs index c9dbc8742c56a..67983b15f4579 100644 --- a/frame/child-bounties/src/tests.rs +++ b/frame/child-bounties/src/tests.rs @@ -71,7 +71,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; @@ -211,19 +211,19 @@ fn add_child_bounty() { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); let fee = 8; - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, fee)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, fee)); Balances::make_free_balance_be(&4, 10); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); // This verifies that the accept curator logic took a deposit. let expected_deposit = CuratorDepositMultiplier::get() * fee; @@ -234,7 +234,7 @@ fn add_child_bounty() { // Acc-4 is the parent curator. // Call from invalid origin & check for error "RequireCurator". assert_noop!( - ChildBounties::add_child_bounty(Origin::signed(0), 0, 10, b"12345-p1".to_vec()), + ChildBounties::add_child_bounty(RuntimeOrigin::signed(0), 0, 10, b"12345-p1".to_vec()), BountiesError::RequireCurator, ); @@ -246,17 +246,22 @@ fn add_child_bounty() { assert_eq!(Balances::reserved_balance(Bounties::bounty_account_id(0)), 0); assert_noop!( - ChildBounties::add_child_bounty(Origin::signed(4), 0, 50, b"12345-p1".to_vec()), + ChildBounties::add_child_bounty(RuntimeOrigin::signed(4), 0, 50, b"12345-p1".to_vec()), pallet_balances::Error::::KeepAlive, ); assert_noop!( - ChildBounties::add_child_bounty(Origin::signed(4), 0, 100, b"12345-p1".to_vec()), + ChildBounties::add_child_bounty(RuntimeOrigin::signed(4), 0, 100, b"12345-p1".to_vec()), Error::::InsufficientBountyBalance, ); // Add child-bounty with valid value, which can be funded by parent bounty. - assert_ok!(ChildBounties::add_child_bounty(Origin::signed(4), 0, 10, b"12345-p1".to_vec())); + assert_ok!(ChildBounties::add_child_bounty( + RuntimeOrigin::signed(4), + 0, + 10, + b"12345-p1".to_vec() + )); // Check for the event child-bounty added. assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); @@ -299,16 +304,16 @@ fn child_bounty_assign_curator() { Balances::make_free_balance_be(&4, 101); Balances::make_free_balance_be(&8, 101); - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); let fee = 4; - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, fee)); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, fee)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); // Bounty account status before adding child-bounty. assert_eq!(Balances::free_balance(Bounties::bounty_account_id(0)), 50); @@ -322,7 +327,12 @@ fn child_bounty_assign_curator() { // Add child-bounty. // Acc-4 is the parent curator & make sure enough deposit. - assert_ok!(ChildBounties::add_child_bounty(Origin::signed(4), 0, 10, b"12345-p1".to_vec())); + assert_ok!(ChildBounties::add_child_bounty( + RuntimeOrigin::signed(4), + 0, + 10, + b"12345-p1".to_vec() + )); assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); @@ -335,7 +345,7 @@ fn child_bounty_assign_curator() { assert_eq!(Balances::reserved_balance(ChildBounties::child_bounty_account_id(0)), 0); let fee = 6u64; - assert_ok!(ChildBounties::propose_curator(Origin::signed(4), 0, 0, 8, fee)); + assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, fee)); assert_eq!( ChildBounties::child_bounties(0, 0).unwrap(), @@ -353,11 +363,11 @@ fn child_bounty_assign_curator() { assert_eq!(Balances::reserved_balance(4), expected_deposit); assert_noop!( - ChildBounties::accept_curator(Origin::signed(3), 0, 0), + ChildBounties::accept_curator(RuntimeOrigin::signed(3), 0, 0), BountiesError::RequireCurator, ); - assert_ok!(ChildBounties::accept_curator(Origin::signed(8), 0, 0)); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(8), 0, 0)); let expected_child_deposit = CuratorDepositMultiplier::get() * fee; @@ -403,34 +413,39 @@ fn award_claim_child_bounty() { Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. Balances::make_free_balance_be(&8, 101); // Child-bounty curator. - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, 6)); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); // Child-bounty. - assert_ok!(ChildBounties::add_child_bounty(Origin::signed(4), 0, 10, b"12345-p1".to_vec())); + assert_ok!(ChildBounties::add_child_bounty( + RuntimeOrigin::signed(4), + 0, + 10, + b"12345-p1".to_vec() + )); assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); // Propose and accept curator for child-bounty. let fee = 8; - assert_ok!(ChildBounties::propose_curator(Origin::signed(4), 0, 0, 8, fee)); - assert_ok!(ChildBounties::accept_curator(Origin::signed(8), 0, 0)); + assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, fee)); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(8), 0, 0)); // Award child-bounty. // Test for non child-bounty curator. assert_noop!( - ChildBounties::award_child_bounty(Origin::signed(3), 0, 0, 7), + ChildBounties::award_child_bounty(RuntimeOrigin::signed(3), 0, 0, 7), BountiesError::RequireCurator, ); - assert_ok!(ChildBounties::award_child_bounty(Origin::signed(8), 0, 0, 7)); + assert_ok!(ChildBounties::award_child_bounty(RuntimeOrigin::signed(8), 0, 0, 7)); let expected_deposit = CuratorDepositMultiplier::get() * fee; assert_eq!( @@ -451,13 +466,13 @@ fn award_claim_child_bounty() { // Claim child-bounty. // Test for Premature condition. assert_noop!( - ChildBounties::claim_child_bounty(Origin::signed(7), 0, 0), + ChildBounties::claim_child_bounty(RuntimeOrigin::signed(7), 0, 0), BountiesError::Premature ); System::set_block_number(9); - assert_ok!(ChildBounties::claim_child_bounty(Origin::signed(7), 0, 0)); + assert_ok!(ChildBounties::claim_child_bounty(RuntimeOrigin::signed(7), 0, 0)); // Ensure child-bounty curator is paid with curator fee & deposit refund. assert_eq!(Balances::free_balance(8), 101 + fee); @@ -489,19 +504,24 @@ fn close_child_bounty_added() { Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. Balances::make_free_balance_be(&8, 101); // Child-bounty curator. - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, 6)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); // Child-bounty. - assert_ok!(ChildBounties::add_child_bounty(Origin::signed(4), 0, 10, b"12345-p1".to_vec())); + assert_ok!(ChildBounties::add_child_bounty( + RuntimeOrigin::signed(4), + 0, + 10, + b"12345-p1".to_vec() + )); assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); @@ -509,11 +529,11 @@ fn close_child_bounty_added() { // Close child-bounty. // Wrong origin. - assert_noop!(ChildBounties::close_child_bounty(Origin::signed(7), 0, 0), BadOrigin); - assert_noop!(ChildBounties::close_child_bounty(Origin::signed(8), 0, 0), BadOrigin); + assert_noop!(ChildBounties::close_child_bounty(RuntimeOrigin::signed(7), 0, 0), BadOrigin); + assert_noop!(ChildBounties::close_child_bounty(RuntimeOrigin::signed(8), 0, 0), BadOrigin); // Correct origin - parent curator. - assert_ok!(ChildBounties::close_child_bounty(Origin::signed(4), 0, 0)); + assert_ok!(ChildBounties::close_child_bounty(RuntimeOrigin::signed(4), 0, 0)); // Check the child-bounty count. assert_eq!(ChildBounties::parent_child_bounties(0), 0); @@ -541,28 +561,33 @@ fn close_child_bounty_active() { Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. Balances::make_free_balance_be(&8, 101); // Child-bounty curator. - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, 6)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); // Child-bounty. - assert_ok!(ChildBounties::add_child_bounty(Origin::signed(4), 0, 10, b"12345-p1".to_vec())); + assert_ok!(ChildBounties::add_child_bounty( + RuntimeOrigin::signed(4), + 0, + 10, + b"12345-p1".to_vec() + )); assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); // Propose and accept curator for child-bounty. - assert_ok!(ChildBounties::propose_curator(Origin::signed(4), 0, 0, 8, 2)); - assert_ok!(ChildBounties::accept_curator(Origin::signed(8), 0, 0)); + assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, 2)); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(8), 0, 0)); // Close child-bounty in active state. - assert_ok!(ChildBounties::close_child_bounty(Origin::signed(4), 0, 0)); + assert_ok!(ChildBounties::close_child_bounty(RuntimeOrigin::signed(4), 0, 0)); // Check the child-bounty count. assert_eq!(ChildBounties::parent_child_bounties(0), 0); @@ -594,33 +619,38 @@ fn close_child_bounty_pending() { Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. Balances::make_free_balance_be(&8, 101); // Child-bounty curator. - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); let parent_fee = 6; - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, parent_fee)); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, parent_fee)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); // Child-bounty. - assert_ok!(ChildBounties::add_child_bounty(Origin::signed(4), 0, 10, b"12345-p1".to_vec())); + assert_ok!(ChildBounties::add_child_bounty( + RuntimeOrigin::signed(4), + 0, + 10, + b"12345-p1".to_vec() + )); assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); // Propose and accept curator for child-bounty. let child_fee = 4; - assert_ok!(ChildBounties::propose_curator(Origin::signed(4), 0, 0, 8, child_fee)); - assert_ok!(ChildBounties::accept_curator(Origin::signed(8), 0, 0)); + assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, child_fee)); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(8), 0, 0)); let expected_child_deposit = CuratorDepositMin::get(); - assert_ok!(ChildBounties::award_child_bounty(Origin::signed(8), 0, 0, 7)); + assert_ok!(ChildBounties::award_child_bounty(RuntimeOrigin::signed(8), 0, 0, 7)); // Close child-bounty in pending_payout state. assert_noop!( - ChildBounties::close_child_bounty(Origin::signed(4), 0, 0), + ChildBounties::close_child_bounty(RuntimeOrigin::signed(4), 0, 0), BountiesError::PendingPayout ); @@ -650,25 +680,30 @@ fn child_bounty_added_unassign_curator() { Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. Balances::make_free_balance_be(&8, 101); // Child-bounty curator. - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, 6)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); // Child-bounty. - assert_ok!(ChildBounties::add_child_bounty(Origin::signed(4), 0, 10, b"12345-p1".to_vec())); + assert_ok!(ChildBounties::add_child_bounty( + RuntimeOrigin::signed(4), + 0, + 10, + b"12345-p1".to_vec() + )); assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); // Unassign curator in added state. assert_noop!( - ChildBounties::unassign_curator(Origin::signed(4), 0, 0), + ChildBounties::unassign_curator(RuntimeOrigin::signed(4), 0, 0), BountiesError::UnexpectedStatus ); }); @@ -687,24 +722,29 @@ fn child_bounty_curator_proposed_unassign_curator() { Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. Balances::make_free_balance_be(&8, 101); // Child-bounty curator. - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, 6)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); // Child-bounty. - assert_ok!(ChildBounties::add_child_bounty(Origin::signed(4), 0, 10, b"12345-p1".to_vec())); + assert_ok!(ChildBounties::add_child_bounty( + RuntimeOrigin::signed(4), + 0, + 10, + b"12345-p1".to_vec() + )); assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); // Propose curator for child-bounty. - assert_ok!(ChildBounties::propose_curator(Origin::signed(4), 0, 0, 8, 2)); + assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, 2)); assert_eq!( ChildBounties::child_bounties(0, 0).unwrap(), @@ -718,10 +758,10 @@ fn child_bounty_curator_proposed_unassign_curator() { ); // Random account cannot unassign the curator when in proposed state. - assert_noop!(ChildBounties::unassign_curator(Origin::signed(99), 0, 0), BadOrigin); + assert_noop!(ChildBounties::unassign_curator(RuntimeOrigin::signed(99), 0, 0), BadOrigin); // Unassign curator. - assert_ok!(ChildBounties::unassign_curator(Origin::signed(4), 0, 0)); + assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(4), 0, 0)); // Verify updated child-bounty status. assert_eq!( @@ -759,18 +799,23 @@ fn child_bounty_active_unassign_curator() { Balances::make_free_balance_be(&7, 101); // Child-bounty curator 2. Balances::make_free_balance_be(&8, 101); // Child-bounty curator 3. - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, 6)); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); // Create Child-bounty. - assert_ok!(ChildBounties::add_child_bounty(Origin::signed(4), 0, 10, b"12345-p1".to_vec())); + assert_ok!(ChildBounties::add_child_bounty( + RuntimeOrigin::signed(4), + 0, + 10, + b"12345-p1".to_vec() + )); assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); System::set_block_number(3); @@ -778,8 +823,8 @@ fn child_bounty_active_unassign_curator() { // Propose and accept curator for child-bounty. let fee = 6; - assert_ok!(ChildBounties::propose_curator(Origin::signed(4), 0, 0, 8, fee)); - assert_ok!(ChildBounties::accept_curator(Origin::signed(8), 0, 0)); + assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, fee)); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(8), 0, 0)); let expected_child_deposit = CuratorDepositMultiplier::get() * fee; assert_eq!( @@ -797,7 +842,7 @@ fn child_bounty_active_unassign_curator() { >::on_initialize(4); // Unassign curator - from reject origin. - assert_ok!(ChildBounties::unassign_curator(Origin::root(), 0, 0)); + assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::root(), 0, 0)); // Verify updated child-bounty status. assert_eq!( @@ -817,8 +862,8 @@ fn child_bounty_active_unassign_curator() { // Propose and accept curator for child-bounty again. let fee = 2; - assert_ok!(ChildBounties::propose_curator(Origin::signed(4), 0, 0, 7, fee)); - assert_ok!(ChildBounties::accept_curator(Origin::signed(7), 0, 0)); + assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 7, fee)); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(7), 0, 0)); let expected_child_deposit = CuratorDepositMin::get(); assert_eq!( @@ -836,7 +881,7 @@ fn child_bounty_active_unassign_curator() { >::on_initialize(5); // Unassign curator again - from parent curator. - assert_ok!(ChildBounties::unassign_curator(Origin::signed(4), 0, 0)); + assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(4), 0, 0)); // Verify updated child-bounty status. assert_eq!( @@ -855,8 +900,8 @@ fn child_bounty_active_unassign_curator() { assert_eq!(Balances::reserved_balance(7), 0); // slashed // Propose and accept curator for child-bounty again. - assert_ok!(ChildBounties::propose_curator(Origin::signed(4), 0, 0, 6, 2)); - assert_ok!(ChildBounties::accept_curator(Origin::signed(6), 0, 0)); + assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 6, 2)); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(6), 0, 0)); assert_eq!( ChildBounties::child_bounties(0, 0).unwrap(), @@ -873,7 +918,7 @@ fn child_bounty_active_unassign_curator() { >::on_initialize(6); // Unassign curator again - from child-bounty curator. - assert_ok!(ChildBounties::unassign_curator(Origin::signed(6), 0, 0)); + assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(6), 0, 0)); // Verify updated child-bounty status. assert_eq!( @@ -893,8 +938,8 @@ fn child_bounty_active_unassign_curator() { // Propose and accept curator for child-bounty one last time. let fee = 2; - assert_ok!(ChildBounties::propose_curator(Origin::signed(4), 0, 0, 6, fee)); - assert_ok!(ChildBounties::accept_curator(Origin::signed(6), 0, 0)); + assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 6, fee)); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(6), 0, 0)); let expected_child_deposit = CuratorDepositMin::get(); assert_eq!( @@ -914,7 +959,7 @@ fn child_bounty_active_unassign_curator() { // Unassign curator again - from non curator; non reject origin; some random guy. // Bounty update period is not yet complete. assert_noop!( - ChildBounties::unassign_curator(Origin::signed(3), 0, 0), + ChildBounties::unassign_curator(RuntimeOrigin::signed(3), 0, 0), BountiesError::Premature ); @@ -922,7 +967,7 @@ fn child_bounty_active_unassign_curator() { >::on_initialize(20); // Unassign child curator from random account after inactivity. - assert_ok!(ChildBounties::unassign_curator(Origin::signed(3), 0, 0)); + assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(3), 0, 0)); // Verify updated child-bounty status. assert_eq!( @@ -960,17 +1005,22 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { Balances::make_free_balance_be(&7, 101); // Child-bounty curator 2. Balances::make_free_balance_be(&8, 101); // Child-bounty curator 3. - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, 6)); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); // Create Child-bounty. - assert_ok!(ChildBounties::add_child_bounty(Origin::signed(4), 0, 10, b"12345-p1".to_vec())); + assert_ok!(ChildBounties::add_child_bounty( + RuntimeOrigin::signed(4), + 0, + 10, + b"12345-p1".to_vec() + )); assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); System::set_block_number(3); @@ -978,8 +1028,8 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { // Propose and accept curator for child-bounty. let fee = 8; - assert_ok!(ChildBounties::propose_curator(Origin::signed(4), 0, 0, 8, fee)); - assert_ok!(ChildBounties::accept_curator(Origin::signed(8), 0, 0)); + assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, fee)); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(8), 0, 0)); let expected_child_deposit = CuratorDepositMultiplier::get() * fee; assert_eq!( @@ -997,7 +1047,7 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { >::on_initialize(4); // Unassign parent bounty curator. - assert_ok!(Bounties::unassign_curator(Origin::root(), 0)); + assert_ok!(Bounties::unassign_curator(RuntimeOrigin::root(), 0)); System::set_block_number(5); >::on_initialize(5); @@ -1005,12 +1055,12 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { // Try unassign child-bounty curator - from non curator; non reject // origin; some random guy. Bounty update period is not yet complete. assert_noop!( - ChildBounties::unassign_curator(Origin::signed(3), 0, 0), + ChildBounties::unassign_curator(RuntimeOrigin::signed(3), 0, 0), Error::::ParentBountyNotActive ); // Unassign curator - from reject origin. - assert_ok!(ChildBounties::unassign_curator(Origin::root(), 0, 0)); + assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::root(), 0, 0)); // Verify updated child-bounty status. assert_eq!( @@ -1032,16 +1082,16 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { >::on_initialize(6); // Propose and accept curator for parent-bounty again. - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 5, 6)); - assert_ok!(Bounties::accept_curator(Origin::signed(5), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 5, 6)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(5), 0)); System::set_block_number(7); >::on_initialize(7); // Propose and accept curator for child-bounty again. let fee = 2; - assert_ok!(ChildBounties::propose_curator(Origin::signed(5), 0, 0, 7, fee)); - assert_ok!(ChildBounties::accept_curator(Origin::signed(7), 0, 0)); + assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(5), 0, 0, 7, fee)); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(7), 0, 0)); let expected_deposit = CuratorDepositMin::get(); assert_eq!( @@ -1059,18 +1109,18 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { >::on_initialize(8); assert_noop!( - ChildBounties::unassign_curator(Origin::signed(3), 0, 0), + ChildBounties::unassign_curator(RuntimeOrigin::signed(3), 0, 0), BountiesError::Premature ); // Unassign parent bounty curator again. - assert_ok!(Bounties::unassign_curator(Origin::signed(5), 0)); + assert_ok!(Bounties::unassign_curator(RuntimeOrigin::signed(5), 0)); System::set_block_number(9); >::on_initialize(9); // Unassign curator again - from parent curator. - assert_ok!(ChildBounties::unassign_curator(Origin::signed(7), 0, 0)); + assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(7), 0, 0)); // Verify updated child-bounty status. assert_eq!( @@ -1103,24 +1153,29 @@ fn close_parent_with_child_bounty() { Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. Balances::make_free_balance_be(&8, 101); // Child-bounty curator. - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); // Try add child-bounty. // Should fail, parent bounty not active yet. assert_noop!( - ChildBounties::add_child_bounty(Origin::signed(4), 0, 10, b"12345-p1".to_vec()), + ChildBounties::add_child_bounty(RuntimeOrigin::signed(4), 0, 10, b"12345-p1".to_vec()), Error::::ParentBountyNotActive ); System::set_block_number(2); >::on_initialize(2); - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, 6)); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); // Child-bounty. - assert_ok!(ChildBounties::add_child_bounty(Origin::signed(4), 0, 10, b"12345-p1".to_vec())); + assert_ok!(ChildBounties::add_child_bounty( + RuntimeOrigin::signed(4), + 0, + 10, + b"12345-p1".to_vec() + )); assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); System::set_block_number(4); @@ -1129,21 +1184,21 @@ fn close_parent_with_child_bounty() { // Try close parent-bounty. // Child bounty active, can't close parent. assert_noop!( - Bounties::close_bounty(Origin::root(), 0), + Bounties::close_bounty(RuntimeOrigin::root(), 0), BountiesError::HasActiveChildBounty ); System::set_block_number(2); // Close child-bounty. - assert_ok!(ChildBounties::close_child_bounty(Origin::root(), 0, 0)); + assert_ok!(ChildBounties::close_child_bounty(RuntimeOrigin::root(), 0, 0)); // Check the child-bounty count. assert_eq!(ChildBounties::parent_child_bounties(0), 0); // Try close parent-bounty again. // Should pass this time. - assert_ok!(Bounties::close_bounty(Origin::root(), 0)); + assert_ok!(Bounties::close_bounty(RuntimeOrigin::root(), 0)); }); } @@ -1162,17 +1217,22 @@ fn children_curator_fee_calculation_test() { Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. Balances::make_free_balance_be(&8, 101); // Child-bounty curator. - assert_ok!(Bounties::propose_bounty(Origin::signed(0), 50, b"12345".to_vec())); - assert_ok!(Bounties::approve_bounty(Origin::root(), 0)); + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); System::set_block_number(2); >::on_initialize(2); - assert_ok!(Bounties::propose_curator(Origin::root(), 0, 4, 6)); - assert_ok!(Bounties::accept_curator(Origin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); // Child-bounty. - assert_ok!(ChildBounties::add_child_bounty(Origin::signed(4), 0, 10, b"12345-p1".to_vec())); + assert_ok!(ChildBounties::add_child_bounty( + RuntimeOrigin::signed(4), + 0, + 10, + b"12345-p1".to_vec() + )); assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); System::set_block_number(4); @@ -1181,13 +1241,13 @@ fn children_curator_fee_calculation_test() { let fee = 6; // Propose curator for child-bounty. - assert_ok!(ChildBounties::propose_curator(Origin::signed(4), 0, 0, 8, fee)); + assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, fee)); // Check curator fee added to the sum. assert_eq!(ChildBounties::children_curator_fees(0), fee); // Accept curator for child-bounty. - assert_ok!(ChildBounties::accept_curator(Origin::signed(8), 0, 0)); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(8), 0, 0)); // Award child-bounty. - assert_ok!(ChildBounties::award_child_bounty(Origin::signed(8), 0, 0, 7)); + assert_ok!(ChildBounties::award_child_bounty(RuntimeOrigin::signed(8), 0, 0, 7)); let expected_child_deposit = CuratorDepositMultiplier::get() * fee; @@ -1209,18 +1269,18 @@ fn children_curator_fee_calculation_test() { System::set_block_number(9); // Claim child-bounty. - assert_ok!(ChildBounties::claim_child_bounty(Origin::signed(7), 0, 0)); + assert_ok!(ChildBounties::claim_child_bounty(RuntimeOrigin::signed(7), 0, 0)); // Check the child-bounty count. assert_eq!(ChildBounties::parent_child_bounties(0), 0); // Award the parent bounty. - assert_ok!(Bounties::award_bounty(Origin::signed(4), 0, 9)); + assert_ok!(Bounties::award_bounty(RuntimeOrigin::signed(4), 0, 9)); System::set_block_number(15); // Claim the parent bounty. - assert_ok!(Bounties::claim_bounty(Origin::signed(9), 0)); + assert_ok!(Bounties::claim_bounty(RuntimeOrigin::signed(9), 0)); // Ensure parent-bounty curator received correctly reduced fee. assert_eq!(Balances::free_balance(4), 101 + 6 - fee); // 101 + 6 - 2 @@ -1247,22 +1307,22 @@ fn accept_curator_handles_different_deposit_calculations() { Balances::make_free_balance_be(&Treasury::account_id(), parent_value * 3); Balances::make_free_balance_be(&parent_curator, parent_fee * 100); assert_ok!(Bounties::propose_bounty( - Origin::signed(parent_curator), + RuntimeOrigin::signed(parent_curator), parent_value, b"12345".to_vec() )); - assert_ok!(Bounties::approve_bounty(Origin::root(), parent_index)); + assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), parent_index)); System::set_block_number(2); >::on_initialize(2); assert_ok!(Bounties::propose_curator( - Origin::root(), + RuntimeOrigin::root(), parent_index, parent_curator, parent_fee )); - assert_ok!(Bounties::accept_curator(Origin::signed(parent_curator), parent_index)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(parent_curator), parent_index)); // Now we can start creating some child bounties. // Case 1: Parent and child curator are not the same. @@ -1275,7 +1335,7 @@ fn accept_curator_handles_different_deposit_calculations() { Balances::make_free_balance_be(&child_curator, starting_balance); assert_ok!(ChildBounties::add_child_bounty( - Origin::signed(parent_curator), + RuntimeOrigin::signed(parent_curator), parent_index, child_value, b"12345-p1".to_vec() @@ -1283,14 +1343,14 @@ fn accept_curator_handles_different_deposit_calculations() { System::set_block_number(3); >::on_initialize(3); assert_ok!(ChildBounties::propose_curator( - Origin::signed(parent_curator), + RuntimeOrigin::signed(parent_curator), parent_index, child_index, child_curator, child_fee )); assert_ok!(ChildBounties::accept_curator( - Origin::signed(child_curator), + RuntimeOrigin::signed(child_curator), parent_index, child_index )); @@ -1310,7 +1370,7 @@ fn accept_curator_handles_different_deposit_calculations() { let reserved_before = Balances::reserved_balance(&parent_curator); assert_ok!(ChildBounties::add_child_bounty( - Origin::signed(parent_curator), + RuntimeOrigin::signed(parent_curator), parent_index, child_value, b"12345-p1".to_vec() @@ -1318,14 +1378,14 @@ fn accept_curator_handles_different_deposit_calculations() { System::set_block_number(4); >::on_initialize(4); assert_ok!(ChildBounties::propose_curator( - Origin::signed(parent_curator), + RuntimeOrigin::signed(parent_curator), parent_index, child_index, child_curator, child_fee )); assert_ok!(ChildBounties::accept_curator( - Origin::signed(child_curator), + RuntimeOrigin::signed(child_curator), parent_index, child_index )); @@ -1343,7 +1403,7 @@ fn accept_curator_handles_different_deposit_calculations() { Balances::make_free_balance_be(&child_curator, starting_balance); assert_ok!(ChildBounties::add_child_bounty( - Origin::signed(parent_curator), + RuntimeOrigin::signed(parent_curator), parent_index, child_value, b"12345-p1".to_vec() @@ -1351,14 +1411,14 @@ fn accept_curator_handles_different_deposit_calculations() { System::set_block_number(5); >::on_initialize(5); assert_ok!(ChildBounties::propose_curator( - Origin::signed(parent_curator), + RuntimeOrigin::signed(parent_curator), parent_index, child_index, child_curator, child_fee )); assert_ok!(ChildBounties::accept_curator( - Origin::signed(child_curator), + RuntimeOrigin::signed(child_curator), parent_index, child_index )); @@ -1379,7 +1439,7 @@ fn accept_curator_handles_different_deposit_calculations() { Balances::make_free_balance_be(&child_curator, starting_balance); assert_ok!(ChildBounties::add_child_bounty( - Origin::signed(parent_curator), + RuntimeOrigin::signed(parent_curator), parent_index, child_value, b"12345-p1".to_vec() @@ -1387,14 +1447,14 @@ fn accept_curator_handles_different_deposit_calculations() { System::set_block_number(5); >::on_initialize(5); assert_ok!(ChildBounties::propose_curator( - Origin::signed(parent_curator), + RuntimeOrigin::signed(parent_curator), parent_index, child_index, child_curator, child_fee )); assert_ok!(ChildBounties::accept_curator( - Origin::signed(child_curator), + RuntimeOrigin::signed(child_curator), parent_index, child_index )); diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 49da641e3e204..e934924033552 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -181,12 +181,14 @@ pub mod pallet { #[pallet::config] pub trait Config: frame_system::Config { /// The outer origin type. - type Origin: From>; + type RuntimeOrigin: From>; /// The outer call dispatch type. type Proposal: Parameter - + Dispatchable>::Origin, PostInfo = PostDispatchInfo> - + From> + + Dispatchable< + RuntimeOrigin = >::RuntimeOrigin, + PostInfo = PostDispatchInfo, + > + From> + GetDispatchInfo; /// The outer event type. diff --git a/frame/collective/src/tests.rs b/frame/collective/src/tests.rs index 13b9a24f7889d..19c54e0493c7b 100644 --- a/frame/collective/src/tests.rs +++ b/frame/collective/src/tests.rs @@ -64,7 +64,7 @@ mod mock_democracy { pub trait Config: frame_system::Config + Sized { type RuntimeEvent: From> + IsType<::RuntimeEvent>; - type ExternalMajorityOrigin: EnsureOrigin; + type ExternalMajorityOrigin: EnsureOrigin; } #[pallet::call] @@ -98,7 +98,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; @@ -120,7 +120,7 @@ impl frame_system::Config for Test { type MaxConsumers = ConstU32<16>; } impl Config for Test { - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Proposal = RuntimeCall; type RuntimeEvent = RuntimeEvent; type MotionDuration = ConstU64<3>; @@ -130,7 +130,7 @@ impl Config for Test { type WeightInfo = (); } impl Config for Test { - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Proposal = RuntimeCall; type RuntimeEvent = RuntimeEvent; type MotionDuration = ConstU64<3>; @@ -144,7 +144,7 @@ impl mock_democracy::Config for Test { type ExternalMajorityOrigin = EnsureProportionAtLeast; } impl Config for Test { - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Proposal = RuntimeCall; type RuntimeEvent = RuntimeEvent; type MotionDuration = ConstU64<3>; @@ -200,22 +200,28 @@ fn close_works() { let hash = BlakeTwo256::hash_of(&proposal); assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len )); - assert_ok!(Collective::vote(Origin::signed(1), hash, 0, true)); - assert_ok!(Collective::vote(Origin::signed(2), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, true)); System::set_block_number(3); assert_noop!( - Collective::close(Origin::signed(4), hash, 0, proposal_weight, proposal_len), + Collective::close(RuntimeOrigin::signed(4), hash, 0, proposal_weight, proposal_len), Error::::TooEarly ); System::set_block_number(4); - assert_ok!(Collective::close(Origin::signed(4), hash, 0, proposal_weight, proposal_len)); + assert_ok!(Collective::close( + RuntimeOrigin::signed(4), + hash, + 0, + proposal_weight, + proposal_len + )); assert_eq!( System::events(), @@ -267,17 +273,17 @@ fn proposal_weight_limit_works_on_approve() { // Set 1 as prime voter Prime::::set(Some(1)); assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len )); - assert_ok!(Collective::vote(Origin::signed(1), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); // With 1's prime vote, this should pass System::set_block_number(4); assert_noop!( Collective::close( - Origin::signed(4), + RuntimeOrigin::signed(4), hash, 0, proposal_weight - Weight::from_ref_time(100), @@ -285,7 +291,13 @@ fn proposal_weight_limit_works_on_approve() { ), Error::::WrongProposalWeight ); - assert_ok!(Collective::close(Origin::signed(4), hash, 0, proposal_weight, proposal_len)); + assert_ok!(Collective::close( + RuntimeOrigin::signed(4), + hash, + 0, + proposal_weight, + proposal_len + )); }) } @@ -302,7 +314,7 @@ fn proposal_weight_limit_ignored_on_disapprove() { let hash = BlakeTwo256::hash_of(&proposal); assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len @@ -310,7 +322,7 @@ fn proposal_weight_limit_ignored_on_disapprove() { // No votes, this proposal wont pass System::set_block_number(4); assert_ok!(Collective::close( - Origin::signed(4), + RuntimeOrigin::signed(4), hash, 0, proposal_weight - Weight::from_ref_time(100), @@ -327,23 +339,29 @@ fn close_with_prime_works() { let proposal_weight = proposal.get_dispatch_info().weight; let hash = BlakeTwo256::hash_of(&proposal); assert_ok!(Collective::set_members( - Origin::root(), + RuntimeOrigin::root(), vec![1, 2, 3], Some(3), MaxMembers::get() )); assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len )); - assert_ok!(Collective::vote(Origin::signed(1), hash, 0, true)); - assert_ok!(Collective::vote(Origin::signed(2), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, true)); System::set_block_number(4); - assert_ok!(Collective::close(Origin::signed(4), hash, 0, proposal_weight, proposal_len)); + assert_ok!(Collective::close( + RuntimeOrigin::signed(4), + hash, + 0, + proposal_weight, + proposal_len + )); assert_eq!( System::events(), @@ -389,23 +407,29 @@ fn close_with_voting_prime_works() { let proposal_weight = proposal.get_dispatch_info().weight; let hash = BlakeTwo256::hash_of(&proposal); assert_ok!(Collective::set_members( - Origin::root(), + RuntimeOrigin::root(), vec![1, 2, 3], Some(1), MaxMembers::get() )); assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len )); - assert_ok!(Collective::vote(Origin::signed(1), hash, 0, true)); - assert_ok!(Collective::vote(Origin::signed(2), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, true)); System::set_block_number(4); - assert_ok!(Collective::close(Origin::signed(4), hash, 0, proposal_weight, proposal_len)); + assert_ok!(Collective::close( + RuntimeOrigin::signed(4), + hash, + 0, + proposal_weight, + proposal_len + )); assert_eq!( System::events(), @@ -453,25 +477,25 @@ fn close_with_no_prime_but_majority_works() { let proposal_weight = proposal.get_dispatch_info().weight; let hash = BlakeTwo256::hash_of(&proposal); assert_ok!(CollectiveMajority::set_members( - Origin::root(), + RuntimeOrigin::root(), vec![1, 2, 3, 4, 5], Some(5), MaxMembers::get() )); assert_ok!(CollectiveMajority::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 5, Box::new(proposal.clone()), proposal_len )); - assert_ok!(CollectiveMajority::vote(Origin::signed(1), hash, 0, true)); - assert_ok!(CollectiveMajority::vote(Origin::signed(2), hash, 0, true)); - assert_ok!(CollectiveMajority::vote(Origin::signed(3), hash, 0, true)); + assert_ok!(CollectiveMajority::vote(RuntimeOrigin::signed(1), hash, 0, true)); + assert_ok!(CollectiveMajority::vote(RuntimeOrigin::signed(2), hash, 0, true)); + assert_ok!(CollectiveMajority::vote(RuntimeOrigin::signed(3), hash, 0, true)); System::set_block_number(4); assert_ok!(CollectiveMajority::close( - Origin::signed(4), + RuntimeOrigin::signed(4), hash, 0, proposal_weight, @@ -533,13 +557,13 @@ fn removal_of_old_voters_votes_works() { let hash = BlakeTwo256::hash_of(&proposal); let end = 4; assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len )); - assert_ok!(Collective::vote(Origin::signed(1), hash, 0, true)); - assert_ok!(Collective::vote(Origin::signed(2), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, true)); assert_eq!( Collective::voting(&hash), Some(Votes { index: 0, threshold: 3, ayes: vec![1, 2], nays: vec![], end }) @@ -554,13 +578,13 @@ fn removal_of_old_voters_votes_works() { let proposal_len: u32 = proposal.using_encoded(|p| p.len() as u32); let hash = BlakeTwo256::hash_of(&proposal); assert_ok!(Collective::propose( - Origin::signed(2), + RuntimeOrigin::signed(2), 2, Box::new(proposal.clone()), proposal_len )); - assert_ok!(Collective::vote(Origin::signed(2), hash, 1, true)); - assert_ok!(Collective::vote(Origin::signed(3), hash, 1, false)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 1, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(3), hash, 1, false)); assert_eq!( Collective::voting(&hash), Some(Votes { index: 1, threshold: 2, ayes: vec![2], nays: vec![3], end }) @@ -581,18 +605,23 @@ fn removal_of_old_voters_votes_works_with_set_members() { let hash = BlakeTwo256::hash_of(&proposal); let end = 4; assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len )); - assert_ok!(Collective::vote(Origin::signed(1), hash, 0, true)); - assert_ok!(Collective::vote(Origin::signed(2), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, true)); assert_eq!( Collective::voting(&hash), Some(Votes { index: 0, threshold: 3, ayes: vec![1, 2], nays: vec![], end }) ); - assert_ok!(Collective::set_members(Origin::root(), vec![2, 3, 4], None, MaxMembers::get())); + assert_ok!(Collective::set_members( + RuntimeOrigin::root(), + vec![2, 3, 4], + None, + MaxMembers::get() + )); assert_eq!( Collective::voting(&hash), Some(Votes { index: 0, threshold: 3, ayes: vec![2], nays: vec![], end }) @@ -602,18 +631,23 @@ fn removal_of_old_voters_votes_works_with_set_members() { let proposal_len: u32 = proposal.using_encoded(|p| p.len() as u32); let hash = BlakeTwo256::hash_of(&proposal); assert_ok!(Collective::propose( - Origin::signed(2), + RuntimeOrigin::signed(2), 2, Box::new(proposal.clone()), proposal_len )); - assert_ok!(Collective::vote(Origin::signed(2), hash, 1, true)); - assert_ok!(Collective::vote(Origin::signed(3), hash, 1, false)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 1, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(3), hash, 1, false)); assert_eq!( Collective::voting(&hash), Some(Votes { index: 1, threshold: 2, ayes: vec![2], nays: vec![3], end }) ); - assert_ok!(Collective::set_members(Origin::root(), vec![2, 4], None, MaxMembers::get())); + assert_ok!(Collective::set_members( + RuntimeOrigin::root(), + vec![2, 4], + None, + MaxMembers::get() + )); assert_eq!( Collective::voting(&hash), Some(Votes { index: 1, threshold: 2, ayes: vec![2], nays: vec![], end }) @@ -629,7 +663,7 @@ fn propose_works() { let hash = proposal.blake2_256().into(); let end = 4; assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len @@ -660,7 +694,7 @@ fn limit_active_proposals() { let proposal = make_proposal(i as u64); let proposal_len: u32 = proposal.using_encoded(|p| p.len() as u32); assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len @@ -669,7 +703,12 @@ fn limit_active_proposals() { let proposal = make_proposal(MaxProposals::get() as u64 + 1); let proposal_len: u32 = proposal.using_encoded(|p| p.len() as u32); assert_noop!( - Collective::propose(Origin::signed(1), 3, Box::new(proposal.clone()), proposal_len), + Collective::propose( + RuntimeOrigin::signed(1), + 3, + Box::new(proposal.clone()), + proposal_len + ), Error::::TooManyProposals ); }) @@ -684,7 +723,12 @@ fn correct_validate_and_get_proposal() { old_count: MaxMembers::get(), }); let length = proposal.encode().len() as u32; - assert_ok!(Collective::propose(Origin::signed(1), 3, Box::new(proposal.clone()), length)); + assert_ok!(Collective::propose( + RuntimeOrigin::signed(1), + 3, + Box::new(proposal.clone()), + length + )); let hash = BlakeTwo256::hash_of(&proposal); let weight = proposal.get_dispatch_info().weight; @@ -722,7 +766,12 @@ fn motions_ignoring_non_collective_proposals_works() { let proposal = make_proposal(42); let proposal_len: u32 = proposal.using_encoded(|p| p.len() as u32); assert_noop!( - Collective::propose(Origin::signed(42), 3, Box::new(proposal.clone()), proposal_len), + Collective::propose( + RuntimeOrigin::signed(42), + 3, + Box::new(proposal.clone()), + proposal_len + ), Error::::NotMember ); }); @@ -735,13 +784,13 @@ fn motions_ignoring_non_collective_votes_works() { let proposal_len: u32 = proposal.using_encoded(|p| p.len() as u32); let hash: H256 = proposal.blake2_256().into(); assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len )); assert_noop!( - Collective::vote(Origin::signed(42), hash, 0, true), + Collective::vote(RuntimeOrigin::signed(42), hash, 0, true), Error::::NotMember, ); }); @@ -755,13 +804,13 @@ fn motions_ignoring_bad_index_collective_vote_works() { let proposal_len: u32 = proposal.using_encoded(|p| p.len() as u32); let hash: H256 = proposal.blake2_256().into(); assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len )); assert_noop!( - Collective::vote(Origin::signed(2), hash, 1, true), + Collective::vote(RuntimeOrigin::signed(2), hash, 1, true), Error::::WrongIndex, ); }); @@ -775,7 +824,7 @@ fn motions_vote_after_works() { let hash: H256 = proposal.blake2_256().into(); let end = 4; assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, Box::new(proposal.clone()), proposal_len @@ -786,25 +835,25 @@ fn motions_vote_after_works() { Some(Votes { index: 0, threshold: 2, ayes: vec![], nays: vec![], end }) ); // Cast first aye vote. - assert_ok!(Collective::vote(Origin::signed(1), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); assert_eq!( Collective::voting(&hash), Some(Votes { index: 0, threshold: 2, ayes: vec![1], nays: vec![], end }) ); // Try to cast a duplicate aye vote. assert_noop!( - Collective::vote(Origin::signed(1), hash, 0, true), + Collective::vote(RuntimeOrigin::signed(1), hash, 0, true), Error::::DuplicateVote, ); // Cast a nay vote. - assert_ok!(Collective::vote(Origin::signed(1), hash, 0, false)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, false)); assert_eq!( Collective::voting(&hash), Some(Votes { index: 0, threshold: 2, ayes: vec![], nays: vec![1], end }) ); // Try to cast a duplicate nay vote. assert_noop!( - Collective::vote(Origin::signed(1), hash, 0, false), + Collective::vote(RuntimeOrigin::signed(1), hash, 0, false), Error::::DuplicateVote, ); @@ -844,7 +893,7 @@ fn motions_all_first_vote_free_works() { let hash: H256 = proposal.blake2_256().into(); let end = 4; assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, Box::new(proposal.clone()), proposal_len, @@ -856,40 +905,40 @@ fn motions_all_first_vote_free_works() { // For the motion, acc 2's first vote, expecting Ok with Pays::No. let vote_rval: DispatchResultWithPostInfo = - Collective::vote(Origin::signed(2), hash, 0, true); + Collective::vote(RuntimeOrigin::signed(2), hash, 0, true); assert_eq!(vote_rval.unwrap().pays_fee, Pays::No); // Duplicate vote, expecting error with Pays::Yes. let vote_rval: DispatchResultWithPostInfo = - Collective::vote(Origin::signed(2), hash, 0, true); + Collective::vote(RuntimeOrigin::signed(2), hash, 0, true); assert_eq!(vote_rval.unwrap_err().post_info.pays_fee, Pays::Yes); // Modifying vote, expecting ok with Pays::Yes. let vote_rval: DispatchResultWithPostInfo = - Collective::vote(Origin::signed(2), hash, 0, false); + Collective::vote(RuntimeOrigin::signed(2), hash, 0, false); assert_eq!(vote_rval.unwrap().pays_fee, Pays::Yes); // For the motion, acc 3's first vote, expecting Ok with Pays::No. let vote_rval: DispatchResultWithPostInfo = - Collective::vote(Origin::signed(3), hash, 0, true); + Collective::vote(RuntimeOrigin::signed(3), hash, 0, true); assert_eq!(vote_rval.unwrap().pays_fee, Pays::No); // acc 3 modify the vote, expecting Ok with Pays::Yes. let vote_rval: DispatchResultWithPostInfo = - Collective::vote(Origin::signed(3), hash, 0, false); + Collective::vote(RuntimeOrigin::signed(3), hash, 0, false); assert_eq!(vote_rval.unwrap().pays_fee, Pays::Yes); // Test close() Extrincis | Check DispatchResultWithPostInfo with Pay Info let proposal_weight = proposal.get_dispatch_info().weight; let close_rval: DispatchResultWithPostInfo = - Collective::close(Origin::signed(2), hash, 0, proposal_weight, proposal_len); + Collective::close(RuntimeOrigin::signed(2), hash, 0, proposal_weight, proposal_len); assert_eq!(close_rval.unwrap().pays_fee, Pays::No); // trying to close the proposal, which is already closed. // Expecting error "ProposalMissing" with Pays::Yes let close_rval: DispatchResultWithPostInfo = - Collective::close(Origin::signed(2), hash, 0, proposal_weight, proposal_len); + Collective::close(RuntimeOrigin::signed(2), hash, 0, proposal_weight, proposal_len); assert_eq!(close_rval.unwrap_err().post_info.pays_fee, Pays::Yes); }); } @@ -902,16 +951,22 @@ fn motions_reproposing_disapproved_works() { let proposal_weight = proposal.get_dispatch_info().weight; let hash: H256 = proposal.blake2_256().into(); assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len )); - assert_ok!(Collective::vote(Origin::signed(2), hash, 0, false)); - assert_ok!(Collective::close(Origin::signed(2), hash, 0, proposal_weight, proposal_len)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, false)); + assert_ok!(Collective::close( + RuntimeOrigin::signed(2), + hash, + 0, + proposal_weight, + proposal_len + )); assert_eq!(*Collective::proposals(), vec![]); assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, Box::new(proposal.clone()), proposal_len @@ -933,14 +988,20 @@ fn motions_approval_with_enough_votes_and_lower_voting_threshold_works() { // // Failed to execute with only 2 yes votes. assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, Box::new(proposal.clone()), proposal_len )); - assert_ok!(Collective::vote(Origin::signed(1), hash, 0, true)); - assert_ok!(Collective::vote(Origin::signed(2), hash, 0, true)); - assert_ok!(Collective::close(Origin::signed(2), hash, 0, proposal_weight, proposal_len)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, true)); + assert_ok!(Collective::close( + RuntimeOrigin::signed(2), + hash, + 0, + proposal_weight, + proposal_len + )); assert_eq!( System::events(), vec![ @@ -981,15 +1042,21 @@ fn motions_approval_with_enough_votes_and_lower_voting_threshold_works() { // Executed with 3 yes votes. assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, Box::new(proposal.clone()), proposal_len )); - assert_ok!(Collective::vote(Origin::signed(1), hash, 1, true)); - assert_ok!(Collective::vote(Origin::signed(2), hash, 1, true)); - assert_ok!(Collective::vote(Origin::signed(3), hash, 1, true)); - assert_ok!(Collective::close(Origin::signed(2), hash, 1, proposal_weight, proposal_len)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 1, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 1, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(3), hash, 1, true)); + assert_ok!(Collective::close( + RuntimeOrigin::signed(2), + hash, + 1, + proposal_weight, + proposal_len + )); assert_eq!( System::events(), vec![ @@ -1046,14 +1113,20 @@ fn motions_disapproval_works() { let proposal_weight = proposal.get_dispatch_info().weight; let hash: H256 = proposal.blake2_256().into(); assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len )); - assert_ok!(Collective::vote(Origin::signed(1), hash, 0, true)); - assert_ok!(Collective::vote(Origin::signed(2), hash, 0, false)); - assert_ok!(Collective::close(Origin::signed(2), hash, 0, proposal_weight, proposal_len)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, false)); + assert_ok!(Collective::close( + RuntimeOrigin::signed(2), + hash, + 0, + proposal_weight, + proposal_len + )); assert_eq!( System::events(), @@ -1099,14 +1172,20 @@ fn motions_approval_works() { let proposal_weight = proposal.get_dispatch_info().weight; let hash: H256 = proposal.blake2_256().into(); assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, Box::new(proposal.clone()), proposal_len )); - assert_ok!(Collective::vote(Origin::signed(1), hash, 0, true)); - assert_ok!(Collective::vote(Origin::signed(2), hash, 0, true)); - assert_ok!(Collective::close(Origin::signed(2), hash, 0, proposal_weight, proposal_len)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, true)); + assert_ok!(Collective::close( + RuntimeOrigin::signed(2), + hash, + 0, + proposal_weight, + proposal_len + )); assert_eq!( System::events(), @@ -1154,7 +1233,7 @@ fn motion_with_no_votes_closes_with_disapproval() { let proposal_weight = proposal.get_dispatch_info().weight; let hash: H256 = proposal.blake2_256().into(); assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, Box::new(proposal.clone()), proposal_len @@ -1172,7 +1251,7 @@ fn motion_with_no_votes_closes_with_disapproval() { // Closing the motion too early is not possible because it has neither // an approving or disapproving simple majority due to the lack of votes. assert_noop!( - Collective::close(Origin::signed(2), hash, 0, proposal_weight, proposal_len), + Collective::close(RuntimeOrigin::signed(2), hash, 0, proposal_weight, proposal_len), Error::::TooEarly ); @@ -1180,7 +1259,13 @@ fn motion_with_no_votes_closes_with_disapproval() { let closing_block = System::block_number() + MotionDuration::get(); System::set_block_number(closing_block); // we can successfully close the motion. - assert_ok!(Collective::close(Origin::signed(2), hash, 0, proposal_weight, proposal_len)); + assert_ok!(Collective::close( + RuntimeOrigin::signed(2), + hash, + 0, + proposal_weight, + proposal_len + )); // Events show that the close ended in a disapproval. assert_eq!( @@ -1208,28 +1293,28 @@ fn close_disapprove_does_not_care_about_weight_or_len() { let proposal_len: u32 = proposal.using_encoded(|p| p.len() as u32); let hash: H256 = proposal.blake2_256().into(); assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, Box::new(proposal.clone()), proposal_len )); // First we make the proposal succeed - assert_ok!(Collective::vote(Origin::signed(1), hash, 0, true)); - assert_ok!(Collective::vote(Origin::signed(2), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, true)); // It will not close with bad weight/len information assert_noop!( - Collective::close(Origin::signed(2), hash, 0, Weight::zero(), 0), + Collective::close(RuntimeOrigin::signed(2), hash, 0, Weight::zero(), 0), Error::::WrongProposalLength, ); assert_noop!( - Collective::close(Origin::signed(2), hash, 0, Weight::zero(), proposal_len), + Collective::close(RuntimeOrigin::signed(2), hash, 0, Weight::zero(), proposal_len), Error::::WrongProposalWeight, ); // Now we make the proposal fail - assert_ok!(Collective::vote(Origin::signed(1), hash, 0, false)); - assert_ok!(Collective::vote(Origin::signed(2), hash, 0, false)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, false)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, false)); // It can close even if the weight/len information is bad - assert_ok!(Collective::close(Origin::signed(2), hash, 0, Weight::zero(), 0)); + assert_ok!(Collective::close(RuntimeOrigin::signed(2), hash, 0, Weight::zero(), 0)); }) } @@ -1240,16 +1325,16 @@ fn disapprove_proposal_works() { let proposal_len: u32 = proposal.using_encoded(|p| p.len() as u32); let hash: H256 = proposal.blake2_256().into(); assert_ok!(Collective::propose( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, Box::new(proposal.clone()), proposal_len )); // Proposal would normally succeed - assert_ok!(Collective::vote(Origin::signed(1), hash, 0, true)); - assert_ok!(Collective::vote(Origin::signed(2), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); + assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, true)); // But Root can disapprove and remove it anyway - assert_ok!(Collective::disapprove_proposal(Origin::root(), hash)); + assert_ok!(Collective::disapprove_proposal(RuntimeOrigin::root(), hash)); assert_eq!( System::events(), vec![ diff --git a/frame/contracts/Cargo.toml b/frame/contracts/Cargo.toml index e9a90504d7db7..30fbad680ebe5 100644 --- a/frame/contracts/Cargo.toml +++ b/frame/contracts/Cargo.toml @@ -45,9 +45,9 @@ sp-sandbox = { version = "0.10.0-dev", default-features = false, path = "../../p sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } [dev-dependencies] +array-bytes = "4.1" assert_matches = "1" env_logger = "0.9" -hex-literal = "0.3" pretty_assertions = "1" wat = "1" diff --git a/frame/contracts/fixtures/create_storage_and_call.wat b/frame/contracts/fixtures/create_storage_and_call.wat new file mode 100644 index 0000000000000..2a1e53f7ce08a --- /dev/null +++ b/frame/contracts/fixtures/create_storage_and_call.wat @@ -0,0 +1,55 @@ +;; This calls another contract as passed as its account id. It also creates some storage. +(module + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_set_storage" (func $seal_set_storage (param i32 i32 i32))) + (import "seal1" "seal_call" (func $seal_call (param i32 i32 i64 i32 i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + (func $assert (param i32) + (block $ok + (br_if $ok + (get_local 0) + ) + (unreachable) + ) + ) + + (func (export "deploy")) + + (func (export "call") + ;; store length of input buffer + (i32.store (i32.const 0) (i32.const 512)) + + ;; copy input at address 4 + (call $seal_input (i32.const 4) (i32.const 0)) + + ;; create 4 byte of storage before calling + (call $seal_set_storage + (i32.const 0) ;; Pointer to storage key + (i32.const 0) ;; Pointer to value + (i32.const 4) ;; Size of value + ) + + ;; call passed contract + (call $assert (i32.eqz + (call $seal_call + (i32.const 0) ;; No flags + (i32.const 8) ;; Pointer to "callee" address. + (i64.const 0) ;; How much gas to devote for the execution. 0 = all. + (i32.const 512) ;; Pointer to the buffer with value to transfer + (i32.const 4) ;; Pointer to input data buffer address + (i32.const 4) ;; Length of input data buffer + (i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output + (i32.const 0) ;; Length is ignored in this case + ) + )) + + ;; create 8 byte of storage after calling + ;; item of 12 bytes because we override 4 bytes + (call $seal_set_storage + (i32.const 0) ;; Pointer to storage key + (i32.const 0) ;; Pointer to value + (i32.const 12) ;; Size of value + ) + ) +) diff --git a/frame/contracts/src/benchmarking/mod.rs b/frame/contracts/src/benchmarking/mod.rs index 4a987fd8dde78..186ac6f63503e 100644 --- a/frame/contracts/src/benchmarking/mod.rs +++ b/frame/contracts/src/benchmarking/mod.rs @@ -87,7 +87,7 @@ where module: WasmModule, data: Vec, ) -> Result, &'static str> { - let value = T::Currency::minimum_balance(); + let value = Pallet::::min_balance(); T::Currency::make_free_balance_be(&caller, caller_funding::()); let salt = vec![0xff]; let addr = Contracts::::contract_address(&caller, &module.hash, &salt); @@ -257,7 +257,7 @@ benchmarks! { let instance = Contract::::with_caller( whitelisted_caller(), WasmModule::sized(c, Location::Deploy), vec![], )?; - let value = T::Currency::minimum_balance(); + let value = Pallet::::min_balance(); let origin = RawOrigin::Signed(instance.caller.clone()); let callee = instance.addr; }: call(origin, callee, value, Weight::MAX, None, vec![]) @@ -280,7 +280,7 @@ benchmarks! { let c in 0 .. Perbill::from_percent(49).mul_ceil(T::MaxCodeLen::get()); let s in 0 .. code::max_pages::() * 64 * 1024; let salt = vec![42u8; s as usize]; - let value = T::Currency::minimum_balance(); + let value = Pallet::::min_balance(); let caller = whitelisted_caller(); T::Currency::make_free_balance_be(&caller, caller_funding::()); let WasmModule { code, hash, .. } = WasmModule::::sized(c, Location::Call); @@ -307,7 +307,7 @@ benchmarks! { instantiate { let s in 0 .. code::max_pages::() * 64 * 1024; let salt = vec![42u8; s as usize]; - let value = T::Currency::minimum_balance(); + let value = Pallet::::min_balance(); let caller = whitelisted_caller(); T::Currency::make_free_balance_be(&caller, caller_funding::()); let WasmModule { code, hash, .. } = WasmModule::::dummy(); @@ -338,7 +338,7 @@ benchmarks! { let instance = Contract::::with_caller( whitelisted_caller(), WasmModule::dummy(), vec![], )?; - let value = T::Currency::minimum_balance(); + let value = Pallet::::min_balance(); let origin = RawOrigin::Signed(instance.caller.clone()); let callee = instance.addr.clone(); let before = T::Currency::free_balance(&instance.account_id); @@ -767,13 +767,13 @@ benchmarks! { let instance = Contract::::new(code, vec![])?; let origin = RawOrigin::Signed(instance.caller.clone()); assert_eq!(T::Currency::total_balance(&beneficiary), 0u32.into()); - assert_eq!(T::Currency::free_balance(&instance.account_id), T::Currency::minimum_balance()); + assert_eq!(T::Currency::free_balance(&instance.account_id), Pallet::::min_balance()); assert_ne!(T::Currency::reserved_balance(&instance.account_id), 0u32.into()); }: call(origin, instance.addr.clone(), 0u32.into(), Weight::MAX, None, vec![]) verify { if r > 0 { assert_eq!(T::Currency::total_balance(&instance.account_id), 0u32.into()); - assert_eq!(T::Currency::total_balance(&beneficiary), T::Currency::minimum_balance()); + assert_eq!(T::Currency::total_balance(&beneficiary), Pallet::::min_balance()); } } @@ -1469,7 +1469,7 @@ benchmarks! { .collect::>(); let account_len = accounts.get(0).map(|i| i.encode().len()).unwrap_or(0); let account_bytes = accounts.iter().flat_map(|x| x.encode()).collect(); - let value = T::Currency::minimum_balance(); + let value = Pallet::::min_balance(); assert!(value > 0u32.into()); let value_bytes = value.encode(); let value_len = value_bytes.len(); @@ -1705,7 +1705,7 @@ benchmarks! { let hash_len = hashes.get(0).map(|x| x.encode().len()).unwrap_or(0); let hashes_bytes = hashes.iter().flat_map(|x| x.encode()).collect::>(); let hashes_len = hashes_bytes.len(); - let value = T::Currency::minimum_balance(); + let value = Pallet::::min_balance(); assert!(value > 0u32.into()); let value_bytes = value.encode(); let value_len = value_bytes.len(); diff --git a/frame/contracts/src/exec.rs b/frame/contracts/src/exec.rs index 0fbf821b2e284..6260dd41de707 100644 --- a/frame/contracts/src/exec.rs +++ b/frame/contracts/src/exec.rs @@ -813,6 +813,15 @@ where return Ok(output) } + // Storage limit is enforced as late as possible (when the last frame returns) so that + // the ordering of storage accesses does not matter. + if self.frames.is_empty() { + let frame = &mut self.first_frame; + frame.contract_info.load(&frame.account_id); + let contract = frame.contract_info.as_contract(); + frame.nested_storage.enforce_limit(contract)?; + } + let frame = self.top_frame(); let account_id = &frame.account_id; match (entry_point, delegated_code_hash) { @@ -911,12 +920,7 @@ where // it was invalidated. frame.contract_info.load(account_id); let mut contract = frame.contract_info.into_contract(); - prev.nested_storage.absorb( - frame.nested_storage, - &self.origin, - account_id, - contract.as_mut(), - ); + prev.nested_storage.absorb(frame.nested_storage, account_id, contract.as_mut()); // In case the contract wasn't terminated we need to persist changes made to it. if let Some(contract) = contract { @@ -954,7 +958,6 @@ where let mut contract = self.first_frame.contract_info.as_contract(); self.storage_meter.absorb( mem::take(&mut self.first_frame.nested_storage), - &self.origin, &self.first_frame.account_id, contract.as_deref_mut(), ); @@ -1306,7 +1309,7 @@ where } fn call_runtime(&self, call: ::RuntimeCall) -> DispatchResultWithPostInfo { - let mut origin: T::Origin = RawOrigin::Signed(self.address().clone()).into(); + let mut origin: T::RuntimeOrigin = RawOrigin::Signed(self.address().clone()).into(); origin.add_filter(T::CallFilter::contains); call.dispatch(origin) } @@ -1379,7 +1382,6 @@ mod tests { use codec::{Decode, Encode}; use frame_support::{assert_err, assert_ok, parameter_types}; use frame_system::{EventRecord, Phase}; - use hex_literal::hex; use pallet_contracts_primitives::ReturnFlags; use pretty_assertions::assert_eq; use sp_core::Bytes; @@ -2355,10 +2357,10 @@ mod tests { let code_bob = MockLoader::insert(Call, |ctx, _| { if ctx.input_data[0] == 0 { let info = ctx.ext.contract_info(); - assert_eq!(info.storage_deposit, 0); - info.storage_deposit = 42; + assert_eq!(info.storage_byte_deposit, 0); + info.storage_byte_deposit = 42; assert_eq!(ctx.ext.call(Weight::zero(), CHARLIE, 0, vec![], true), exec_trapped()); - assert_eq!(ctx.ext.contract_info().storage_deposit, 42); + assert_eq!(ctx.ext.contract_info().storage_byte_deposit, 42); } exec_success() }); @@ -3210,13 +3212,12 @@ mod tests { #[test] fn ecdsa_to_eth_address_returns_proper_value() { let bob_ch = MockLoader::insert(Call, |ctx, _| { - let pubkey_compressed: [u8; 33] = - hex!("028db55b05db86c0b1786ca49f095d76344c9e6056b2f02701a7e7f3c20aabfd91")[..] - .try_into() - .unwrap(); + let pubkey_compressed = array_bytes::hex2array_unchecked( + "028db55b05db86c0b1786ca49f095d76344c9e6056b2f02701a7e7f3c20aabfd91", + ); assert_eq!( ctx.ext.ecdsa_to_eth_address(&pubkey_compressed).unwrap(), - hex!("09231da7b19A016f9e576d23B16277062F4d46A8")[..] + array_bytes::hex2array_unchecked::<20>("09231da7b19A016f9e576d23B16277062F4d46A8") ); exec_success() }); diff --git a/frame/contracts/src/lib.rs b/frame/contracts/src/lib.rs index 842fa02f34529..fc44e4507ca00 100644 --- a/frame/contracts/src/lib.rs +++ b/frame/contracts/src/lib.rs @@ -87,12 +87,12 @@ mod gas; mod benchmarking; mod exec; +mod migration; mod schedule; mod storage; mod wasm; pub mod chain_extension; -pub mod migration; pub mod weights; #[cfg(test)] @@ -109,7 +109,10 @@ use codec::{Encode, HasCompact}; use frame_support::{ dispatch::{DispatchClass, Dispatchable, GetDispatchInfo, Pays, PostDispatchInfo}, ensure, - traits::{ConstU32, Contains, Currency, Get, Randomness, ReservableCurrency, Time}, + traits::{ + tokens::fungible::Inspect, ConstU32, Contains, Currency, Get, Randomness, + ReservableCurrency, Time, + }, weights::Weight, BoundedVec, WeakBoundedVec, }; @@ -126,6 +129,7 @@ use sp_std::{fmt::Debug, marker::PhantomData, prelude::*}; pub use crate::{ exec::{Frame, VarSizedKey as StorageKey}, + migration::Migration, pallet::*, schedule::{HostFnWeights, InstructionWeights, Limits, Schedule}, }; @@ -225,7 +229,7 @@ pub mod pallet { use frame_system::pallet_prelude::*; /// The current storage version. - const STORAGE_VERSION: StorageVersion = StorageVersion::new(7); + const STORAGE_VERSION: StorageVersion = StorageVersion::new(8); #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] @@ -236,17 +240,18 @@ pub mod pallet { /// The time implementation used to supply timestamps to contracts through `seal_now`. type Time: Time; - /// The generator used to supply randomness to contracts through `seal_random`. + /// The generator used to supply randomness to contracts through `seal_random` type Randomness: Randomness; /// The currency in which fees are paid and contract balances are held. - type Currency: ReservableCurrency; + type Currency: ReservableCurrency + + Inspect>; /// The overarching event type. type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// The overarching call type. - type RuntimeCall: Dispatchable + type RuntimeCall: Dispatchable + GetDispatchInfo + codec::Decode + IsType<::RuntimeCall>; @@ -1036,7 +1041,7 @@ where }; let schedule = T::Schedule::get(); let result = ExecStack::>::run_call( - origin, + origin.clone(), dest, &mut gas_meter, &mut storage_meter, @@ -1045,7 +1050,11 @@ where data, debug_message, ); - InternalCallOutput { result, gas_meter, storage_deposit: storage_meter.into_deposit() } + InternalCallOutput { + result, + gas_meter, + storage_deposit: storage_meter.into_deposit(&origin), + } } /// Internal function that does the actual instantiation. @@ -1089,7 +1098,7 @@ where value.saturating_add(extra_deposit), )?; let result = ExecStack::>::run_instantiate( - origin, + origin.clone(), executable, &mut gas_meter, &mut storage_meter, @@ -1100,17 +1109,23 @@ where debug_message, ); storage_deposit = storage_meter - .into_deposit() + .into_deposit(&origin) .saturating_add(&StorageDeposit::Charge(extra_deposit)); result }; InternalInstantiateOutput { result: try_exec(), gas_meter, storage_deposit } } + /// Deposit a pallet contracts event. Handles the conversion to the overarching event type. fn deposit_event(topics: Vec, event: Event) { >::deposit_event_indexed( &topics, ::RuntimeEvent::from(event).into(), ) } + + /// Return the existential deposit of [`Config::Currency`]. + fn min_balance() -> BalanceOf { + >>::minimum_balance() + } } diff --git a/frame/contracts/src/migration.rs b/frame/contracts/src/migration.rs index 0db285e81a91f..5ea821aac7682 100644 --- a/frame/contracts/src/migration.rs +++ b/frame/contracts/src/migration.rs @@ -18,37 +18,80 @@ use crate::{BalanceOf, CodeHash, Config, Pallet, TrieId, Weight}; use codec::{Decode, Encode}; use frame_support::{ - codec, pallet_prelude::*, storage::migration, storage_alias, traits::Get, Identity, - Twox64Concat, + codec, + pallet_prelude::*, + storage::migration, + storage_alias, + traits::{Get, OnRuntimeUpgrade}, + Identity, Twox64Concat, }; +use sp_runtime::traits::Saturating; use sp_std::{marker::PhantomData, prelude::*}; -/// Wrapper for all migrations of this pallet, based on `StorageVersion`. -pub fn migrate() -> Weight { - let version = StorageVersion::get::>(); - let mut weight = Weight::zero(); +/// Performs all necessary migrations based on `StorageVersion`. +pub struct Migration(PhantomData); +impl OnRuntimeUpgrade for Migration { + fn on_runtime_upgrade() -> Weight { + let version = StorageVersion::get::>(); + let mut weight = Weight::zero(); - if version < 4 { - weight = weight.saturating_add(v4::migrate::()); - StorageVersion::new(4).put::>(); - } + if version < 4 { + weight = weight.saturating_add(v4::migrate::()); + StorageVersion::new(4).put::>(); + } - if version < 5 { - weight = weight.saturating_add(v5::migrate::()); - StorageVersion::new(5).put::>(); - } + if version < 5 { + weight = weight.saturating_add(v5::migrate::()); + StorageVersion::new(5).put::>(); + } + + if version < 6 { + weight = weight.saturating_add(v6::migrate::()); + StorageVersion::new(6).put::>(); + } + + if version < 7 { + weight = weight.saturating_add(v7::migrate::()); + StorageVersion::new(7).put::>(); + } + + if version < 8 { + weight = weight.saturating_add(v8::migrate::()); + StorageVersion::new(8).put::>(); + } - if version < 6 { - weight = weight.saturating_add(v6::migrate::()); - StorageVersion::new(6).put::>(); + weight } - if version < 7 { - weight = weight.saturating_add(v7::migrate::()); - StorageVersion::new(7).put::>(); + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, &'static str> { + let version = StorageVersion::get::>(); + + if version < 7 { + return Ok(vec![]) + } + + if version < 8 { + v8::pre_upgrade::()?; + } + + Ok(vec![]) } - weight + #[cfg(feature = "try-runtime")] + fn post_upgrade(_state: Vec) -> Result<(), &'static str> { + let version = StorageVersion::get::>(); + + if version < 7 { + return Ok(()) + } + + if version < 8 { + v8::post_upgrade::()?; + } + + Ok(()) + } } /// V4: `Schedule` is changed to be a config item rather than an in-storage value. @@ -185,9 +228,9 @@ mod v6 { #[derive(Encode, Decode)] pub struct RawContractInfo { - trie_id: TrieId, - code_hash: CodeHash, - storage_deposit: Balance, + pub trie_id: TrieId, + pub code_hash: CodeHash, + pub storage_deposit: Balance, } #[derive(Encode, Decode)] @@ -199,7 +242,7 @@ mod v6 { refcount: u64, } - type ContractInfo = RawContractInfo, BalanceOf>; + pub type ContractInfo = RawContractInfo, BalanceOf>; #[storage_alias] type ContractInfoOf = StorageMap< @@ -266,3 +309,108 @@ mod v7 { T::DbWeight::get().reads_writes(1, 2) } } + +/// Update `ContractInfo` with new fields that track storage deposits. +mod v8 { + use super::*; + use sp_io::default_child_storage as child; + use v6::ContractInfo as OldContractInfo; + + #[derive(Encode, Decode)] + struct ContractInfo { + trie_id: TrieId, + code_hash: CodeHash, + storage_bytes: u32, + storage_items: u32, + storage_byte_deposit: BalanceOf, + storage_item_deposit: BalanceOf, + storage_base_deposit: BalanceOf, + } + + #[storage_alias] + type ContractInfoOf = + StorageMap, Twox64Concat, ::AccountId, V>; + + pub fn migrate() -> Weight { + let mut weight = Weight::zero(); + + >>::translate_values(|old: OldContractInfo| { + // Count storage items of this contract + let mut storage_bytes = 0u32; + let mut storage_items = 0u32; + let mut key = Vec::new(); + while let Some(next) = child::next_key(&old.trie_id, &key) { + key = next; + let mut val_out = []; + let len = child::read(&old.trie_id, &key, &mut val_out, 0) + .expect("The loop conditions checks for existence of the key; qed"); + storage_bytes.saturating_accrue(len); + storage_items.saturating_accrue(1); + } + + let storage_byte_deposit = + T::DepositPerByte::get().saturating_mul(storage_bytes.into()); + let storage_item_deposit = + T::DepositPerItem::get().saturating_mul(storage_items.into()); + let storage_base_deposit = old + .storage_deposit + .saturating_sub(storage_byte_deposit) + .saturating_sub(storage_item_deposit); + + // Reads: One read for each storage item plus the contract info itself. + // Writes: Only the new contract info. + weight = weight + .saturating_add(T::DbWeight::get().reads_writes(u64::from(storage_items) + 1, 1)); + + Some(ContractInfo { + trie_id: old.trie_id, + code_hash: old.code_hash, + storage_bytes, + storage_items, + storage_byte_deposit, + storage_item_deposit, + storage_base_deposit, + }) + }); + + weight + } + + #[cfg(feature = "try-runtime")] + pub fn pre_upgrade() -> Result<(), &'static str> { + use frame_support::traits::ReservableCurrency; + for (key, value) in ContractInfoOf::>::iter() { + let reserved = T::Currency::reserved_balance(&key); + ensure!(reserved >= value.storage_deposit, "Reserved balance out of sync."); + } + Ok(()) + } + + #[cfg(feature = "try-runtime")] + pub fn post_upgrade() -> Result<(), &'static str> { + use frame_support::traits::ReservableCurrency; + for (key, value) in ContractInfoOf::>::iter() { + let reserved = T::Currency::reserved_balance(&key); + let stored = value + .storage_base_deposit + .saturating_add(value.storage_byte_deposit) + .saturating_add(value.storage_item_deposit); + ensure!(reserved >= stored, "Reserved balance out of sync."); + + let mut storage_bytes = 0u32; + let mut storage_items = 0u32; + let mut key = Vec::new(); + while let Some(next) = child::next_key(&value.trie_id, &key) { + key = next; + let mut val_out = []; + let len = child::read(&value.trie_id, &key, &mut val_out, 0) + .expect("The loop conditions checks for existence of the key; qed"); + storage_bytes.saturating_accrue(len); + storage_items.saturating_accrue(1); + } + ensure!(storage_bytes == value.storage_bytes, "Storage bytes do not match.",); + ensure!(storage_items == value.storage_items, "Storage items do not match.",); + } + Ok(()) + } +} diff --git a/frame/contracts/src/storage.rs b/frame/contracts/src/storage.rs index ec49a6325c125..c3fc0840d8649 100644 --- a/frame/contracts/src/storage.rs +++ b/frame/contracts/src/storage.rs @@ -34,31 +34,51 @@ use scale_info::TypeInfo; use sp_core::crypto::UncheckedFrom; use sp_io::KillStorageResult; use sp_runtime::{ - traits::{Hash, Zero}, + traits::{Hash, Saturating, Zero}, RuntimeDebug, }; use sp_std::{marker::PhantomData, prelude::*}; -pub type ContractInfo = RawContractInfo, BalanceOf>; - /// Information for managing an account and its sub trie abstraction. /// This is the required info to cache for an account. #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] -pub struct RawContractInfo { +#[scale_info(skip_type_params(T))] +pub struct ContractInfo { /// Unique ID for the subtree encoded as a bytes vector. pub trie_id: TrieId, /// The code associated with a given account. - pub code_hash: CodeHash, - /// The amount of balance that is currently deposited to pay for consumed storage. - pub storage_deposit: Balance, + pub code_hash: CodeHash, + /// How many bytes of storage are accumulated in this contract's child trie. + pub storage_bytes: u32, + /// How many items of storage are accumulated in this contract's child trie. + pub storage_items: u32, + /// This records to how much deposit the accumulated `storage_bytes` amount to. + pub storage_byte_deposit: BalanceOf, + /// This records to how much deposit the accumulated `storage_items` amount to. + pub storage_item_deposit: BalanceOf, + /// This records how much deposit is put down in order to pay for the contract itself. + /// + /// We need to store this information separately so it is not used when calculating any refunds + /// since the base deposit can only ever be refunded on contract termination. + pub storage_base_deposit: BalanceOf, } -impl RawContractInfo { +impl ContractInfo { /// Associated child trie unique id is built from the hash part of the trie id. #[cfg(test)] pub fn child_trie_info(&self) -> ChildInfo { child_trie_info(&self.trie_id[..]) } + + /// The deposit paying for the accumulated storage generated within the contract's child trie. + pub fn extra_deposit(&self) -> BalanceOf { + self.storage_byte_deposit.saturating_add(self.storage_item_deposit) + } + + /// Same as [`Self::extra_deposit`] but including the base deposit. + pub fn total_deposit(&self) -> BalanceOf { + self.extra_deposit().saturating_add(self.storage_base_deposit) + } } /// Associated child trie unique id is built from the hash part of the trie id. @@ -178,7 +198,7 @@ where }, (None, None) => (), } - storage_meter.charge(&diff)?; + storage_meter.charge(&diff); } match &new_value { @@ -200,14 +220,21 @@ where pub fn new_contract( account: &AccountIdOf, trie_id: TrieId, - ch: CodeHash, + code_hash: CodeHash, ) -> Result, DispatchError> { if >::contains_key(account) { return Err(Error::::DuplicateContract.into()) } - let contract = - ContractInfo:: { code_hash: ch, trie_id, storage_deposit: >::zero() }; + let contract = ContractInfo:: { + code_hash, + trie_id, + storage_bytes: 0, + storage_items: 0, + storage_byte_deposit: Zero::zero(), + storage_item_deposit: Zero::zero(), + storage_base_deposit: Zero::zero(), + }; Ok(contract) } diff --git a/frame/contracts/src/storage/meter.rs b/frame/contracts/src/storage/meter.rs index d89208812bcac..0a63eb42b86cb 100644 --- a/frame/contracts/src/storage/meter.rs +++ b/frame/contracts/src/storage/meter.rs @@ -17,17 +17,24 @@ //! This module contains functions to meter the storage deposit. -use crate::{storage::ContractInfo, BalanceOf, Config, Error}; +use crate::{storage::ContractInfo, BalanceOf, Config, Error, Inspect, Pallet}; use codec::Encode; use frame_support::{ dispatch::DispatchError, - traits::{tokens::BalanceStatus, Currency, ExistenceRequirement, Get, ReservableCurrency}, - DefaultNoBound, + ensure, + traits::{ + tokens::{BalanceStatus, WithdrawConsequence}, + Currency, ExistenceRequirement, Get, ReservableCurrency, + }, + DefaultNoBound, RuntimeDebugNoBound, }; use pallet_contracts_primitives::StorageDeposit as Deposit; use sp_core::crypto::UncheckedFrom; -use sp_runtime::traits::{Saturating, Zero}; -use sp_std::marker::PhantomData; +use sp_runtime::{ + traits::{Saturating, Zero}, + FixedPointNumber, FixedU128, +}; +use sp_std::{marker::PhantomData, vec::Vec}; /// Deposit that uses the native currency's balance type. pub type DepositOf = Deposit>; @@ -99,22 +106,25 @@ impl State for Root {} impl State for Nested {} /// A type that allows the metering of consumed or freed storage of a single contract call stack. -#[derive(DefaultNoBound)] -pub struct RawMeter, S: State> { +#[derive(DefaultNoBound, RuntimeDebugNoBound)] +pub struct RawMeter { /// The limit of how much balance this meter is allowed to consume. limit: BalanceOf, /// The amount of balance that was used in this meter and all of its already absorbed children. total_deposit: DepositOf, - /// The amount of balance that was used in this meter alone. - own_deposit: DepositOf, - /// Only when a contract was terminated we allow it to drop below the minimum balance. - terminated: bool, + /// The amount of storage changes that were recorded in this meter alone. + own_contribution: Contribution, + /// List of charges that should be applied at the end of a contract stack execution. + /// + /// We only have one charge per contract hence the size of this vector is + /// limited by the maximum call depth. + charges: Vec>, /// Type parameters are only used in impls. _phantom: PhantomData<(E, S)>, } /// This type is used to describe a storage change when charging from the meter. -#[derive(Default)] +#[derive(Default, RuntimeDebugNoBound)] pub struct Diff { /// How many bytes were added to storage. pub bytes_added: u32, @@ -124,43 +134,120 @@ pub struct Diff { pub items_added: u32, /// How many storage items were removed from storage. pub items_removed: u32, - /// If set to true the derived deposit will always a `Charge` larger than the - /// the existential deposit. - pub require_ed: bool, } impl Diff { - /// Calculate how much of a charge or refund results from applying the diff. - pub fn to_deposit(&self) -> DepositOf { - let mut deposit = Deposit::default(); + /// Calculate how much of a charge or refund results from applying the diff and store it + /// in the passed `info` if any. + /// + /// # Note + /// + /// In case `None` is passed for `info` only charges are calculated. This is because refunds + /// are calculated pro rata of the existing storage within a contract and hence need extract + /// this information from the passed `info`. + pub fn update_contract(&self, info: Option<&mut ContractInfo>) -> DepositOf { let per_byte = T::DepositPerByte::get(); let per_item = T::DepositPerItem::get(); + let bytes_added = self.bytes_added.saturating_sub(self.bytes_removed); + let items_added = self.items_added.saturating_sub(self.items_removed); + let mut bytes_deposit = Deposit::Charge(per_byte.saturating_mul((bytes_added).into())); + let mut items_deposit = Deposit::Charge(per_item.saturating_mul((items_added).into())); + + // Without any contract info we can only calculate diffs which add storage + let info = if let Some(info) = info { + info + } else { + debug_assert_eq!(self.bytes_removed, 0); + debug_assert_eq!(self.items_removed, 0); + return bytes_deposit.saturating_add(&items_deposit) + }; - if self.bytes_added > self.bytes_removed { - deposit = deposit.saturating_add(&Deposit::Charge( - per_byte.saturating_mul((self.bytes_added - self.bytes_removed).into()), - )); - } else if self.bytes_removed > self.bytes_added { - deposit = deposit.saturating_add(&Deposit::Refund( - per_byte.saturating_mul((self.bytes_removed - self.bytes_added).into()), - )); + // Refunds are calculated pro rata based on the accumulated storage within the contract + let bytes_removed = self.bytes_removed.saturating_sub(self.bytes_added); + let items_removed = self.items_removed.saturating_sub(self.items_added); + let ratio = FixedU128::checked_from_rational(bytes_removed, info.storage_bytes) + .unwrap_or_default() + .min(FixedU128::from_u32(1)); + bytes_deposit = bytes_deposit + .saturating_add(&Deposit::Refund(ratio.saturating_mul_int(info.storage_byte_deposit))); + let ratio = FixedU128::checked_from_rational(items_removed, info.storage_items) + .unwrap_or_default() + .min(FixedU128::from_u32(1)); + items_deposit = items_deposit + .saturating_add(&Deposit::Refund(ratio.saturating_mul_int(info.storage_item_deposit))); + + // We need to update the contract info structure with the new deposits + info.storage_bytes = + info.storage_bytes.saturating_add(bytes_added).saturating_sub(bytes_removed); + info.storage_items = + info.storage_items.saturating_add(items_added).saturating_sub(items_removed); + match &bytes_deposit { + Deposit::Charge(amount) => + info.storage_byte_deposit = info.storage_byte_deposit.saturating_add(*amount), + Deposit::Refund(amount) => + info.storage_byte_deposit = info.storage_byte_deposit.saturating_sub(*amount), } + match &items_deposit { + Deposit::Charge(amount) => + info.storage_item_deposit = info.storage_item_deposit.saturating_add(*amount), + Deposit::Refund(amount) => + info.storage_item_deposit = info.storage_item_deposit.saturating_sub(*amount), + } + + bytes_deposit.saturating_add(&items_deposit) + } +} - if self.items_added > self.items_removed { - deposit = deposit.saturating_add(&Deposit::Charge( - per_item.saturating_mul((self.items_added - self.items_removed).into()), - )); - } else if self.items_removed > self.items_added { - deposit = deposit.saturating_add(&Deposit::Refund( - per_item.saturating_mul((self.items_removed - self.items_added).into()), - )); +impl Diff { + fn saturating_add(&self, rhs: &Self) -> Self { + Self { + bytes_added: self.bytes_added.saturating_add(rhs.bytes_added), + bytes_removed: self.bytes_removed.saturating_add(rhs.bytes_removed), + items_added: self.items_added.saturating_add(rhs.items_added), + items_removed: self.items_removed.saturating_add(rhs.items_removed), } + } +} + +/// Records information to charge or refund a plain account. +/// +/// All the charges are deferred to the end of a whole call stack. Reason is that by doing +/// this we can do all the refunds before doing any charge. This way a plain account can use +/// more deposit than it has balance as along as it is covered by a refund. This +/// essentially makes the order of storage changes irrelevant with regard to the deposit system. +#[derive(RuntimeDebugNoBound, Clone)] +struct Charge { + contract: T::AccountId, + amount: DepositOf, + terminated: bool, +} + +/// Records the storage changes of a storage meter. +#[derive(RuntimeDebugNoBound)] +enum Contribution { + /// The contract the meter belongs to is alive and accumulates changes using a [`Diff`]. + Alive(Diff), + /// The meter was checked against its limit using [`RawMeter::enforce_limit`] at the end of + /// its execution. In this process the [`Diff`] was converted into a [`Deposit`]. + Checked(DepositOf), + /// The contract was terminated. In this process the [`Diff`] was converted into a [`Deposit`] + /// in order to calculate the refund. + Terminated(DepositOf), +} - if self.require_ed { - deposit = deposit.max(Deposit::Charge(T::Currency::minimum_balance())) +impl Contribution { + /// See [`Diff::update_contract`]. + fn update_contract(&self, info: Option<&mut ContractInfo>) -> DepositOf { + match self { + Self::Alive(diff) => diff.update_contract::(info), + Self::Terminated(deposit) | Self::Checked(deposit) => deposit.clone(), } + } +} - deposit +impl Default for Contribution { + fn default() -> Self { + Self::Alive(Default::default()) } } @@ -178,6 +265,7 @@ where /// usage for this sub call separately. This is necessary because we want to exchange balance /// with the current contract we are interacting with. pub fn nested(&self) -> RawMeter { + debug_assert!(self.is_alive()); RawMeter { limit: self.available(), ..Default::default() } } @@ -192,45 +280,28 @@ where /// /// # Parameters /// - /// `absorbed`: The child storage meter that should be absorbed. - /// `origin`: The origin that spawned the original root meter. - /// `contract`: The contract that this sub call belongs to. - /// `info`: The info of the contract in question. `None` if the contract was terminated. + /// - `absorbed`: The child storage meter that should be absorbed. + /// - `origin`: The origin that spawned the original root meter. + /// - `contract`: The contract that this sub call belongs to. + /// - `info`: The info of the contract in question. `None` if the contract was terminated. pub fn absorb( &mut self, - mut absorbed: RawMeter, - origin: &T::AccountId, + absorbed: RawMeter, contract: &T::AccountId, info: Option<&mut ContractInfo>, ) { - // Absorbing from an existing (non terminated) contract. - if let Some(info) = info { - match &mut absorbed.own_deposit { - Deposit::Charge(amount) => - info.storage_deposit = info.storage_deposit.saturating_add(*amount), - Deposit::Refund(amount) => { - // We need to make sure to never refund more than what was deposited and - // still leave the existential deposit inside the contract's account. - // This case can happen when costs change due to a runtime upgrade where - // increased costs could remove an account due to refunds. - let amount = { - let corrected_amount = (*amount).min( - info.storage_deposit.saturating_sub(T::Currency::minimum_balance()), - ); - let correction = (*amount).saturating_sub(corrected_amount); - absorbed.total_deposit = - absorbed.total_deposit.saturating_sub(&Deposit::Refund(correction)); - *amount = corrected_amount; - corrected_amount - }; - info.storage_deposit = info.storage_deposit.saturating_sub(amount); - }, - } - } - - self.total_deposit = self.total_deposit.saturating_add(&absorbed.total_deposit); - if !absorbed.own_deposit.is_zero() { - E::charge(origin, contract, &absorbed.own_deposit, absorbed.terminated); + let own_deposit = absorbed.own_contribution.update_contract(info); + self.total_deposit = self + .total_deposit + .saturating_add(&absorbed.total_deposit) + .saturating_add(&own_deposit); + if !own_deposit.is_zero() { + self.charges.extend_from_slice(&absorbed.charges); + self.charges.push(Charge { + contract: contract.clone(), + amount: own_deposit, + terminated: absorbed.is_terminated(), + }); } } @@ -238,6 +309,16 @@ where fn available(&self) -> BalanceOf { self.total_deposit.available(&self.limit) } + + /// True if the contract is alive. + fn is_alive(&self) -> bool { + matches!(self.own_contribution, Contribution::Alive(_)) + } + + /// True if the contract is terminated. + fn is_terminated(&self) -> bool { + matches!(self.own_contribution, Contribution::Terminated(_)) + } } /// Functions that only apply to the root state. @@ -260,11 +341,18 @@ where } /// The total amount of deposit that should change hands as result of the execution - /// that this meter was passed into. + /// that this meter was passed into. This will also perform all the charges accumulated + /// in the whole contract stack. /// /// This drops the root meter in order to make sure it is only called when the whole /// execution did finish. - pub fn into_deposit(self) -> DepositOf { + pub fn into_deposit(self, origin: &T::AccountId) -> DepositOf { + for charge in self.charges.iter().filter(|c| matches!(c.amount, Deposit::Refund(_))) { + E::charge(origin, &charge.contract, &charge.amount, charge.terminated); + } + for charge in self.charges.iter().filter(|c| matches!(c.amount, Deposit::Charge(_))) { + E::charge(origin, &charge.contract, &charge.amount, charge.terminated); + } self.total_deposit } } @@ -277,18 +365,12 @@ where E: Ext, { /// Try to charge the `diff` from the meter. Fails if this would exceed the original limit. - pub fn charge(&mut self, diff: &Diff) -> Result, DispatchError> { - debug_assert!(!self.terminated); - let deposit = diff.to_deposit::(); - let total_deposit = self.total_deposit.saturating_add(&deposit); - if let Deposit::Charge(amount) = total_deposit { - if amount > self.limit { - return Err(>::StorageDepositLimitExhausted.into()) - } - } - self.total_deposit = total_deposit; - self.own_deposit = self.own_deposit.saturating_add(&deposit); - Ok(deposit) + pub fn charge(&mut self, diff: &Diff) { + debug_assert!(self.is_alive()); + match &mut self.own_contribution { + Contribution::Alive(own) => *own = own.saturating_add(diff), + _ => panic!("Charge is never called after termination; qed"), + }; } /// Charge from `origin` a storage deposit for contract instantiation. @@ -300,25 +382,22 @@ where contract: &T::AccountId, info: &mut ContractInfo, ) -> Result, DispatchError> { - debug_assert!(!self.terminated); - let deposit = Diff { - bytes_added: info.encoded_size() as u32, - items_added: 1, - require_ed: true, - ..Default::default() + debug_assert!(self.is_alive()); + let mut deposit = + Diff { bytes_added: info.encoded_size() as u32, items_added: 1, ..Default::default() } + .update_contract::(None); + + // Instantiate needs to transfer the minimum balance at least in order to pull the + // contract's account into existence. + deposit = deposit.max(Deposit::Charge(Pallet::::min_balance())); + if deposit.charge_or_zero() > self.limit { + return Err(>::StorageDepositLimitExhausted.into()) } - .to_deposit::(); - debug_assert!(matches!(deposit, Deposit::Charge(_))); - // We do not increase `own_deposit` because this will be charged later when the contract - // execution does conclude. - let total_deposit = self.total_deposit.saturating_add(&deposit); - if let Deposit::Charge(amount) = &total_deposit { - if amount > &self.limit { - return Err(>::StorageDepositLimitExhausted.into()) - } - } - info.storage_deposit = info.storage_deposit.saturating_add(deposit.charge_or_zero()); - self.total_deposit = total_deposit; + + // We do not increase `own_contribution` because this will be charged later when the + // contract execution does conclude and hence would lead to a double charge. + self.total_deposit = deposit.clone(); + info.storage_base_deposit = deposit.charge_or_zero(); if !deposit.is_zero() { // We need to charge immediately so that the account is created before the `value` // is transferred from the caller to the contract. @@ -331,34 +410,55 @@ where /// /// This will manipulate the meter so that all storage deposit accumulated in /// `contract_info` will be refunded to the `origin` of the meter. - pub fn terminate(&mut self, contract_info: &ContractInfo) { - debug_assert!(!self.terminated); - let refund = Deposit::Refund(contract_info.storage_deposit); - - // The deposit for `own_deposit` isn't persisted into the contract info until the current - // frame is dropped. This means that whatever changes were introduced during the - // current frame are dicarded when terminating. - self.total_deposit = - self.total_deposit.saturating_add(&refund).saturating_sub(&self.own_deposit); - self.own_deposit = refund; - self.terminated = true; + pub fn terminate(&mut self, info: &ContractInfo) { + debug_assert!(self.is_alive()); + self.own_contribution = Contribution::Terminated(Deposit::Refund(info.total_deposit())); + } + + /// [`Self::charge`] does not enforce the storage limit since we want to do this check as late + /// as possible to allow later refunds to offset earlier charges. + /// + /// # Note + /// + /// We only need to call this **once** for every call stack and not for every cross contract + /// call. Hence this is only called when the last call frame returns. + pub fn enforce_limit( + &mut self, + info: Option<&mut ContractInfo>, + ) -> Result<(), DispatchError> { + let deposit = self.own_contribution.update_contract(info); + let total_deposit = self.total_deposit.saturating_add(&deposit); + // We don't want to override a `Terminated` with a `Checked`. + if self.is_alive() { + self.own_contribution = Contribution::Checked(deposit); + } + if let Deposit::Charge(amount) = total_deposit { + if amount > self.limit { + return Err(>::StorageDepositLimitExhausted.into()) + } + } + Ok(()) } } -impl Ext for ReservingExt { +impl Ext for ReservingExt +where + T: Config, + T::AccountId: UncheckedFrom + AsRef<[u8]>, +{ fn check_limit( origin: &T::AccountId, limit: Option>, min_leftover: BalanceOf, ) -> Result, DispatchError> { - let max = T::Currency::free_balance(origin) - .saturating_sub(T::Currency::minimum_balance()) - .saturating_sub(min_leftover); - match limit { - Some(limit) if limit <= max => Ok(limit), - None => Ok(max), - _ => Err(>::StorageDepositNotEnoughFunds.into()), - } + let max = T::Currency::reducible_balance(origin, true).saturating_sub(min_leftover); + let limit = limit.unwrap_or(max); + ensure!( + limit <= max && + matches!(T::Currency::can_withdraw(origin, limit), WithdrawConsequence::Success), + >::StorageDepositNotEnoughFunds, + ); + Ok(limit) } fn charge( @@ -393,6 +493,9 @@ impl Ext for ReservingExt { "Failed to transfer storage deposit {:?} from origin {:?} to contract {:?}: {:?}", amount, origin, contract, err, ); + if cfg!(debug_assertions) { + panic!("Unable to collect storage deposit. This is a bug."); + } } }, // For `Refund(_)` no error happen because the initial value transfer from the @@ -411,7 +514,7 @@ impl Ext for ReservingExt { // refund because we consider this unexpected behaviour. *amount.min( &T::Currency::reserved_balance(contract) - .saturating_sub(T::Currency::minimum_balance()), + .saturating_sub(Pallet::::min_balance()), ) }; let result = @@ -422,6 +525,9 @@ impl Ext for ReservingExt { "Failed to repatriate storage deposit {:?} from contract {:?} to origin {:?}: {:?}", amount, contract, origin, result, ); + if cfg!(debug_assertions) { + panic!("Unable to refund storage deposit. This is a bug."); + } } }, }; @@ -513,14 +619,26 @@ mod tests { TestExtTestValue::mutate(|ext| ext.clear()) } - fn new_info(deposit: BalanceOf) -> ContractInfo { + #[derive(Default)] + struct StorageInfo { + bytes: u32, + items: u32, + bytes_deposit: BalanceOf, + items_deposit: BalanceOf, + } + + fn new_info(info: StorageInfo) -> ContractInfo { use crate::storage::Storage; use sp_runtime::traits::Hash; ContractInfo:: { trie_id: >::generate_trie_id(&ALICE, 42), code_hash: ::Hashing::hash(b"42"), - storage_deposit: deposit, + storage_bytes: info.bytes, + storage_items: info.items, + storage_byte_deposit: info.bytes_deposit, + storage_item_deposit: info.items_deposit, + storage_base_deposit: Default::default(), } } @@ -548,8 +666,8 @@ mod tests { // an empty charge does not create a `Charge` entry let mut nested0 = meter.nested(); - nested0.charge(&Default::default()).unwrap(); - meter.absorb(nested0, &ALICE, &BOB, None); + nested0.charge(&Default::default()); + meter.absorb(nested0, &BOB, None); assert_eq!( TestExtTestValue::get(), @@ -560,79 +678,49 @@ mod tests { ) } - #[test] - fn existential_deposit_works() { - clear_ext(); - - let mut meter = TestMeter::new(&ALICE, Some(1_000), 0).unwrap(); - assert_eq!(meter.available(), 1_000); - - // a `Refund` will be turned into a `Charge(ed)` which is intended behaviour - let mut nested0 = meter.nested(); - nested0.charge(&Diff { require_ed: true, ..Default::default() }).unwrap(); - nested0 - .charge(&Diff { bytes_removed: 1, require_ed: true, ..Default::default() }) - .unwrap(); - meter.absorb(nested0, &ALICE, &BOB, None); - - assert_eq!( - TestExtTestValue::get(), - TestExt { - limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], - charges: vec![Charge { - origin: ALICE, - contract: BOB, - amount: Deposit::Charge(::Currency::minimum_balance() * 2), - terminated: false, - }] - } - ) - } - #[test] fn charging_works() { clear_ext(); - let min_balance = ::Currency::minimum_balance(); - - let mut meter = TestMeter::new(&ALICE, Some(1_000), 0).unwrap(); - assert_eq!(meter.available(), 1_000); + let mut meter = TestMeter::new(&ALICE, Some(100), 0).unwrap(); + assert_eq!(meter.available(), 100); - let mut nested0_info = new_info(100); + let mut nested0_info = + new_info(StorageInfo { bytes: 100, items: 5, bytes_deposit: 100, items_deposit: 10 }); let mut nested0 = meter.nested(); - nested0 - .charge(&Diff { - bytes_added: 10, - bytes_removed: 5, - items_added: 1, - items_removed: 2, - ..Default::default() - }) - .unwrap(); - nested0.charge(&Diff { bytes_removed: 1, ..Default::default() }).unwrap(); + nested0.charge(&Diff { + bytes_added: 108, + bytes_removed: 5, + items_added: 1, + items_removed: 2, + }); + nested0.charge(&Diff { bytes_removed: 99, ..Default::default() }); - let mut nested1_info = new_info(50); + let mut nested1_info = + new_info(StorageInfo { bytes: 100, items: 10, bytes_deposit: 100, items_deposit: 20 }); let mut nested1 = nested0.nested(); - nested1.charge(&Diff { items_removed: 5, ..Default::default() }).unwrap(); - nested0.absorb(nested1, &ALICE, &CHARLIE, Some(&mut nested1_info)); + nested1.charge(&Diff { items_removed: 5, ..Default::default() }); + nested0.absorb(nested1, &CHARLIE, Some(&mut nested1_info)); - // Trying to refund more than is available in the contract will cap the charge - // to (deposit_in_contract - ed). - let mut nested2_info = new_info(5); + let mut nested2_info = + new_info(StorageInfo { bytes: 100, items: 7, bytes_deposit: 100, items_deposit: 20 }); let mut nested2 = nested0.nested(); - nested2.charge(&Diff { bytes_removed: 7, ..Default::default() }).unwrap(); - nested0.absorb(nested2, &ALICE, &CHARLIE, Some(&mut nested2_info)); + nested2.charge(&Diff { items_removed: 7, ..Default::default() }); + nested0.absorb(nested2, &CHARLIE, Some(&mut nested2_info)); + + nested0.enforce_limit(Some(&mut nested0_info)).unwrap(); + meter.absorb(nested0, &BOB, Some(&mut nested0_info)); - meter.absorb(nested0, &ALICE, &BOB, Some(&mut nested0_info)); + meter.into_deposit(&ALICE); - assert_eq!(nested0_info.storage_deposit, 102); - assert_eq!(nested1_info.storage_deposit, 40); - assert_eq!(nested2_info.storage_deposit, min_balance); + assert_eq!(nested0_info.extra_deposit(), 112); + assert_eq!(nested1_info.extra_deposit(), 110); + assert_eq!(nested2_info.extra_deposit(), 100); assert_eq!( TestExtTestValue::get(), TestExt { - limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], + limit_checks: vec![LimitCheck { origin: ALICE, limit: 100, min_leftover: 0 }], charges: vec![ Charge { origin: ALICE, @@ -643,7 +731,7 @@ mod tests { Charge { origin: ALICE, contract: CHARLIE, - amount: Deposit::Refund(4), + amount: Deposit::Refund(20), terminated: false }, Charge { @@ -665,26 +753,25 @@ mod tests { assert_eq!(meter.available(), 1_000); let mut nested0 = meter.nested(); - nested0 - .charge(&Diff { - bytes_added: 5, - bytes_removed: 1, - items_added: 3, - items_removed: 1, - ..Default::default() - }) - .unwrap(); - nested0.charge(&Diff { items_added: 2, ..Default::default() }).unwrap(); - - let nested1_info = new_info(400); + nested0.charge(&Diff { + bytes_added: 5, + bytes_removed: 1, + items_added: 3, + items_removed: 1, + }); + nested0.charge(&Diff { items_added: 2, ..Default::default() }); + + let mut nested1_info = + new_info(StorageInfo { bytes: 100, items: 10, bytes_deposit: 100, items_deposit: 20 }); let mut nested1 = nested0.nested(); - nested1.charge(&Diff { items_removed: 5, ..Default::default() }).unwrap(); - nested1.charge(&Diff { bytes_added: 20, ..Default::default() }).unwrap(); + nested1.charge(&Diff { items_removed: 5, ..Default::default() }); + nested1.charge(&Diff { bytes_added: 20, ..Default::default() }); nested1.terminate(&nested1_info); - nested0.absorb(nested1, &ALICE, &CHARLIE, None); + nested0.enforce_limit(Some(&mut nested1_info)).unwrap(); + nested0.absorb(nested1, &CHARLIE, None); - meter.absorb(nested0, &ALICE, &BOB, None); - drop(meter); + meter.absorb(nested0, &BOB, None); + meter.into_deposit(&ALICE); assert_eq!( TestExtTestValue::get(), @@ -694,7 +781,7 @@ mod tests { Charge { origin: ALICE, contract: CHARLIE, - amount: Deposit::Refund(400), + amount: Deposit::Refund(120), terminated: true }, Charge { diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index d5f4df161b723..a56e4f5564845 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -23,6 +23,7 @@ use crate::{ }, exec::{FixSizedKey, Frame}, storage::Storage, + tests::test_utils::{get_contract, get_contract_checked}, wasm::{PrefabWasmModule, ReturnCode as RuntimeReturnCode}, weights::WeightInfo, BalanceOf, Code, CodeStorage, Config, ContractInfoOf, DefaultAddressGenerator, @@ -36,8 +37,8 @@ use frame_support::{ parameter_types, storage::child, traits::{ - BalanceStatus, ConstU32, ConstU64, Contains, Currency, Get, OnIdle, OnInitialize, - ReservableCurrency, + BalanceStatus, ConstU32, ConstU64, Contains, Currency, Get, LockableCurrency, OnIdle, + OnInitialize, ReservableCurrency, WithdrawReasons, }, weights::{constants::WEIGHT_PER_SECOND, Weight}, }; @@ -76,7 +77,9 @@ frame_support::construct_runtime!( #[macro_use] pub mod test_utils { use super::{Balances, Hash, SysConfig, Test}; - use crate::{exec::AccountIdOf, storage::Storage, CodeHash, Config, ContractInfoOf, Nonce}; + use crate::{ + exec::AccountIdOf, storage::Storage, CodeHash, Config, ContractInfo, ContractInfoOf, Nonce, + }; use codec::Encode; use frame_support::traits::Currency; @@ -97,6 +100,12 @@ pub mod test_utils { pub fn get_balance(who: &AccountIdOf) -> u64 { Balances::free_balance(who) } + pub fn get_contract(addr: &AccountIdOf) -> ContractInfo { + get_contract_checked(addr).unwrap() + } + pub fn get_contract_checked(addr: &AccountIdOf) -> Option> { + ContractInfoOf::::get(addr) + } pub fn hash(s: &S) -> <::Hashing as Hash>::Output { <::Hashing as Hash>::hash_of(s) } @@ -105,6 +114,7 @@ pub mod test_utils { assert_eq!(u32::from_le_bytes($x.data[..].try_into().unwrap()), $y as u32); }}; } + macro_rules! assert_refcount { ( $code_hash:expr , $should:expr $(,)? ) => {{ let is = crate::OwnerInfoOf::::get($code_hash).map(|m| m.refcount()).unwrap(); @@ -277,7 +287,7 @@ impl frame_system::Config for Test { type BlockWeights = BlockWeights; type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = H256; @@ -489,7 +499,7 @@ fn calling_plain_account_fails() { let base_cost = <::WeightInfo as WeightInfo>::call(); assert_eq!( - Contracts::call(Origin::signed(ALICE), BOB, 0, GAS_LIMIT, None, Vec::new()), + Contracts::call(RuntimeOrigin::signed(ALICE), BOB, 0, GAS_LIMIT, None, Vec::new()), Err(DispatchErrorWithPostInfo { error: Error::::ContractNotFound.into(), post_info: PostDispatchInfo { @@ -512,14 +522,14 @@ fn instantiate_and_call_and_deposit_event() { // We determine the storage deposit limit after uploading because it depends on ALICEs free // balance which is changed by uploading a module. - assert_ok!(Contracts::upload_code(Origin::signed(ALICE), wasm, None)); + assert_ok!(Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, None)); // Drop previous events initialize_block(2); // Check at the end to get hash on error easily assert_ok!(Contracts::instantiate( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), value, GAS_LIMIT, None, @@ -603,7 +613,7 @@ fn deposit_event_max_value_limit() { // Create let _ = Balances::deposit_creating(&ALICE, 1_000_000); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 30_000, GAS_LIMIT, None, @@ -615,7 +625,7 @@ fn deposit_event_max_value_limit() { // Call contract with allowed storage value. assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT * 2, // we are copying a huge buffer, @@ -626,7 +636,7 @@ fn deposit_event_max_value_limit() { // Call contract with too large a storage value. assert_err_ignore_postinfo!( Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr, 0, GAS_LIMIT, @@ -646,7 +656,7 @@ fn run_out_of_gas() { let _ = Balances::deposit_creating(&ALICE, 1_000_000); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 100 * min_balance, GAS_LIMIT, None, @@ -660,7 +670,7 @@ fn run_out_of_gas() { // loops forever. assert_err_ignore_postinfo!( Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr, // newly created account 0, Weight::from_ref_time(1_000_000_000_000), @@ -680,12 +690,12 @@ fn instantiate_unique_trie_id() { ExtBuilder::default().existential_deposit(500).build().execute_with(|| { let _ = Balances::deposit_creating(&ALICE, 1_000_000); - Contracts::upload_code(Origin::signed(ALICE), wasm, None).unwrap(); + Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, None).unwrap(); let addr = Contracts::contract_address(&ALICE, &code_hash, &[]); // Instantiate the contract and store its trie id for later comparison. assert_ok!(Contracts::instantiate( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 0, GAS_LIMIT, None, @@ -693,12 +703,12 @@ fn instantiate_unique_trie_id() { vec![], vec![], )); - let trie_id = ContractInfoOf::::get(&addr).unwrap().trie_id; + let trie_id = get_contract(&addr).trie_id; // Try to instantiate it again without termination should yield an error. assert_err_ignore_postinfo!( Contracts::instantiate( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 0, GAS_LIMIT, None, @@ -711,7 +721,7 @@ fn instantiate_unique_trie_id() { // Terminate the contract. assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, @@ -721,7 +731,7 @@ fn instantiate_unique_trie_id() { // Re-Instantiate after termination. assert_ok!(Contracts::instantiate( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 0, GAS_LIMIT, None, @@ -731,7 +741,7 @@ fn instantiate_unique_trie_id() { )); // Trie ids shouldn't match or we might have a collision - assert_ne!(trie_id, ContractInfoOf::::get(&addr).unwrap().trie_id); + assert_ne!(trie_id, get_contract(&addr).trie_id); }); } @@ -743,7 +753,7 @@ fn storage_max_value_limit() { // Create let _ = Balances::deposit_creating(&ALICE, 1_000_000); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 30_000, GAS_LIMIT, None, @@ -752,11 +762,11 @@ fn storage_max_value_limit() { vec![], )); let addr = Contracts::contract_address(&ALICE, &code_hash, &[]); - ContractInfoOf::::get(&addr).unwrap(); + get_contract(&addr); // Call contract with allowed storage value. assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT * 2, // we are copying a huge buffer @@ -767,7 +777,7 @@ fn storage_max_value_limit() { // Call contract with too large a storage value. assert_err_ignore_postinfo!( Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr, 0, GAS_LIMIT, @@ -792,7 +802,7 @@ fn deploy_and_call_other_contract() { // Create let _ = Balances::deposit_creating(&ALICE, 1_000_000); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 100_000, GAS_LIMIT, None, @@ -801,7 +811,7 @@ fn deploy_and_call_other_contract() { vec![], )); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 100_000, GAS_LIMIT, None, @@ -816,7 +826,7 @@ fn deploy_and_call_other_contract() { // Call BOB contract, which attempts to instantiate and call the callee contract and // makes various assertions on the results from those calls. assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), caller_addr.clone(), 0, GAS_LIMIT, @@ -917,7 +927,7 @@ fn delegate_call() { // Instantiate the 'caller' assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 300_000, GAS_LIMIT, None, @@ -927,13 +937,13 @@ fn delegate_call() { )); // Only upload 'callee' code assert_ok!(Contracts::upload_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), callee_wasm, Some(codec::Compact(100_000)), )); assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), caller_addr.clone(), 1337, GAS_LIMIT, @@ -951,7 +961,7 @@ fn cannot_self_destruct_through_draning() { // Instantiate the BOB contract. assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 1_000, GAS_LIMIT, None, @@ -962,12 +972,12 @@ fn cannot_self_destruct_through_draning() { let addr = Contracts::contract_address(&ALICE, &code_hash, &[]); // Check that the BOB contract has been instantiated. - assert_matches!(ContractInfoOf::::get(&addr), Some(_)); + get_contract(&addr); // Call BOB which makes it send all funds to the zero address // The contract code asserts that the transfer was successful assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, @@ -992,7 +1002,7 @@ fn cannot_self_destruct_through_storage_refund_after_price_change() { // Instantiate the BOB contract. assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 0, GAS_LIMIT, None, @@ -1003,25 +1013,26 @@ fn cannot_self_destruct_through_storage_refund_after_price_change() { let addr = Contracts::contract_address(&ALICE, &code_hash, &[]); // Check that the BOB contract has been instantiated and has the minimum balance - let info = ContractInfoOf::::get(&addr).unwrap(); - assert_eq!(info.storage_deposit, min_balance); + assert_eq!(get_contract(&addr).total_deposit(), min_balance); + assert_eq!(get_contract(&addr).extra_deposit(), 0); assert_eq!(::Currency::total_balance(&addr), min_balance); - // Create 100 bytes of storage with a price of per byte + // Create 100 bytes of storage with a price of per byte and a single storage item of price 2 assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, None, 100u32.to_le_bytes().to_vec() )); + assert_eq!(get_contract(&addr).total_deposit(), min_balance + 102); - // Increase the byte price and trigger a refund. This could potentially destroy the account - // because the refund removes the reserved existential deposit. This should not happen. + // Increase the byte price and trigger a refund. This should not have any influence because + // the removal is pro rata and exactly those 100 bytes should have been removed. DEPOSIT_PER_BYTE.with(|c| *c.borrow_mut() = 500); assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, @@ -1032,8 +1043,9 @@ fn cannot_self_destruct_through_storage_refund_after_price_change() { // Make sure the account wasn't removed by the refund assert_eq!( ::Currency::total_balance(&addr), - ::Currency::minimum_balance(), + get_contract(&addr).total_deposit(), ); + assert_eq!(get_contract(&addr).extra_deposit(), 2,); }); } @@ -1045,7 +1057,7 @@ fn cannot_self_destruct_by_refund_after_slash() { let min_balance = ::Currency::minimum_balance(); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 0, GAS_LIMIT, None, @@ -1057,7 +1069,7 @@ fn cannot_self_destruct_by_refund_after_slash() { // create 100 more reserved balance assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, @@ -1075,7 +1087,7 @@ fn cannot_self_destruct_by_refund_after_slash() { // trigger a refund of 50 which would bring the contract below min when actually refunded assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, @@ -1086,9 +1098,6 @@ fn cannot_self_destruct_by_refund_after_slash() { // Make sure the account kept the minimum balance and was not destroyed assert_eq!(::Currency::total_balance(&addr), min_balance); - // even though it was not charged it is still substracted from the storage deposit tracker - assert_eq!(ContractInfoOf::::get(&addr).unwrap().storage_deposit, 550); - assert_eq!( System::events(), vec![ @@ -1131,7 +1140,7 @@ fn cannot_self_destruct_while_live() { // Instantiate the BOB contract. assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 100_000, GAS_LIMIT, None, @@ -1142,17 +1151,24 @@ fn cannot_self_destruct_while_live() { let addr = Contracts::contract_address(&ALICE, &code_hash, &[]); // Check that the BOB contract has been instantiated. - assert_matches!(ContractInfoOf::::get(&addr), Some(_)); + get_contract(&addr); // Call BOB with input data, forcing it make a recursive call to itself to // self-destruct, resulting in a trap. assert_err_ignore_postinfo!( - Contracts::call(Origin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, None, vec![0],), + Contracts::call( + RuntimeOrigin::signed(ALICE), + addr.clone(), + 0, + GAS_LIMIT, + None, + vec![0], + ), Error::::ContractTrapped, ); // Check that BOB is still there. - assert_matches!(ContractInfoOf::::get(&addr), Some(_)); + get_contract(&addr); }); } @@ -1165,7 +1181,7 @@ fn self_destruct_works() { // Instantiate the BOB contract. assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 100_000, GAS_LIMIT, None, @@ -1176,14 +1192,14 @@ fn self_destruct_works() { let addr = Contracts::contract_address(&ALICE, &code_hash, &[]); // Check that the BOB contract has been instantiated. - assert_matches!(ContractInfoOf::::get(&addr), Some(_)); + get_contract(&addr); // Drop all previous events initialize_block(2); // Call BOB without input data which triggers termination. assert_matches!( - Contracts::call(Origin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, None, vec![],), + Contracts::call(RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, None, vec![],), Ok(_) ); @@ -1191,7 +1207,7 @@ fn self_destruct_works() { assert_refcount!(&code_hash, 0); // Check that account is gone - assert!(ContractInfoOf::::get(&addr).is_none()); + assert!(get_contract_checked(&addr).is_none()); assert_eq!(Balances::total_balance(&addr), 0); // check that the beneficiary (django) got remaining balance @@ -1258,7 +1274,7 @@ fn destroy_contract_and_transfer_funds() { // Create let _ = Balances::deposit_creating(&ALICE, 1_000_000); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 200_000, GAS_LIMIT, None, @@ -1270,7 +1286,7 @@ fn destroy_contract_and_transfer_funds() { // This deploys the BOB contract, which in turn deploys the CHARLIE contract during // construction. assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 200_000, GAS_LIMIT, None, @@ -1282,11 +1298,11 @@ fn destroy_contract_and_transfer_funds() { let addr_charlie = Contracts::contract_address(&addr_bob, &callee_code_hash, &[0x47, 0x11]); // Check that the CHARLIE contract has been instantiated. - assert_matches!(ContractInfoOf::::get(&addr_charlie), Some(_)); + get_contract(&addr_charlie); // Call BOB, which calls CHARLIE, forcing CHARLIE to self-destruct. assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr_bob, 0, GAS_LIMIT, @@ -1295,7 +1311,7 @@ fn destroy_contract_and_transfer_funds() { )); // Check that CHARLIE has moved on to the great beyond (ie. died). - assert!(ContractInfoOf::::get(&addr_charlie).is_none()); + assert!(get_contract_checked(&addr_charlie).is_none()); }); } @@ -1308,7 +1324,7 @@ fn cannot_self_destruct_in_constructor() { // Fail to instantiate the BOB because the contructor calls seal_terminate. assert_err_ignore_postinfo!( Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 100_000, GAS_LIMIT, None, @@ -1330,7 +1346,7 @@ fn crypto_hashes() { // Instantiate the CRYPTO_HASHES contract. assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 100_000, GAS_LIMIT, None, @@ -1379,7 +1395,7 @@ fn transfer_return_code() { let _ = Balances::deposit_creating(&ALICE, 1000 * min_balance); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -1418,7 +1434,7 @@ fn call_return_code() { let _ = Balances::deposit_creating(&CHARLIE, 1000 * min_balance); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -1444,7 +1460,7 @@ fn call_return_code() { assert_return_code!(result, RuntimeReturnCode::NotCallable); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(CHARLIE), + RuntimeOrigin::signed(CHARLIE), min_balance * 100, GAS_LIMIT, None, @@ -1545,7 +1561,7 @@ fn instantiate_return_code() { let callee_hash = callee_hash.as_ref().to_vec(); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -1555,7 +1571,7 @@ fn instantiate_return_code() { ),); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -1645,7 +1661,7 @@ fn disabled_chain_extension_wont_deploy() { TestExtension::disable(); assert_err_ignore_postinfo!( Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 3 * min_balance, GAS_LIMIT, None, @@ -1665,7 +1681,7 @@ fn disabled_chain_extension_errors_on_call() { let min_balance = ::Currency::minimum_balance(); let _ = Balances::deposit_creating(&ALICE, 1000 * min_balance); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -1676,7 +1692,7 @@ fn disabled_chain_extension_errors_on_call() { let addr = Contracts::contract_address(&ALICE, &hash, &[]); TestExtension::disable(); assert_err_ignore_postinfo!( - Contracts::call(Origin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, None, vec![],), + Contracts::call(RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, None, vec![],), Error::::NoChainExtension, ); }); @@ -1689,7 +1705,7 @@ fn chain_extension_works() { let min_balance = ::Currency::minimum_balance(); let _ = Balances::deposit_creating(&ALICE, 1000 * min_balance); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -1792,7 +1808,7 @@ fn chain_extension_works() { // We set the MSB part to 2 (instead of 0) which routes the request into the third extension assert_err_ignore_postinfo!( Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, @@ -1811,7 +1827,7 @@ fn chain_extension_temp_storage_works() { let min_balance = ::Currency::minimum_balance(); let _ = Balances::deposit_creating(&ALICE, 1000 * min_balance); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -1845,7 +1861,7 @@ fn lazy_removal_works() { let _ = Balances::deposit_creating(&ALICE, 1000 * min_balance); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -1855,7 +1871,7 @@ fn lazy_removal_works() { ),); let addr = Contracts::contract_address(&ALICE, &hash, &[]); - let info = >::get(&addr).unwrap(); + let info = get_contract(&addr); let trie = &info.child_trie_info(); // Put value into the contracts child trie @@ -1863,7 +1879,7 @@ fn lazy_removal_works() { // Terminate the contract assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, @@ -1914,7 +1930,7 @@ fn lazy_batch_removal_works() { for i in 0..3u8 { assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -1924,7 +1940,7 @@ fn lazy_batch_removal_works() { ),); let addr = Contracts::contract_address(&ALICE, &hash, &[i]); - let info = >::get(&addr).unwrap(); + let info = get_contract(&addr); let trie = &info.child_trie_info(); // Put value into the contracts child trie @@ -1933,7 +1949,7 @@ fn lazy_batch_removal_works() { // Terminate the contract. Contract info should be gone, but value should be still there // as the lazy removal did not run, yet. assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, @@ -1976,7 +1992,7 @@ fn lazy_removal_partial_remove_works() { let _ = Balances::deposit_creating(&ALICE, 1000 * min_balance); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -1986,7 +2002,7 @@ fn lazy_removal_partial_remove_works() { ),); let addr = Contracts::contract_address(&ALICE, &hash, &[]); - let info = >::get(&addr).unwrap(); + let info = get_contract(&addr); // Put value into the contracts child trie for val in &vals { @@ -2003,7 +2019,7 @@ fn lazy_removal_partial_remove_works() { // Terminate the contract assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, @@ -2088,7 +2104,7 @@ fn lazy_removal_does_no_run_on_low_remaining_weight() { let _ = Balances::deposit_creating(&ALICE, 1000 * min_balance); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -2098,7 +2114,7 @@ fn lazy_removal_does_no_run_on_low_remaining_weight() { ),); let addr = Contracts::contract_address(&ALICE, &hash, &[]); - let info = >::get(&addr).unwrap(); + let info = get_contract(&addr); let trie = &info.child_trie_info(); // Put value into the contracts child trie @@ -2106,7 +2122,7 @@ fn lazy_removal_does_no_run_on_low_remaining_weight() { // Terminate the contract assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, @@ -2156,7 +2172,7 @@ fn lazy_removal_does_not_use_all_weight() { let _ = Balances::deposit_creating(&ALICE, 1000 * min_balance); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -2166,7 +2182,7 @@ fn lazy_removal_does_not_use_all_weight() { ),); let addr = Contracts::contract_address(&ALICE, &hash, &[]); - let info = >::get(&addr).unwrap(); + let info = get_contract(&addr); let (weight_per_key, max_keys) = Storage::::deletion_budget(1, weight_limit); // We create a contract with one less storage item than we can remove within the limit @@ -2189,7 +2205,7 @@ fn lazy_removal_does_not_use_all_weight() { // Terminate the contract assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, @@ -2236,7 +2252,7 @@ fn deletion_queue_full() { let _ = Balances::deposit_creating(&ALICE, 1000 * min_balance); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -2252,12 +2268,12 @@ fn deletion_queue_full() { // Terminate the contract should fail assert_err_ignore_postinfo!( - Contracts::call(Origin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, None, vec![],), + Contracts::call(RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, None, vec![],), Error::::DeletionQueueFull, ); // Contract should exist because removal failed - >::get(&addr).unwrap(); + get_contract(&addr); }); } @@ -2270,7 +2286,7 @@ fn refcounter() { // Create two contracts with the same code and check that they do in fact share it. assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -2279,7 +2295,7 @@ fn refcounter() { vec![0], )); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -2291,7 +2307,7 @@ fn refcounter() { // Sharing should also work with the usual instantiate call assert_ok!(Contracts::instantiate( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -2307,18 +2323,39 @@ fn refcounter() { let addr2 = Contracts::contract_address(&ALICE, &code_hash, &[2]); // Terminating one contract should decrement the refcount - assert_ok!(Contracts::call(Origin::signed(ALICE), addr0, 0, GAS_LIMIT, None, vec![])); + assert_ok!(Contracts::call( + RuntimeOrigin::signed(ALICE), + addr0, + 0, + GAS_LIMIT, + None, + vec![] + )); assert_refcount!(code_hash, 2); // remove another one - assert_ok!(Contracts::call(Origin::signed(ALICE), addr1, 0, GAS_LIMIT, None, vec![])); + assert_ok!(Contracts::call( + RuntimeOrigin::signed(ALICE), + addr1, + 0, + GAS_LIMIT, + None, + vec![] + )); assert_refcount!(code_hash, 1); // Pristine code should still be there crate::PristineCode::::get(code_hash).unwrap(); // remove the last contract - assert_ok!(Contracts::call(Origin::signed(ALICE), addr2, 0, GAS_LIMIT, None, vec![])); + assert_ok!(Contracts::call( + RuntimeOrigin::signed(ALICE), + addr2, + 0, + GAS_LIMIT, + None, + vec![] + )); assert_refcount!(code_hash, 0); // refcount is `0` but code should still exists because it needs to be removed manually @@ -2337,7 +2374,7 @@ fn reinstrument_does_charge() { let code_len = wasm.len() as u32; assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -2386,7 +2423,7 @@ fn debug_message_works() { ExtBuilder::default().existential_deposit(50).build().execute_with(|| { let _ = Balances::deposit_creating(&ALICE, 1_000_000); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 30_000, GAS_LIMIT, None, @@ -2409,7 +2446,7 @@ fn debug_message_logging_disabled() { ExtBuilder::default().existential_deposit(50).build().execute_with(|| { let _ = Balances::deposit_creating(&ALICE, 1_000_000); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 30_000, GAS_LIMIT, None, @@ -2422,7 +2459,7 @@ fn debug_message_logging_disabled() { let result = Contracts::bare_call(ALICE, addr.clone(), 0, GAS_LIMIT, None, vec![], false); assert_matches!(result.result, Ok(_)); // the dispatchables always run without debugging - assert_ok!(Contracts::call(Origin::signed(ALICE), addr, 0, GAS_LIMIT, None, vec![])); + assert_ok!(Contracts::call(RuntimeOrigin::signed(ALICE), addr, 0, GAS_LIMIT, None, vec![])); assert!(result.debug_message.is_empty()); }); } @@ -2434,7 +2471,7 @@ fn debug_message_invalid_utf8() { ExtBuilder::default().existential_deposit(50).build().execute_with(|| { let _ = Balances::deposit_creating(&ALICE, 1_000_000); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 30_000, GAS_LIMIT, None, @@ -2458,7 +2495,7 @@ fn gas_estimation_nested_call_fixed_limit() { let _ = Balances::deposit_creating(&CHARLIE, 1000 * min_balance); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -2469,7 +2506,7 @@ fn gas_estimation_nested_call_fixed_limit() { let addr_caller = Contracts::contract_address(&ALICE, &caller_hash, &[0]); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -2527,7 +2564,7 @@ fn gas_estimation_call_runtime() { let _ = Balances::deposit_creating(&CHARLIE, 1000 * min_balance); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -2538,7 +2575,7 @@ fn gas_estimation_call_runtime() { let addr_caller = Contracts::contract_address(&ALICE, &caller_hash, &[0]); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), min_balance * 100, GAS_LIMIT, None, @@ -2595,7 +2632,7 @@ fn ecdsa_recover() { // Instantiate the ecdsa_recover contract. assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 100_000, GAS_LIMIT, None, @@ -2649,7 +2686,7 @@ fn upload_code_works() { assert!(!>::contains_key(code_hash)); assert_ok!(Contracts::upload_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), wasm, Some(codec::Compact(1_000)) )); @@ -2687,7 +2724,7 @@ fn upload_code_limit_too_low() { initialize_block(2); assert_noop!( - Contracts::upload_code(Origin::signed(ALICE), wasm, Some(codec::Compact(100))), + Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, Some(codec::Compact(100))), >::StorageDepositLimitExhausted, ); @@ -2706,7 +2743,7 @@ fn upload_code_not_enough_balance() { initialize_block(2); assert_noop!( - Contracts::upload_code(Origin::signed(ALICE), wasm, Some(codec::Compact(1_000))), + Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, Some(codec::Compact(1_000))), >::StorageDepositNotEnoughFunds, ); @@ -2725,13 +2762,13 @@ fn remove_code_works() { initialize_block(2); assert_ok!(Contracts::upload_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), wasm, Some(codec::Compact(1_000)) )); assert!(>::contains_key(code_hash)); - assert_ok!(Contracts::remove_code(Origin::signed(ALICE), code_hash)); + assert_ok!(Contracts::remove_code(RuntimeOrigin::signed(ALICE), code_hash)); assert!(!>::contains_key(code_hash)); assert_eq!( @@ -2779,13 +2816,13 @@ fn remove_code_wrong_origin() { initialize_block(2); assert_ok!(Contracts::upload_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), wasm, Some(codec::Compact(1_000)) )); assert_noop!( - Contracts::remove_code(Origin::signed(BOB), code_hash), + Contracts::remove_code(RuntimeOrigin::signed(BOB), code_hash), sp_runtime::traits::BadOrigin, ); @@ -2818,7 +2855,7 @@ fn remove_code_in_use() { let _ = Balances::deposit_creating(&ALICE, 1_000_000); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 0, GAS_LIMIT, None, @@ -2831,7 +2868,7 @@ fn remove_code_in_use() { initialize_block(2); assert_noop!( - Contracts::remove_code(Origin::signed(ALICE), code_hash), + Contracts::remove_code(RuntimeOrigin::signed(ALICE), code_hash), >::CodeInUse, ); @@ -2850,7 +2887,7 @@ fn remove_code_not_found() { initialize_block(2); assert_noop!( - Contracts::remove_code(Origin::signed(ALICE), code_hash), + Contracts::remove_code(RuntimeOrigin::signed(ALICE), code_hash), >::CodeNotFound, ); @@ -2870,7 +2907,7 @@ fn instantiate_with_zero_balance_works() { // Instantiate the BOB contract. assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 0, GAS_LIMIT, None, @@ -2881,7 +2918,7 @@ fn instantiate_with_zero_balance_works() { let addr = Contracts::contract_address(&ALICE, &code_hash, &[]); // Check that the BOB contract has been instantiated. - assert_matches!(ContractInfoOf::::get(&addr), Some(_)); + get_contract(&addr); // Make sure the account exists even though no free balance was send assert_eq!(::Currency::free_balance(&addr), 0,); @@ -2963,7 +3000,7 @@ fn instantiate_with_below_existential_deposit_works() { // Instantiate the BOB contract. assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 50, GAS_LIMIT, None, @@ -2974,7 +3011,7 @@ fn instantiate_with_below_existential_deposit_works() { let addr = Contracts::contract_address(&ALICE, &code_hash, &[]); // Check that the BOB contract has been instantiated. - assert_matches!(ContractInfoOf::::get(&addr), Some(_)); + get_contract(&addr); // Make sure the account exists even though no free balance was send assert_eq!(::Currency::free_balance(&addr), 50,); @@ -3061,7 +3098,7 @@ fn storage_deposit_works() { let mut deposit = ::Currency::minimum_balance(); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 0, GAS_LIMIT, None, @@ -3076,7 +3113,7 @@ fn storage_deposit_works() { // Create storage assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 42, GAS_LIMIT, @@ -3086,11 +3123,11 @@ fn storage_deposit_works() { // 4 is for creating 2 storage items let charged0 = 4 + 1_000 + 5_000; deposit += charged0; - assert_eq!(>::get(&addr).unwrap().storage_deposit, deposit); + assert_eq!(get_contract(&addr).total_deposit(), deposit); // Add more storage (but also remove some) assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, @@ -3099,20 +3136,21 @@ fn storage_deposit_works() { )); let charged1 = 1_000 - 100; deposit += charged1; - assert_eq!(>::get(&addr).unwrap().storage_deposit, deposit); + assert_eq!(get_contract(&addr).total_deposit(), deposit); // Remove more storage (but also add some) assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, None, (2_100u32, 900u32).encode(), )); - let refunded0 = 4_000 - 100; + // -1 for numeric instability + let refunded0 = 4_000 - 100 - 1; deposit -= refunded0; - assert_eq!(>::get(&addr).unwrap().storage_deposit, deposit); + assert_eq!(get_contract(&addr).total_deposit(), deposit); assert_eq!( System::events(), @@ -3210,7 +3248,7 @@ fn set_code_extrinsic() { let _ = Balances::deposit_creating(&ALICE, 1_000_000); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 0, GAS_LIMIT, None, @@ -3220,48 +3258,48 @@ fn set_code_extrinsic() { )); let addr = Contracts::contract_address(&ALICE, &code_hash, &[]); - assert_ok!(Contracts::upload_code(Origin::signed(ALICE), new_wasm, None,)); + assert_ok!(Contracts::upload_code(RuntimeOrigin::signed(ALICE), new_wasm, None,)); // Drop previous events initialize_block(2); - assert_eq!(>::get(&addr).unwrap().code_hash, code_hash); + assert_eq!(get_contract(&addr).code_hash, code_hash); assert_refcount!(&code_hash, 1); assert_refcount!(&new_code_hash, 0); // only root can execute this extrinsic assert_noop!( - Contracts::set_code(Origin::signed(ALICE), addr.clone(), new_code_hash), + Contracts::set_code(RuntimeOrigin::signed(ALICE), addr.clone(), new_code_hash), sp_runtime::traits::BadOrigin, ); - assert_eq!(>::get(&addr).unwrap().code_hash, code_hash); + assert_eq!(get_contract(&addr).code_hash, code_hash); assert_refcount!(&code_hash, 1); assert_refcount!(&new_code_hash, 0); assert_eq!(System::events(), vec![],); // contract must exist assert_noop!( - Contracts::set_code(Origin::root(), BOB, new_code_hash), + Contracts::set_code(RuntimeOrigin::root(), BOB, new_code_hash), >::ContractNotFound, ); - assert_eq!(>::get(&addr).unwrap().code_hash, code_hash); + assert_eq!(get_contract(&addr).code_hash, code_hash); assert_refcount!(&code_hash, 1); assert_refcount!(&new_code_hash, 0); assert_eq!(System::events(), vec![],); // new code hash must exist assert_noop!( - Contracts::set_code(Origin::root(), addr.clone(), Default::default()), + Contracts::set_code(RuntimeOrigin::root(), addr.clone(), Default::default()), >::CodeNotFound, ); - assert_eq!(>::get(&addr).unwrap().code_hash, code_hash); + assert_eq!(get_contract(&addr).code_hash, code_hash); assert_refcount!(&code_hash, 1); assert_refcount!(&new_code_hash, 0); assert_eq!(System::events(), vec![],); // successful call - assert_ok!(Contracts::set_code(Origin::root(), addr.clone(), new_code_hash)); - assert_eq!(>::get(&addr).unwrap().code_hash, new_code_hash); + assert_ok!(Contracts::set_code(RuntimeOrigin::root(), addr.clone(), new_code_hash)); + assert_eq!(get_contract(&addr).code_hash, new_code_hash); assert_refcount!(&code_hash, 0); assert_refcount!(&new_code_hash, 1); assert_eq!( @@ -3287,7 +3325,7 @@ fn call_after_killed_account_needs_funding() { let min_balance = ::Currency::minimum_balance(); assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 700, GAS_LIMIT, None, @@ -3312,7 +3350,7 @@ fn call_after_killed_account_needs_funding() { // account in order to send balance there. assert_err_ignore_postinfo!( Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), min_balance - 1, GAS_LIMIT, @@ -3324,7 +3362,7 @@ fn call_after_killed_account_needs_funding() { // Sending zero should work as it does not do a transfer assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, @@ -3334,7 +3372,7 @@ fn call_after_killed_account_needs_funding() { // Sending minimum balance should work assert_ok!(Contracts::call( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), addr.clone(), min_balance, GAS_LIMIT, @@ -3416,12 +3454,12 @@ fn contract_reverted() { let input = (flags.bits(), buffer).encode(); // We just upload the code for later use - assert_ok!(Contracts::upload_code(Origin::signed(ALICE), wasm.clone(), None)); + assert_ok!(Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm.clone(), None)); // Calling extrinsic: revert leads to an error assert_err_ignore_postinfo!( Contracts::instantiate( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 0, GAS_LIMIT, None, @@ -3435,7 +3473,7 @@ fn contract_reverted() { // Calling extrinsic: revert leads to an error assert_err_ignore_postinfo!( Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 0, GAS_LIMIT, None, @@ -3483,7 +3521,14 @@ fn contract_reverted() { // Calling extrinsic: revert leads to an error assert_err_ignore_postinfo!( - Contracts::call(Origin::signed(ALICE), addr.clone(), 0, GAS_LIMIT, None, input.clone()), + Contracts::call( + RuntimeOrigin::signed(ALICE), + addr.clone(), + 0, + GAS_LIMIT, + None, + input.clone() + ), >::ContractReverted, ); @@ -3503,7 +3548,7 @@ fn code_rejected_error_works() { let _ = Balances::deposit_creating(&ALICE, 1_000_000); assert_noop!( - Contracts::upload_code(Origin::signed(ALICE), wasm.clone(), None), + Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm.clone(), None), >::CodeRejected, ); @@ -3537,7 +3582,7 @@ fn set_code_hash() { // Instantiate the 'caller' assert_ok!(Contracts::instantiate_with_code( - Origin::signed(ALICE), + RuntimeOrigin::signed(ALICE), 300_000, GAS_LIMIT, None, @@ -3546,7 +3591,7 @@ fn set_code_hash() { vec![], )); // upload new code - assert_ok!(Contracts::upload_code(Origin::signed(ALICE), new_wasm.clone(), None)); + assert_ok!(Contracts::upload_code(RuntimeOrigin::signed(ALICE), new_wasm.clone(), None)); System::reset_events(); @@ -3604,3 +3649,301 @@ fn set_code_hash() { ); }); } + +#[test] +fn storage_deposit_limit_is_enforced() { + let (wasm, code_hash) = compile_module::("store").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = Balances::deposit_creating(&ALICE, 1_000_000); + let min_balance = ::Currency::minimum_balance(); + + // Instantiate the BOB contract. + assert_ok!(Contracts::instantiate_with_code( + RuntimeOrigin::signed(ALICE), + 0, + GAS_LIMIT, + None, + wasm, + vec![], + vec![], + )); + let addr = Contracts::contract_address(&ALICE, &code_hash, &[]); + + // Check that the BOB contract has been instantiated and has the minimum balance + assert_eq!(get_contract(&addr).total_deposit(), min_balance); + assert_eq!(::Currency::total_balance(&addr), min_balance); + + // Create 100 bytes of storage with a price of per byte + assert_err_ignore_postinfo!( + Contracts::call( + RuntimeOrigin::signed(ALICE), + addr.clone(), + 0, + GAS_LIMIT, + Some(codec::Compact(1)), + 100u32.to_le_bytes().to_vec() + ), + >::StorageDepositLimitExhausted, + ); + }); +} + +#[test] +fn storage_deposit_limit_is_enforced_late() { + let (wasm_caller, code_hash_caller) = + compile_module::("create_storage_and_call").unwrap(); + let (wasm_callee, code_hash_callee) = compile_module::("store").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = Balances::deposit_creating(&ALICE, 1_000_000); + + // Create both contracts: Constructors do nothing. + assert_ok!(Contracts::instantiate_with_code( + RuntimeOrigin::signed(ALICE), + 0, + GAS_LIMIT, + None, + wasm_caller, + vec![], + vec![], + )); + let addr_caller = Contracts::contract_address(&ALICE, &code_hash_caller, &[]); + assert_ok!(Contracts::instantiate_with_code( + RuntimeOrigin::signed(ALICE), + 0, + GAS_LIMIT, + None, + wasm_callee, + vec![], + vec![], + )); + let addr_callee = Contracts::contract_address(&ALICE, &code_hash_callee, &[]); + + // Create 100 bytes of storage with a price of per byte + // This is 100 Balance + 2 Balance for the item + assert_ok!(Contracts::call( + RuntimeOrigin::signed(ALICE), + addr_callee.clone(), + 0, + GAS_LIMIT, + Some(codec::Compact(102)), + 100u32.to_le_bytes().to_vec() + )); + + // We do not remove any storage but require 14 bytes of storage for the new + // storage created in the immediate contract. + assert_err_ignore_postinfo!( + Contracts::call( + RuntimeOrigin::signed(ALICE), + addr_caller.clone(), + 0, + GAS_LIMIT, + Some(codec::Compact(5)), + 100u32 + .to_le_bytes() + .as_ref() + .iter() + .chain(<_ as AsRef<[u8]>>::as_ref(&addr_callee)) + .cloned() + .collect(), + ), + >::StorageDepositLimitExhausted, + ); + + // Allow for the additional 14 bytes but demand an additional byte in the callee contract. + assert_err_ignore_postinfo!( + Contracts::call( + RuntimeOrigin::signed(ALICE), + addr_caller.clone(), + 0, + GAS_LIMIT, + Some(codec::Compact(14)), + 101u32 + .to_le_bytes() + .as_ref() + .iter() + .chain(<_ as AsRef<[u8]>>::as_ref(&addr_callee)) + .cloned() + .collect(), + ), + >::StorageDepositLimitExhausted, + ); + + // Refund in the callee contract but not enough to cover the 14 balance required by the + // caller. + assert_err_ignore_postinfo!( + Contracts::call( + RuntimeOrigin::signed(ALICE), + addr_caller.clone(), + 0, + GAS_LIMIT, + Some(codec::Compact(0)), + 87u32 + .to_le_bytes() + .as_ref() + .iter() + .chain(<_ as AsRef<[u8]>>::as_ref(&addr_callee)) + .cloned() + .collect(), + ), + >::StorageDepositLimitExhausted, + ); + + let _ = Balances::make_free_balance_be(&ALICE, 1_000); + + // Send more than the sender has balance. + assert_err_ignore_postinfo!( + Contracts::call( + RuntimeOrigin::signed(ALICE), + addr_caller.clone(), + 0, + GAS_LIMIT, + Some(codec::Compact(50)), + 1_200u32 + .to_le_bytes() + .as_ref() + .iter() + .chain(<_ as AsRef<[u8]>>::as_ref(&addr_callee)) + .cloned() + .collect(), + ), + >::StorageDepositLimitExhausted, + ); + + // Same as above but allow for the additional balance. + assert_ok!(Contracts::call( + RuntimeOrigin::signed(ALICE), + addr_caller.clone(), + 0, + GAS_LIMIT, + Some(codec::Compact(1)), + 87u32 + .to_le_bytes() + .as_ref() + .iter() + .chain(<_ as AsRef<[u8]>>::as_ref(&addr_callee)) + .cloned() + .collect(), + )); + }); +} + +#[test] +fn deposit_limit_honors_liquidity_restrictions() { + let (wasm, code_hash) = compile_module::("store").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = Balances::deposit_creating(&ALICE, 1_000_000); + let _ = Balances::deposit_creating(&BOB, 1_000); + let min_balance = ::Currency::minimum_balance(); + + // Instantiate the BOB contract. + assert_ok!(Contracts::instantiate_with_code( + RuntimeOrigin::signed(ALICE), + 0, + GAS_LIMIT, + None, + wasm, + vec![], + vec![], + )); + let addr = Contracts::contract_address(&ALICE, &code_hash, &[]); + + // Check that the contract has been instantiated and has the minimum balance + assert_eq!(get_contract(&addr).total_deposit(), min_balance); + assert_eq!(::Currency::total_balance(&addr), min_balance); + + // check that the lock ins honored + Balances::set_lock([0; 8], &BOB, 1_000, WithdrawReasons::TRANSFER); + assert_err_ignore_postinfo!( + Contracts::call( + RuntimeOrigin::signed(BOB), + addr.clone(), + 0, + GAS_LIMIT, + Some(codec::Compact(200)), + 100u32.to_le_bytes().to_vec() + ), + >::StorageDepositNotEnoughFunds, + ); + assert_eq!(Balances::free_balance(&BOB), 1_000); + }); +} + +#[test] +fn deposit_limit_honors_existential_deposit() { + let (wasm, code_hash) = compile_module::("store").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = Balances::deposit_creating(&ALICE, 1_000_000); + let _ = Balances::deposit_creating(&BOB, 1_000); + let min_balance = ::Currency::minimum_balance(); + + // Instantiate the BOB contract. + assert_ok!(Contracts::instantiate_with_code( + RuntimeOrigin::signed(ALICE), + 0, + GAS_LIMIT, + None, + wasm, + vec![], + vec![], + )); + let addr = Contracts::contract_address(&ALICE, &code_hash, &[]); + + // Check that the contract has been instantiated and has the minimum balance + assert_eq!(get_contract(&addr).total_deposit(), min_balance); + assert_eq!(::Currency::total_balance(&addr), min_balance); + + // check that the deposit can't bring the account below the existential deposit + assert_err_ignore_postinfo!( + Contracts::call( + RuntimeOrigin::signed(BOB), + addr.clone(), + 0, + GAS_LIMIT, + Some(codec::Compact(900)), + 100u32.to_le_bytes().to_vec() + ), + >::StorageDepositNotEnoughFunds, + ); + assert_eq!(Balances::free_balance(&BOB), 1_000); + }); +} + +#[test] +fn deposit_limit_honors_min_leftover() { + let (wasm, code_hash) = compile_module::("store").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = Balances::deposit_creating(&ALICE, 1_000_000); + let _ = Balances::deposit_creating(&BOB, 1_000); + let min_balance = ::Currency::minimum_balance(); + + // Instantiate the BOB contract. + assert_ok!(Contracts::instantiate_with_code( + RuntimeOrigin::signed(ALICE), + 0, + GAS_LIMIT, + None, + wasm, + vec![], + vec![], + )); + let addr = Contracts::contract_address(&ALICE, &code_hash, &[]); + + // Check that the contract has been instantiated and has the minimum balance + assert_eq!(get_contract(&addr).total_deposit(), min_balance); + assert_eq!(::Currency::total_balance(&addr), min_balance); + + // check that the minumum leftover (value send) is considered + assert_err_ignore_postinfo!( + Contracts::call( + RuntimeOrigin::signed(BOB), + addr.clone(), + 400, + GAS_LIMIT, + Some(codec::Compact(500)), + 100u32.to_le_bytes().to_vec() + ), + >::StorageDepositNotEnoughFunds, + ); + assert_eq!(Balances::free_balance(&BOB), 1_000); + }); +} diff --git a/frame/contracts/src/wasm/mod.rs b/frame/contracts/src/wasm/mod.rs index 085bc5a8c6423..126a37e9401ec 100644 --- a/frame/contracts/src/wasm/mod.rs +++ b/frame/contracts/src/wasm/mod.rs @@ -275,7 +275,6 @@ mod tests { }; use assert_matches::assert_matches; use frame_support::{assert_ok, dispatch::DispatchResultWithPostInfo, weights::Weight}; - use hex_literal::hex; use pallet_contracts_primitives::{ExecReturnValue, ReturnFlags}; use pretty_assertions::assert_eq; use sp_core::{Bytes, H256}; @@ -1828,10 +1827,9 @@ mod tests { output, ExecReturnValue { flags: ReturnFlags::empty(), - data: Bytes( - hex!("000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F") - .to_vec() - ), + data: array_bytes::hex_into_unchecked( + "000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F" + ) }, ); } @@ -1901,7 +1899,9 @@ mod tests { flags: ReturnFlags::empty(), data: Bytes( ( - hex!("000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F"), + array_bytes::hex2array_unchecked::<32>( + "000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F" + ), 42u64, ) .encode() @@ -2110,7 +2110,7 @@ mod tests { fn seal_return_with_success_status() { let output = execute( CODE_RETURN_WITH_DATA, - hex!("00000000445566778899").to_vec(), + array_bytes::hex2bytes_unchecked("00000000445566778899"), MockExt::default(), ) .unwrap(); @@ -2119,7 +2119,7 @@ mod tests { output, ExecReturnValue { flags: ReturnFlags::empty(), - data: Bytes(hex!("445566778899").to_vec()), + data: Bytes(array_bytes::hex2bytes_unchecked("445566778899")), } ); assert!(!output.did_revert()); @@ -2127,15 +2127,18 @@ mod tests { #[test] fn return_with_revert_status() { - let output = - execute(CODE_RETURN_WITH_DATA, hex!("010000005566778899").to_vec(), MockExt::default()) - .unwrap(); + let output = execute( + CODE_RETURN_WITH_DATA, + array_bytes::hex2bytes_unchecked("010000005566778899"), + MockExt::default(), + ) + .unwrap(); assert_eq!( output, ExecReturnValue { flags: ReturnFlags::REVERT, - data: Bytes(hex!("5566778899").to_vec()), + data: Bytes(array_bytes::hex2bytes_unchecked("5566778899")), } ); assert!(output.did_revert()); diff --git a/frame/contracts/src/wasm/prepare.rs b/frame/contracts/src/wasm/prepare.rs index 9c130b562c275..e8873f604c9c7 100644 --- a/frame/contracts/src/wasm/prepare.rs +++ b/frame/contracts/src/wasm/prepare.rs @@ -426,7 +426,7 @@ fn do_preparation( .saturating_add(original_code_len) .saturating_add(>::max_encoded_len()) as u32; let deposit = Diff { bytes_added, items_added: 3, ..Default::default() } - .to_deposit::() + .update_contract::(None) .charge_or_zero(); module.owner_info = Some(OwnerInfo { owner, deposit, refcount: 0 }); diff --git a/frame/conviction-voting/src/tests.rs b/frame/conviction-voting/src/tests.rs index 7a97a46086398..7a3f80442014a 100644 --- a/frame/conviction-voting/src/tests.rs +++ b/frame/conviction-voting/src/tests.rs @@ -65,7 +65,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; @@ -269,28 +269,28 @@ fn basic_stuff() { #[test] fn basic_voting_works() { new_test_ext().execute_with(|| { - assert_ok!(Voting::vote(Origin::signed(1), 3, aye(2, 5))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, aye(2, 5))); assert_eq!(tally(3), Tally::from_parts(10, 0, 2)); - assert_ok!(Voting::vote(Origin::signed(1), 3, nay(2, 5))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, nay(2, 5))); assert_eq!(tally(3), Tally::from_parts(0, 10, 0)); assert_eq!(Balances::usable_balance(1), 8); - assert_ok!(Voting::vote(Origin::signed(1), 3, aye(5, 1))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, aye(5, 1))); assert_eq!(tally(3), Tally::from_parts(5, 0, 5)); - assert_ok!(Voting::vote(Origin::signed(1), 3, nay(5, 1))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, nay(5, 1))); assert_eq!(tally(3), Tally::from_parts(0, 5, 0)); assert_eq!(Balances::usable_balance(1), 5); - assert_ok!(Voting::vote(Origin::signed(1), 3, aye(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, aye(10, 0))); assert_eq!(tally(3), Tally::from_parts(1, 0, 10)); - assert_ok!(Voting::vote(Origin::signed(1), 3, nay(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, nay(10, 0))); assert_eq!(tally(3), Tally::from_parts(0, 1, 0)); assert_eq!(Balances::usable_balance(1), 0); - assert_ok!(Voting::remove_vote(Origin::signed(1), None, 3)); + assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(1), None, 3)); assert_eq!(tally(3), Tally::from_parts(0, 0, 0)); - assert_ok!(Voting::unlock(Origin::signed(1), class(3), 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), class(3), 1)); assert_eq!(Balances::usable_balance(1), 10); }); } @@ -298,28 +298,28 @@ fn basic_voting_works() { #[test] fn voting_balance_gets_locked() { new_test_ext().execute_with(|| { - assert_ok!(Voting::vote(Origin::signed(1), 3, aye(2, 5))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, aye(2, 5))); assert_eq!(tally(3), Tally::from_parts(10, 0, 2)); - assert_ok!(Voting::vote(Origin::signed(1), 3, nay(2, 5))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, nay(2, 5))); assert_eq!(tally(3), Tally::from_parts(0, 10, 0)); assert_eq!(Balances::usable_balance(1), 8); - assert_ok!(Voting::vote(Origin::signed(1), 3, aye(5, 1))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, aye(5, 1))); assert_eq!(tally(3), Tally::from_parts(5, 0, 5)); - assert_ok!(Voting::vote(Origin::signed(1), 3, nay(5, 1))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, nay(5, 1))); assert_eq!(tally(3), Tally::from_parts(0, 5, 0)); assert_eq!(Balances::usable_balance(1), 5); - assert_ok!(Voting::vote(Origin::signed(1), 3, aye(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, aye(10, 0))); assert_eq!(tally(3), Tally::from_parts(1, 0, 10)); - assert_ok!(Voting::vote(Origin::signed(1), 3, nay(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, nay(10, 0))); assert_eq!(tally(3), Tally::from_parts(0, 1, 0)); assert_eq!(Balances::usable_balance(1), 0); - assert_ok!(Voting::remove_vote(Origin::signed(1), None, 3)); + assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(1), None, 3)); assert_eq!(tally(3), Tally::from_parts(0, 0, 0)); - assert_ok!(Voting::unlock(Origin::signed(1), class(3), 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), class(3), 1)); assert_eq!(Balances::usable_balance(1), 10); }); } @@ -327,12 +327,12 @@ fn voting_balance_gets_locked() { #[test] fn successful_but_zero_conviction_vote_balance_can_be_unlocked() { new_test_ext().execute_with(|| { - assert_ok!(Voting::vote(Origin::signed(1), 3, aye(1, 1))); - assert_ok!(Voting::vote(Origin::signed(2), 3, nay(20, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, aye(1, 1))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(2), 3, nay(20, 0))); let c = class(3); Polls::set(vec![(3, Completed(3, false))].into_iter().collect()); - assert_ok!(Voting::remove_vote(Origin::signed(2), Some(c), 3)); - assert_ok!(Voting::unlock(Origin::signed(2), c, 2)); + assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(2), Some(c), 3)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(2), c, 2)); assert_eq!(Balances::usable_balance(2), 20); }); } @@ -340,12 +340,12 @@ fn successful_but_zero_conviction_vote_balance_can_be_unlocked() { #[test] fn unsuccessful_conviction_vote_balance_can_be_unlocked() { new_test_ext().execute_with(|| { - assert_ok!(Voting::vote(Origin::signed(1), 3, aye(1, 1))); - assert_ok!(Voting::vote(Origin::signed(2), 3, nay(20, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, aye(1, 1))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(2), 3, nay(20, 0))); let c = class(3); Polls::set(vec![(3, Completed(3, false))].into_iter().collect()); - assert_ok!(Voting::remove_vote(Origin::signed(1), Some(c), 3)); - assert_ok!(Voting::unlock(Origin::signed(1), c, 1)); + assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(1), Some(c), 3)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), c, 1)); assert_eq!(Balances::usable_balance(1), 10); }); } @@ -354,17 +354,17 @@ fn unsuccessful_conviction_vote_balance_can_be_unlocked() { fn successful_conviction_vote_balance_stays_locked_for_correct_time() { new_test_ext().execute_with(|| { for i in 1..=5 { - assert_ok!(Voting::vote(Origin::signed(i), 3, aye(10, i as u8))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(i), 3, aye(10, i as u8))); } let c = class(3); Polls::set(vec![(3, Completed(3, true))].into_iter().collect()); for i in 1..=5 { - assert_ok!(Voting::remove_vote(Origin::signed(i), Some(c), 3)); + assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(i), Some(c), 3)); } for block in 1..=(3 + 5 * 3) { run_to(block); for i in 1..=5 { - assert_ok!(Voting::unlock(Origin::signed(i), c, i)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(i), c, i)); let expired = block >= (3 << (i - 1)) + 3; assert_eq!(Balances::usable_balance(i), i * 10 - if expired { 0 } else { 10 }); } @@ -385,20 +385,20 @@ fn classwise_delegation_works() { .into_iter() .collect(), ); - assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 5)); - assert_ok!(Voting::delegate(Origin::signed(1), 1, 3, Conviction::Locked1x, 5)); - assert_ok!(Voting::delegate(Origin::signed(1), 2, 4, Conviction::Locked1x, 5)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 0, 2, Conviction::Locked1x, 5)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 1, 3, Conviction::Locked1x, 5)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 2, 4, Conviction::Locked1x, 5)); assert_eq!(Balances::usable_balance(1), 5); - assert_ok!(Voting::vote(Origin::signed(2), 0, aye(10, 0))); - assert_ok!(Voting::vote(Origin::signed(2), 1, nay(10, 0))); - assert_ok!(Voting::vote(Origin::signed(2), 2, nay(10, 0))); - assert_ok!(Voting::vote(Origin::signed(3), 0, nay(10, 0))); - assert_ok!(Voting::vote(Origin::signed(3), 1, aye(10, 0))); - assert_ok!(Voting::vote(Origin::signed(3), 2, nay(10, 0))); - assert_ok!(Voting::vote(Origin::signed(4), 0, nay(10, 0))); - assert_ok!(Voting::vote(Origin::signed(4), 1, nay(10, 0))); - assert_ok!(Voting::vote(Origin::signed(4), 2, aye(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(2), 0, aye(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(2), 1, nay(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(2), 2, nay(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(3), 0, nay(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(3), 1, aye(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(3), 2, nay(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(4), 0, nay(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(4), 1, nay(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(4), 2, aye(10, 0))); // 4 hasn't voted yet assert_eq!( @@ -414,7 +414,7 @@ fn classwise_delegation_works() { ); // 4 votes nay to 3. - assert_ok!(Voting::vote(Origin::signed(4), 3, nay(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(4), 3, nay(10, 0))); assert_eq!( Polls::get(), vec![ @@ -428,8 +428,8 @@ fn classwise_delegation_works() { ); // Redelegate for class 2 to account 3. - assert_ok!(Voting::undelegate(Origin::signed(1), 2)); - assert_ok!(Voting::delegate(Origin::signed(1), 2, 3, Conviction::Locked1x, 5)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 2)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 2, 3, Conviction::Locked1x, 5)); assert_eq!( Polls::get(), vec![ @@ -443,12 +443,12 @@ fn classwise_delegation_works() { ); // Redelegating with a lower lock does not forget previous lock and updates correctly. - assert_ok!(Voting::undelegate(Origin::signed(1), 0)); - assert_ok!(Voting::undelegate(Origin::signed(1), 1)); - assert_ok!(Voting::undelegate(Origin::signed(1), 2)); - assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 3)); - assert_ok!(Voting::delegate(Origin::signed(1), 1, 3, Conviction::Locked1x, 3)); - assert_ok!(Voting::delegate(Origin::signed(1), 2, 4, Conviction::Locked1x, 3)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 0)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 1)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 2)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 0, 2, Conviction::Locked1x, 3)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 1, 3, Conviction::Locked1x, 3)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 2, 4, Conviction::Locked1x, 3)); assert_eq!( Polls::get(), vec![ @@ -462,24 +462,24 @@ fn classwise_delegation_works() { ); assert_eq!(Balances::usable_balance(1), 5); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); - assert_ok!(Voting::unlock(Origin::signed(1), 1, 1)); - assert_ok!(Voting::unlock(Origin::signed(1), 2, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 1, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 2, 1)); // unlock does nothing since the delegation already took place. assert_eq!(Balances::usable_balance(1), 5); // Redelegating with higher amount extends previous lock. - assert_ok!(Voting::undelegate(Origin::signed(1), 0)); - assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 6)); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 0)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 0, 2, Conviction::Locked1x, 6)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 4); - assert_ok!(Voting::undelegate(Origin::signed(1), 1)); - assert_ok!(Voting::delegate(Origin::signed(1), 1, 3, Conviction::Locked1x, 7)); - assert_ok!(Voting::unlock(Origin::signed(1), 1, 1)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 1)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 1, 3, Conviction::Locked1x, 7)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 1, 1)); assert_eq!(Balances::usable_balance(1), 3); - assert_ok!(Voting::undelegate(Origin::signed(1), 2)); - assert_ok!(Voting::delegate(Origin::signed(1), 2, 4, Conviction::Locked1x, 8)); - assert_ok!(Voting::unlock(Origin::signed(1), 2, 1)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 2)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 2, 4, Conviction::Locked1x, 8)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 2, 1)); assert_eq!(Balances::usable_balance(1), 2); assert_eq!( Polls::get(), @@ -499,14 +499,14 @@ fn classwise_delegation_works() { fn redelegation_after_vote_ending_should_keep_lock() { new_test_ext().execute_with(|| { Polls::set(vec![(0, Ongoing(Tally::new(0), 0))].into_iter().collect()); - assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 5)); - assert_ok!(Voting::vote(Origin::signed(2), 0, aye(10, 1))); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 0, 2, Conviction::Locked1x, 5)); + assert_ok!(Voting::vote(RuntimeOrigin::signed(2), 0, aye(10, 1))); Polls::set(vec![(0, Completed(1, true))].into_iter().collect()); assert_eq!(Balances::usable_balance(1), 5); - assert_ok!(Voting::undelegate(Origin::signed(1), 0)); - assert_ok!(Voting::delegate(Origin::signed(1), 0, 3, Conviction::Locked1x, 3)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 0)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 0, 3, Conviction::Locked1x, 3)); assert_eq!(Balances::usable_balance(1), 5); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 5); }); } @@ -523,9 +523,9 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { .into_iter() .collect(), ); - assert_ok!(Voting::vote(Origin::signed(1), 0, aye(5, 1))); - assert_ok!(Voting::vote(Origin::signed(1), 1, aye(10, 1))); - assert_ok!(Voting::vote(Origin::signed(1), 2, aye(5, 2))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 0, aye(5, 1))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 1, aye(10, 1))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 2, aye(5, 2))); assert_eq!(Balances::usable_balance(1), 0); Polls::set( @@ -533,28 +533,28 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { .into_iter() .collect(), ); - assert_ok!(Voting::remove_vote(Origin::signed(1), Some(0), 0)); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(1), Some(0), 0)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 0); - assert_ok!(Voting::remove_vote(Origin::signed(1), Some(0), 1)); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(1), Some(0), 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 0); - assert_ok!(Voting::remove_vote(Origin::signed(1), Some(0), 2)); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(1), Some(0), 2)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 0); run_to(3); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 0); run_to(6); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert!(Balances::usable_balance(1) <= 5); run_to(7); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 10); }); } @@ -562,25 +562,25 @@ fn lock_amalgamation_valid_with_multiple_removed_votes() { #[test] fn lock_amalgamation_valid_with_multiple_delegations() { new_test_ext().execute_with(|| { - assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 5)); - assert_ok!(Voting::undelegate(Origin::signed(1), 0)); - assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 10)); - assert_ok!(Voting::undelegate(Origin::signed(1), 0)); - assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked2x, 5)); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 0, 2, Conviction::Locked1x, 5)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 0)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 0, 2, Conviction::Locked1x, 10)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 0)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 0, 2, Conviction::Locked2x, 5)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 0); - assert_ok!(Voting::undelegate(Origin::signed(1), 0)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 0)); run_to(3); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 0); run_to(6); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert!(Balances::usable_balance(1) <= 5); run_to(7); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 10); }); } @@ -589,32 +589,32 @@ fn lock_amalgamation_valid_with_multiple_delegations() { fn lock_amalgamation_valid_with_move_roundtrip_to_delegation() { new_test_ext().execute_with(|| { Polls::set(vec![(0, Ongoing(Tally::new(0), 0))].into_iter().collect()); - assert_ok!(Voting::vote(Origin::signed(1), 0, aye(5, 1))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 0, aye(5, 1))); Polls::set(vec![(0, Completed(1, true))].into_iter().collect()); - assert_ok!(Voting::remove_vote(Origin::signed(1), Some(0), 0)); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(1), Some(0), 0)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 5); - assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 10)); - assert_ok!(Voting::undelegate(Origin::signed(1), 0)); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 0, 2, Conviction::Locked1x, 10)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 0)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 0); Polls::set(vec![(1, Ongoing(Tally::new(0), 0))].into_iter().collect()); - assert_ok!(Voting::vote(Origin::signed(1), 1, aye(5, 2))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 1, aye(5, 2))); Polls::set(vec![(1, Completed(1, true))].into_iter().collect()); - assert_ok!(Voting::remove_vote(Origin::signed(1), Some(0), 1)); + assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(1), Some(0), 1)); run_to(3); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 0); run_to(6); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert!(Balances::usable_balance(1) <= 5); run_to(7); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 10); }); } @@ -622,33 +622,33 @@ fn lock_amalgamation_valid_with_move_roundtrip_to_delegation() { #[test] fn lock_amalgamation_valid_with_move_roundtrip_to_casting() { new_test_ext().execute_with(|| { - assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 5)); - assert_ok!(Voting::undelegate(Origin::signed(1), 0)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 0, 2, Conviction::Locked1x, 5)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 0)); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 5); Polls::set(vec![(0, Ongoing(Tally::new(0), 0))].into_iter().collect()); - assert_ok!(Voting::vote(Origin::signed(1), 0, aye(10, 1))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 0, aye(10, 1))); Polls::set(vec![(0, Completed(1, true))].into_iter().collect()); - assert_ok!(Voting::remove_vote(Origin::signed(1), Some(0), 0)); + assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(1), Some(0), 0)); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 0); - assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked2x, 10)); - assert_ok!(Voting::undelegate(Origin::signed(1), 0)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 0, 2, Conviction::Locked2x, 10)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 0)); run_to(3); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 0); run_to(6); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert!(Balances::usable_balance(1) <= 5); run_to(7); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::usable_balance(1), 10); }); } @@ -656,30 +656,30 @@ fn lock_amalgamation_valid_with_move_roundtrip_to_casting() { #[test] fn lock_aggregation_over_different_classes_with_delegation_works() { new_test_ext().execute_with(|| { - assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 5)); - assert_ok!(Voting::delegate(Origin::signed(1), 1, 2, Conviction::Locked2x, 5)); - assert_ok!(Voting::delegate(Origin::signed(1), 2, 2, Conviction::Locked1x, 10)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 0, 2, Conviction::Locked1x, 5)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 1, 2, Conviction::Locked2x, 5)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 2, 2, Conviction::Locked1x, 10)); - assert_ok!(Voting::undelegate(Origin::signed(1), 0)); - assert_ok!(Voting::undelegate(Origin::signed(1), 1)); - assert_ok!(Voting::undelegate(Origin::signed(1), 2)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 0)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 1)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 2)); run_to(3); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); - assert_ok!(Voting::unlock(Origin::signed(1), 1, 1)); - assert_ok!(Voting::unlock(Origin::signed(1), 2, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 1, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 2, 1)); assert_eq!(Balances::usable_balance(1), 0); run_to(6); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); - assert_ok!(Voting::unlock(Origin::signed(1), 1, 1)); - assert_ok!(Voting::unlock(Origin::signed(1), 2, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 1, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 2, 1)); assert_eq!(Balances::usable_balance(1), 5); run_to(7); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); - assert_ok!(Voting::unlock(Origin::signed(1), 1, 1)); - assert_ok!(Voting::unlock(Origin::signed(1), 2, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 1, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 2, 1)); assert_eq!(Balances::usable_balance(1), 10); }); } @@ -696,34 +696,34 @@ fn lock_aggregation_over_different_classes_with_casting_works() { .into_iter() .collect(), ); - assert_ok!(Voting::vote(Origin::signed(1), 0, aye(5, 1))); - assert_ok!(Voting::vote(Origin::signed(1), 1, aye(10, 1))); - assert_ok!(Voting::vote(Origin::signed(1), 2, aye(5, 2))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 0, aye(5, 1))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 1, aye(10, 1))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 2, aye(5, 2))); Polls::set( vec![(0, Completed(1, true)), (1, Completed(1, true)), (2, Completed(1, true))] .into_iter() .collect(), ); - assert_ok!(Voting::remove_vote(Origin::signed(1), Some(0), 0)); - assert_ok!(Voting::remove_vote(Origin::signed(1), Some(1), 1)); - assert_ok!(Voting::remove_vote(Origin::signed(1), Some(2), 2)); + assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(1), Some(0), 0)); + assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(1), Some(1), 1)); + assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(1), Some(2), 2)); run_to(3); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); - assert_ok!(Voting::unlock(Origin::signed(1), 1, 1)); - assert_ok!(Voting::unlock(Origin::signed(1), 2, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 1, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 2, 1)); assert_eq!(Balances::usable_balance(1), 0); run_to(6); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); - assert_ok!(Voting::unlock(Origin::signed(1), 1, 1)); - assert_ok!(Voting::unlock(Origin::signed(1), 2, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 1, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 2, 1)); assert_eq!(Balances::usable_balance(1), 5); run_to(7); - assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); - assert_ok!(Voting::unlock(Origin::signed(1), 1, 1)); - assert_ok!(Voting::unlock(Origin::signed(1), 2, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 1, 1)); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), 2, 1)); assert_eq!(Balances::usable_balance(1), 10); }); } @@ -731,21 +731,30 @@ fn lock_aggregation_over_different_classes_with_casting_works() { #[test] fn errors_with_vote_work() { new_test_ext().execute_with(|| { - assert_noop!(Voting::vote(Origin::signed(1), 0, aye(10, 0)), Error::::NotOngoing); - assert_noop!(Voting::vote(Origin::signed(1), 1, aye(10, 0)), Error::::NotOngoing); - assert_noop!(Voting::vote(Origin::signed(1), 2, aye(10, 0)), Error::::NotOngoing); assert_noop!( - Voting::vote(Origin::signed(1), 3, aye(11, 0)), + Voting::vote(RuntimeOrigin::signed(1), 0, aye(10, 0)), + Error::::NotOngoing + ); + assert_noop!( + Voting::vote(RuntimeOrigin::signed(1), 1, aye(10, 0)), + Error::::NotOngoing + ); + assert_noop!( + Voting::vote(RuntimeOrigin::signed(1), 2, aye(10, 0)), + Error::::NotOngoing + ); + assert_noop!( + Voting::vote(RuntimeOrigin::signed(1), 3, aye(11, 0)), Error::::InsufficientFunds ); - assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::None, 10)); + assert_ok!(Voting::delegate(RuntimeOrigin::signed(1), 0, 2, Conviction::None, 10)); assert_noop!( - Voting::vote(Origin::signed(1), 3, aye(10, 0)), + Voting::vote(RuntimeOrigin::signed(1), 3, aye(10, 0)), Error::::AlreadyDelegating ); - assert_ok!(Voting::undelegate(Origin::signed(1), 0)); + assert_ok!(Voting::undelegate(RuntimeOrigin::signed(1), 0)); Polls::set( vec![ (0, Ongoing(Tally::new(0), 0)), @@ -756,11 +765,11 @@ fn errors_with_vote_work() { .into_iter() .collect(), ); - assert_ok!(Voting::vote(Origin::signed(1), 0, aye(10, 0))); - assert_ok!(Voting::vote(Origin::signed(1), 1, aye(10, 0))); - assert_ok!(Voting::vote(Origin::signed(1), 2, aye(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 0, aye(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 1, aye(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 2, aye(10, 0))); assert_noop!( - Voting::vote(Origin::signed(1), 3, aye(10, 0)), + Voting::vote(RuntimeOrigin::signed(1), 3, aye(10, 0)), Error::::MaxVotesReached ); }); @@ -770,21 +779,21 @@ fn errors_with_vote_work() { fn errors_with_delegating_work() { new_test_ext().execute_with(|| { assert_noop!( - Voting::delegate(Origin::signed(1), 0, 2, Conviction::None, 11), + Voting::delegate(RuntimeOrigin::signed(1), 0, 2, Conviction::None, 11), Error::::InsufficientFunds ); assert_noop!( - Voting::delegate(Origin::signed(1), 3, 2, Conviction::None, 10), + Voting::delegate(RuntimeOrigin::signed(1), 3, 2, Conviction::None, 10), Error::::BadClass ); - assert_ok!(Voting::vote(Origin::signed(1), 3, aye(10, 0))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, aye(10, 0))); assert_noop!( - Voting::delegate(Origin::signed(1), 0, 2, Conviction::None, 10), + Voting::delegate(RuntimeOrigin::signed(1), 0, 2, Conviction::None, 10), Error::::AlreadyVoting ); - assert_noop!(Voting::undelegate(Origin::signed(1), 0), Error::::NotDelegating); + assert_noop!(Voting::undelegate(RuntimeOrigin::signed(1), 0), Error::::NotDelegating); }); } @@ -792,31 +801,37 @@ fn errors_with_delegating_work() { fn remove_other_vote_works() { new_test_ext().execute_with(|| { assert_noop!( - Voting::remove_other_vote(Origin::signed(2), 1, 0, 3), + Voting::remove_other_vote(RuntimeOrigin::signed(2), 1, 0, 3), Error::::NotVoter ); - assert_ok!(Voting::vote(Origin::signed(1), 3, aye(10, 2))); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, aye(10, 2))); assert_noop!( - Voting::remove_other_vote(Origin::signed(2), 1, 0, 3), + Voting::remove_other_vote(RuntimeOrigin::signed(2), 1, 0, 3), Error::::NoPermission ); Polls::set(vec![(3, Completed(1, true))].into_iter().collect()); run_to(6); assert_noop!( - Voting::remove_other_vote(Origin::signed(2), 1, 0, 3), + Voting::remove_other_vote(RuntimeOrigin::signed(2), 1, 0, 3), Error::::NoPermissionYet ); run_to(7); - assert_ok!(Voting::remove_other_vote(Origin::signed(2), 1, 0, 3)); + assert_ok!(Voting::remove_other_vote(RuntimeOrigin::signed(2), 1, 0, 3)); }); } #[test] fn errors_with_remove_vote_work() { new_test_ext().execute_with(|| { - assert_noop!(Voting::remove_vote(Origin::signed(1), Some(0), 3), Error::::NotVoter); - assert_ok!(Voting::vote(Origin::signed(1), 3, aye(10, 2))); + assert_noop!( + Voting::remove_vote(RuntimeOrigin::signed(1), Some(0), 3), + Error::::NotVoter + ); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, aye(10, 2))); Polls::set(vec![(3, Completed(1, true))].into_iter().collect()); - assert_noop!(Voting::remove_vote(Origin::signed(1), None, 3), Error::::ClassNeeded); + assert_noop!( + Voting::remove_vote(RuntimeOrigin::signed(1), None, 3), + Error::::ClassNeeded + ); }); } diff --git a/frame/democracy/src/benchmarking.rs b/frame/democracy/src/benchmarking.rs index ab4075bc82fc5..ab7ee3331e319 100644 --- a/frame/democracy/src/benchmarking.rs +++ b/frame/democracy/src/benchmarking.rs @@ -198,7 +198,7 @@ benchmarks! { let origin = T::CancellationOrigin::successful_origin(); let referendum_index = add_referendum::(0)?; assert_ok!(Democracy::::referendum_status(referendum_index)); - }: _(origin, referendum_index) + }: _(origin, referendum_index) verify { // Referendum has been canceled assert_noop!( @@ -225,7 +225,7 @@ benchmarks! { // Add a referendum of our proposal. let referendum_index = add_referendum::(0)?; assert_ok!(Democracy::::referendum_status(referendum_index)); - }: _(origin, hash, Some(referendum_index)) + }: _(origin, hash, Some(referendum_index)) verify { // Referendum has been canceled assert_noop!( @@ -250,7 +250,7 @@ benchmarks! { proposal_hash, (T::BlockNumber::zero(), addresses), ); - }: _(origin, proposal_hash) + }: _(origin, proposal_hash) verify { // External proposal created ensure!(>::exists(), "External proposal didn't work"); @@ -259,7 +259,7 @@ benchmarks! { external_propose_majority { let origin = T::ExternalMajorityOrigin::successful_origin(); let proposal_hash = T::Hashing::hash_of(&0); - }: _(origin, proposal_hash) + }: _(origin, proposal_hash) verify { // External proposal created ensure!(>::exists(), "External proposal didn't work"); @@ -268,7 +268,7 @@ benchmarks! { external_propose_default { let origin = T::ExternalDefaultOrigin::successful_origin(); let proposal_hash = T::Hashing::hash_of(&0); - }: _(origin, proposal_hash) + }: _(origin, proposal_hash) verify { // External proposal created ensure!(>::exists(), "External proposal didn't work"); @@ -283,7 +283,7 @@ benchmarks! { let origin_fast_track = T::FastTrackOrigin::successful_origin(); let voting_period = T::FastTrackVotingPeriod::get(); let delay = 0u32; - }: _(origin_fast_track, proposal_hash, voting_period, delay.into()) + }: _(origin_fast_track, proposal_hash, voting_period, delay.into()) verify { assert_eq!(Democracy::::referendum_count(), 1, "referendum not created") } @@ -306,7 +306,7 @@ benchmarks! { let origin = T::VetoOrigin::successful_origin(); ensure!(NextExternal::::get().is_some(), "no external proposal"); - }: _(origin, proposal_hash) + }: _(origin, proposal_hash) verify { assert!(NextExternal::::get().is_none()); let (_, new_vetoers) = >::get(&proposal_hash).ok_or("no blacklist")?; @@ -322,7 +322,7 @@ benchmarks! { } let cancel_origin = T::CancelProposalOrigin::successful_origin(); - }: _(cancel_origin, 0) + }: _(cancel_origin, 0) cancel_referendum { let referendum_index = add_referendum::(0)?; diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index f6696065bfc87..3c1be19103998 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -253,7 +253,9 @@ pub mod pallet { #[pallet::config] pub trait Config: frame_system::Config + Sized { - type Proposal: Parameter + Dispatchable + From>; + type Proposal: Parameter + + Dispatchable + + From>; type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// Currency type for this pallet. @@ -289,25 +291,25 @@ pub mod pallet { /// Origin from which the next tabled referendum may be forced. This is a normal /// "super-majority-required" referendum. - type ExternalOrigin: EnsureOrigin; + type ExternalOrigin: EnsureOrigin; /// Origin from which the next tabled referendum may be forced; this allows for the tabling /// of a majority-carries referendum. - type ExternalMajorityOrigin: EnsureOrigin; + type ExternalMajorityOrigin: EnsureOrigin; /// Origin from which the next tabled referendum may be forced; this allows for the tabling /// of a negative-turnout-bias (default-carries) referendum. - type ExternalDefaultOrigin: EnsureOrigin; + type ExternalDefaultOrigin: EnsureOrigin; /// Origin from which the next majority-carries (or more permissive) referendum may be /// tabled to vote according to the `FastTrackVotingPeriod` asynchronously in a similar /// manner to the emergency origin. It retains its threshold method. - type FastTrackOrigin: EnsureOrigin; + type FastTrackOrigin: EnsureOrigin; /// Origin from which the next majority-carries (or more permissive) referendum may be /// tabled to vote immediately and asynchronously in a similar manner to the emergency /// origin. It retains its threshold method. - type InstantOrigin: EnsureOrigin; + type InstantOrigin: EnsureOrigin; /// Indicator for whether an emergency origin is even allowed to happen. Some chains may /// want to set this permanently to `false`, others may want to condition it on things such @@ -320,13 +322,13 @@ pub mod pallet { type FastTrackVotingPeriod: Get; /// Origin from which any referendum may be cancelled in an emergency. - type CancellationOrigin: EnsureOrigin; + type CancellationOrigin: EnsureOrigin; /// Origin from which proposals may be blacklisted. - type BlacklistOrigin: EnsureOrigin; + type BlacklistOrigin: EnsureOrigin; /// Origin from which a proposal may be cancelled and its backers slashed. - type CancelProposalOrigin: EnsureOrigin; + type CancelProposalOrigin: EnsureOrigin; /// Origin for anyone able to veto proposals. /// @@ -334,7 +336,7 @@ pub mod pallet { /// /// The number of Vetoers for a proposal must be small, extrinsics are weighted according to /// [MAX_VETOERS](./const.MAX_VETOERS.html) - type VetoOrigin: EnsureOrigin; + type VetoOrigin: EnsureOrigin; /// Period in blocks where an external proposal may not be re-submitted after being vetoed. #[pallet::constant] @@ -345,7 +347,7 @@ pub mod pallet { type PreimageByteDeposit: Get>; /// An origin that can provide a preimage using operational extrinsics. - type OperationalPreimageOrigin: EnsureOrigin; + type OperationalPreimageOrigin: EnsureOrigin; /// Handler for the unbalanced reduction when slashing a preimage deposit. type Slash: OnUnbalanced>; diff --git a/frame/democracy/src/tests.rs b/frame/democracy/src/tests.rs index e3ed046813e23..17b35ee3c38cd 100644 --- a/frame/democracy/src/tests.rs +++ b/frame/democracy/src/tests.rs @@ -85,7 +85,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; @@ -111,7 +111,7 @@ parameter_types! { } impl pallet_scheduler::Config for Test { type RuntimeEvent = RuntimeEvent; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type PalletsOrigin = OriginCaller; type RuntimeCall = RuntimeCall; type MaximumWeight = MaximumSchedulerWeight; @@ -240,7 +240,7 @@ fn set_balance_proposal_hash(value: u64) -> H256 { fn set_balance_proposal_hash_and_note(value: u64) -> H256 { let p = set_balance_proposal(value); let h = BlakeTwo256::hash(&p[..]); - match Democracy::note_preimage(Origin::signed(6), p) { + match Democracy::note_preimage(RuntimeOrigin::signed(6), p) { Ok(_) => (), Err(x) if x == Error::::DuplicatePreimage.into() => (), Err(x) => panic!("{:?}", x), @@ -249,11 +249,11 @@ fn set_balance_proposal_hash_and_note(value: u64) -> H256 { } fn propose_set_balance(who: u64, value: u64, delay: u64) -> DispatchResult { - Democracy::propose(Origin::signed(who), set_balance_proposal_hash(value), delay) + Democracy::propose(RuntimeOrigin::signed(who), set_balance_proposal_hash(value), delay) } fn propose_set_balance_and_note(who: u64, value: u64, delay: u64) -> DispatchResult { - Democracy::propose(Origin::signed(who), set_balance_proposal_hash_and_note(value), delay) + Democracy::propose(RuntimeOrigin::signed(who), set_balance_proposal_hash_and_note(value), delay) } fn next_block() { diff --git a/frame/democracy/src/tests/cancellation.rs b/frame/democracy/src/tests/cancellation.rs index 9035e17c5c80b..b98e51aa3d4d1 100644 --- a/frame/democracy/src/tests/cancellation.rs +++ b/frame/democracy/src/tests/cancellation.rs @@ -28,8 +28,8 @@ fn cancel_referendum_should_work() { VoteThreshold::SuperMajorityApprove, 0, ); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - assert_ok!(Democracy::cancel_referendum(Origin::root(), r.into())); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); + assert_ok!(Democracy::cancel_referendum(RuntimeOrigin::root(), r.into())); assert_eq!(Democracy::lowest_unbaked(), 0); next_block(); @@ -51,14 +51,17 @@ fn cancel_queued_should_work() { // start of 2 => next referendum scheduled. fast_forward_to(2); - assert_ok!(Democracy::vote(Origin::signed(1), 0, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), 0, aye(1))); fast_forward_to(4); assert!(pallet_scheduler::Agenda::::get(6)[0].is_some()); - assert_noop!(Democracy::cancel_queued(Origin::root(), 1), Error::::ProposalMissing); - assert_ok!(Democracy::cancel_queued(Origin::root(), 0)); + assert_noop!( + Democracy::cancel_queued(RuntimeOrigin::root(), 1), + Error::::ProposalMissing + ); + assert_ok!(Democracy::cancel_queued(RuntimeOrigin::root(), 0)); assert!(pallet_scheduler::Agenda::::get(6)[0].is_none()); }); } @@ -75,8 +78,8 @@ fn emergency_cancel_should_work() { ); assert!(Democracy::referendum_status(r).is_ok()); - assert_noop!(Democracy::emergency_cancel(Origin::signed(3), r), BadOrigin); - assert_ok!(Democracy::emergency_cancel(Origin::signed(4), r)); + assert_noop!(Democracy::emergency_cancel(RuntimeOrigin::signed(3), r), BadOrigin); + assert_ok!(Democracy::emergency_cancel(RuntimeOrigin::signed(4), r)); assert!(Democracy::referendum_info(r).is_none()); // some time later... @@ -89,7 +92,7 @@ fn emergency_cancel_should_work() { ); assert!(Democracy::referendum_status(r).is_ok()); assert_noop!( - Democracy::emergency_cancel(Origin::signed(4), r), + Democracy::emergency_cancel(RuntimeOrigin::signed(4), r), Error::::AlreadyCanceled, ); }); diff --git a/frame/democracy/src/tests/delegation.rs b/frame/democracy/src/tests/delegation.rs index 3551ca8f91123..4c5ee79286055 100644 --- a/frame/democracy/src/tests/delegation.rs +++ b/frame/democracy/src/tests/delegation.rs @@ -29,33 +29,33 @@ fn single_proposal_should_work_with_delegation() { fast_forward_to(2); // Delegate first vote. - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 20)); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(2), 1, Conviction::None, 20)); let r = 0; - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); assert_eq!(tally(r), Tally { ayes: 3, nays: 0, turnout: 30 }); // Delegate a second vote. - assert_ok!(Democracy::delegate(Origin::signed(3), 1, Conviction::None, 30)); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(3), 1, Conviction::None, 30)); assert_eq!(tally(r), Tally { ayes: 6, nays: 0, turnout: 60 }); // Reduce first vote. - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 10)); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(2), 1, Conviction::None, 10)); assert_eq!(tally(r), Tally { ayes: 5, nays: 0, turnout: 50 }); // Second vote delegates to first; we don't do tiered delegation, so it doesn't get used. - assert_ok!(Democracy::delegate(Origin::signed(3), 2, Conviction::None, 30)); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(3), 2, Conviction::None, 30)); assert_eq!(tally(r), Tally { ayes: 2, nays: 0, turnout: 20 }); // Main voter cancels their vote - assert_ok!(Democracy::remove_vote(Origin::signed(1), r)); + assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(1), r)); assert_eq!(tally(r), Tally { ayes: 0, nays: 0, turnout: 0 }); // First delegator delegates half funds with conviction; nothing changes yet. - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::Locked1x, 10)); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(2), 1, Conviction::Locked1x, 10)); assert_eq!(tally(r), Tally { ayes: 0, nays: 0, turnout: 0 }); // Main voter reinstates their vote - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); assert_eq!(tally(r), Tally { ayes: 11, nays: 0, turnout: 20 }); }); } @@ -64,7 +64,7 @@ fn single_proposal_should_work_with_delegation() { fn self_delegation_not_allowed() { new_test_ext().execute_with(|| { assert_noop!( - Democracy::delegate(Origin::signed(1), 1, Conviction::None, 10), + Democracy::delegate(RuntimeOrigin::signed(1), 1, Conviction::None, 10), Error::::Nonsense, ); }); @@ -80,14 +80,14 @@ fn cyclic_delegation_should_unwind() { fast_forward_to(2); // Check behavior with cycle. - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 20)); - assert_ok!(Democracy::delegate(Origin::signed(3), 2, Conviction::None, 30)); - assert_ok!(Democracy::delegate(Origin::signed(1), 3, Conviction::None, 10)); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(2), 1, Conviction::None, 20)); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(3), 2, Conviction::None, 30)); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(1), 3, Conviction::None, 10)); let r = 0; - assert_ok!(Democracy::undelegate(Origin::signed(3))); - assert_ok!(Democracy::vote(Origin::signed(3), r, aye(3))); - assert_ok!(Democracy::undelegate(Origin::signed(1))); - assert_ok!(Democracy::vote(Origin::signed(1), r, nay(1))); + assert_ok!(Democracy::undelegate(RuntimeOrigin::signed(3))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(3), r, aye(3))); + assert_ok!(Democracy::undelegate(RuntimeOrigin::signed(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, nay(1))); // Delegated vote is counted. assert_eq!(tally(r), Tally { ayes: 3, nays: 3, turnout: 60 }); @@ -105,13 +105,13 @@ fn single_proposal_should_work_with_vote_and_delegation() { fast_forward_to(2); let r = 0; - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - assert_ok!(Democracy::vote(Origin::signed(2), r, nay(2))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(2), r, nay(2))); assert_eq!(tally(r), Tally { ayes: 1, nays: 2, turnout: 30 }); // Delegate vote. - assert_ok!(Democracy::remove_vote(Origin::signed(2), r)); - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 20)); + assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(2), r)); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(2), 1, Conviction::None, 20)); // Delegated vote replaces the explicit vote. assert_eq!(tally(r), Tally { ayes: 3, nays: 0, turnout: 30 }); }); @@ -125,12 +125,12 @@ fn single_proposal_should_work_with_undelegation() { assert_ok!(propose_set_balance_and_note(1, 2, 1)); // Delegate and undelegate vote. - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 20)); - assert_ok!(Democracy::undelegate(Origin::signed(2))); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(2), 1, Conviction::None, 20)); + assert_ok!(Democracy::undelegate(RuntimeOrigin::signed(2))); fast_forward_to(2); let r = 0; - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); // Delegated vote is not counted. assert_eq!(tally(r), Tally { ayes: 1, nays: 0, turnout: 10 }); @@ -143,11 +143,11 @@ fn single_proposal_should_work_with_delegation_and_vote() { new_test_ext().execute_with(|| { let r = begin_referendum(); // Delegate, undelegate and vote. - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 20)); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(2), 1, Conviction::None, 20)); assert_eq!(tally(r), Tally { ayes: 3, nays: 0, turnout: 30 }); - assert_ok!(Democracy::undelegate(Origin::signed(2))); - assert_ok!(Democracy::vote(Origin::signed(2), r, aye(2))); + assert_ok!(Democracy::undelegate(RuntimeOrigin::signed(2))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(2), r, aye(2))); // Delegated vote is not counted. assert_eq!(tally(r), Tally { ayes: 3, nays: 0, turnout: 30 }); }); @@ -159,8 +159,8 @@ fn conviction_should_be_honored_in_delegation() { new_test_ext().execute_with(|| { let r = begin_referendum(); // Delegate and vote. - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::Locked6x, 20)); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(2), 1, Conviction::Locked6x, 20)); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); // Delegated vote is huge. assert_eq!(tally(r), Tally { ayes: 121, nays: 0, turnout: 30 }); }); @@ -171,8 +171,12 @@ fn split_vote_delegation_should_be_ignored() { // If transactor voted, delegated vote is overwritten. new_test_ext().execute_with(|| { let r = begin_referendum(); - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::Locked6x, 20)); - assert_ok!(Democracy::vote(Origin::signed(1), r, AccountVote::Split { aye: 10, nay: 0 })); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(2), 1, Conviction::Locked6x, 20)); + assert_ok!(Democracy::vote( + RuntimeOrigin::signed(1), + r, + AccountVote::Split { aye: 10, nay: 0 } + )); // Delegated vote is huge. assert_eq!(tally(r), Tally { ayes: 1, nays: 0, turnout: 10 }); }); @@ -184,8 +188,8 @@ fn redelegation_keeps_lock() { new_test_ext().execute_with(|| { let r = begin_referendum(); // Delegate and vote. - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::Locked6x, 20)); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(2), 1, Conviction::Locked6x, 20)); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); // Delegated vote is huge. assert_eq!(tally(r), Tally { ayes: 121, nays: 0, turnout: 30 }); @@ -196,14 +200,14 @@ fn redelegation_keeps_lock() { assert_eq!(VotingOf::::get(2).prior(), &prior_lock); // Delegate someone else at a lower conviction and amount - assert_ok!(Democracy::delegate(Origin::signed(2), 3, Conviction::None, 10)); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(2), 3, Conviction::None, 10)); // 6x prior should appear w/ locked balance. prior_lock.accumulate(98, 20); assert_eq!(VotingOf::::get(2).prior(), &prior_lock); assert_eq!(VotingOf::::get(2).locked_balance(), 20); // Unlock shouldn't work - assert_ok!(Democracy::unlock(Origin::signed(2), 2)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(2), 2)); assert_eq!(VotingOf::::get(2).prior(), &prior_lock); assert_eq!(VotingOf::::get(2).locked_balance(), 20); @@ -211,7 +215,7 @@ fn redelegation_keeps_lock() { // Now unlock can remove the prior lock and reduce the locked amount. assert_eq!(VotingOf::::get(2).prior(), &prior_lock); - assert_ok!(Democracy::unlock(Origin::signed(2), 2)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(2), 2)); assert_eq!(VotingOf::::get(2).prior(), &vote::PriorLock::default()); assert_eq!(VotingOf::::get(2).locked_balance(), 10); }); diff --git a/frame/democracy/src/tests/external_proposing.rs b/frame/democracy/src/tests/external_proposing.rs index 6ac34a38723ce..fda555b9c3459 100644 --- a/frame/democracy/src/tests/external_proposing.rs +++ b/frame/democracy/src/tests/external_proposing.rs @@ -24,53 +24,56 @@ fn veto_external_works() { new_test_ext().execute_with(|| { System::set_block_number(0); assert_ok!(Democracy::external_propose( - Origin::signed(2), + RuntimeOrigin::signed(2), set_balance_proposal_hash_and_note(2), )); assert!(>::exists()); let h = set_balance_proposal_hash_and_note(2); - assert_ok!(Democracy::veto_external(Origin::signed(3), h)); + assert_ok!(Democracy::veto_external(RuntimeOrigin::signed(3), h)); // cancelled. assert!(!>::exists()); // fails - same proposal can't be resubmitted. assert_noop!( - Democracy::external_propose(Origin::signed(2), set_balance_proposal_hash(2),), + Democracy::external_propose(RuntimeOrigin::signed(2), set_balance_proposal_hash(2),), Error::::ProposalBlacklisted ); fast_forward_to(1); // fails as we're still in cooloff period. assert_noop!( - Democracy::external_propose(Origin::signed(2), set_balance_proposal_hash(2),), + Democracy::external_propose(RuntimeOrigin::signed(2), set_balance_proposal_hash(2),), Error::::ProposalBlacklisted ); fast_forward_to(2); // works; as we're out of the cooloff period. assert_ok!(Democracy::external_propose( - Origin::signed(2), + RuntimeOrigin::signed(2), set_balance_proposal_hash_and_note(2), )); assert!(>::exists()); // 3 can't veto the same thing twice. - assert_noop!(Democracy::veto_external(Origin::signed(3), h), Error::::AlreadyVetoed); + assert_noop!( + Democracy::veto_external(RuntimeOrigin::signed(3), h), + Error::::AlreadyVetoed + ); // 4 vetoes. - assert_ok!(Democracy::veto_external(Origin::signed(4), h)); + assert_ok!(Democracy::veto_external(RuntimeOrigin::signed(4), h)); // cancelled again. assert!(!>::exists()); fast_forward_to(3); // same proposal fails as we're still in cooloff assert_noop!( - Democracy::external_propose(Origin::signed(2), set_balance_proposal_hash(2),), + Democracy::external_propose(RuntimeOrigin::signed(2), set_balance_proposal_hash(2),), Error::::ProposalBlacklisted ); // different proposal works fine. assert_ok!(Democracy::external_propose( - Origin::signed(2), + RuntimeOrigin::signed(2), set_balance_proposal_hash_and_note(3), )); }); @@ -82,18 +85,21 @@ fn external_blacklisting_should_work() { System::set_block_number(0); assert_ok!(Democracy::external_propose( - Origin::signed(2), + RuntimeOrigin::signed(2), set_balance_proposal_hash_and_note(2), )); let hash = set_balance_proposal_hash(2); - assert_ok!(Democracy::blacklist(Origin::root(), hash, None)); + assert_ok!(Democracy::blacklist(RuntimeOrigin::root(), hash, None)); fast_forward_to(2); assert_noop!(Democracy::referendum_status(0), Error::::ReferendumInvalid); assert_noop!( - Democracy::external_propose(Origin::signed(2), set_balance_proposal_hash_and_note(2),), + Democracy::external_propose( + RuntimeOrigin::signed(2), + set_balance_proposal_hash_and_note(2), + ), Error::::ProposalBlacklisted, ); }); @@ -104,15 +110,15 @@ fn external_referendum_works() { new_test_ext().execute_with(|| { System::set_block_number(0); assert_noop!( - Democracy::external_propose(Origin::signed(1), set_balance_proposal_hash(2),), + Democracy::external_propose(RuntimeOrigin::signed(1), set_balance_proposal_hash(2),), BadOrigin, ); assert_ok!(Democracy::external_propose( - Origin::signed(2), + RuntimeOrigin::signed(2), set_balance_proposal_hash_and_note(2), )); assert_noop!( - Democracy::external_propose(Origin::signed(2), set_balance_proposal_hash(1),), + Democracy::external_propose(RuntimeOrigin::signed(2), set_balance_proposal_hash(1),), Error::::DuplicateProposal ); fast_forward_to(2); @@ -134,11 +140,14 @@ fn external_majority_referendum_works() { new_test_ext().execute_with(|| { System::set_block_number(0); assert_noop!( - Democracy::external_propose_majority(Origin::signed(1), set_balance_proposal_hash(2)), + Democracy::external_propose_majority( + RuntimeOrigin::signed(1), + set_balance_proposal_hash(2) + ), BadOrigin, ); assert_ok!(Democracy::external_propose_majority( - Origin::signed(3), + RuntimeOrigin::signed(3), set_balance_proposal_hash_and_note(2) )); fast_forward_to(2); @@ -160,11 +169,14 @@ fn external_default_referendum_works() { new_test_ext().execute_with(|| { System::set_block_number(0); assert_noop!( - Democracy::external_propose_default(Origin::signed(3), set_balance_proposal_hash(2)), + Democracy::external_propose_default( + RuntimeOrigin::signed(3), + set_balance_proposal_hash(2) + ), BadOrigin, ); assert_ok!(Democracy::external_propose_default( - Origin::signed(1), + RuntimeOrigin::signed(1), set_balance_proposal_hash_and_note(2) )); fast_forward_to(2); @@ -186,7 +198,7 @@ fn external_and_public_interleaving_works() { new_test_ext().execute_with(|| { System::set_block_number(0); assert_ok!(Democracy::external_propose( - Origin::signed(2), + RuntimeOrigin::signed(2), set_balance_proposal_hash_and_note(1), )); assert_ok!(propose_set_balance_and_note(6, 2, 2)); @@ -206,7 +218,7 @@ fn external_and_public_interleaving_works() { ); // replenish external assert_ok!(Democracy::external_propose( - Origin::signed(2), + RuntimeOrigin::signed(2), set_balance_proposal_hash_and_note(3), )); @@ -240,7 +252,7 @@ fn external_and_public_interleaving_works() { ); // replenish external assert_ok!(Democracy::external_propose( - Origin::signed(2), + RuntimeOrigin::signed(2), set_balance_proposal_hash_and_note(5), )); @@ -259,7 +271,7 @@ fn external_and_public_interleaving_works() { ); // replenish both assert_ok!(Democracy::external_propose( - Origin::signed(2), + RuntimeOrigin::signed(2), set_balance_proposal_hash_and_note(7), )); assert_ok!(propose_set_balance_and_note(6, 4, 2)); @@ -281,7 +293,7 @@ fn external_and_public_interleaving_works() { assert_ok!(propose_set_balance_and_note(6, 6, 2)); // cancel external let h = set_balance_proposal_hash_and_note(7); - assert_ok!(Democracy::veto_external(Origin::signed(3), h)); + assert_ok!(Democracy::veto_external(RuntimeOrigin::signed(3), h)); fast_forward_to(12); diff --git a/frame/democracy/src/tests/fast_tracking.rs b/frame/democracy/src/tests/fast_tracking.rs index caf83c6d46120..8fef985c8561c 100644 --- a/frame/democracy/src/tests/fast_tracking.rs +++ b/frame/democracy/src/tests/fast_tracking.rs @@ -25,15 +25,15 @@ fn fast_track_referendum_works() { System::set_block_number(0); let h = set_balance_proposal_hash_and_note(2); assert_noop!( - Democracy::fast_track(Origin::signed(5), h, 3, 2), + Democracy::fast_track(RuntimeOrigin::signed(5), h, 3, 2), Error::::ProposalMissing ); assert_ok!(Democracy::external_propose_majority( - Origin::signed(3), + RuntimeOrigin::signed(3), set_balance_proposal_hash_and_note(2) )); - assert_noop!(Democracy::fast_track(Origin::signed(1), h, 3, 2), BadOrigin); - assert_ok!(Democracy::fast_track(Origin::signed(5), h, 2, 0)); + assert_noop!(Democracy::fast_track(RuntimeOrigin::signed(1), h, 3, 2), BadOrigin); + assert_ok!(Democracy::fast_track(RuntimeOrigin::signed(5), h, 2, 0)); assert_eq!( Democracy::referendum_status(0), Ok(ReferendumStatus { @@ -53,25 +53,25 @@ fn instant_referendum_works() { System::set_block_number(0); let h = set_balance_proposal_hash_and_note(2); assert_noop!( - Democracy::fast_track(Origin::signed(5), h, 3, 2), + Democracy::fast_track(RuntimeOrigin::signed(5), h, 3, 2), Error::::ProposalMissing ); assert_ok!(Democracy::external_propose_majority( - Origin::signed(3), + RuntimeOrigin::signed(3), set_balance_proposal_hash_and_note(2) )); - assert_noop!(Democracy::fast_track(Origin::signed(1), h, 3, 2), BadOrigin); - assert_noop!(Democracy::fast_track(Origin::signed(5), h, 1, 0), BadOrigin); + assert_noop!(Democracy::fast_track(RuntimeOrigin::signed(1), h, 3, 2), BadOrigin); + assert_noop!(Democracy::fast_track(RuntimeOrigin::signed(5), h, 1, 0), BadOrigin); assert_noop!( - Democracy::fast_track(Origin::signed(6), h, 1, 0), + Democracy::fast_track(RuntimeOrigin::signed(6), h, 1, 0), Error::::InstantNotAllowed ); INSTANT_ALLOWED.with(|v| *v.borrow_mut() = true); assert_noop!( - Democracy::fast_track(Origin::signed(6), h, 0, 0), + Democracy::fast_track(RuntimeOrigin::signed(6), h, 0, 0), Error::::VotingPeriodLow ); - assert_ok!(Democracy::fast_track(Origin::signed(6), h, 1, 0)); + assert_ok!(Democracy::fast_track(RuntimeOrigin::signed(6), h, 1, 0)); assert_eq!( Democracy::referendum_status(0), Ok(ReferendumStatus { @@ -102,13 +102,13 @@ fn instant_next_block_referendum_backed() { // propose with majority origin assert_ok!(Democracy::external_propose_majority( - Origin::signed(majority_origin_id), + RuntimeOrigin::signed(majority_origin_id), proposal_hash )); // fast track with instant origin and voting period pointing to the next block assert_ok!(Democracy::fast_track( - Origin::signed(instant_origin_id), + RuntimeOrigin::signed(instant_origin_id), proposal_hash, voting_period, delay @@ -145,11 +145,11 @@ fn fast_track_referendum_fails_when_no_simple_majority() { System::set_block_number(0); let h = set_balance_proposal_hash_and_note(2); assert_ok!(Democracy::external_propose( - Origin::signed(2), + RuntimeOrigin::signed(2), set_balance_proposal_hash_and_note(2) )); assert_noop!( - Democracy::fast_track(Origin::signed(5), h, 3, 2), + Democracy::fast_track(RuntimeOrigin::signed(5), h, 3, 2), Error::::NotSimpleMajority ); }); diff --git a/frame/democracy/src/tests/lock_voting.rs b/frame/democracy/src/tests/lock_voting.rs index 0718734367314..de1137f03fd38 100644 --- a/frame/democracy/src/tests/lock_voting.rs +++ b/frame/democracy/src/tests/lock_voting.rs @@ -47,11 +47,11 @@ fn lock_voting_should_work() { VoteThreshold::SuperMajorityApprove, 0, ); - assert_ok!(Democracy::vote(Origin::signed(1), r, nay(5, 10))); - assert_ok!(Democracy::vote(Origin::signed(2), r, aye(4, 20))); - assert_ok!(Democracy::vote(Origin::signed(3), r, aye(3, 30))); - assert_ok!(Democracy::vote(Origin::signed(4), r, aye(2, 40))); - assert_ok!(Democracy::vote(Origin::signed(5), r, nay(1, 50))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, nay(5, 10))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(2), r, aye(4, 20))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(3), r, aye(3, 30))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(4), r, aye(2, 40))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(5), r, nay(1, 50))); assert_eq!(tally(r), Tally { ayes: 250, nays: 100, turnout: 150 }); // All balances are currently locked. @@ -62,20 +62,20 @@ fn lock_voting_should_work() { fast_forward_to(2); // Referendum passed; 1 and 5 didn't get their way and can now reap and unlock. - assert_ok!(Democracy::remove_vote(Origin::signed(1), r)); - assert_ok!(Democracy::unlock(Origin::signed(1), 1)); + assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(1), r)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(1), 1)); // Anyone can reap and unlock anyone else's in this context. - assert_ok!(Democracy::remove_other_vote(Origin::signed(2), 5, r)); - assert_ok!(Democracy::unlock(Origin::signed(2), 5)); + assert_ok!(Democracy::remove_other_vote(RuntimeOrigin::signed(2), 5, r)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(2), 5)); // 2, 3, 4 got their way with the vote, so they cannot be reaped by others. assert_noop!( - Democracy::remove_other_vote(Origin::signed(1), 2, r), + Democracy::remove_other_vote(RuntimeOrigin::signed(1), 2, r), Error::::NoPermission ); // However, they can be unvoted by the owner, though it will make no difference to the lock. - assert_ok!(Democracy::remove_vote(Origin::signed(2), r)); - assert_ok!(Democracy::unlock(Origin::signed(2), 2)); + assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(2), r)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(2), 2)); assert_eq!(Balances::locks(1), vec![]); assert_eq!(Balances::locks(2), vec![the_lock(20)]); @@ -87,35 +87,35 @@ fn lock_voting_should_work() { fast_forward_to(7); // No change yet... assert_noop!( - Democracy::remove_other_vote(Origin::signed(1), 4, r), + Democracy::remove_other_vote(RuntimeOrigin::signed(1), 4, r), Error::::NoPermission ); - assert_ok!(Democracy::unlock(Origin::signed(1), 4)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(1), 4)); assert_eq!(Balances::locks(4), vec![the_lock(40)]); fast_forward_to(8); // 4 should now be able to reap and unlock - assert_ok!(Democracy::remove_other_vote(Origin::signed(1), 4, r)); - assert_ok!(Democracy::unlock(Origin::signed(1), 4)); + assert_ok!(Democracy::remove_other_vote(RuntimeOrigin::signed(1), 4, r)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(1), 4)); assert_eq!(Balances::locks(4), vec![]); fast_forward_to(13); assert_noop!( - Democracy::remove_other_vote(Origin::signed(1), 3, r), + Democracy::remove_other_vote(RuntimeOrigin::signed(1), 3, r), Error::::NoPermission ); - assert_ok!(Democracy::unlock(Origin::signed(1), 3)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(1), 3)); assert_eq!(Balances::locks(3), vec![the_lock(30)]); fast_forward_to(14); - assert_ok!(Democracy::remove_other_vote(Origin::signed(1), 3, r)); - assert_ok!(Democracy::unlock(Origin::signed(1), 3)); + assert_ok!(Democracy::remove_other_vote(RuntimeOrigin::signed(1), 3, r)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(1), 3)); assert_eq!(Balances::locks(3), vec![]); // 2 doesn't need to reap_vote here because it was already done before. fast_forward_to(25); - assert_ok!(Democracy::unlock(Origin::signed(1), 2)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(1), 2)); assert_eq!(Balances::locks(2), vec![the_lock(20)]); fast_forward_to(26); - assert_ok!(Democracy::unlock(Origin::signed(1), 2)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(1), 2)); assert_eq!(Balances::locks(2), vec![]); }); } @@ -130,13 +130,13 @@ fn no_locks_without_conviction_should_work() { VoteThreshold::SuperMajorityApprove, 0, ); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(0, 10))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(0, 10))); fast_forward_to(2); assert_eq!(Balances::free_balance(42), 2); - assert_ok!(Democracy::remove_other_vote(Origin::signed(2), 1, r)); - assert_ok!(Democracy::unlock(Origin::signed(2), 1)); + assert_ok!(Democracy::remove_other_vote(RuntimeOrigin::signed(2), 1, r)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(2), 1)); assert_eq!(Balances::locks(1), vec![]); }); } @@ -150,11 +150,11 @@ fn lock_voting_should_work_with_delegation() { VoteThreshold::SuperMajorityApprove, 0, ); - assert_ok!(Democracy::vote(Origin::signed(1), r, nay(5, 10))); - assert_ok!(Democracy::vote(Origin::signed(2), r, aye(4, 20))); - assert_ok!(Democracy::vote(Origin::signed(3), r, aye(3, 30))); - assert_ok!(Democracy::delegate(Origin::signed(4), 2, Conviction::Locked2x, 40)); - assert_ok!(Democracy::vote(Origin::signed(5), r, nay(1, 50))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, nay(5, 10))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(2), r, aye(4, 20))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(3), r, aye(3, 30))); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(4), 2, Conviction::Locked2x, 40)); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(5), r, nay(1, 50))); assert_eq!(tally(r), Tally { ayes: 250, nays: 100, turnout: 150 }); @@ -173,7 +173,7 @@ fn setup_three_referenda() -> (u32, u32, u32) { VoteThreshold::SimpleMajority, 0, ); - assert_ok!(Democracy::vote(Origin::signed(5), r1, aye(4, 10))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(5), r1, aye(4, 10))); let r2 = Democracy::inject_referendum( 2, @@ -181,7 +181,7 @@ fn setup_three_referenda() -> (u32, u32, u32) { VoteThreshold::SimpleMajority, 0, ); - assert_ok!(Democracy::vote(Origin::signed(5), r2, aye(3, 20))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(5), r2, aye(3, 20))); let r3 = Democracy::inject_referendum( 2, @@ -189,7 +189,7 @@ fn setup_three_referenda() -> (u32, u32, u32) { VoteThreshold::SimpleMajority, 0, ); - assert_ok!(Democracy::vote(Origin::signed(5), r3, aye(2, 50))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(5), r3, aye(2, 50))); fast_forward_to(2); @@ -206,36 +206,36 @@ fn prior_lockvotes_should_be_enforced() { fast_forward_to(7); assert_noop!( - Democracy::remove_other_vote(Origin::signed(1), 5, r.2), + Democracy::remove_other_vote(RuntimeOrigin::signed(1), 5, r.2), Error::::NoPermission ); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert_eq!(Balances::locks(5), vec![the_lock(50)]); fast_forward_to(8); - assert_ok!(Democracy::remove_other_vote(Origin::signed(1), 5, r.2)); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::remove_other_vote(RuntimeOrigin::signed(1), 5, r.2)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert_eq!(Balances::locks(5), vec![the_lock(20)]); fast_forward_to(13); assert_noop!( - Democracy::remove_other_vote(Origin::signed(1), 5, r.1), + Democracy::remove_other_vote(RuntimeOrigin::signed(1), 5, r.1), Error::::NoPermission ); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert_eq!(Balances::locks(5), vec![the_lock(20)]); fast_forward_to(14); - assert_ok!(Democracy::remove_other_vote(Origin::signed(1), 5, r.1)); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::remove_other_vote(RuntimeOrigin::signed(1), 5, r.1)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert_eq!(Balances::locks(5), vec![the_lock(10)]); fast_forward_to(25); assert_noop!( - Democracy::remove_other_vote(Origin::signed(1), 5, r.0), + Democracy::remove_other_vote(RuntimeOrigin::signed(1), 5, r.0), Error::::NoPermission ); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert_eq!(Balances::locks(5), vec![the_lock(10)]); fast_forward_to(26); - assert_ok!(Democracy::remove_other_vote(Origin::signed(1), 5, r.0)); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::remove_other_vote(RuntimeOrigin::signed(1), 5, r.0)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert_eq!(Balances::locks(5), vec![]); }); } @@ -249,27 +249,27 @@ fn single_consolidation_of_lockvotes_should_work_as_before() { // r.2 locked 50 until 2 + 2 * 3 = #8 fast_forward_to(7); - assert_ok!(Democracy::remove_vote(Origin::signed(5), r.2)); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(5), r.2)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert_eq!(Balances::locks(5), vec![the_lock(50)]); fast_forward_to(8); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert_eq!(Balances::locks(5), vec![the_lock(20)]); fast_forward_to(13); - assert_ok!(Democracy::remove_vote(Origin::signed(5), r.1)); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(5), r.1)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert_eq!(Balances::locks(5), vec![the_lock(20)]); fast_forward_to(14); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert_eq!(Balances::locks(5), vec![the_lock(10)]); fast_forward_to(25); - assert_ok!(Democracy::remove_vote(Origin::signed(5), r.0)); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(5), r.0)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert_eq!(Balances::locks(5), vec![the_lock(10)]); fast_forward_to(26); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert_eq!(Balances::locks(5), vec![]); }); } @@ -282,20 +282,20 @@ fn multi_consolidation_of_lockvotes_should_be_conservative() { // r.1 locked 20 until 2 + 4 * 3 = #14 // r.2 locked 50 until 2 + 2 * 3 = #8 - assert_ok!(Democracy::remove_vote(Origin::signed(5), r.2)); - assert_ok!(Democracy::remove_vote(Origin::signed(5), r.1)); - assert_ok!(Democracy::remove_vote(Origin::signed(5), r.0)); + assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(5), r.2)); + assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(5), r.1)); + assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(5), r.0)); fast_forward_to(8); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert!(Balances::locks(5)[0].amount >= 20); fast_forward_to(14); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert!(Balances::locks(5)[0].amount >= 10); fast_forward_to(26); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert_eq!(Balances::locks(5), vec![]); }); } @@ -310,32 +310,32 @@ fn locks_should_persist_from_voting_to_delegation() { VoteThreshold::SimpleMajority, 0, ); - assert_ok!(Democracy::vote(Origin::signed(5), r, aye(4, 10))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(5), r, aye(4, 10))); fast_forward_to(2); - assert_ok!(Democracy::remove_vote(Origin::signed(5), r)); + assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(5), r)); // locked 10 until #26. - assert_ok!(Democracy::delegate(Origin::signed(5), 1, Conviction::Locked3x, 20)); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(5), 1, Conviction::Locked3x, 20)); // locked 20. assert!(Balances::locks(5)[0].amount == 20); - assert_ok!(Democracy::undelegate(Origin::signed(5))); + assert_ok!(Democracy::undelegate(RuntimeOrigin::signed(5))); // locked 20 until #14 fast_forward_to(13); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert!(Balances::locks(5)[0].amount == 20); fast_forward_to(14); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert!(Balances::locks(5)[0].amount >= 10); fast_forward_to(25); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert!(Balances::locks(5)[0].amount >= 10); fast_forward_to(26); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert_eq!(Balances::locks(5), vec![]); }); } @@ -344,8 +344,8 @@ fn locks_should_persist_from_voting_to_delegation() { fn locks_should_persist_from_delegation_to_voting() { new_test_ext().execute_with(|| { System::set_block_number(0); - assert_ok!(Democracy::delegate(Origin::signed(5), 1, Conviction::Locked5x, 5)); - assert_ok!(Democracy::undelegate(Origin::signed(5))); + assert_ok!(Democracy::delegate(RuntimeOrigin::signed(5), 1, Conviction::Locked5x, 5)); + assert_ok!(Democracy::undelegate(RuntimeOrigin::signed(5))); // locked 5 until 16 * 3 = #48 let r = setup_three_referenda(); @@ -353,24 +353,24 @@ fn locks_should_persist_from_delegation_to_voting() { // r.1 locked 20 until 2 + 4 * 3 = #14 // r.2 locked 50 until 2 + 2 * 3 = #8 - assert_ok!(Democracy::remove_vote(Origin::signed(5), r.2)); - assert_ok!(Democracy::remove_vote(Origin::signed(5), r.1)); - assert_ok!(Democracy::remove_vote(Origin::signed(5), r.0)); + assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(5), r.2)); + assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(5), r.1)); + assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(5), r.0)); fast_forward_to(8); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert!(Balances::locks(5)[0].amount >= 20); fast_forward_to(14); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert!(Balances::locks(5)[0].amount >= 10); fast_forward_to(26); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert!(Balances::locks(5)[0].amount >= 5); fast_forward_to(48); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert_eq!(Balances::locks(5), vec![]); }); } diff --git a/frame/democracy/src/tests/preimage.rs b/frame/democracy/src/tests/preimage.rs index 21303c8eddae3..39536eab8009b 100644 --- a/frame/democracy/src/tests/preimage.rs +++ b/frame/democracy/src/tests/preimage.rs @@ -28,7 +28,7 @@ fn missing_preimage_should_fail() { VoteThreshold::SuperMajorityApprove, 0, ); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); next_block(); next_block(); @@ -44,9 +44,9 @@ fn preimage_deposit_should_be_required_and_returned() { PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 100); assert_noop!( if operational { - Democracy::note_preimage_operational(Origin::signed(6), vec![0; 500]) + Democracy::note_preimage_operational(RuntimeOrigin::signed(6), vec![0; 500]) } else { - Democracy::note_preimage(Origin::signed(6), vec![0; 500]) + Democracy::note_preimage(RuntimeOrigin::signed(6), vec![0; 500]) }, BalancesError::::InsufficientBalance, ); @@ -58,7 +58,7 @@ fn preimage_deposit_should_be_required_and_returned() { VoteThreshold::SuperMajorityApprove, 0, ); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); assert_eq!(Balances::reserved_balance(6), 12); @@ -76,21 +76,25 @@ fn preimage_deposit_should_be_reapable_earlier_by_owner() { new_test_ext_execute_with_cond(|operational| { PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 1); assert_ok!(if operational { - Democracy::note_preimage_operational(Origin::signed(6), set_balance_proposal(2)) + Democracy::note_preimage_operational(RuntimeOrigin::signed(6), set_balance_proposal(2)) } else { - Democracy::note_preimage(Origin::signed(6), set_balance_proposal(2)) + Democracy::note_preimage(RuntimeOrigin::signed(6), set_balance_proposal(2)) }); assert_eq!(Balances::reserved_balance(6), 12); next_block(); assert_noop!( - Democracy::reap_preimage(Origin::signed(6), set_balance_proposal_hash(2), u32::MAX), + Democracy::reap_preimage( + RuntimeOrigin::signed(6), + set_balance_proposal_hash(2), + u32::MAX + ), Error::::TooEarly ); next_block(); assert_ok!(Democracy::reap_preimage( - Origin::signed(6), + RuntimeOrigin::signed(6), set_balance_proposal_hash(2), u32::MAX )); @@ -104,15 +108,19 @@ fn preimage_deposit_should_be_reapable_earlier_by_owner() { fn preimage_deposit_should_be_reapable() { new_test_ext_execute_with_cond(|operational| { assert_noop!( - Democracy::reap_preimage(Origin::signed(5), set_balance_proposal_hash(2), u32::MAX), + Democracy::reap_preimage( + RuntimeOrigin::signed(5), + set_balance_proposal_hash(2), + u32::MAX + ), Error::::PreimageMissing ); PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 1); assert_ok!(if operational { - Democracy::note_preimage_operational(Origin::signed(6), set_balance_proposal(2)) + Democracy::note_preimage_operational(RuntimeOrigin::signed(6), set_balance_proposal(2)) } else { - Democracy::note_preimage(Origin::signed(6), set_balance_proposal(2)) + Democracy::note_preimage(RuntimeOrigin::signed(6), set_balance_proposal(2)) }); assert_eq!(Balances::reserved_balance(6), 12); @@ -120,13 +128,17 @@ fn preimage_deposit_should_be_reapable() { next_block(); next_block(); assert_noop!( - Democracy::reap_preimage(Origin::signed(5), set_balance_proposal_hash(2), u32::MAX), + Democracy::reap_preimage( + RuntimeOrigin::signed(5), + set_balance_proposal_hash(2), + u32::MAX + ), Error::::TooEarly ); next_block(); assert_ok!(Democracy::reap_preimage( - Origin::signed(5), + RuntimeOrigin::signed(5), set_balance_proposal_hash(2), u32::MAX )); @@ -147,16 +159,16 @@ fn noting_imminent_preimage_for_free_should_work() { VoteThreshold::SuperMajorityApprove, 1, ); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); assert_noop!( if operational { Democracy::note_imminent_preimage_operational( - Origin::signed(6), + RuntimeOrigin::signed(6), set_balance_proposal(2), ) } else { - Democracy::note_imminent_preimage(Origin::signed(6), set_balance_proposal(2)) + Democracy::note_imminent_preimage(RuntimeOrigin::signed(6), set_balance_proposal(2)) }, Error::::NotImminent ); @@ -164,7 +176,10 @@ fn noting_imminent_preimage_for_free_should_work() { next_block(); // Now we're in the dispatch queue it's all good. - assert_ok!(Democracy::note_imminent_preimage(Origin::signed(6), set_balance_proposal(2))); + assert_ok!(Democracy::note_imminent_preimage( + RuntimeOrigin::signed(6), + set_balance_proposal(2) + )); next_block(); @@ -177,11 +192,11 @@ fn reaping_imminent_preimage_should_fail() { new_test_ext().execute_with(|| { let h = set_balance_proposal_hash_and_note(2); let r = Democracy::inject_referendum(3, h, VoteThreshold::SuperMajorityApprove, 1); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); next_block(); next_block(); assert_noop!( - Democracy::reap_preimage(Origin::signed(6), h, u32::MAX), + Democracy::reap_preimage(RuntimeOrigin::signed(6), h, u32::MAX), Error::::Imminent ); }); @@ -198,21 +213,24 @@ fn note_imminent_preimage_can_only_be_successful_once() { VoteThreshold::SuperMajorityApprove, 1, ); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); next_block(); // First time works - assert_ok!(Democracy::note_imminent_preimage(Origin::signed(6), set_balance_proposal(2))); + assert_ok!(Democracy::note_imminent_preimage( + RuntimeOrigin::signed(6), + set_balance_proposal(2) + )); // Second time fails assert_noop!( - Democracy::note_imminent_preimage(Origin::signed(6), set_balance_proposal(2)), + Democracy::note_imminent_preimage(RuntimeOrigin::signed(6), set_balance_proposal(2)), Error::::DuplicatePreimage ); // Fails from any user assert_noop!( - Democracy::note_imminent_preimage(Origin::signed(5), set_balance_proposal(2)), + Democracy::note_imminent_preimage(RuntimeOrigin::signed(5), set_balance_proposal(2)), Error::::DuplicatePreimage ); }); diff --git a/frame/democracy/src/tests/public_proposals.rs b/frame/democracy/src/tests/public_proposals.rs index 65e5466857dc1..c52533e46ccc5 100644 --- a/frame/democracy/src/tests/public_proposals.rs +++ b/frame/democracy/src/tests/public_proposals.rs @@ -35,10 +35,10 @@ fn backing_for_should_work() { fn deposit_for_proposals_should_be_taken() { new_test_ext().execute_with(|| { assert_ok!(propose_set_balance_and_note(1, 2, 5)); - assert_ok!(Democracy::second(Origin::signed(2), 0, u32::MAX)); - assert_ok!(Democracy::second(Origin::signed(5), 0, u32::MAX)); - assert_ok!(Democracy::second(Origin::signed(5), 0, u32::MAX)); - assert_ok!(Democracy::second(Origin::signed(5), 0, u32::MAX)); + assert_ok!(Democracy::second(RuntimeOrigin::signed(2), 0, u32::MAX)); + assert_ok!(Democracy::second(RuntimeOrigin::signed(5), 0, u32::MAX)); + assert_ok!(Democracy::second(RuntimeOrigin::signed(5), 0, u32::MAX)); + assert_ok!(Democracy::second(RuntimeOrigin::signed(5), 0, u32::MAX)); assert_eq!(Balances::free_balance(1), 5); assert_eq!(Balances::free_balance(2), 15); assert_eq!(Balances::free_balance(5), 35); @@ -49,10 +49,10 @@ fn deposit_for_proposals_should_be_taken() { fn deposit_for_proposals_should_be_returned() { new_test_ext().execute_with(|| { assert_ok!(propose_set_balance_and_note(1, 2, 5)); - assert_ok!(Democracy::second(Origin::signed(2), 0, u32::MAX)); - assert_ok!(Democracy::second(Origin::signed(5), 0, u32::MAX)); - assert_ok!(Democracy::second(Origin::signed(5), 0, u32::MAX)); - assert_ok!(Democracy::second(Origin::signed(5), 0, u32::MAX)); + assert_ok!(Democracy::second(RuntimeOrigin::signed(2), 0, u32::MAX)); + assert_ok!(Democracy::second(RuntimeOrigin::signed(5), 0, u32::MAX)); + assert_ok!(Democracy::second(RuntimeOrigin::signed(5), 0, u32::MAX)); + assert_ok!(Democracy::second(RuntimeOrigin::signed(5), 0, u32::MAX)); fast_forward_to(3); assert_eq!(Balances::free_balance(1), 10); assert_eq!(Balances::free_balance(2), 20); @@ -79,7 +79,7 @@ fn poor_seconder_should_not_work() { new_test_ext().execute_with(|| { assert_ok!(propose_set_balance_and_note(2, 2, 11)); assert_noop!( - Democracy::second(Origin::signed(1), 0, u32::MAX), + Democracy::second(RuntimeOrigin::signed(1), 0, u32::MAX), BalancesError::::InsufficientBalance ); }); @@ -89,7 +89,10 @@ fn poor_seconder_should_not_work() { fn invalid_seconds_upper_bound_should_not_work() { new_test_ext().execute_with(|| { assert_ok!(propose_set_balance_and_note(1, 2, 5)); - assert_noop!(Democracy::second(Origin::signed(2), 0, 0), Error::::WrongUpperBound); + assert_noop!( + Democracy::second(RuntimeOrigin::signed(2), 0, 0), + Error::::WrongUpperBound + ); }); } @@ -98,8 +101,8 @@ fn cancel_proposal_should_work() { new_test_ext().execute_with(|| { assert_ok!(propose_set_balance_and_note(1, 2, 2)); assert_ok!(propose_set_balance_and_note(1, 4, 4)); - assert_noop!(Democracy::cancel_proposal(Origin::signed(1), 0), BadOrigin); - assert_ok!(Democracy::cancel_proposal(Origin::root(), 0)); + assert_noop!(Democracy::cancel_proposal(RuntimeOrigin::signed(1), 0), BadOrigin); + assert_ok!(Democracy::cancel_proposal(RuntimeOrigin::root(), 0)); System::assert_last_event(crate::Event::ProposalCanceled { prop_index: 0 }.into()); assert_eq!(Democracy::backing_for(0), None); assert_eq!(Democracy::backing_for(1), Some(4)); @@ -115,8 +118,8 @@ fn blacklisting_should_work() { assert_ok!(propose_set_balance_and_note(1, 2, 2)); assert_ok!(propose_set_balance_and_note(1, 4, 4)); - assert_noop!(Democracy::blacklist(Origin::signed(1), hash, None), BadOrigin); - assert_ok!(Democracy::blacklist(Origin::root(), hash, None)); + assert_noop!(Democracy::blacklist(RuntimeOrigin::signed(1), hash, None), BadOrigin); + assert_ok!(Democracy::blacklist(RuntimeOrigin::root(), hash, None)); assert_eq!(Democracy::backing_for(0), None); assert_eq!(Democracy::backing_for(1), Some(4)); @@ -127,7 +130,7 @@ fn blacklisting_should_work() { let hash = set_balance_proposal_hash(4); assert_ok!(Democracy::referendum_status(0)); - assert_ok!(Democracy::blacklist(Origin::root(), hash, Some(0))); + assert_ok!(Democracy::blacklist(RuntimeOrigin::root(), hash, Some(0))); assert_noop!(Democracy::referendum_status(0), Error::::ReferendumInvalid); }); } @@ -140,10 +143,10 @@ fn runners_up_should_come_after() { assert_ok!(propose_set_balance_and_note(1, 4, 4)); assert_ok!(propose_set_balance_and_note(1, 3, 3)); fast_forward_to(2); - assert_ok!(Democracy::vote(Origin::signed(1), 0, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), 0, aye(1))); fast_forward_to(4); - assert_ok!(Democracy::vote(Origin::signed(1), 1, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), 1, aye(1))); fast_forward_to(6); - assert_ok!(Democracy::vote(Origin::signed(1), 2, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), 2, aye(1))); }); } diff --git a/frame/democracy/src/tests/scheduling.rs b/frame/democracy/src/tests/scheduling.rs index d28f24d76bb5b..4b5fe8dd9c1c3 100644 --- a/frame/democracy/src/tests/scheduling.rs +++ b/frame/democracy/src/tests/scheduling.rs @@ -28,7 +28,7 @@ fn simple_passing_should_work() { VoteThreshold::SuperMajorityApprove, 0, ); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); assert_eq!(tally(r), Tally { ayes: 1, nays: 0, turnout: 10 }); assert_eq!(Democracy::lowest_unbaked(), 0); next_block(); @@ -47,7 +47,7 @@ fn simple_failing_should_work() { VoteThreshold::SuperMajorityApprove, 0, ); - assert_ok!(Democracy::vote(Origin::signed(1), r, nay(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, nay(1))); assert_eq!(tally(r), Tally { ayes: 0, nays: 1, turnout: 10 }); next_block(); @@ -73,13 +73,13 @@ fn ooo_inject_referendums_should_work() { 0, ); - assert_ok!(Democracy::vote(Origin::signed(1), r2, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r2, aye(1))); assert_eq!(tally(r2), Tally { ayes: 1, nays: 0, turnout: 10 }); next_block(); assert_eq!(Balances::free_balance(42), 2); - assert_ok!(Democracy::vote(Origin::signed(1), r1, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r1, aye(1))); assert_eq!(tally(r1), Tally { ayes: 1, nays: 0, turnout: 10 }); next_block(); @@ -96,12 +96,12 @@ fn delayed_enactment_should_work() { VoteThreshold::SuperMajorityApprove, 1, ); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - assert_ok!(Democracy::vote(Origin::signed(2), r, aye(2))); - assert_ok!(Democracy::vote(Origin::signed(3), r, aye(3))); - assert_ok!(Democracy::vote(Origin::signed(4), r, aye(4))); - assert_ok!(Democracy::vote(Origin::signed(5), r, aye(5))); - assert_ok!(Democracy::vote(Origin::signed(6), r, aye(6))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(2), r, aye(2))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(3), r, aye(3))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(4), r, aye(4))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(5), r, aye(5))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(6), r, aye(6))); assert_eq!(tally(r), Tally { ayes: 21, nays: 0, turnout: 210 }); @@ -134,10 +134,10 @@ fn lowest_unbaked_should_be_sensible() { VoteThreshold::SuperMajorityApprove, 0, ); - assert_ok!(Democracy::vote(Origin::signed(1), r1, aye(1))); - assert_ok!(Democracy::vote(Origin::signed(1), r2, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r1, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r2, aye(1))); // r3 is canceled - assert_ok!(Democracy::cancel_referendum(Origin::root(), r3.into())); + assert_ok!(Democracy::cancel_referendum(RuntimeOrigin::root(), r3.into())); assert_eq!(Democracy::lowest_unbaked(), 0); next_block(); diff --git a/frame/democracy/src/tests/voting.rs b/frame/democracy/src/tests/voting.rs index d4fceaf0ee489..59d0cd6bc50ef 100644 --- a/frame/democracy/src/tests/voting.rs +++ b/frame/democracy/src/tests/voting.rs @@ -24,7 +24,7 @@ fn overvoting_should_fail() { new_test_ext().execute_with(|| { let r = begin_referendum(); assert_noop!( - Democracy::vote(Origin::signed(1), r, aye(2)), + Democracy::vote(RuntimeOrigin::signed(1), r, aye(2)), Error::::InsufficientFunds ); }); @@ -35,9 +35,12 @@ fn split_voting_should_work() { new_test_ext().execute_with(|| { let r = begin_referendum(); let v = AccountVote::Split { aye: 40, nay: 20 }; - assert_noop!(Democracy::vote(Origin::signed(5), r, v), Error::::InsufficientFunds); + assert_noop!( + Democracy::vote(RuntimeOrigin::signed(5), r, v), + Error::::InsufficientFunds + ); let v = AccountVote::Split { aye: 30, nay: 20 }; - assert_ok!(Democracy::vote(Origin::signed(5), r, v)); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(5), r, v)); assert_eq!(tally(r), Tally { ayes: 3, nays: 2, turnout: 50 }); }); @@ -48,10 +51,10 @@ fn split_vote_cancellation_should_work() { new_test_ext().execute_with(|| { let r = begin_referendum(); let v = AccountVote::Split { aye: 30, nay: 20 }; - assert_ok!(Democracy::vote(Origin::signed(5), r, v)); - assert_ok!(Democracy::remove_vote(Origin::signed(5), r)); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(5), r, v)); + assert_ok!(Democracy::remove_vote(RuntimeOrigin::signed(5), r)); assert_eq!(tally(r), Tally { ayes: 0, nays: 0, turnout: 0 }); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); + assert_ok!(Democracy::unlock(RuntimeOrigin::signed(5), 5)); assert_eq!(Balances::locks(5), vec![]); }); } @@ -66,7 +69,7 @@ fn single_proposal_should_work() { // start of 2 => next referendum scheduled. fast_forward_to(2); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); assert_eq!(Democracy::referendum_count(), 1); assert_eq!( @@ -108,12 +111,12 @@ fn controversial_voting_should_work() { 0, ); - assert_ok!(Democracy::vote(Origin::signed(1), r, big_aye(1))); - assert_ok!(Democracy::vote(Origin::signed(2), r, big_nay(2))); - assert_ok!(Democracy::vote(Origin::signed(3), r, big_nay(3))); - assert_ok!(Democracy::vote(Origin::signed(4), r, big_aye(4))); - assert_ok!(Democracy::vote(Origin::signed(5), r, big_nay(5))); - assert_ok!(Democracy::vote(Origin::signed(6), r, big_aye(6))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, big_aye(1))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(2), r, big_nay(2))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(3), r, big_nay(3))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(4), r, big_aye(4))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(5), r, big_nay(5))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(6), r, big_aye(6))); assert_eq!(tally(r), Tally { ayes: 110, nays: 100, turnout: 210 }); @@ -133,8 +136,8 @@ fn controversial_low_turnout_voting_should_work() { VoteThreshold::SuperMajorityApprove, 0, ); - assert_ok!(Democracy::vote(Origin::signed(5), r, big_nay(5))); - assert_ok!(Democracy::vote(Origin::signed(6), r, big_aye(6))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(5), r, big_nay(5))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(6), r, big_aye(6))); assert_eq!(tally(r), Tally { ayes: 60, nays: 50, turnout: 110 }); @@ -157,9 +160,9 @@ fn passing_low_turnout_voting_should_work() { VoteThreshold::SuperMajorityApprove, 0, ); - assert_ok!(Democracy::vote(Origin::signed(4), r, big_aye(4))); - assert_ok!(Democracy::vote(Origin::signed(5), r, big_nay(5))); - assert_ok!(Democracy::vote(Origin::signed(6), r, big_aye(6))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(4), r, big_aye(4))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(5), r, big_nay(5))); + assert_ok!(Democracy::vote(RuntimeOrigin::signed(6), r, big_aye(6))); assert_eq!(tally(r), Tally { ayes: 100, nays: 50, turnout: 150 }); next_block(); diff --git a/frame/election-provider-multi-phase/src/lib.rs b/frame/election-provider-multi-phase/src/lib.rs index 1188e3353bc96..05353e5a3ac61 100644 --- a/frame/election-provider-multi-phase/src/lib.rs +++ b/frame/election-provider-multi-phase/src/lib.rs @@ -318,6 +318,10 @@ impl ElectionProvider for NoFallback { type DataProvider = T::DataProvider; type Error = &'static str; + fn ongoing() -> bool { + false + } + fn elect() -> Result, Self::Error> { // Do nothing, this will enable the emergency phase. Err("NoFallback.") @@ -700,7 +704,7 @@ pub mod pallet { /// Origin that can control this pallet. Note that any action taken by this origin (such) /// as providing an emergency solution is not checked. Thus, it must be a trusted origin. - type ForceOrigin: EnsureOrigin; + type ForceOrigin: EnsureOrigin; /// The configuration of benchmarking. type BenchmarkingConfig: BenchmarkingConfig; @@ -1598,6 +1602,13 @@ impl ElectionProvider for Pallet { type Error = ElectionError; type DataProvider = T::DataProvider; + fn ongoing() -> bool { + match Self::current_phase() { + Phase::Off => false, + _ => true, + } + } + fn elect() -> Result, Self::Error> { match Self::do_elect() { Ok(supports) => { @@ -1828,7 +1839,7 @@ mod tests { use crate::{ mock::{ multi_phase_events, raw_solution, roll_to, AccountId, ExtBuilder, MockWeightInfo, - MockedWeightInfo, MultiPhase, Origin, Runtime, SignedMaxSubmissions, System, + MockedWeightInfo, MultiPhase, Runtime, RuntimeOrigin, SignedMaxSubmissions, System, TargetIndex, Targets, }, Phase, @@ -2030,7 +2041,10 @@ mod tests { score: ElectionScore { minimal_stake: (5 + s).into(), ..Default::default() }, ..Default::default() }; - assert_ok!(MultiPhase::submit(crate::mock::Origin::signed(99), Box::new(solution))); + assert_ok!(MultiPhase::submit( + crate::mock::RuntimeOrigin::signed(99), + Box::new(solution) + )); } // an unexpected call to elect. @@ -2057,7 +2071,10 @@ mod tests { assert!(MultiPhase::current_phase().is_signed()); let solution = raw_solution(); - assert_ok!(MultiPhase::submit(crate::mock::Origin::signed(99), Box::new(solution))); + assert_ok!(MultiPhase::submit( + crate::mock::RuntimeOrigin::signed(99), + Box::new(solution) + )); roll_to(30); assert_ok!(MultiPhase::elect()); @@ -2098,7 +2115,7 @@ mod tests { // ensure this solution is valid. assert!(MultiPhase::queued_solution().is_none()); assert_ok!(MultiPhase::submit_unsigned( - crate::mock::Origin::none(), + crate::mock::RuntimeOrigin::none(), Box::new(solution), witness )); @@ -2176,12 +2193,12 @@ mod tests { // no single account can trigger this assert_noop!( - MultiPhase::governance_fallback(Origin::signed(99), None, None), + MultiPhase::governance_fallback(RuntimeOrigin::signed(99), None, None), DispatchError::BadOrigin ); // only root can - assert_ok!(MultiPhase::governance_fallback(Origin::root(), None, None)); + assert_ok!(MultiPhase::governance_fallback(RuntimeOrigin::root(), None, None)); // something is queued now assert!(MultiPhase::queued_solution().is_some()); // next election call with fix everything.; diff --git a/frame/election-provider-multi-phase/src/mock.rs b/frame/election-provider-multi-phase/src/mock.rs index efe9d8ea587cb..34aa2e1bbfc58 100644 --- a/frame/election-provider-multi-phase/src/mock.rs +++ b/frame/election-provider-multi-phase/src/mock.rs @@ -199,7 +199,7 @@ pub fn witness() -> SolutionOrSnapshotSize { impl frame_system::Config for Runtime { type SS58Prefix = (); type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; @@ -303,6 +303,10 @@ impl ElectionProvider for MockFallback { type Error = &'static str; type DataProvider = StakingMock; + fn ongoing() -> bool { + false + } + fn elect() -> Result, Self::Error> { Self::elect_with_bounds(Bounded::max_value(), Bounded::max_value()) } diff --git a/frame/election-provider-multi-phase/src/signed.rs b/frame/election-provider-multi-phase/src/signed.rs index b9abfdfba14fb..1cf071e6796f1 100644 --- a/frame/election-provider-multi-phase/src/signed.rs +++ b/frame/election-provider-multi-phase/src/signed.rs @@ -529,7 +529,7 @@ mod tests { use crate::{ mock::{ balances, raw_solution, roll_to, Balances, ExtBuilder, MockedWeightInfo, MultiPhase, - Origin, Runtime, SignedMaxRefunds, SignedMaxSubmissions, SignedMaxWeight, + Runtime, RuntimeOrigin, SignedMaxRefunds, SignedMaxSubmissions, SignedMaxWeight, }, Error, Perbill, Phase, }; @@ -546,7 +546,7 @@ mod tests { let solution = raw_solution(); assert_noop!( - MultiPhase::submit(Origin::signed(10), Box::new(solution)), + MultiPhase::submit(RuntimeOrigin::signed(10), Box::new(solution)), Error::::PreDispatchEarlySubmission, ); }) @@ -561,7 +561,7 @@ mod tests { let solution = raw_solution(); assert_eq!(balances(&99), (100, 0)); - assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution))); assert_eq!(balances(&99), (95, 5)); assert_eq!(MultiPhase::signed_submissions().iter().next().unwrap().deposit, 5); @@ -577,7 +577,7 @@ mod tests { let solution = raw_solution(); assert_eq!(balances(&99), (100, 0)); - assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution))); assert_eq!(balances(&99), (95, 5)); assert!(MultiPhase::finalize_signed_phase()); @@ -597,7 +597,7 @@ mod tests { // make the solution invalid. solution.score.minimal_stake += 1; - assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution))); assert_eq!(balances(&99), (95, 5)); // no good solution was stored. @@ -618,11 +618,11 @@ mod tests { assert_eq!(balances(&999), (100, 0)); // submit as correct. - assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(solution.clone()))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution.clone()))); // make the solution invalid and weaker. solution.score.minimal_stake -= 1; - assert_ok!(MultiPhase::submit(Origin::signed(999), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(999), Box::new(solution))); assert_eq!(balances(&99), (95, 5)); assert_eq!(balances(&999), (95, 5)); @@ -648,7 +648,7 @@ mod tests { score: ElectionScore { minimal_stake: (5 + s).into(), ..Default::default() }, ..Default::default() }; - assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution))); } // weaker. @@ -658,7 +658,7 @@ mod tests { }; assert_noop!( - MultiPhase::submit(Origin::signed(99), Box::new(solution)), + MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution)), Error::::SignedQueueFull, ); }) @@ -679,7 +679,7 @@ mod tests { let mut solution = raw_solution(); solution.score.minimal_stake -= s as u128; - assert_ok!(MultiPhase::submit(Origin::signed(account), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(account), Box::new(solution))); assert_eq!(balances(&account), (95, 5)); } @@ -719,7 +719,7 @@ mod tests { }, ..Default::default() }; - assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution))); // This is 10% better, so does not meet the 20% threshold and is therefore rejected. solution = RawSolution { @@ -732,7 +732,7 @@ mod tests { }; assert_noop!( - MultiPhase::submit(Origin::signed(99), Box::new(solution)), + MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution)), Error::::SignedQueueFull, ); @@ -746,7 +746,7 @@ mod tests { ..Default::default() }; - assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution))); }) } @@ -764,7 +764,7 @@ mod tests { score: ElectionScore { minimal_stake: (5 + s).into(), ..Default::default() }, ..Default::default() }; - assert_ok!(MultiPhase::submit(Origin::signed(account), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(account), Box::new(solution))); assert_eq!(balances(&account), (95, 5)); } @@ -781,7 +781,7 @@ mod tests { score: ElectionScore { minimal_stake: 20, ..Default::default() }, ..Default::default() }; - assert_ok!(MultiPhase::submit(Origin::signed(999), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(999), Box::new(solution))); // the one with score 5 was rejected, the new one inserted. assert_eq!( @@ -809,14 +809,14 @@ mod tests { score: ElectionScore { minimal_stake: (5 + s).into(), ..Default::default() }, ..Default::default() }; - assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution))); } let solution = RawSolution { score: ElectionScore { minimal_stake: 4, ..Default::default() }, ..Default::default() }; - assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution))); assert_eq!( MultiPhase::signed_submissions() @@ -831,7 +831,7 @@ mod tests { score: ElectionScore { minimal_stake: 5, ..Default::default() }, ..Default::default() }; - assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution))); // the one with score 5 was rejected, the new one inserted. assert_eq!( @@ -856,7 +856,7 @@ mod tests { score: ElectionScore { minimal_stake: (5 + s).into(), ..Default::default() }, ..Default::default() }; - assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution))); } assert_eq!(balances(&99).1, 2 * 5); @@ -867,7 +867,7 @@ mod tests { score: ElectionScore { minimal_stake: 20, ..Default::default() }, ..Default::default() }; - assert_ok!(MultiPhase::submit(Origin::signed(999), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(999), Box::new(solution))); // got one bond back. assert_eq!(balances(&99).1, 2 * 4); @@ -886,7 +886,7 @@ mod tests { score: ElectionScore { minimal_stake: (5 + i).into(), ..Default::default() }, ..Default::default() }; - assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution))); } assert_eq!( MultiPhase::signed_submissions() @@ -902,7 +902,7 @@ mod tests { ..Default::default() }; assert_noop!( - MultiPhase::submit(Origin::signed(99), Box::new(solution)), + MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution)), Error::::SignedQueueFull, ); }) @@ -924,18 +924,18 @@ mod tests { let solution = raw_solution(); // submit a correct one. - assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(solution.clone()))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution.clone()))); // make the solution invalidly better and submit. This ought to be slashed. let mut solution_999 = solution.clone(); solution_999.score.minimal_stake += 1; - assert_ok!(MultiPhase::submit(Origin::signed(999), Box::new(solution_999))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(999), Box::new(solution_999))); // make the solution invalidly worse and submit. This ought to be suppressed and // returned. let mut solution_9999 = solution.clone(); solution_9999.score.minimal_stake -= 1; - assert_ok!(MultiPhase::submit(Origin::signed(9999), Box::new(solution_9999))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(9999), Box::new(solution_9999))); assert_eq!( MultiPhase::signed_submissions().iter().map(|x| x.who).collect::>(), @@ -975,14 +975,14 @@ mod tests { assert_eq!(raw.solution.voter_count(), 5); assert_eq!(::SignedMaxWeight::get(), Weight::from_ref_time(40)); - assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(raw.clone()))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(raw.clone()))); ::set(Weight::from_ref_time(30)); // note: resubmitting the same solution is technically okay as long as the queue has // space. assert_noop!( - MultiPhase::submit(Origin::signed(99), Box::new(raw)), + MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(raw)), Error::::SignedTooMuchWeight, ); }) @@ -998,7 +998,7 @@ mod tests { assert_eq!(balances(&123), (0, 0)); assert_noop!( - MultiPhase::submit(Origin::signed(123), Box::new(solution)), + MultiPhase::submit(RuntimeOrigin::signed(123), Box::new(solution)), Error::::SignedCannotPayDeposit, ); @@ -1020,7 +1020,7 @@ mod tests { score: ElectionScore { minimal_stake: (5 + s).into(), ..Default::default() }, ..Default::default() }; - assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution))); } // this solution has a higher score than any in the queue @@ -1034,7 +1034,7 @@ mod tests { assert_eq!(balances(&123), (0, 0)); assert_noop!( - MultiPhase::submit(Origin::signed(123), Box::new(solution)), + MultiPhase::submit(RuntimeOrigin::signed(123), Box::new(solution)), Error::::SignedCannotPayDeposit, ); @@ -1063,7 +1063,7 @@ mod tests { let solution = raw_solution(); // submit a correct one. - assert_ok!(MultiPhase::submit(Origin::signed(99), Box::new(solution))); + assert_ok!(MultiPhase::submit(RuntimeOrigin::signed(99), Box::new(solution))); // _some_ good solution was stored. assert!(MultiPhase::finalize_signed_phase()); diff --git a/frame/election-provider-multi-phase/src/unsigned.rs b/frame/election-provider-multi-phase/src/unsigned.rs index 7dadd320abdf8..cf8df237bafb0 100644 --- a/frame/election-provider-multi-phase/src/unsigned.rs +++ b/frame/election-provider-multi-phase/src/unsigned.rs @@ -856,7 +856,7 @@ mod tests { use crate::{ mock::{ roll_to, roll_to_with_ocw, trim_helpers, witness, BlockNumber, ExtBuilder, Extrinsic, - MinerMaxWeight, MultiPhase, Origin, Runtime, RuntimeCall as OuterCall, System, + MinerMaxWeight, MultiPhase, Runtime, RuntimeCall as OuterCall, RuntimeOrigin, System, TestNposSolution, TrimHelpers, UnsignedPhase, }, CurrentPhase, InvalidTransaction, Phase, QueuedSolution, TransactionSource, @@ -1071,7 +1071,7 @@ mod tests { witness: witness(), }; let outer_call: OuterCall = call.into(); - let _ = outer_call.dispatch(Origin::none()); + let _ = outer_call.dispatch(RuntimeOrigin::none()); }) } @@ -1097,7 +1097,7 @@ mod tests { witness: correct_witness, }; let outer_call: OuterCall = call.into(); - let _ = outer_call.dispatch(Origin::none()); + let _ = outer_call.dispatch(RuntimeOrigin::none()); }) } @@ -1116,7 +1116,11 @@ mod tests { // ensure this solution is valid. assert!(MultiPhase::queued_solution().is_none()); - assert_ok!(MultiPhase::submit_unsigned(Origin::none(), Box::new(solution), witness)); + assert_ok!(MultiPhase::submit_unsigned( + RuntimeOrigin::none(), + Box::new(solution), + witness + )); assert!(MultiPhase::queued_solution().is_some()); }) } @@ -1215,7 +1219,7 @@ mod tests { let solution = RawSolution { solution: raw, score, round: MultiPhase::round() }; assert_ok!(MultiPhase::unsigned_pre_dispatch_checks(&solution)); assert_ok!(MultiPhase::submit_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(solution), witness )); @@ -1276,7 +1280,7 @@ mod tests { // and it is fine assert_ok!(MultiPhase::unsigned_pre_dispatch_checks(&solution)); assert_ok!(MultiPhase::submit_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(solution), witness )); diff --git a/frame/election-provider-support/src/lib.rs b/frame/election-provider-support/src/lib.rs index 9f60411435da0..0bf62bd8c35cd 100644 --- a/frame/election-provider-support/src/lib.rs +++ b/frame/election-provider-support/src/lib.rs @@ -136,7 +136,7 @@ //! type BlockNumber = BlockNumber; //! type Error = &'static str; //! type DataProvider = T::DataProvider; -//! +//! fn ongoing() -> bool { false } //! fn elect() -> Result, Self::Error> { //! Self::DataProvider::electable_targets(None) //! .map_err(|_| "failed to elect") @@ -370,6 +370,9 @@ pub trait ElectionProvider { BlockNumber = Self::BlockNumber, >; + /// Indicate if this election provider is currently ongoing an asynchronous election or not. + fn ongoing() -> bool; + /// Elect a new set of winners, without specifying any bounds on the amount of data fetched from /// [`Self::DataProvider`]. An implementation could nonetheless impose its own custom limits. /// @@ -420,6 +423,10 @@ where fn elect() -> Result, Self::Error> { Err(" cannot do anything.") } + + fn ongoing() -> bool { + false + } } /// A utility trait for something to implement `ElectionDataProvider` in a sensible way. diff --git a/frame/election-provider-support/src/onchain.rs b/frame/election-provider-support/src/onchain.rs index 05bbd11e1ae9d..10c3519d03df6 100644 --- a/frame/election-provider-support/src/onchain.rs +++ b/frame/election-provider-support/src/onchain.rs @@ -138,6 +138,10 @@ impl ElectionProvider for UnboundedExecution { type Error = Error; type DataProvider = T::DataProvider; + fn ongoing() -> bool { + false + } + fn elect() -> Result, Self::Error> { // This should not be called if not in `std` mode (and therefore neither in genesis nor in // testing) @@ -167,6 +171,10 @@ impl ElectionProvider for BoundedExecution { type Error = Error; type DataProvider = T::DataProvider; + fn ongoing() -> bool { + false + } + fn elect() -> Result, Self::Error> { elect_with::(Some(T::VotersBound::get() as usize), Some(T::TargetsBound::get() as usize)) } @@ -211,7 +219,7 @@ mod tests { impl frame_system::Config for Runtime { type SS58Prefix = (); type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = AccountId; type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 18210513f8ab6..0616087d975e8 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -1182,7 +1182,7 @@ mod tests { type BlockWeights = BlockWeights; type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; @@ -1486,11 +1486,11 @@ mod tests { ensure_members_has_approval_stake(); } - fn submit_candidacy(origin: Origin) -> sp_runtime::DispatchResult { + fn submit_candidacy(origin: RuntimeOrigin) -> sp_runtime::DispatchResult { Elections::submit_candidacy(origin, Elections::candidates().len() as u32) } - fn vote(origin: Origin, votes: Vec, stake: u64) -> DispatchResultWithPostInfo { + fn vote(origin: RuntimeOrigin, votes: Vec, stake: u64) -> DispatchResultWithPostInfo { // historical note: helper function was created in a period of time in which the API of vote // call was changing. Currently it is a wrapper for the original call and does not do much. // Nonetheless, totally harmless. @@ -1572,8 +1572,8 @@ mod tests { Voter { stake: 20u64, votes: vec![2], deposit: 0 } ); - assert_ok!(Elections::remove_voter(Origin::signed(1))); - assert_ok!(Elections::remove_voter(Origin::signed(2))); + assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(1))); + assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(2))); assert_eq!(Elections::voting(1), Default::default()); assert_eq!(Elections::voting(2), Default::default()); @@ -1666,7 +1666,7 @@ mod tests { assert!(Elections::is_candidate(&2).is_err()); assert_eq!(balances(&1), (10, 0)); - assert_ok!(submit_candidacy(Origin::signed(1))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(1))); assert_eq!(balances(&1), (7, 3)); assert_eq!(candidate_ids(), vec![1]); @@ -1675,7 +1675,7 @@ mod tests { assert!(Elections::is_candidate(&2).is_err()); assert_eq!(balances(&2), (20, 0)); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); assert_eq!(balances(&2), (17, 3)); assert_eq!(candidate_ids(), vec![1, 2]); @@ -1692,15 +1692,15 @@ mod tests { #[test] fn updating_candidacy_bond_works() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); assert_eq!(Elections::candidates(), vec![(5, 3)]); // a runtime upgrade changes the bond. CANDIDACY_BOND.with(|v| *v.borrow_mut() = 4); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); assert_eq!(Elections::candidates(), vec![(4, 4), (5, 3)]); // once elected, they each hold their candidacy bond, no more. @@ -1724,13 +1724,13 @@ mod tests { ExtBuilder::default().build_and_execute(|| { assert_eq!(candidate_ids(), Vec::::new()); - assert_ok!(submit_candidacy(Origin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); assert_eq!(candidate_ids(), vec![3]); - assert_ok!(submit_candidacy(Origin::signed(1))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(1))); assert_eq!(candidate_ids(), vec![1, 3]); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); assert_eq!(candidate_ids(), vec![1, 2, 3]); - assert_ok!(submit_candidacy(Origin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); assert_eq!(candidate_ids(), vec![1, 2, 3, 4]); }); } @@ -1739,9 +1739,12 @@ mod tests { fn dupe_candidate_submission_should_not_work() { ExtBuilder::default().build_and_execute(|| { assert_eq!(candidate_ids(), Vec::::new()); - assert_ok!(submit_candidacy(Origin::signed(1))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(1))); assert_eq!(candidate_ids(), vec![1]); - assert_noop!(submit_candidacy(Origin::signed(1)), Error::::DuplicatedCandidate); + assert_noop!( + submit_candidacy(RuntimeOrigin::signed(1)), + Error::::DuplicatedCandidate + ); }); } @@ -1749,8 +1752,8 @@ mod tests { fn member_candidacy_submission_should_not_work() { // critically important to make sure that outgoing candidates and losers are not mixed up. ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(vote(Origin::signed(2), vec![5], 20)); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![5], 20)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -1759,19 +1762,19 @@ mod tests { assert!(Elections::runners_up().is_empty()); assert!(candidate_ids().is_empty()); - assert_noop!(submit_candidacy(Origin::signed(5)), Error::::MemberSubmit); + assert_noop!(submit_candidacy(RuntimeOrigin::signed(5)), Error::::MemberSubmit); }); } #[test] fn runner_candidate_submission_should_not_work() { ExtBuilder::default().desired_runners_up(2).build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); - assert_ok!(vote(Origin::signed(2), vec![5, 4], 20)); - assert_ok!(vote(Origin::signed(1), vec![3], 10)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![5, 4], 20)); + assert_ok!(vote(RuntimeOrigin::signed(1), vec![3], 10)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -1779,7 +1782,7 @@ mod tests { assert_eq!(members_ids(), vec![4, 5]); assert_eq!(runners_up_ids(), vec![3]); - assert_noop!(submit_candidacy(Origin::signed(3)), Error::::RunnerUpSubmit); + assert_noop!(submit_candidacy(RuntimeOrigin::signed(3)), Error::::RunnerUpSubmit); }); } @@ -1788,7 +1791,7 @@ mod tests { ExtBuilder::default().build_and_execute(|| { assert_eq!(candidate_ids(), Vec::::new()); assert_noop!( - submit_candidacy(Origin::signed(7)), + submit_candidacy(RuntimeOrigin::signed(7)), Error::::InsufficientCandidateFunds, ); }); @@ -1800,8 +1803,8 @@ mod tests { assert_eq!(candidate_ids(), Vec::::new()); assert_eq!(balances(&2), (20, 0)); - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(vote(Origin::signed(2), vec![5], 20)); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![5], 20)); assert_eq!(balances(&2), (18, 2)); assert_eq!(has_lock(&2), 18); @@ -1814,8 +1817,8 @@ mod tests { assert_eq!(candidate_ids(), Vec::::new()); assert_eq!(balances(&2), (20, 0)); - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(vote(Origin::signed(2), vec![5], 12)); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![5], 12)); assert_eq!(balances(&2), (18, 2)); assert_eq!(has_lock(&2), 12); @@ -1827,9 +1830,9 @@ mod tests { ExtBuilder::default().build_and_execute(|| { assert_eq!(balances(&2), (20, 0)); - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(vote(Origin::signed(2), vec![5], 20)); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![5], 20)); // User only locks up to their free balance. assert_eq!(balances(&2), (18, 2)); @@ -1837,7 +1840,7 @@ mod tests { assert_eq!(locked_stake_of(&2), 18); // can update; different stake; different lock and reserve. - assert_ok!(vote(Origin::signed(2), vec![5, 4], 15)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![5, 4], 15)); assert_eq!(balances(&2), (18, 2)); assert_eq!(has_lock(&2), 15); assert_eq!(locked_stake_of(&2), 15); @@ -1847,10 +1850,10 @@ mod tests { #[test] fn updated_voting_bond_works() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); assert_eq!(balances(&2), (20, 0)); - assert_ok!(vote(Origin::signed(2), vec![5], 5)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![5], 5)); assert_eq!(balances(&2), (18, 2)); assert_eq!(voter_deposit(&2), 2); @@ -1860,11 +1863,11 @@ mod tests { // proof that bond changed. assert_eq!(balances(&1), (10, 0)); - assert_ok!(vote(Origin::signed(1), vec![5], 5)); + assert_ok!(vote(RuntimeOrigin::signed(1), vec![5], 5)); assert_eq!(balances(&1), (9, 1)); assert_eq!(voter_deposit(&1), 1); - assert_ok!(Elections::remove_voter(Origin::signed(2))); + assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(2))); assert_eq!(balances(&2), (20, 0)); }) } @@ -1874,11 +1877,11 @@ mod tests { ExtBuilder::default().voter_bond_factor(1).build_and_execute(|| { assert_eq!(balances(&2), (20, 0)); - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); // initial vote. - assert_ok!(vote(Origin::signed(2), vec![5], 10)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![5], 10)); // 2 + 1 assert_eq!(balances(&2), (17, 3)); @@ -1887,7 +1890,7 @@ mod tests { assert_eq!(locked_stake_of(&2), 10); // can update; different stake; different lock and reserve. - assert_ok!(vote(Origin::signed(2), vec![5, 4], 15)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![5, 4], 15)); // 2 + 2 assert_eq!(balances(&2), (16, 4)); assert_eq!(Elections::voting(&2).deposit, 4); @@ -1895,7 +1898,7 @@ mod tests { assert_eq!(locked_stake_of(&2), 15); // stay at two votes with different stake. - assert_ok!(vote(Origin::signed(2), vec![5, 3], 18)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![5, 3], 18)); // 2 + 2 assert_eq!(balances(&2), (16, 4)); assert_eq!(Elections::voting(&2).deposit, 4); @@ -1903,7 +1906,7 @@ mod tests { assert_eq!(locked_stake_of(&2), 16); // back to 1 vote. - assert_ok!(vote(Origin::signed(2), vec![4], 12)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![4], 12)); // 2 + 1 assert_eq!(balances(&2), (17, 3)); assert_eq!(Elections::voting(&2).deposit, 3); @@ -1915,17 +1918,17 @@ mod tests { #[test] fn cannot_vote_for_no_candidate() { ExtBuilder::default().build_and_execute(|| { - assert_noop!(vote(Origin::signed(2), vec![], 20), Error::::NoVotes); + assert_noop!(vote(RuntimeOrigin::signed(2), vec![], 20), Error::::NoVotes); }); } #[test] fn can_vote_for_old_members_even_when_no_new_candidates() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); - assert_ok!(vote(Origin::signed(2), vec![4, 5], 20)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![4, 5], 20)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -1933,22 +1936,22 @@ mod tests { assert_eq!(members_ids(), vec![4, 5]); assert!(candidate_ids().is_empty()); - assert_ok!(vote(Origin::signed(3), vec![4, 5], 10)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![4, 5], 10)); }); } #[test] fn prime_works() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); - assert_ok!(vote(Origin::signed(1), vec![4, 3], 10)); - assert_ok!(vote(Origin::signed(2), vec![4], 20)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(1), vec![4, 3], 10)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![4], 20)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -1956,7 +1959,7 @@ mod tests { assert_eq!(members_ids(), vec![4, 5]); assert!(candidate_ids().is_empty()); - assert_ok!(vote(Origin::signed(3), vec![4, 5], 10)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![4, 5], 10)); assert_eq!(PRIME.with(|p| *p.borrow()), Some(4)); }); } @@ -1964,17 +1967,20 @@ mod tests { #[test] fn prime_votes_for_exiting_members_are_removed() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); - assert_ok!(vote(Origin::signed(1), vec![4, 3], 10)); - assert_ok!(vote(Origin::signed(2), vec![4], 20)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(1), vec![4, 3], 10)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![4], 20)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); - assert_ok!(Elections::renounce_candidacy(Origin::signed(4), Renouncing::Candidate(3))); + assert_ok!(Elections::renounce_candidacy( + RuntimeOrigin::signed(4), + Renouncing::Candidate(3) + )); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -1989,18 +1995,18 @@ mod tests { #[test] fn prime_is_kept_if_other_members_leave() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); System::set_block_number(5); Elections::on_initialize(System::block_number()); assert_eq!(members_ids(), vec![4, 5]); assert_eq!(PRIME.with(|p| *p.borrow()), Some(5)); - assert_ok!(Elections::renounce_candidacy(Origin::signed(4), Renouncing::Member)); + assert_ok!(Elections::renounce_candidacy(RuntimeOrigin::signed(4), Renouncing::Member)); assert_eq!(members_ids(), vec![5]); assert_eq!(PRIME.with(|p| *p.borrow()), Some(5)); @@ -2010,18 +2016,18 @@ mod tests { #[test] fn prime_is_gone_if_renouncing() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); System::set_block_number(5); Elections::on_initialize(System::block_number()); assert_eq!(members_ids(), vec![4, 5]); assert_eq!(PRIME.with(|p| *p.borrow()), Some(5)); - assert_ok!(Elections::renounce_candidacy(Origin::signed(5), Renouncing::Member)); + assert_ok!(Elections::renounce_candidacy(RuntimeOrigin::signed(5), Renouncing::Member)); assert_eq!(members_ids(), vec![4]); assert_eq!(PRIME.with(|p| *p.borrow()), None); @@ -2035,29 +2041,29 @@ mod tests { .balance_factor(10) .build_and_execute(|| { // when we have only candidates - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); assert_noop!( // content of the vote is irrelevant. - vote(Origin::signed(1), vec![9, 99, 999, 9999], 5), + vote(RuntimeOrigin::signed(1), vec![9, 99, 999, 9999], 5), Error::::TooManyVotes, ); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); System::set_block_number(5); Elections::on_initialize(System::block_number()); // now we have 2 members, 1 runner-up, and 1 new candidate - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_ok!(vote(Origin::signed(1), vec![9, 99, 999, 9999], 5)); + assert_ok!(vote(RuntimeOrigin::signed(1), vec![9, 99, 999, 9999], 5)); assert_noop!( - vote(Origin::signed(1), vec![9, 99, 999, 9_999, 99_999], 5), + vote(RuntimeOrigin::signed(1), vec![9, 99, 999, 9_999, 99_999], 5), Error::::TooManyVotes, ); }); @@ -2066,23 +2072,23 @@ mod tests { #[test] fn cannot_vote_for_less_than_ed() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); - assert_noop!(vote(Origin::signed(2), vec![4], 1), Error::::LowBalance); + assert_noop!(vote(RuntimeOrigin::signed(2), vec![4], 1), Error::::LowBalance); }) } #[test] fn can_vote_for_more_than_free_balance_but_moot() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); // User has 100 free and 50 reserved. - assert_ok!(Balances::set_balance(Origin::root(), 2, 100, 50)); + assert_ok!(Balances::set_balance(RuntimeOrigin::root(), 2, 100, 50)); // User tries to vote with 150 tokens. - assert_ok!(vote(Origin::signed(2), vec![4, 5], 150)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![4, 5], 150)); // We truncate to only their free balance, after reserving additional for voting. assert_eq!(locked_stake_of(&2), 98); assert_eq!(has_lock(&2), 98); @@ -2092,10 +2098,10 @@ mod tests { #[test] fn remove_voter_should_work() { ExtBuilder::default().voter_bond(8).build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); - assert_ok!(vote(Origin::signed(2), vec![5], 20)); - assert_ok!(vote(Origin::signed(3), vec![5], 30)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![5], 20)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![5], 30)); assert_eq_uvec!(all_voters(), vec![2, 3]); assert_eq!(balances(&2), (12, 8)); @@ -2105,7 +2111,7 @@ mod tests { assert_eq!(votes_of(&2), vec![5]); assert_eq!(votes_of(&3), vec![5]); - assert_ok!(Elections::remove_voter(Origin::signed(2))); + assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(2))); assert_eq_uvec!(all_voters(), vec![3]); assert!(votes_of(&2).is_empty()); @@ -2119,35 +2125,41 @@ mod tests { #[test] fn non_voter_remove_should_not_work() { ExtBuilder::default().build_and_execute(|| { - assert_noop!(Elections::remove_voter(Origin::signed(3)), Error::::MustBeVoter); + assert_noop!( + Elections::remove_voter(RuntimeOrigin::signed(3)), + Error::::MustBeVoter + ); }); } #[test] fn dupe_remove_should_fail() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(vote(Origin::signed(2), vec![5], 20)); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![5], 20)); - assert_ok!(Elections::remove_voter(Origin::signed(2))); + assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(2))); assert!(all_voters().is_empty()); - assert_noop!(Elections::remove_voter(Origin::signed(2)), Error::::MustBeVoter); + assert_noop!( + Elections::remove_voter(RuntimeOrigin::signed(2)), + Error::::MustBeVoter + ); }); } #[test] fn removed_voter_should_not_be_counted() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); - assert_ok!(Elections::remove_voter(Origin::signed(4))); + assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(4))); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2159,13 +2171,13 @@ mod tests { #[test] fn simple_voting_rounds_should_work() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); - assert_ok!(vote(Origin::signed(2), vec![5], 20)); - assert_ok!(vote(Origin::signed(4), vec![4], 15)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![5], 20)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 15)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); assert_eq_uvec!(all_voters(), vec![2, 3, 4]); @@ -2209,11 +2221,11 @@ mod tests { #[test] fn all_outgoing() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2225,8 +2237,8 @@ mod tests { assert_eq!(members_and_stake(), vec![(4, 35), (5, 45)]); assert_eq!(runners_up_and_stake(), vec![]); - assert_ok!(Elections::remove_voter(Origin::signed(5))); - assert_ok!(Elections::remove_voter(Origin::signed(4))); + assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(5))); + assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(4))); System::set_block_number(10); Elections::on_initialize(System::block_number()); @@ -2244,11 +2256,11 @@ mod tests { #[test] fn defunct_voter_will_be_counted() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); // This guy's vote is pointless for this round. - assert_ok!(vote(Origin::signed(3), vec![4], 30)); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![4], 30)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2257,7 +2269,7 @@ mod tests { assert_eq!(Elections::election_rounds(), 1); // but now it has a valid target. - assert_ok!(submit_candidacy(Origin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); System::set_block_number(10); Elections::on_initialize(System::block_number()); @@ -2272,15 +2284,15 @@ mod tests { #[test] fn only_desired_seats_are_chosen() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_ok!(vote(Origin::signed(2), vec![2], 20)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![2], 20)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2293,8 +2305,8 @@ mod tests { #[test] fn phragmen_should_not_self_vote() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2312,15 +2324,15 @@ mod tests { #[test] fn runners_up_should_be_kept() { ExtBuilder::default().desired_runners_up(2).build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_ok!(vote(Origin::signed(2), vec![3], 20)); - assert_ok!(vote(Origin::signed(3), vec![2], 30)); - assert_ok!(vote(Origin::signed(4), vec![5], 40)); - assert_ok!(vote(Origin::signed(5), vec![4], 50)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![3], 20)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![2], 30)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![5], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![4], 50)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2339,22 +2351,22 @@ mod tests { #[test] fn runners_up_should_be_next_candidates() { ExtBuilder::default().desired_runners_up(2).build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_ok!(vote(Origin::signed(2), vec![2], 20)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![2], 20)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); System::set_block_number(5); Elections::on_initialize(System::block_number()); assert_eq!(members_and_stake(), vec![(4, 35), (5, 45)]); assert_eq!(runners_up_and_stake(), vec![(2, 15), (3, 25)]); - assert_ok!(vote(Origin::signed(5), vec![5], 10)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 10)); System::set_block_number(10); Elections::on_initialize(System::block_number()); @@ -2367,13 +2379,13 @@ mod tests { #[test] fn runners_up_lose_bond_once_outgoing() { ExtBuilder::default().desired_runners_up(1).build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_ok!(vote(Origin::signed(2), vec![2], 20)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![2], 20)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2381,8 +2393,8 @@ mod tests { assert_eq!(runners_up_ids(), vec![2]); assert_eq!(balances(&2), (15, 5)); - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); System::set_block_number(10); Elections::on_initialize(System::block_number()); @@ -2397,17 +2409,17 @@ mod tests { ExtBuilder::default().build_and_execute(|| { assert_eq!(balances(&5), (50, 0)); - assert_ok!(submit_candidacy(Origin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); assert_eq!(balances(&5), (47, 3)); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); assert_eq!(balances(&5), (45, 5)); System::set_block_number(5); Elections::on_initialize(System::block_number()); assert_eq!(members_ids(), vec![5]); - assert_ok!(Elections::remove_voter(Origin::signed(5))); + assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(5))); assert_eq!(balances(&5), (47, 3)); System::set_block_number(10); @@ -2421,10 +2433,10 @@ mod tests { #[test] fn candidates_lose_the_bond_when_outgoing() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); - assert_ok!(vote(Origin::signed(4), vec![5], 40)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![5], 40)); assert_eq!(balances(&5), (47, 3)); assert_eq!(balances(&3), (27, 3)); @@ -2444,11 +2456,11 @@ mod tests { #[test] fn current_members_are_always_next_candidate() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2456,13 +2468,13 @@ mod tests { assert_eq!(members_ids(), vec![4, 5]); assert_eq!(Elections::election_rounds(), 1); - assert_ok!(submit_candidacy(Origin::signed(2))); - assert_ok!(vote(Origin::signed(2), vec![2], 20)); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![2], 20)); - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); - assert_ok!(Elections::remove_voter(Origin::signed(4))); + assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(4))); // 5 will persist as candidates despite not being in the list. assert_eq!(candidate_ids(), vec![2, 3]); @@ -2480,15 +2492,15 @@ mod tests { // what I mean by uninterrupted: // given no input or stimulants the same members are re-elected. ExtBuilder::default().desired_runners_up(2).build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); - assert_ok!(vote(Origin::signed(2), vec![2], 20)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![2], 20)); let check_at_block = |b: u32| { System::set_block_number(b.into()); @@ -2513,11 +2525,11 @@ mod tests { #[test] fn remove_members_triggers_election() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2525,10 +2537,10 @@ mod tests { assert_eq!(Elections::election_rounds(), 1); // a new candidate - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); - assert_ok!(Elections::remove_member(Origin::root(), 4, true, true)); + assert_ok!(Elections::remove_member(RuntimeOrigin::root(), 4, true, true)); assert_eq!(balances(&4), (35, 2)); // slashed assert_eq!(Elections::election_rounds(), 2); // new election round @@ -2539,14 +2551,14 @@ mod tests { #[test] fn seats_should_be_released_when_no_vote() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); - assert_ok!(vote(Origin::signed(2), vec![3], 20)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![3], 20)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); assert_eq!(>::decode_len().unwrap(), 3); @@ -2557,10 +2569,10 @@ mod tests { assert_eq!(members_ids(), vec![3, 5]); assert_eq!(Elections::election_rounds(), 1); - assert_ok!(Elections::remove_voter(Origin::signed(2))); - assert_ok!(Elections::remove_voter(Origin::signed(3))); - assert_ok!(Elections::remove_voter(Origin::signed(4))); - assert_ok!(Elections::remove_voter(Origin::signed(5))); + assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(2))); + assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(3))); + assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(4))); + assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(5))); // meanwhile, no one cares to become a candidate again. System::set_block_number(10); @@ -2573,29 +2585,29 @@ mod tests { #[test] fn incoming_outgoing_are_reported() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); System::set_block_number(5); Elections::on_initialize(System::block_number()); assert_eq!(members_ids(), vec![4, 5]); - assert_ok!(submit_candidacy(Origin::signed(1))); - assert_ok!(submit_candidacy(Origin::signed(2))); - assert_ok!(submit_candidacy(Origin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(1))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); // 5 will change their vote and becomes an `outgoing` - assert_ok!(vote(Origin::signed(5), vec![4], 8)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![4], 8)); // 4 will stay in the set - assert_ok!(vote(Origin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); // 3 will become a winner - assert_ok!(vote(Origin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); // these two are losers. - assert_ok!(vote(Origin::signed(2), vec![2], 20)); - assert_ok!(vote(Origin::signed(1), vec![1], 10)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![2], 20)); + assert_ok!(vote(RuntimeOrigin::signed(1), vec![1], 10)); System::set_block_number(10); Elections::on_initialize(System::block_number()); @@ -2620,12 +2632,12 @@ mod tests { #[test] fn invalid_votes_are_moot() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(5), vec![10], 50)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![10], 50)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2638,15 +2650,15 @@ mod tests { #[test] fn members_are_sorted_based_on_id_runners_on_merit() { ExtBuilder::default().desired_runners_up(2).build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_ok!(vote(Origin::signed(2), vec![3], 20)); - assert_ok!(vote(Origin::signed(3), vec![2], 30)); - assert_ok!(vote(Origin::signed(4), vec![5], 40)); - assert_ok!(vote(Origin::signed(5), vec![4], 50)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![3], 20)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![2], 30)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![5], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![4], 50)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2660,19 +2672,19 @@ mod tests { #[test] fn runner_up_replacement_maintains_members_order() { ExtBuilder::default().desired_runners_up(2).build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_ok!(vote(Origin::signed(2), vec![5], 20)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(5), vec![2], 50)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![5], 20)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![2], 50)); System::set_block_number(5); Elections::on_initialize(System::block_number()); assert_eq!(members_ids(), vec![2, 4]); - assert_ok!(Elections::remove_member(Origin::root(), 2, true, false)); + assert_ok!(Elections::remove_member(RuntimeOrigin::root(), 2, true, false)); assert_eq!(members_ids(), vec![4, 5]); }); } @@ -2680,15 +2692,15 @@ mod tests { #[test] fn can_renounce_candidacy_member_with_runners_bond_is_refunded() { ExtBuilder::default().desired_runners_up(2).build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); - assert_ok!(vote(Origin::signed(2), vec![2], 20)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![2], 20)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2696,7 +2708,7 @@ mod tests { assert_eq!(members_ids(), vec![4, 5]); assert_eq!(runners_up_ids(), vec![2, 3]); - assert_ok!(Elections::renounce_candidacy(Origin::signed(4), Renouncing::Member)); + assert_ok!(Elections::renounce_candidacy(RuntimeOrigin::signed(4), Renouncing::Member)); assert_eq!(balances(&4), (38, 2)); // 2 is voting bond. assert_eq!(members_ids(), vec![3, 5]); @@ -2707,11 +2719,11 @@ mod tests { #[test] fn can_renounce_candidacy_member_without_runners_bond_is_refunded() { ExtBuilder::default().desired_runners_up(2).build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2719,7 +2731,7 @@ mod tests { assert_eq!(members_ids(), vec![4, 5]); assert!(runners_up_ids().is_empty()); - assert_ok!(Elections::renounce_candidacy(Origin::signed(4), Renouncing::Member)); + assert_ok!(Elections::renounce_candidacy(RuntimeOrigin::signed(4), Renouncing::Member)); assert_eq!(balances(&4), (38, 2)); // 2 is voting bond. // no replacement @@ -2731,15 +2743,15 @@ mod tests { #[test] fn can_renounce_candidacy_runner_up() { ExtBuilder::default().desired_runners_up(2).build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_ok!(vote(Origin::signed(5), vec![4], 50)); - assert_ok!(vote(Origin::signed(4), vec![5], 40)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); - assert_ok!(vote(Origin::signed(2), vec![2], 20)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![4], 50)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![5], 40)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![2], 20)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2747,7 +2759,10 @@ mod tests { assert_eq!(members_ids(), vec![4, 5]); assert_eq!(runners_up_ids(), vec![2, 3]); - assert_ok!(Elections::renounce_candidacy(Origin::signed(3), Renouncing::RunnerUp)); + assert_ok!(Elections::renounce_candidacy( + RuntimeOrigin::signed(3), + Renouncing::RunnerUp + )); assert_eq!(balances(&3), (28, 2)); // 2 is voting bond. assert_eq!(members_ids(), vec![4, 5]); @@ -2758,22 +2773,25 @@ mod tests { #[test] fn runner_up_replacement_works_when_out_of_order() { ExtBuilder::default().desired_runners_up(2).build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_ok!(vote(Origin::signed(2), vec![5], 20)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(5), vec![2], 50)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![5], 20)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![2], 50)); System::set_block_number(5); Elections::on_initialize(System::block_number()); assert_eq!(members_ids(), vec![2, 4]); assert_eq!(runners_up_ids(), vec![5, 3]); - assert_ok!(Elections::renounce_candidacy(Origin::signed(3), Renouncing::RunnerUp)); + assert_ok!(Elections::renounce_candidacy( + RuntimeOrigin::signed(3), + Renouncing::RunnerUp + )); assert_eq!(members_ids(), vec![2, 4]); assert_eq!(runners_up_ids(), vec![5]); }); @@ -2782,11 +2800,14 @@ mod tests { #[test] fn can_renounce_candidacy_candidate() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); assert_eq!(balances(&5), (47, 3)); assert_eq!(candidate_ids(), vec![5]); - assert_ok!(Elections::renounce_candidacy(Origin::signed(5), Renouncing::Candidate(1))); + assert_ok!(Elections::renounce_candidacy( + RuntimeOrigin::signed(5), + Renouncing::Candidate(1) + )); assert_eq!(balances(&5), (50, 0)); assert!(candidate_ids().is_empty()); }) @@ -2796,15 +2817,15 @@ mod tests { fn wrong_renounce_candidacy_should_fail() { ExtBuilder::default().build_and_execute(|| { assert_noop!( - Elections::renounce_candidacy(Origin::signed(5), Renouncing::Candidate(0)), + Elections::renounce_candidacy(RuntimeOrigin::signed(5), Renouncing::Candidate(0)), Error::::InvalidRenouncing, ); assert_noop!( - Elections::renounce_candidacy(Origin::signed(5), Renouncing::Member), + Elections::renounce_candidacy(RuntimeOrigin::signed(5), Renouncing::Member), Error::::InvalidRenouncing, ); assert_noop!( - Elections::renounce_candidacy(Origin::signed(5), Renouncing::RunnerUp), + Elections::renounce_candidacy(RuntimeOrigin::signed(5), Renouncing::RunnerUp), Error::::InvalidRenouncing, ); }) @@ -2813,13 +2834,13 @@ mod tests { #[test] fn non_member_renounce_member_should_fail() { ExtBuilder::default().desired_runners_up(1).build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2828,7 +2849,7 @@ mod tests { assert_eq!(runners_up_ids(), vec![3]); assert_noop!( - Elections::renounce_candidacy(Origin::signed(3), Renouncing::Member), + Elections::renounce_candidacy(RuntimeOrigin::signed(3), Renouncing::Member), Error::::InvalidRenouncing, ); }) @@ -2837,13 +2858,13 @@ mod tests { #[test] fn non_runner_up_renounce_runner_up_should_fail() { ExtBuilder::default().desired_runners_up(1).build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2852,7 +2873,7 @@ mod tests { assert_eq!(runners_up_ids(), vec![3]); assert_noop!( - Elections::renounce_candidacy(Origin::signed(4), Renouncing::RunnerUp), + Elections::renounce_candidacy(RuntimeOrigin::signed(4), Renouncing::RunnerUp), Error::::InvalidRenouncing, ); }) @@ -2861,27 +2882,33 @@ mod tests { #[test] fn wrong_candidate_count_renounce_should_fail() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); assert_noop!( - Elections::renounce_candidacy(Origin::signed(4), Renouncing::Candidate(2)), + Elections::renounce_candidacy(RuntimeOrigin::signed(4), Renouncing::Candidate(2)), Error::::InvalidWitnessData, ); - assert_ok!(Elections::renounce_candidacy(Origin::signed(4), Renouncing::Candidate(3))); + assert_ok!(Elections::renounce_candidacy( + RuntimeOrigin::signed(4), + Renouncing::Candidate(3) + )); }) } #[test] fn renounce_candidacy_count_can_overestimate() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); // while we have only 3 candidates. - assert_ok!(Elections::renounce_candidacy(Origin::signed(4), Renouncing::Candidate(4))); + assert_ok!(Elections::renounce_candidacy( + RuntimeOrigin::signed(4), + Renouncing::Candidate(4) + )); }) } @@ -2891,13 +2918,13 @@ mod tests { .desired_runners_up(2) .desired_members(1) .build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); - assert_ok!(vote(Origin::signed(4), vec![4], 5)); - assert_ok!(vote(Origin::signed(3), vec![3], 15)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 5)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 15)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2905,8 +2932,8 @@ mod tests { assert_eq!(members_ids(), vec![5]); assert_eq!(runners_up_ids(), vec![4, 3]); - assert_ok!(submit_candidacy(Origin::signed(2))); - assert_ok!(vote(Origin::signed(2), vec![2], 10)); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![2], 10)); System::set_block_number(10); Elections::on_initialize(System::block_number()); @@ -2927,13 +2954,13 @@ mod tests { .desired_runners_up(2) .desired_members(1) .build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); - assert_ok!(vote(Origin::signed(2), vec![2], 20)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![2], 20)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2946,8 +2973,8 @@ mod tests { assert_eq!(balances(&2), (15, 5)); // this guy will shift everyone down. - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); System::set_block_number(10); Elections::on_initialize(System::block_number()); @@ -2970,13 +2997,13 @@ mod tests { .desired_runners_up(2) .desired_members(1) .build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); - assert_ok!(vote(Origin::signed(2), vec![2], 20)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![2], 20)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2989,8 +3016,8 @@ mod tests { assert_eq!(balances(&2), (15, 5)); // swap some votes. - assert_ok!(vote(Origin::signed(4), vec![2], 40)); - assert_ok!(vote(Origin::signed(2), vec![4], 20)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![2], 40)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![4], 20)); System::set_block_number(10); Elections::on_initialize(System::block_number()); @@ -3010,13 +3037,13 @@ mod tests { #[test] fn remove_and_replace_member_works() { let setup = || { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); - assert_ok!(vote(Origin::signed(5), vec![5], 50)); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -3037,7 +3064,10 @@ mod tests { // member removed, no replacement found. ExtBuilder::default().desired_runners_up(1).build_and_execute(|| { setup(); - assert_ok!(Elections::renounce_candidacy(Origin::signed(3), Renouncing::RunnerUp)); + assert_ok!(Elections::renounce_candidacy( + RuntimeOrigin::signed(3), + Renouncing::RunnerUp + )); assert_eq!(Elections::remove_and_replace_member(&4, false), Ok(false)); assert_eq!(members_ids(), vec![5]); @@ -3060,15 +3090,15 @@ mod tests { .build_and_execute(|| { assert_eq!(Elections::candidates().len(), 0); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); assert_eq!(Elections::candidates().len(), 3); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); - assert_ok!(vote(Origin::signed(2), vec![2], 20)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![2], 20)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -3086,15 +3116,15 @@ mod tests { .build_and_execute(|| { assert_eq!(Elections::candidates().len(), 0); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); assert_eq!(Elections::candidates().len(), 3); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); - assert_ok!(vote(Origin::signed(2), vec![2], 20)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![2], 20)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -3112,15 +3142,15 @@ mod tests { .build_and_execute(|| { assert_eq!(Elections::candidates().len(), 0); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(submit_candidacy(Origin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); assert_eq!(Elections::candidates().len(), 3); - assert_ok!(vote(Origin::signed(4), vec![4], 40)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); - assert_ok!(vote(Origin::signed(2), vec![2], 20)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![2], 20)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -3135,17 +3165,17 @@ mod tests { #[test] fn dupe_vote_is_moot() { ExtBuilder::default().desired_members(1).build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); - assert_ok!(submit_candidacy(Origin::signed(2))); - assert_ok!(submit_candidacy(Origin::signed(1))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(1))); // all these duplicate votes will not cause 2 to win. - assert_ok!(vote(Origin::signed(1), vec![2, 2, 2, 2], 5)); - assert_ok!(vote(Origin::signed(2), vec![2, 2, 2, 2], 20)); + assert_ok!(vote(RuntimeOrigin::signed(1), vec![2, 2, 2, 2], 5)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![2, 2, 2, 2], 20)); - assert_ok!(vote(Origin::signed(3), vec![3], 30)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -3157,24 +3187,33 @@ mod tests { #[test] fn remove_defunct_voter_works() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(submit_candidacy(Origin::signed(5))); - assert_ok!(submit_candidacy(Origin::signed(4))); - assert_ok!(submit_candidacy(Origin::signed(3))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); + assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); // defunct - assert_ok!(vote(Origin::signed(5), vec![5, 4], 5)); + assert_ok!(vote(RuntimeOrigin::signed(5), vec![5, 4], 5)); // defunct - assert_ok!(vote(Origin::signed(4), vec![4], 5)); + assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 5)); // ok - assert_ok!(vote(Origin::signed(3), vec![3], 5)); + assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 5)); // ok - assert_ok!(vote(Origin::signed(2), vec![3, 4], 5)); - - assert_ok!(Elections::renounce_candidacy(Origin::signed(5), Renouncing::Candidate(3))); - assert_ok!(Elections::renounce_candidacy(Origin::signed(4), Renouncing::Candidate(2))); - assert_ok!(Elections::renounce_candidacy(Origin::signed(3), Renouncing::Candidate(1))); - - assert_ok!(Elections::clean_defunct_voters(Origin::root(), 4, 2)); + assert_ok!(vote(RuntimeOrigin::signed(2), vec![3, 4], 5)); + + assert_ok!(Elections::renounce_candidacy( + RuntimeOrigin::signed(5), + Renouncing::Candidate(3) + )); + assert_ok!(Elections::renounce_candidacy( + RuntimeOrigin::signed(4), + Renouncing::Candidate(2) + )); + assert_ok!(Elections::renounce_candidacy( + RuntimeOrigin::signed(3), + Renouncing::Candidate(1) + )); + + assert_ok!(Elections::clean_defunct_voters(RuntimeOrigin::root(), 4, 2)); }) } } diff --git a/frame/examples/basic/src/lib.rs b/frame/examples/basic/src/lib.rs index caa2d825262db..f754348782cec 100644 --- a/frame/examples/basic/src/lib.rs +++ b/frame/examples/basic/src/lib.rs @@ -655,7 +655,7 @@ pub mod pallet { impl Pallet { // Add public immutables and private mutables. #[allow(dead_code)] - fn accumulate_foo(origin: T::Origin, increase_by: T::Balance) -> DispatchResult { + fn accumulate_foo(origin: T::RuntimeOrigin, increase_by: T::Balance) -> DispatchResult { let _sender = ensure_signed(origin)?; let prev = >::get(); diff --git a/frame/examples/basic/src/tests.rs b/frame/examples/basic/src/tests.rs index 793cb4287f505..db4787eaa0faa 100644 --- a/frame/examples/basic/src/tests.rs +++ b/frame/examples/basic/src/tests.rs @@ -60,7 +60,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = H256; @@ -128,12 +128,12 @@ fn it_works_for_optional_value() { assert_eq!(Example::dummy(), Some(val1)); // Check that accumulate works when we have Some value in Dummy already. - assert_ok!(Example::accumulate_dummy(Origin::signed(1), val2)); + assert_ok!(Example::accumulate_dummy(RuntimeOrigin::signed(1), val2)); assert_eq!(Example::dummy(), Some(val1 + val2)); // Check that accumulate works when we Dummy has None in it. >::on_initialize(2); - assert_ok!(Example::accumulate_dummy(Origin::signed(1), val1)); + assert_ok!(Example::accumulate_dummy(RuntimeOrigin::signed(1), val1)); assert_eq!(Example::dummy(), Some(val1 + val2 + val1)); }); } @@ -142,7 +142,7 @@ fn it_works_for_optional_value() { fn it_works_for_default_value() { new_test_ext().execute_with(|| { assert_eq!(Example::foo(), 24); - assert_ok!(Example::accumulate_foo(Origin::signed(1), 1)); + assert_ok!(Example::accumulate_foo(RuntimeOrigin::signed(1), 1)); assert_eq!(Example::foo(), 25); }); } @@ -151,7 +151,7 @@ fn it_works_for_default_value() { fn set_dummy_works() { new_test_ext().execute_with(|| { let test_val = 133; - assert_ok!(Example::set_dummy(Origin::root(), test_val.into())); + assert_ok!(Example::set_dummy(RuntimeOrigin::root(), test_val.into())); assert_eq!(Example::dummy(), Some(test_val)); }); } diff --git a/frame/examples/offchain-worker/src/tests.rs b/frame/examples/offchain-worker/src/tests.rs index 2c189935ac19d..72c001fd6e6cc 100644 --- a/frame/examples/offchain-worker/src/tests.rs +++ b/frame/examples/offchain-worker/src/tests.rs @@ -60,7 +60,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = u64; @@ -134,10 +134,10 @@ fn it_aggregates_the_price() { sp_io::TestExternalities::default().execute_with(|| { assert_eq!(Example::average_price(), None); - assert_ok!(Example::submit_price(Origin::signed(test_pub()), 27)); + assert_ok!(Example::submit_price(RuntimeOrigin::signed(test_pub()), 27)); assert_eq!(Example::average_price(), Some(27)); - assert_ok!(Example::submit_price(Origin::signed(test_pub()), 43)); + assert_ok!(Example::submit_price(RuntimeOrigin::signed(test_pub()), 43)); assert_eq!(Example::average_price(), Some(35)); }); } diff --git a/frame/examples/parallel/src/tests.rs b/frame/examples/parallel/src/tests.rs index 80c8213fdfb1c..fdef24a39ae36 100644 --- a/frame/examples/parallel/src/tests.rs +++ b/frame/examples/parallel/src/tests.rs @@ -45,7 +45,7 @@ parameter_types! { impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type PalletInfo = PalletInfo; type Index = u64; @@ -76,8 +76,8 @@ fn test_pub(n: u8) -> sp_core::sr25519::Public { sp_core::sr25519::Public::from_raw([n; 32]) } -fn test_origin(n: u8) -> Origin { - Origin::signed(test_pub(n)) +fn test_origin(n: u8) -> RuntimeOrigin { + RuntimeOrigin::signed(test_pub(n)) } #[test] @@ -103,7 +103,7 @@ fn it_can_enlist() { }, ]; - Example::enlist_participants(Origin::signed(test_pub(1)), participants) + Example::enlist_participants(RuntimeOrigin::signed(test_pub(1)), participants) .expect("Failed to enlist"); assert_eq!(Example::participants().len(), 2); diff --git a/frame/executive/Cargo.toml b/frame/executive/Cargo.toml index 1ae22ddbb0260..cd5c793ee2ee0 100644 --- a/frame/executive/Cargo.toml +++ b/frame/executive/Cargo.toml @@ -27,7 +27,7 @@ sp-std = { version = "4.0.0", default-features = false, path = "../../primitives sp-tracing = { version = "5.0.0", default-features = false, path = "../../primitives/tracing" } [dev-dependencies] -hex-literal = "0.3.4" +array-bytes = "4.1" pallet-balances = { version = "4.0.0-dev", path = "../balances" } pallet-transaction-payment = { version = "4.0.0-dev", path = "../transaction-payment" } sp-core = { version = "6.0.0", path = "../../primitives/core" } diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index 88cefb17c2895..a41c82da5757c 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -138,7 +138,7 @@ use sp_std::{marker::PhantomData, prelude::*}; pub type CheckedOf = >::Checked; pub type CallOf = as Applyable>::Call; -pub type OriginOf = as Dispatchable>::Origin; +pub type OriginOf = as Dispatchable>::RuntimeOrigin; /// Main entry point for certain runtime actions as e.g. `execute_block`. /// @@ -287,15 +287,7 @@ where /// /// This should only be used for testing. pub fn try_runtime_upgrade() -> Result { - // ensure both `pre_upgrade` and `post_upgrade` won't change the storage root - let state = { - let _guard = frame_support::StorageNoopGuard::default(); - <(COnRuntimeUpgrade, AllPalletsWithSystem) as OnRuntimeUpgrade>::pre_upgrade().unwrap() - }; let weight = Self::execute_on_runtime_upgrade(); - let _guard = frame_support::StorageNoopGuard::default(); - <(COnRuntimeUpgrade, AllPalletsWithSystem) as OnRuntimeUpgrade>::post_upgrade(state) - .unwrap(); Ok(weight) } } @@ -602,8 +594,6 @@ where mod tests { use super::*; - use hex_literal::hex; - use sp_core::H256; use sp_runtime::{ generic::{DigestItem, Era}, @@ -789,7 +779,7 @@ mod tests { type BlockWeights = BlockWeights; type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type RuntimeCall = RuntimeCall; type BlockNumber = u64; @@ -947,11 +937,15 @@ mod tests { fn block_import_works() { block_import_works_inner( new_test_ext_v0(1), - hex!("1039e1a4bd0cf5deefe65f313577e70169c41c7773d6acf31ca8d671397559f5").into(), + array_bytes::hex_n_into_unchecked( + "1039e1a4bd0cf5deefe65f313577e70169c41c7773d6acf31ca8d671397559f5", + ), ); block_import_works_inner( new_test_ext(1), - hex!("75e7d8f360d375bbe91bcf8019c01ab6362448b4a89e3b329717eb9d910340e5").into(), + array_bytes::hex_n_into_unchecked( + "75e7d8f360d375bbe91bcf8019c01ab6362448b4a89e3b329717eb9d910340e5", + ), ); } fn block_import_works_inner(mut ext: sp_io::TestExternalities, state_root: H256) { @@ -961,10 +955,9 @@ mod tests { parent_hash: [69u8; 32].into(), number: 1, state_root, - extrinsics_root: hex!( - "03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314" - ) - .into(), + extrinsics_root: array_bytes::hex_n_into_unchecked( + "03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314", + ), digest: Digest { logs: vec![] }, }, extrinsics: vec![], @@ -981,10 +974,9 @@ mod tests { parent_hash: [69u8; 32].into(), number: 1, state_root: [0u8; 32].into(), - extrinsics_root: hex!( - "03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314" - ) - .into(), + extrinsics_root: array_bytes::hex_n_into_unchecked( + "03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314", + ), digest: Digest { logs: vec![] }, }, extrinsics: vec![], @@ -1000,10 +992,9 @@ mod tests { header: Header { parent_hash: [69u8; 32].into(), number: 1, - state_root: hex!( - "75e7d8f360d375bbe91bcf8019c01ab6362448b4a89e3b329717eb9d910340e5" - ) - .into(), + state_root: array_bytes::hex_n_into_unchecked( + "75e7d8f360d375bbe91bcf8019c01ab6362448b4a89e3b329717eb9d910340e5", + ), extrinsics_root: [0u8; 32].into(), digest: Digest { logs: vec![] }, }, diff --git a/frame/fast-unstake/Cargo.toml b/frame/fast-unstake/Cargo.toml new file mode 100644 index 0000000000000..1fa118dba4a8d --- /dev/null +++ b/frame/fast-unstake/Cargo.toml @@ -0,0 +1,70 @@ +[package] +name = "pallet-fast-unstake" +version = "4.0.0-dev" +authors = ["Parity Technologies "] +edition = "2021" +license = "Unlicense" +homepage = "https://substrate.io" +repository = "https://github.com/paritytech/substrate/" +description = "FRAME fast unstake pallet" +readme = "README.md" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } +log = { version = "0.4.17", default-features = false } +scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } + +frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } +frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } + +sp-io = { version = "6.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "6.0.0", default-features = false, path = "../../primitives/runtime" } +sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } +sp-staking = { default-features = false, path = "../../primitives/staking" } + +pallet-balances = { default-features = false, path = "../balances" } +pallet-timestamp = { default-features = false, path = "../timestamp" } +pallet-staking = { default-features = false, path = "../staking" } +pallet-nomination-pools = { default-features = false, path = "../nomination-pools" } +frame-election-provider-support = { default-features = false, path = "../election-provider-support" } + +frame-benchmarking = { version = "4.0.0-dev", default-features = false, optional = true, path = "../benchmarking" } + +[dev-dependencies] +pallet-staking-reward-curve = { version = "4.0.0-dev", path = "../staking/reward-curve" } +sp-core = { version = "6.0.0", default-features = false, path = "../../primitives/core" } +substrate-test-utils = { version = "4.0.0-dev", path = "../../test-utils" } +sp-tracing = { version = "5.0.0", path = "../../primitives/tracing" } + +[features] +default = ["std"] +std = [ + "codec/std", + "log/std", + "scale-info/std", + + "frame-support/std", + "frame-system/std", + + "sp-io/std", + "sp-staking/std", + "sp-runtime/std", + "sp-std/std", + + "pallet-staking/std", + "pallet-nomination-pools/std", + "pallet-balances/std", + "pallet-timestamp/std", + "frame-election-provider-support/std", + + "frame-benchmarking/std", +] +runtime-benchmarks = [ + "frame-benchmarking/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-staking/runtime-benchmarks", +] +try-runtime = ["frame-support/try-runtime"] diff --git a/frame/fast-unstake/src/benchmarking.rs b/frame/fast-unstake/src/benchmarking.rs new file mode 100644 index 0000000000000..68a3da0d40af3 --- /dev/null +++ b/frame/fast-unstake/src/benchmarking.rs @@ -0,0 +1,228 @@ +// This file is part of Substrate. + +// Copyright (C) 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. + +//! Benchmarking for pallet-fast-unstake. + +#![cfg(feature = "runtime-benchmarks")] + +use crate::{types::*, Pallet as FastUnstake, *}; +use frame_benchmarking::{benchmarks, whitelist_account}; +use frame_support::{ + assert_ok, + traits::{Currency, EnsureOrigin, Get, Hooks}, +}; +use frame_system::RawOrigin; +use pallet_nomination_pools::{Pallet as Pools, PoolId}; +use pallet_staking::Pallet as Staking; +use sp_runtime::traits::{StaticLookup, Zero}; +use sp_staking::EraIndex; +use sp_std::prelude::*; + +const USER_SEED: u32 = 0; +const DEFAULT_BACKER_PER_VALIDATOR: u32 = 128; +const MAX_VALIDATORS: u32 = 128; + +type CurrencyOf = ::Currency; + +fn l( + who: T::AccountId, +) -> <::Lookup as StaticLookup>::Source { + T::Lookup::unlookup(who) +} + +fn create_unexposed_nominator() -> T::AccountId { + let account = frame_benchmarking::account::("nominator_42", 0, USER_SEED); + fund_and_bond_account::(&account); + account +} + +fn fund_and_bond_account(account: &T::AccountId) { + let stake = CurrencyOf::::minimum_balance() * 100u32.into(); + CurrencyOf::::make_free_balance_be(&account, stake * 10u32.into()); + + let account_lookup = l::(account.clone()); + // bond and nominate ourselves, this will guarantee that we are not backing anyone. + assert_ok!(Staking::::bond( + RawOrigin::Signed(account.clone()).into(), + account_lookup.clone(), + stake, + pallet_staking::RewardDestination::Controller, + )); + assert_ok!(Staking::::nominate( + RawOrigin::Signed(account.clone()).into(), + vec![account_lookup] + )); +} + +pub(crate) fn fast_unstake_events() -> Vec> { + frame_system::Pallet::::events() + .into_iter() + .map(|r| r.event) + .filter_map(|e| ::RuntimeEvent::from(e).try_into().ok()) + .collect::>() +} + +fn setup_pool() -> PoolId { + let depositor = frame_benchmarking::account::("depositor_42", 0, USER_SEED); + let depositor_lookup = l::(depositor.clone()); + + let stake = Pools::::depositor_min_bond(); + CurrencyOf::::make_free_balance_be(&depositor, stake * 10u32.into()); + + Pools::::create( + RawOrigin::Signed(depositor.clone()).into(), + stake, + depositor_lookup.clone(), + depositor_lookup.clone(), + depositor_lookup, + ) + .unwrap(); + + pallet_nomination_pools::LastPoolId::::get() +} + +fn setup_staking(v: u32, until: EraIndex) { + let ed = CurrencyOf::::minimum_balance(); + + log!(debug, "registering {} validators and {} eras.", v, until); + + // our validators don't actually need to registered in staking -- just generate `v` random + // accounts. + let validators = (0..v) + .map(|x| frame_benchmarking::account::("validator", x, USER_SEED)) + .collect::>(); + + for era in 0..=until { + let others = (0..DEFAULT_BACKER_PER_VALIDATOR) + .map(|s| { + let who = frame_benchmarking::account::("nominator", era, s); + let value = ed; + pallet_staking::IndividualExposure { who, value } + }) + .collect::>(); + let exposure = + pallet_staking::Exposure { total: Default::default(), own: Default::default(), others }; + validators.iter().for_each(|v| { + Staking::::add_era_stakers(era, v.clone(), exposure.clone()); + }); + } +} + +fn on_idle_full_block() { + let remaining_weight = ::BlockWeights::get().max_block; + FastUnstake::::on_idle(Zero::zero(), remaining_weight); +} + +benchmarks! { + // on_idle, we we don't check anyone, but fully unbond and move them to another pool. + on_idle_unstake { + let who = create_unexposed_nominator::(); + let pool_id = setup_pool::(); + assert_ok!(FastUnstake::::register_fast_unstake( + RawOrigin::Signed(who.clone()).into(), + Some(pool_id) + )); + ErasToCheckPerBlock::::put(1); + + // run on_idle once. This will check era 0. + assert_eq!(Head::::get(), None); + on_idle_full_block::(); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { stash: who.clone(), checked: vec![0].try_into().unwrap(), maybe_pool_id: Some(pool_id) }) + ); + } + : { + on_idle_full_block::(); + } + verify { + assert!(matches!( + fast_unstake_events::().last(), + Some(Event::Unstaked { .. }) + )); + } + + // on_idle, when we check some number of eras, + on_idle_check { + // number of eras multiplied by validators in that era. + let x in (::BondingDuration::get() * 1) .. (::BondingDuration::get() * MAX_VALIDATORS); + + let v = x / ::BondingDuration::get(); + let u = ::BondingDuration::get(); + + ErasToCheckPerBlock::::put(u); + pallet_staking::CurrentEra::::put(u); + + // setup staking with v validators and u eras of data (0..=u) + setup_staking::(v, u); + let who = create_unexposed_nominator::(); + assert_ok!(FastUnstake::::register_fast_unstake( + RawOrigin::Signed(who.clone()).into(), + None, + )); + + // no one is queued thus far. + assert_eq!(Head::::get(), None); + } + : { + on_idle_full_block::(); + } + verify { + let checked: frame_support::BoundedVec<_, _> = (1..=u).rev().collect::>().try_into().unwrap(); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { stash: who.clone(), checked, maybe_pool_id: None }) + ); + assert!(matches!( + fast_unstake_events::().last(), + Some(Event::Checking { .. }) + )); + } + + register_fast_unstake { + let who = create_unexposed_nominator::(); + whitelist_account!(who); + assert_eq!(Queue::::count(), 0); + + } + :_(RawOrigin::Signed(who.clone()), None) + verify { + assert_eq!(Queue::::count(), 1); + } + + deregister { + let who = create_unexposed_nominator::(); + assert_ok!(FastUnstake::::register_fast_unstake( + RawOrigin::Signed(who.clone()).into(), + None + )); + assert_eq!(Queue::::count(), 1); + whitelist_account!(who); + } + :_(RawOrigin::Signed(who.clone())) + verify { + assert_eq!(Queue::::count(), 0); + } + + control { + let origin = ::ControlOrigin::successful_origin(); + } + : _(origin, 128) + verify {} + + impl_benchmark_test_suite!(Pallet, crate::mock::ExtBuilder::default().build(), crate::mock::Runtime) +} diff --git a/frame/fast-unstake/src/lib.rs b/frame/fast-unstake/src/lib.rs new file mode 100644 index 0000000000000..51416808f48c8 --- /dev/null +++ b/frame/fast-unstake/src/lib.rs @@ -0,0 +1,505 @@ +// This file is part of Substrate. + +// Copyright (C) 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. + +//! A pallet that's designed to JUST do the following: +//! +//! If a nominator is not exposed in any `ErasStakers` (i.e. "has not actively backed any +//! validators in the last `BondingDuration` days"), then they can register themselves in this +//! pallet, unstake faster than having to wait an entire bonding duration, and potentially move +//! into a nomination pool. +//! +//! Appearing in the exposure of a validator means being exposed equal to that validator from the +//! point of view of the staking system. This usually means earning rewards with the validator, and +//! also being at the risk of slashing with the validator. This is equivalent to the "Active +//! Nominator" role explained in the +//! [February Staking Update](https://polkadot.network/blog/staking-update-february-2022/). +//! +//! This pallet works off the basis of `on_idle`, meaning that it provides no guarantee about when +//! it will succeed, if at all. Moreover, the queue implementation is unordered. In case of +//! congestion, no FIFO ordering is provided. +//! +//! Stakers who are certain about NOT being exposed can register themselves with +//! [`Call::register_fast_unstake`]. This will chill, and fully unbond the staker, and place them in +//! the queue to be checked. +//! +//! Once queued, but not being actively processed, stakers can withdraw their request via +//! [`Call::deregister`]. +//! +//! Once queued, a staker wishing to unbond can perform no further action in pallet-staking. This is +//! to prevent them from accidentally exposing themselves behind a validator etc. +//! +//! Once processed, if successful, no additional fee for the checking process is taken, and the +//! staker is instantly unbonded. Optionally, if they have asked to join a pool, their *entire* +//! stake is joined into their pool of choice. +//! +//! If unsuccessful, meaning that the staker was exposed sometime in the last `BondingDuration` eras +//! they will end up being slashed for the amount of wasted work they have inflicted on the chian. + +#![cfg_attr(not(feature = "std"), no_std)] + +pub use pallet::*; + +#[cfg(test)] +mod mock; + +#[cfg(test)] +mod tests; + +// NOTE: enable benchmarking in tests as well. +#[cfg(feature = "runtime-benchmarks")] +mod benchmarking; +mod types; +pub mod weights; + +pub const LOG_TARGET: &'static str = "runtime::fast-unstake"; + +// syntactic sugar for logging. +#[macro_export] +macro_rules! log { + ($level:tt, $patter:expr $(, $values:expr)* $(,)?) => { + log::$level!( + target: crate::LOG_TARGET, + concat!("[{:?}] 💨 ", $patter), >::block_number() $(, $values)* + ) + }; +} + +#[frame_support::pallet] +pub mod pallet { + use super::*; + use crate::types::*; + use frame_election_provider_support::ElectionProvider; + use frame_support::pallet_prelude::*; + use frame_system::{pallet_prelude::*, RawOrigin}; + use pallet_nomination_pools::PoolId; + use pallet_staking::Pallet as Staking; + use sp_runtime::{ + traits::{Saturating, Zero}, + DispatchResult, + }; + use sp_staking::EraIndex; + use sp_std::{prelude::*, vec::Vec}; + use weights::WeightInfo; + + #[derive(scale_info::TypeInfo, codec::Encode, codec::Decode, codec::MaxEncodedLen)] + #[codec(mel_bound(T: Config))] + #[scale_info(skip_type_params(T))] + pub struct MaxChecking(sp_std::marker::PhantomData); + impl frame_support::traits::Get for MaxChecking { + fn get() -> u32 { + ::BondingDuration::get() + 1 + } + } + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: + frame_system::Config + + pallet_staking::Config< + CurrencyBalance = ::CurrencyBalance, + > + pallet_nomination_pools::Config + { + /// The overarching event type. + type RuntimeEvent: From> + + IsType<::RuntimeEvent> + + TryInto>; + + /// The amount of balance slashed per each era that was wastefully checked. + /// + /// A reasonable value could be `runtime_weight_to_fee(weight_per_era_check)`. + type SlashPerEra: Get>; + + /// The origin that can control this pallet. + type ControlOrigin: frame_support::traits::EnsureOrigin; + + /// The weight information of this pallet. + type WeightInfo: WeightInfo; + } + + /// The current "head of the queue" being unstaked. + #[pallet::storage] + pub type Head = + StorageValue<_, UnstakeRequest>, OptionQuery>; + + /// The map of all accounts wishing to be unstaked. + /// + /// Points the `AccountId` wishing to unstake to the optional `PoolId` they wish to join + /// thereafter. + #[pallet::storage] + pub type Queue = CountedStorageMap<_, Twox64Concat, T::AccountId, Option>; + + /// Number of eras to check per block. + /// + /// If set to 0, this pallet does absolutely nothing. + /// + /// Based on the amount of weight available at `on_idle`, up to this many eras of a single + /// nominator might be checked. + #[pallet::storage] + pub type ErasToCheckPerBlock = StorageValue<_, u32, ValueQuery>; + + /// The events of this pallet. + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + /// A staker was unstaked. + Unstaked { stash: T::AccountId, maybe_pool_id: Option, result: DispatchResult }, + /// A staker was slashed for requesting fast-unstake whilst being exposed. + Slashed { stash: T::AccountId, amount: BalanceOf }, + /// A staker was partially checked for the given eras, but the process did not finish. + Checking { stash: T::AccountId, eras: Vec }, + /// Some internal error happened while migrating stash. They are removed as head as a + /// consequence. + Errored { stash: T::AccountId }, + /// An internal error happened. Operations will be paused now. + InternalError, + } + + #[pallet::error] + #[cfg_attr(test, derive(PartialEq))] + pub enum Error { + /// The provided Controller account was not found. + /// + /// This means that the given account is not bonded. + NotController, + /// The bonded account has already been queued. + AlreadyQueued, + /// The bonded account has active unlocking chunks. + NotFullyBonded, + /// The provided un-staker is not in the `Queue`. + NotQueued, + /// The provided un-staker is already in Head, and cannot deregister. + AlreadyHead, + } + + #[pallet::hooks] + impl Hooks for Pallet { + fn on_idle(_: T::BlockNumber, remaining_weight: Weight) -> Weight { + if remaining_weight.any_lt(T::DbWeight::get().reads(2)) { + return Weight::from_ref_time(0) + } + + Self::do_on_idle(remaining_weight) + } + } + + #[pallet::call] + impl Pallet { + /// Register oneself for fast-unstake. + /// + /// The dispatch origin of this call must be signed by the controller account, similar to + /// `staking::unbond`. + /// + /// The stash associated with the origin must have no ongoing unlocking chunks. If + /// successful, this will fully unbond and chill the stash. Then, it will enqueue the stash + /// to be checked in further blocks. + /// + /// If by the time this is called, the stash is actually eligible for fast-unstake, then + /// they are guaranteed to remain eligible, because the call will chill them as well. + /// + /// If the check works, the entire staking data is removed, i.e. the stash is fully + /// unstaked, and they potentially join a pool with their entire bonded stake. + /// + /// If the check fails, the stash remains chilled and waiting for being unbonded as in with + /// the normal staking system, but they lose part of their unbonding chunks due to consuming + /// the chain's resources. + #[pallet::weight(::WeightInfo::register_fast_unstake())] + pub fn register_fast_unstake( + origin: OriginFor, + maybe_pool_id: Option, + ) -> DispatchResult { + let ctrl = ensure_signed(origin)?; + + let ledger = + pallet_staking::Ledger::::get(&ctrl).ok_or(Error::::NotController)?; + ensure!(!Queue::::contains_key(&ledger.stash), Error::::AlreadyQueued); + ensure!( + Head::::get().map_or(true, |UnstakeRequest { stash, .. }| stash != ledger.stash), + Error::::AlreadyHead + ); + // second part of the && is defensive. + ensure!( + ledger.active == ledger.total && ledger.unlocking.is_empty(), + Error::::NotFullyBonded + ); + + // chill and fully unstake. + Staking::::chill(RawOrigin::Signed(ctrl.clone()).into())?; + Staking::::unbond(RawOrigin::Signed(ctrl).into(), ledger.total)?; + + // enqueue them. + Queue::::insert(ledger.stash, maybe_pool_id); + Ok(()) + } + + /// Deregister oneself from the fast-unstake (also cancels joining the pool if that was + /// supplied on `register_fast_unstake` . + /// + /// This is useful if one is registered, they are still waiting, and they change their mind. + /// + /// Note that the associated stash is still fully unbonded and chilled as a consequence of + /// calling `register_fast_unstake`. This should probably be followed by a call to + /// `Staking::rebond`. + #[pallet::weight(::WeightInfo::deregister())] + pub fn deregister(origin: OriginFor) -> DispatchResult { + let ctrl = ensure_signed(origin)?; + let stash = pallet_staking::Ledger::::get(&ctrl) + .map(|l| l.stash) + .ok_or(Error::::NotController)?; + ensure!(Queue::::contains_key(&stash), Error::::NotQueued); + ensure!( + Head::::get().map_or(true, |UnstakeRequest { stash, .. }| stash != stash), + Error::::AlreadyHead + ); + Queue::::remove(stash); + Ok(()) + } + + /// Control the operation of this pallet. + /// + /// Dispatch origin must be signed by the [`Config::ControlOrigin`]. + #[pallet::weight(::WeightInfo::control())] + pub fn control(origin: OriginFor, unchecked_eras_to_check: EraIndex) -> DispatchResult { + let _ = T::ControlOrigin::ensure_origin(origin)?; + ErasToCheckPerBlock::::put(unchecked_eras_to_check); + Ok(()) + } + } + + impl Pallet { + /// process up to `remaining_weight`. + /// + /// Returns the actual weight consumed. + /// + /// Written for readability in mind, not efficiency. For example: + /// + /// 1. We assume this is only ever called once per `on_idle`. This is because we know that + /// in all use cases, even a single nominator cannot be unbonded in a single call. Multiple + /// calls to this function are thus not needed. + /// + /// 2. We will only mark a staker as unstaked if at the beginning of a check cycle, they are + /// found out to have no eras to check. At the end of a check cycle, even if they are fully + /// checked, we don't finish the process. + pub(crate) fn do_on_idle(remaining_weight: Weight) -> Weight { + let mut eras_to_check_per_block = ErasToCheckPerBlock::::get(); + if eras_to_check_per_block.is_zero() { + return T::DbWeight::get().reads(1) + } + + // NOTE: here we're assuming that the number of validators has only ever increased, + // meaning that the number of exposures to check is either this per era, or less. + let validator_count = pallet_staking::ValidatorCount::::get(); + + // determine the number of eras to check. This is based on both `ErasToCheckPerBlock` + // and `remaining_weight` passed on to us from the runtime executive. + let max_weight = |v, u| { + ::WeightInfo::on_idle_check(v * u) + .max(::WeightInfo::on_idle_unstake()) + }; + while max_weight(validator_count, eras_to_check_per_block).any_gt(remaining_weight) { + eras_to_check_per_block.saturating_dec(); + if eras_to_check_per_block.is_zero() { + log!(debug, "early existing because eras_to_check_per_block is zero"); + return T::DbWeight::get().reads(2) + } + } + + if ::ElectionProvider::ongoing() { + // NOTE: we assume `ongoing` does not consume any weight. + // there is an ongoing election -- we better not do anything. Imagine someone is not + // exposed anywhere in the last era, and the snapshot for the election is already + // taken. In this time period, we don't want to accidentally unstake them. + return T::DbWeight::get().reads(2) + } + + let UnstakeRequest { stash, mut checked, maybe_pool_id } = match Head::::take() + .or_else(|| { + // NOTE: there is no order guarantees in `Queue`. + Queue::::drain() + .map(|(stash, maybe_pool_id)| UnstakeRequest { + stash, + maybe_pool_id, + checked: Default::default(), + }) + .next() + }) { + None => { + // There's no `Head` and nothing in the `Queue`, nothing to do here. + return T::DbWeight::get().reads(4) + }, + Some(head) => head, + }; + + log!( + debug, + "checking {:?}, eras_to_check_per_block = {:?}, remaining_weight = {:?}", + stash, + eras_to_check_per_block, + remaining_weight + ); + + // the range that we're allowed to check in this round. + let current_era = pallet_staking::CurrentEra::::get().unwrap_or_default(); + let bonding_duration = ::BondingDuration::get(); + // prune all the old eras that we don't care about. This will help us keep the bound + // of `checked`. + checked.retain(|e| *e >= current_era.saturating_sub(bonding_duration)); + let unchecked_eras_to_check = { + // get the last available `bonding_duration` eras up to current era in reverse + // order. + let total_check_range = (current_era.saturating_sub(bonding_duration)..= + current_era) + .rev() + .collect::>(); + debug_assert!( + total_check_range.len() <= (bonding_duration + 1) as usize, + "{:?}", + total_check_range + ); + + // remove eras that have already been checked, take a maximum of + // eras_to_check_per_block. + total_check_range + .into_iter() + .filter(|e| !checked.contains(e)) + .take(eras_to_check_per_block as usize) + .collect::>() + }; + + log!( + debug, + "{} eras to check: {:?}", + unchecked_eras_to_check.len(), + unchecked_eras_to_check + ); + + if unchecked_eras_to_check.is_empty() { + // `stash` is not exposed in any era now -- we can let go of them now. + let num_slashing_spans = Staking::::slashing_spans(&stash).iter().count() as u32; + + let ctrl = match pallet_staking::Bonded::::get(&stash) { + Some(ctrl) => ctrl, + None => { + Self::deposit_event(Event::::Errored { stash }); + return ::WeightInfo::on_idle_unstake() + }, + }; + + let ledger = match pallet_staking::Ledger::::get(ctrl) { + Some(ledger) => ledger, + None => { + Self::deposit_event(Event::::Errored { stash }); + return ::WeightInfo::on_idle_unstake() + }, + }; + + let unstake_result = pallet_staking::Pallet::::force_unstake( + RawOrigin::Root.into(), + stash.clone(), + num_slashing_spans, + ); + + let pool_stake_result = if let Some(pool_id) = maybe_pool_id { + pallet_nomination_pools::Pallet::::join( + RawOrigin::Signed(stash.clone()).into(), + ledger.total, + pool_id, + ) + } else { + Ok(()) + }; + + let result = unstake_result.and(pool_stake_result); + log!( + info, + "unstaked {:?}, maybe_pool {:?}, outcome: {:?}", + stash, + maybe_pool_id, + result + ); + + Self::deposit_event(Event::::Unstaked { stash, maybe_pool_id, result }); + ::WeightInfo::on_idle_unstake() + } else { + // eras remaining to be checked. + let mut eras_checked = 0u32; + let is_exposed = unchecked_eras_to_check.iter().any(|e| { + eras_checked.saturating_inc(); + Self::is_exposed_in_era(&stash, e) + }); + + log!( + debug, + "checked {:?} eras, exposed? {}, (v: {:?}, u: {:?})", + eras_checked, + is_exposed, + validator_count, + unchecked_eras_to_check.len() + ); + + // NOTE: you can be extremely unlucky and get slashed here: You are not exposed in + // the last 28 eras, have registered yourself to be unstaked, midway being checked, + // you are exposed. + if is_exposed { + let amount = T::SlashPerEra::get() + .saturating_mul(eras_checked.saturating_add(checked.len() as u32).into()); + pallet_staking::slashing::do_slash::( + &stash, + amount, + &mut Default::default(), + &mut Default::default(), + current_era, + ); + log!(info, "slashed {:?} by {:?}", stash, amount); + Self::deposit_event(Event::::Slashed { stash, amount }); + } else { + // Not exposed in these eras. + match checked.try_extend(unchecked_eras_to_check.clone().into_iter()) { + Ok(_) => { + Head::::put(UnstakeRequest { + stash: stash.clone(), + checked, + maybe_pool_id, + }); + Self::deposit_event(Event::::Checking { + stash, + eras: unchecked_eras_to_check, + }); + }, + Err(_) => { + // don't put the head back in -- there is an internal error in the + // pallet. + frame_support::defensive!("`checked is pruned via retain above`"); + ErasToCheckPerBlock::::put(0); + Self::deposit_event(Event::::InternalError); + }, + } + } + + ::WeightInfo::on_idle_check(validator_count * eras_checked) + } + } + + /// Checks whether an account `staker` has been exposed in an era. + fn is_exposed_in_era(staker: &T::AccountId, era: &EraIndex) -> bool { + pallet_staking::ErasStakers::::iter_prefix(era).any(|(validator, exposures)| { + validator == *staker || exposures.others.iter().any(|i| i.who == *staker) + }) + } + } +} diff --git a/frame/fast-unstake/src/mock.rs b/frame/fast-unstake/src/mock.rs new file mode 100644 index 0000000000000..b9cf16e18e8d1 --- /dev/null +++ b/frame/fast-unstake/src/mock.rs @@ -0,0 +1,387 @@ +// This file is part of Substrate. + +// Copyright (C) 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 crate::{self as fast_unstake}; +use frame_support::{ + assert_ok, + pallet_prelude::*, + parameter_types, + traits::{ConstU64, ConstU8, Currency}, + weights::constants::WEIGHT_PER_SECOND, + PalletId, +}; +use sp_runtime::{ + traits::{Convert, IdentityLookup}, + FixedU128, +}; + +use frame_system::RawOrigin; +use pallet_staking::{Exposure, IndividualExposure, StakerStatus}; +use sp_std::prelude::*; + +pub type AccountId = u128; +pub type AccountIndex = u32; +pub type BlockNumber = u64; +pub type Balance = u128; +pub type T = Runtime; + +parameter_types! { + pub BlockWeights: frame_system::limits::BlockWeights = + frame_system::limits::BlockWeights::simple_max(2u64 * WEIGHT_PER_SECOND); +} + +impl frame_system::Config for Runtime { + type BaseCallFilter = frame_support::traits::Everything; + type BlockWeights = BlockWeights; + type BlockLength = (); + 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 RuntimeEvent = RuntimeEvent; + type BlockHashCount = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; +} + +impl pallet_timestamp::Config for Runtime { + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = ConstU64<5>; + type WeightInfo = (); +} + +parameter_types! { + pub static ExistentialDeposit: Balance = 1; +} + +impl pallet_balances::Config for Runtime { + type MaxLocks = ConstU32<128>; + type MaxReserves = (); + type ReserveIdentifier = [u8; 8]; + type Balance = Balance; + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = (); +} + +pallet_staking_reward_curve::build! { + const I_NPOS: sp_runtime::curve::PiecewiseLinear<'static> = curve!( + min_inflation: 0_025_000, + max_inflation: 0_100_000, + ideal_stake: 0_500_000, + falloff: 0_050_000, + max_piece_count: 40, + test_precision: 0_005_000, + ); +} + +parameter_types! { + pub const RewardCurve: &'static sp_runtime::curve::PiecewiseLinear<'static> = &I_NPOS; + pub static BondingDuration: u32 = 3; + pub static CurrentEra: u32 = 0; + pub static Ongoing: bool = false; +} + +pub struct MockElection; +impl frame_election_provider_support::ElectionProvider for MockElection { + type AccountId = AccountId; + type BlockNumber = BlockNumber; + type DataProvider = Staking; + type Error = (); + + fn ongoing() -> bool { + Ongoing::get() + } + + fn elect() -> Result, Self::Error> { + Err(()) + } +} + +impl pallet_staking::Config for Runtime { + type MaxNominations = ConstU32<16>; + type Currency = Balances; + type CurrencyBalance = Balance; + type UnixTime = pallet_timestamp::Pallet; + type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; + type RewardRemainder = (); + type RuntimeEvent = RuntimeEvent; + type Slash = (); + type Reward = (); + type SessionsPerEra = (); + type SlashDeferDuration = (); + type SlashCancelOrigin = frame_system::EnsureRoot; + type BondingDuration = BondingDuration; + type SessionInterface = (); + type EraPayout = pallet_staking::ConvertCurve; + type NextNewSession = (); + type HistoryDepth = ConstU32<84>; + type MaxNominatorRewardedPerValidator = ConstU32<64>; + type OffendingValidatorsThreshold = (); + type ElectionProvider = MockElection; + type GenesisElectionProvider = Self::ElectionProvider; + type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; + type TargetList = pallet_staking::UseValidatorsMap; + type MaxUnlockingChunks = ConstU32<32>; + type OnStakerSlash = Pools; + type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; + type WeightInfo = (); +} + +pub struct BalanceToU256; +impl Convert for BalanceToU256 { + fn convert(n: Balance) -> sp_core::U256 { + n.into() + } +} + +pub struct U256ToBalance; +impl Convert for U256ToBalance { + fn convert(n: sp_core::U256) -> Balance { + n.try_into().unwrap() + } +} + +parameter_types! { + pub const PostUnbondingPoolsWindow: u32 = 10; + pub const PoolsPalletId: PalletId = PalletId(*b"py/nopls"); + pub static MaxMetadataLen: u32 = 10; + pub static CheckLevel: u8 = 255; +} + +impl pallet_nomination_pools::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type WeightInfo = (); + type Currency = Balances; + type CurrencyBalance = Balance; + type RewardCounter = FixedU128; + type BalanceToU256 = BalanceToU256; + type U256ToBalance = U256ToBalance; + type StakingInterface = Staking; + type PostUnbondingPoolsWindow = PostUnbondingPoolsWindow; + type MaxMetadataLen = MaxMetadataLen; + type MaxUnbonding = ConstU32<8>; + type MaxPointsToBalance = ConstU8<10>; + type PalletId = PoolsPalletId; +} + +parameter_types! { + pub static SlashPerEra: u32 = 100; +} + +impl fast_unstake::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type SlashPerEra = SlashPerEra; + type ControlOrigin = frame_system::EnsureRoot; + type WeightInfo = (); +} + +type Block = frame_system::mocking::MockBlock; +type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +frame_support::construct_runtime!( + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic + { + System: frame_system, + Timestamp: pallet_timestamp, + Balances: pallet_balances, + Staking: pallet_staking, + Pools: pallet_nomination_pools, + FastUnstake: fast_unstake, + } +); + +parameter_types! { + static FastUnstakeEvents: u32 = 0; +} + +pub(crate) fn fast_unstake_events_since_last_call() -> Vec> { + let events = System::events() + .into_iter() + .map(|r| r.event) + .filter_map(|e| if let RuntimeEvent::FastUnstake(inner) = e { Some(inner) } else { None }) + .collect::>(); + let already_seen = FastUnstakeEvents::get(); + FastUnstakeEvents::set(events.len() as u32); + events.into_iter().skip(already_seen as usize).collect() +} + +pub struct ExtBuilder { + exposed_nominators: Vec<(AccountId, AccountId, Balance)>, +} + +impl Default for ExtBuilder { + fn default() -> Self { + Self { + exposed_nominators: vec![ + (1, 2, 100), + (3, 4, 100), + (5, 6, 100), + (7, 8, 100), + (9, 10, 100), + ], + } + } +} + +pub(crate) const VALIDATORS_PER_ERA: AccountId = 32; +pub(crate) const VALIDATOR_PREFIX: AccountId = 100; +pub(crate) const NOMINATORS_PER_VALIDATOR_PER_ERA: AccountId = 4; +pub(crate) const NOMINATOR_PREFIX: AccountId = 1000; + +impl ExtBuilder { + pub(crate) fn register_stakers_for_era(era: u32) { + // validators are prefixed with 100 and nominators with 1000 to prevent conflict. Make sure + // all the other accounts used in tests are below 100. Also ensure here that we don't + // overlap. + assert!(VALIDATOR_PREFIX + VALIDATORS_PER_ERA < NOMINATOR_PREFIX); + + (VALIDATOR_PREFIX..VALIDATOR_PREFIX + VALIDATORS_PER_ERA) + .map(|v| { + // for the sake of sanity, let's register this taker as an actual validator. + let others = (NOMINATOR_PREFIX.. + (NOMINATOR_PREFIX + NOMINATORS_PER_VALIDATOR_PER_ERA)) + .map(|n| IndividualExposure { who: n, value: 0 as Balance }) + .collect::>(); + (v, Exposure { total: 0, own: 0, others }) + }) + .for_each(|(validator, exposure)| { + pallet_staking::ErasStakers::::insert(era, validator, exposure); + }); + } + + pub(crate) fn build(self) -> sp_io::TestExternalities { + sp_tracing::try_init_simple(); + let mut storage = + frame_system::GenesisConfig::default().build_storage::().unwrap(); + + // create one default pool. + let _ = pallet_nomination_pools::GenesisConfig:: { ..Default::default() } + .assimilate_storage(&mut storage); + + let validators_range = VALIDATOR_PREFIX..VALIDATOR_PREFIX + VALIDATORS_PER_ERA; + let nominators_range = + NOMINATOR_PREFIX..NOMINATOR_PREFIX + NOMINATORS_PER_VALIDATOR_PER_ERA; + + let _ = pallet_balances::GenesisConfig:: { + balances: self + .exposed_nominators + .clone() + .into_iter() + .map(|(stash, _, balance)| (stash, balance * 2)) + .chain( + self.exposed_nominators + .clone() + .into_iter() + .map(|(_, ctrl, balance)| (ctrl, balance * 2)), + ) + .chain(validators_range.clone().map(|x| (x, 100))) + .chain(nominators_range.clone().map(|x| (x, 100))) + .collect::>(), + } + .assimilate_storage(&mut storage); + + let _ = pallet_staking::GenesisConfig:: { + stakers: self + .exposed_nominators + .into_iter() + .map(|(x, y, z)| (x, y, z, pallet_staking::StakerStatus::Nominator(vec![42]))) + .chain(validators_range.map(|x| (x, x, 100, StakerStatus::Validator))) + .chain(nominators_range.map(|x| (x, x, 100, StakerStatus::Nominator(vec![x])))) + .collect::>(), + ..Default::default() + } + .assimilate_storage(&mut storage); + + let mut ext = sp_io::TestExternalities::from(storage); + + ext.execute_with(|| { + // for events to be deposited. + frame_system::Pallet::::set_block_number(1); + + for era in 0..=(BondingDuration::get()) { + Self::register_stakers_for_era(era); + } + + // because we read this value as a measure of how many validators we have. + pallet_staking::ValidatorCount::::put(VALIDATORS_PER_ERA as u32); + + // make a pool + let amount_to_bond = Pools::depositor_min_bond(); + Balances::make_free_balance_be(&10, amount_to_bond * 5); + assert_ok!(Pools::create(RawOrigin::Signed(10).into(), amount_to_bond, 900, 901, 902)); + }); + ext + } + + pub fn build_and_execute(self, test: impl FnOnce() -> ()) { + self.build().execute_with(|| { + test(); + }) + } +} + +pub(crate) fn run_to_block(n: u64, on_idle: bool) { + let current_block = System::block_number(); + assert!(n > current_block); + while System::block_number() < n { + Balances::on_finalize(System::block_number()); + Staking::on_finalize(System::block_number()); + Pools::on_finalize(System::block_number()); + FastUnstake::on_finalize(System::block_number()); + + System::set_block_number(System::block_number() + 1); + + Balances::on_initialize(System::block_number()); + Staking::on_initialize(System::block_number()); + Pools::on_initialize(System::block_number()); + FastUnstake::on_initialize(System::block_number()); + if on_idle { + FastUnstake::on_idle(System::block_number(), BlockWeights::get().max_block); + } + } +} + +pub(crate) fn next_block(on_idle: bool) { + let current = System::block_number(); + run_to_block(current + 1, on_idle); +} + +pub fn assert_unstaked(stash: &AccountId) { + assert!(!pallet_staking::Bonded::::contains_key(stash)); + assert!(!pallet_staking::Payee::::contains_key(stash)); + assert!(!pallet_staking::Validators::::contains_key(stash)); + assert!(!pallet_staking::Nominators::::contains_key(stash)); +} diff --git a/frame/fast-unstake/src/tests.rs b/frame/fast-unstake/src/tests.rs new file mode 100644 index 0000000000000..a51c1acdf06eb --- /dev/null +++ b/frame/fast-unstake/src/tests.rs @@ -0,0 +1,1036 @@ +// This file is part of Substrate. + +// Copyright (C) 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. + +//! Tests for pallet-fast-unstake. + +use super::*; +use crate::{mock::*, types::*, weights::WeightInfo, Event}; +use frame_support::{assert_noop, assert_ok, bounded_vec, pallet_prelude::*, traits::Currency}; +use pallet_nomination_pools::{BondedPools, LastPoolId, RewardPools}; +use pallet_staking::{CurrentEra, IndividualExposure, RewardDestination}; + +use sp_runtime::{traits::BadOrigin, DispatchError, ModuleError}; +use sp_staking::StakingInterface; + +#[test] +fn test_setup_works() { + ExtBuilder::default().build_and_execute(|| { + assert_eq!(BondedPools::::count(), 1); + assert_eq!(RewardPools::::count(), 1); + assert_eq!(Staking::bonding_duration(), 3); + let last_pool = LastPoolId::::get(); + assert_eq!(last_pool, 1); + }); +} + +#[test] +fn register_works() { + ExtBuilder::default().build_and_execute(|| { + // Controller account registers for fast unstake. + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), Some(1_u32))); + // Ensure stash is in the queue. + assert_ne!(Queue::::get(1), None); + }); +} + +#[test] +fn cannot_register_if_not_bonded() { + ExtBuilder::default().build_and_execute(|| { + // Mint accounts 1 and 2 with 200 tokens. + for _ in 1..2 { + let _ = Balances::make_free_balance_be(&1, 200); + } + // Attempt to fast unstake. + assert_noop!( + FastUnstake::register_fast_unstake(RuntimeOrigin::signed(1), Some(1_u32)), + Error::::NotController + ); + }); +} + +#[test] +fn cannot_register_if_in_queue() { + ExtBuilder::default().build_and_execute(|| { + // Insert some Queue item + Queue::::insert(1, Some(1_u32)); + // Cannot re-register, already in queue + assert_noop!( + FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), Some(1_u32)), + Error::::AlreadyQueued + ); + }); +} + +#[test] +fn cannot_register_if_head() { + ExtBuilder::default().build_and_execute(|| { + // Insert some Head item for stash + Head::::put(UnstakeRequest { stash: 1, checked: bounded_vec![], maybe_pool_id: None }); + // Controller attempts to regsiter + assert_noop!( + FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), Some(1_u32)), + Error::::AlreadyHead + ); + }); +} + +#[test] +fn cannot_register_if_has_unlocking_chunks() { + ExtBuilder::default().build_and_execute(|| { + // Start unbonding half of staked tokens + assert_ok!(Staking::unbond(RuntimeOrigin::signed(2), 50_u128)); + // Cannot register for fast unstake with unlock chunks active + assert_noop!( + FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), Some(1_u32)), + Error::::NotFullyBonded + ); + }); +} + +#[test] +fn deregister_works() { + ExtBuilder::default().build_and_execute(|| { + // Controller account registers for fast unstake. + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), Some(1_u32))); + // Controller then changes mind and deregisters. + assert_ok!(FastUnstake::deregister(RuntimeOrigin::signed(2))); + // Ensure stash no longer exists in the queue. + assert_eq!(Queue::::get(1), None); + }); +} + +#[test] +fn cannot_deregister_if_not_controller() { + ExtBuilder::default().build_and_execute(|| { + // Controller account registers for fast unstake. + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), Some(1_u32))); + // Stash tries to deregister. + assert_noop!(FastUnstake::deregister(RuntimeOrigin::signed(1)), Error::::NotController); + }); +} + +#[test] +fn cannot_deregister_if_not_queued() { + ExtBuilder::default().build_and_execute(|| { + // Controller tries to deregister without first registering + assert_noop!(FastUnstake::deregister(RuntimeOrigin::signed(2)), Error::::NotQueued); + }); +} + +#[test] +fn cannot_deregister_already_head() { + ExtBuilder::default().build_and_execute(|| { + // Controller attempts to register, should fail + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), Some(1_u32))); + // Insert some Head item for stash. + Head::::put(UnstakeRequest { stash: 1, checked: bounded_vec![], maybe_pool_id: None }); + // Controller attempts to deregister + assert_noop!(FastUnstake::deregister(RuntimeOrigin::signed(2)), Error::::AlreadyHead); + }); +} + +#[test] +fn control_works() { + ExtBuilder::default().build_and_execute(|| { + // account with control (root) origin wants to only check 1 era per block. + assert_ok!(FastUnstake::control(RuntimeOrigin::root(), 1_u32)); + }); +} + +#[test] +fn control_must_be_control_origin() { + ExtBuilder::default().build_and_execute(|| { + // account without control (root) origin wants to only check 1 era per block. + assert_noop!(FastUnstake::control(RuntimeOrigin::signed(1), 1_u32), BadOrigin); + }); +} + +mod on_idle { + use super::*; + + #[test] + fn early_exit() { + ExtBuilder::default().build_and_execute(|| { + ErasToCheckPerBlock::::put(BondingDuration::get() + 1); + CurrentEra::::put(BondingDuration::get()); + + // set up Queue item + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), Some(1))); + assert_eq!(Queue::::get(1), Some(Some(1))); + + // call on_idle with no remaining weight + FastUnstake::on_idle(System::block_number(), Weight::from_ref_time(0)); + + // assert nothing changed in Queue and Head + assert_eq!(Head::::get(), None); + assert_eq!(Queue::::get(1), Some(Some(1))); + }); + } + + #[test] + fn respects_weight() { + ExtBuilder::default().build_and_execute(|| { + // we want to check all eras in one block... + ErasToCheckPerBlock::::put(BondingDuration::get() + 1); + CurrentEra::::put(BondingDuration::get()); + + // given + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), Some(1))); + assert_eq!(Queue::::get(1), Some(Some(1))); + + assert_eq!(Queue::::count(), 1); + assert_eq!(Head::::get(), None); + + // when: call fast unstake with not enough weight to process the whole thing, just one + // era. + let remaining_weight = ::WeightInfo::on_idle_check( + pallet_staking::ValidatorCount::::get() * 1, + ); + assert_eq!(FastUnstake::on_idle(0, remaining_weight), remaining_weight); + + // then + assert_eq!( + fast_unstake_events_since_last_call(), + vec![Event::Checking { stash: 1, eras: vec![3] }] + ); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { stash: 1, checked: bounded_vec![3], maybe_pool_id: Some(1) }) + ); + + // when: another 1 era. + let remaining_weight = ::WeightInfo::on_idle_check( + pallet_staking::ValidatorCount::::get() * 1, + ); + assert_eq!(FastUnstake::on_idle(0, remaining_weight), remaining_weight); + + // then: + assert_eq!( + fast_unstake_events_since_last_call(), + vec![Event::Checking { stash: 1, eras: bounded_vec![2] }] + ); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2], + maybe_pool_id: Some(1) + }) + ); + + // when: then 5 eras, we only need 2 more. + let remaining_weight = ::WeightInfo::on_idle_check( + pallet_staking::ValidatorCount::::get() * 5, + ); + assert_eq!( + FastUnstake::on_idle(0, remaining_weight), + // note the amount of weight consumed: 2 eras worth of weight. + ::WeightInfo::on_idle_check( + pallet_staking::ValidatorCount::::get() * 2, + ) + ); + + // then: + assert_eq!( + fast_unstake_events_since_last_call(), + vec![Event::Checking { stash: 1, eras: vec![1, 0] }] + ); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2, 1, 0], + maybe_pool_id: Some(1) + }) + ); + + // when: not enough weight to unstake: + let remaining_weight = + ::WeightInfo::on_idle_unstake() - Weight::from_ref_time(1); + assert_eq!(FastUnstake::on_idle(0, remaining_weight), Weight::from_ref_time(0)); + + // then nothing happens: + assert_eq!(fast_unstake_events_since_last_call(), vec![]); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2, 1, 0], + maybe_pool_id: Some(1) + }) + ); + + // when: enough weight to get over at least one iteration: then we are unblocked and can + // unstake. + let remaining_weight = ::WeightInfo::on_idle_check( + pallet_staking::ValidatorCount::::get() * 1, + ); + assert_eq!( + FastUnstake::on_idle(0, remaining_weight), + ::WeightInfo::on_idle_unstake() + ); + + // then we finish the unbonding: + assert_eq!( + fast_unstake_events_since_last_call(), + vec![Event::Unstaked { stash: 1, maybe_pool_id: Some(1), result: Ok(()) }] + ); + assert_eq!(Head::::get(), None,); + + assert_unstaked(&1); + }); + } + + #[test] + fn if_head_not_set_one_random_fetched_from_queue() { + ExtBuilder::default().build_and_execute(|| { + ErasToCheckPerBlock::::put(BondingDuration::get() + 1); + CurrentEra::::put(BondingDuration::get()); + + // given + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), None)); + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(4), None)); + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(6), None)); + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(8), None)); + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(10), None)); + + assert_eq!(Queue::::count(), 5); + assert_eq!(Head::::get(), None); + + // when + next_block(true); + + // then + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2, 1, 0], + maybe_pool_id: None + }) + ); + assert_eq!(Queue::::count(), 4); + + // when + next_block(true); + + // then + assert_eq!(Head::::get(), None,); + assert_eq!(Queue::::count(), 4); + + // when + next_block(true); + + // then + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 5, + checked: bounded_vec![3, 2, 1, 0], + maybe_pool_id: None + }), + ); + assert_eq!(Queue::::count(), 3); + + assert_eq!( + fast_unstake_events_since_last_call(), + vec![ + Event::Checking { stash: 1, eras: vec![3, 2, 1, 0] }, + Event::Unstaked { stash: 1, maybe_pool_id: None, result: Ok(()) }, + Event::Checking { stash: 5, eras: vec![3, 2, 1, 0] } + ] + ); + }); + } + + #[test] + fn successful_multi_queue() { + ExtBuilder::default().build_and_execute(|| { + ErasToCheckPerBlock::::put(BondingDuration::get() + 1); + CurrentEra::::put(BondingDuration::get()); + + // register multi accounts for fast unstake + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), Some(1))); + assert_eq!(Queue::::get(1), Some(Some(1))); + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(4), Some(1))); + assert_eq!(Queue::::get(3), Some(Some(1))); + + // assert 2 queue items are in Queue & None in Head to start with + assert_eq!(Queue::::count(), 2); + assert_eq!(Head::::get(), None); + + // process on idle and check eras for next Queue item + next_block(true); + + // process on idle & let go of current Head + next_block(true); + + // confirm Head / Queue items remaining + assert_eq!(Queue::::count(), 1); + assert_eq!(Head::::get(), None); + + // process on idle and check eras for next Queue item + next_block(true); + + // process on idle & let go of current Head + next_block(true); + + // Head & Queue should now be empty + assert_eq!(Head::::get(), None); + assert_eq!(Queue::::count(), 0); + + assert_eq!( + fast_unstake_events_since_last_call(), + vec![ + Event::Checking { stash: 1, eras: vec![3, 2, 1, 0] }, + Event::Unstaked { stash: 1, maybe_pool_id: Some(1), result: Ok(()) }, + Event::Checking { stash: 3, eras: vec![3, 2, 1, 0] }, + Event::Unstaked { stash: 3, maybe_pool_id: Some(1), result: Ok(()) }, + ] + ); + + assert_unstaked(&1); + assert_unstaked(&3); + }); + } + + #[test] + fn successful_unstake_without_pool_join() { + ExtBuilder::default().build_and_execute(|| { + ErasToCheckPerBlock::::put(BondingDuration::get() + 1); + CurrentEra::::put(BondingDuration::get()); + + // register for fast unstake + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), None)); + assert_eq!(Queue::::get(1), Some(None)); + + // process on idle + next_block(true); + + // assert queue item has been moved to head + assert_eq!(Queue::::get(1), None); + + // assert head item present + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2, 1, 0], + maybe_pool_id: None + }) + ); + + next_block(true); + assert_eq!(Head::::get(), None,); + + assert_eq!( + fast_unstake_events_since_last_call(), + vec![ + Event::Checking { stash: 1, eras: vec![3, 2, 1, 0] }, + Event::Unstaked { stash: 1, maybe_pool_id: None, result: Ok(()) } + ] + ); + assert_unstaked(&1); + }); + } + + #[test] + fn successful_unstake_joining_bad_pool() { + ExtBuilder::default().build_and_execute(|| { + ErasToCheckPerBlock::::put(BondingDuration::get() + 1); + CurrentEra::::put(BondingDuration::get()); + + // register for fast unstake + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), Some(0))); + assert_eq!(Queue::::get(1), Some(Some(0))); + + // process on idle + next_block(true); + + // assert queue item has been moved to head + assert_eq!(Queue::::get(1), None); + + // assert head item present + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2, 1, 0], + maybe_pool_id: Some(0) + }) + ); + + next_block(true); + assert_eq!(Head::::get(), None,); + + assert_eq!( + fast_unstake_events_since_last_call(), + vec![ + Event::Checking { stash: 1, eras: vec![3, 2, 1, 0] }, + Event::Unstaked { + stash: 1, + maybe_pool_id: Some(0), + result: Err(DispatchError::Module(ModuleError { + index: 4, + error: [0, 0, 0, 0], + message: None + })) + } + ] + ); + assert_unstaked(&1); + }); + } + + #[test] + fn successful_unstake_all_eras_per_block() { + ExtBuilder::default().build_and_execute(|| { + ErasToCheckPerBlock::::put(BondingDuration::get() + 1); + CurrentEra::::put(BondingDuration::get()); + + // register for fast unstake + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), Some(1_u32))); + assert_eq!(Queue::::get(1), Some(Some(1))); + + // process on idle + next_block(true); + + // assert queue item has been moved to head + assert_eq!(Queue::::get(1), None); + + // assert head item present + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2, 1, 0], + maybe_pool_id: Some(1) + }) + ); + + next_block(true); + assert_eq!(Head::::get(), None,); + + assert_eq!( + fast_unstake_events_since_last_call(), + vec![ + Event::Checking { stash: 1, eras: vec![3, 2, 1, 0] }, + Event::Unstaked { stash: 1, maybe_pool_id: Some(1), result: Ok(()) } + ] + ); + assert_unstaked(&1); + assert!(pallet_nomination_pools::PoolMembers::::contains_key(&1)); + }); + } + + #[test] + fn successful_unstake_one_era_per_block() { + ExtBuilder::default().build_and_execute(|| { + // put 1 era per block + ErasToCheckPerBlock::::put(1); + CurrentEra::::put(BondingDuration::get()); + + // register for fast unstake + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), Some(1_u32))); + assert_eq!(Queue::::get(1), Some(Some(1))); + + // process on idle + next_block(true); + + // assert queue item has been moved to head + assert_eq!(Queue::::get(1), None); + + // assert head item present + assert_eq!( + Head::::get(), + Some(UnstakeRequest { stash: 1, checked: bounded_vec![3], maybe_pool_id: Some(1) }) + ); + + next_block(true); + + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2], + maybe_pool_id: Some(1) + }) + ); + + next_block(true); + + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2, 1], + maybe_pool_id: Some(1) + }) + ); + + next_block(true); + + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2, 1, 0], + maybe_pool_id: Some(1) + }) + ); + + next_block(true); + + assert_eq!(Head::::get(), None,); + + assert_eq!( + fast_unstake_events_since_last_call(), + vec![ + Event::Checking { stash: 1, eras: vec![3] }, + Event::Checking { stash: 1, eras: vec![2] }, + Event::Checking { stash: 1, eras: vec![1] }, + Event::Checking { stash: 1, eras: vec![0] }, + Event::Unstaked { stash: 1, maybe_pool_id: Some(1), result: Ok(()) } + ] + ); + assert_unstaked(&1); + assert!(pallet_nomination_pools::PoolMembers::::contains_key(&1)); + }); + } + + #[test] + fn old_checked_era_pruned() { + // the only scenario where checked era pruning (checked.retain) comes handy is a follows: + // the whole vector is full and at capacity and in the next call we are ready to unstake, + // but then a new era happens. + ExtBuilder::default().build_and_execute(|| { + // given + ErasToCheckPerBlock::::put(1); + CurrentEra::::put(BondingDuration::get()); + + // register for fast unstake + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), None)); + assert_eq!(Queue::::get(1), Some(None)); + + next_block(true); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { stash: 1, checked: bounded_vec![3], maybe_pool_id: None }) + ); + + next_block(true); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { stash: 1, checked: bounded_vec![3, 2], maybe_pool_id: None }) + ); + + next_block(true); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2, 1], + maybe_pool_id: None + }) + ); + + next_block(true); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2, 1, 0], + maybe_pool_id: None + }) + ); + + // when: a new era happens right before one is free. + CurrentEra::::put(CurrentEra::::get().unwrap() + 1); + ExtBuilder::register_stakers_for_era(CurrentEra::::get().unwrap()); + + // then + next_block(true); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + // note era 0 is pruned to keep the vector length sane. + checked: bounded_vec![3, 2, 1, 4], + maybe_pool_id: None + }) + ); + + next_block(true); + assert_eq!(Head::::get(), None); + + assert_eq!( + fast_unstake_events_since_last_call(), + vec![ + Event::Checking { stash: 1, eras: vec![3] }, + Event::Checking { stash: 1, eras: vec![2] }, + Event::Checking { stash: 1, eras: vec![1] }, + Event::Checking { stash: 1, eras: vec![0] }, + Event::Checking { stash: 1, eras: vec![4] }, + Event::Unstaked { stash: 1, maybe_pool_id: None, result: Ok(()) } + ] + ); + assert_unstaked(&1); + }); + } + + #[test] + fn unstake_paused_mid_election() { + ExtBuilder::default().build_and_execute(|| { + // give: put 1 era per block + ErasToCheckPerBlock::::put(1); + CurrentEra::::put(BondingDuration::get()); + + // register for fast unstake + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), Some(1_u32))); + + // process 2 blocks + next_block(true); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { stash: 1, checked: bounded_vec![3], maybe_pool_id: Some(1) }) + ); + + next_block(true); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2], + maybe_pool_id: Some(1) + }) + ); + + // when + Ongoing::set(true); + + // then nothing changes + next_block(true); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2], + maybe_pool_id: Some(1) + }) + ); + + next_block(true); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2], + maybe_pool_id: Some(1) + }) + ); + + // then we register a new era. + Ongoing::set(false); + CurrentEra::::put(CurrentEra::::get().unwrap() + 1); + ExtBuilder::register_stakers_for_era(CurrentEra::::get().unwrap()); + + // then we can progress again, but notice that the new era that had to be checked. + next_block(true); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2, 4], + maybe_pool_id: Some(1) + }) + ); + + // progress to end + next_block(true); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 1, + checked: bounded_vec![3, 2, 4, 1], + maybe_pool_id: Some(1) + }) + ); + + // but notice that we don't care about era 0 instead anymore! we're done. + next_block(true); + assert_eq!(Head::::get(), None); + + assert_eq!( + fast_unstake_events_since_last_call(), + vec![ + Event::Checking { stash: 1, eras: vec![3] }, + Event::Checking { stash: 1, eras: vec![2] }, + Event::Checking { stash: 1, eras: vec![4] }, + Event::Checking { stash: 1, eras: vec![1] }, + Event::Unstaked { stash: 1, maybe_pool_id: Some(1), result: Ok(()) } + ] + ); + + assert_unstaked(&1); + assert!(pallet_nomination_pools::PoolMembers::::contains_key(&1)); + }); + } + + #[test] + fn exposed_nominator_cannot_unstake() { + ExtBuilder::default().build_and_execute(|| { + ErasToCheckPerBlock::::put(1); + SlashPerEra::set(7); + CurrentEra::::put(BondingDuration::get()); + + // create an exposed nominator in era 1 + let exposed = 666 as AccountId; + pallet_staking::ErasStakers::::mutate(1, VALIDATORS_PER_ERA, |expo| { + expo.others.push(IndividualExposure { who: exposed, value: 0 as Balance }); + }); + Balances::make_free_balance_be(&exposed, 100); + assert_ok!(Staking::bond( + RuntimeOrigin::signed(exposed), + exposed, + 10, + RewardDestination::Staked + )); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(exposed), vec![exposed])); + + // register the exposed one. + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(exposed), None)); + + // a few blocks later, we realize they are slashed + next_block(true); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: exposed, + checked: bounded_vec![3], + maybe_pool_id: None + }) + ); + next_block(true); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: exposed, + checked: bounded_vec![3, 2], + maybe_pool_id: None + }) + ); + next_block(true); + assert_eq!(Head::::get(), None); + + assert_eq!( + fast_unstake_events_since_last_call(), + // we slash them by 21, since we checked 3 eras in total (3, 2, 1). + vec![ + Event::Checking { stash: exposed, eras: vec![3] }, + Event::Checking { stash: exposed, eras: vec![2] }, + Event::Slashed { stash: exposed, amount: 3 * 7 } + ] + ); + }); + } + + #[test] + fn exposed_nominator_cannot_unstake_multi_check() { + ExtBuilder::default().build_and_execute(|| { + // same as the previous check, but we check 2 eras per block, and we make the exposed be + // exposed in era 0, so that it is detected halfway in a check era. + ErasToCheckPerBlock::::put(2); + SlashPerEra::set(7); + CurrentEra::::put(BondingDuration::get()); + + // create an exposed nominator in era 1 + let exposed = 666 as AccountId; + pallet_staking::ErasStakers::::mutate(0, VALIDATORS_PER_ERA, |expo| { + expo.others.push(IndividualExposure { who: exposed, value: 0 as Balance }); + }); + Balances::make_free_balance_be(&exposed, 100); + assert_ok!(Staking::bond( + RuntimeOrigin::signed(exposed), + exposed, + 10, + RewardDestination::Staked + )); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(exposed), vec![exposed])); + + // register the exposed one. + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(exposed), None)); + + // a few blocks later, we realize they are slashed + next_block(true); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: exposed, + checked: bounded_vec![3, 2], + maybe_pool_id: None + }) + ); + next_block(true); + assert_eq!(Head::::get(), None); + + assert_eq!( + fast_unstake_events_since_last_call(), + // we slash them by 28, since we checked 4 eras in total. + vec![ + Event::Checking { stash: exposed, eras: vec![3, 2] }, + Event::Slashed { stash: exposed, amount: 4 * 7 } + ] + ); + }); + } + + #[test] + fn validators_cannot_bail() { + ExtBuilder::default().build_and_execute(|| { + ErasToCheckPerBlock::::put(BondingDuration::get() + 1); + CurrentEra::::put(BondingDuration::get()); + + // a validator switches role and register... + assert_ok!(Staking::nominate( + RuntimeOrigin::signed(VALIDATOR_PREFIX), + vec![VALIDATOR_PREFIX] + )); + assert_ok!(FastUnstake::register_fast_unstake( + RuntimeOrigin::signed(VALIDATOR_PREFIX), + None + )); + + // but they indeed are exposed! + assert!(pallet_staking::ErasStakers::::contains_key( + BondingDuration::get() - 1, + VALIDATOR_PREFIX + )); + + // process a block, this validator is exposed and has been slashed. + next_block(true); + assert_eq!(Head::::get(), None); + + assert_eq!( + fast_unstake_events_since_last_call(), + vec![Event::Slashed { stash: 100, amount: 100 }] + ); + }); + } + + #[test] + fn unexposed_validator_can_fast_unstake() { + ExtBuilder::default().build_and_execute(|| { + ErasToCheckPerBlock::::put(BondingDuration::get() + 1); + CurrentEra::::put(BondingDuration::get()); + + // create a new validator that 100% not exposed. + Balances::make_free_balance_be(&42, 100); + assert_ok!(Staking::bond(RuntimeOrigin::signed(42), 42, 10, RewardDestination::Staked)); + assert_ok!(Staking::validate(RuntimeOrigin::signed(42), Default::default())); + + // let them register: + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(42), None)); + + // 2 block's enough to unstake them. + next_block(true); + assert_eq!( + Head::::get(), + Some(UnstakeRequest { + stash: 42, + checked: bounded_vec![3, 2, 1, 0], + maybe_pool_id: None + }) + ); + next_block(true); + assert_eq!(Head::::get(), None); + + assert_eq!( + fast_unstake_events_since_last_call(), + vec![ + Event::Checking { stash: 42, eras: vec![3, 2, 1, 0] }, + Event::Unstaked { stash: 42, maybe_pool_id: None, result: Ok(()) } + ] + ); + }); + } +} + +mod signed_extension { + use super::*; + use sp_runtime::traits::SignedExtension; + + const STAKING_CALL: crate::mock::RuntimeCall = + crate::mock::RuntimeCall::Staking(pallet_staking::Call::::chill {}); + + #[test] + fn does_nothing_if_not_queued() { + ExtBuilder::default().build_and_execute(|| { + assert!(PreventStakingOpsIfUnbonding::::new() + .pre_dispatch(&1, &STAKING_CALL, &Default::default(), Default::default()) + .is_ok()); + }) + } + + #[test] + fn prevents_queued() { + ExtBuilder::default().build_and_execute(|| { + // given: stash for 2 is 1. + // when + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), None)); + + // then + // stash can't. + assert!(PreventStakingOpsIfUnbonding::::new() + .pre_dispatch(&1, &STAKING_CALL, &Default::default(), Default::default()) + .is_err()); + + // controller can't. + assert!(PreventStakingOpsIfUnbonding::::new() + .pre_dispatch(&2, &STAKING_CALL, &Default::default(), Default::default()) + .is_err()); + }) + } + + #[test] + fn prevents_head_stash() { + ExtBuilder::default().build_and_execute(|| { + // given: stash for 2 is 1. + // when + assert_ok!(FastUnstake::register_fast_unstake(RuntimeOrigin::signed(2), None)); + + ErasToCheckPerBlock::::put(1); + CurrentEra::::put(BondingDuration::get()); + next_block(true); + + assert_eq!( + Head::::get(), + Some(UnstakeRequest { stash: 1, checked: bounded_vec![3], maybe_pool_id: None }) + ); + + // then + // stash can't + assert!(PreventStakingOpsIfUnbonding::::new() + .pre_dispatch(&2, &STAKING_CALL, &Default::default(), Default::default()) + .is_err()); + + // controller can't + assert!(PreventStakingOpsIfUnbonding::::new() + .pre_dispatch(&1, &STAKING_CALL, &Default::default(), Default::default()) + .is_err()); + }) + } +} diff --git a/frame/fast-unstake/src/types.rs b/frame/fast-unstake/src/types.rs new file mode 100644 index 0000000000000..ae8702e56a842 --- /dev/null +++ b/frame/fast-unstake/src/types.rs @@ -0,0 +1,119 @@ +// This file is part of Substrate. + +// Copyright (C) 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. + +//! Types used in the Fast Unstake pallet. + +use crate::*; +use codec::{Decode, Encode, MaxEncodedLen}; +use frame_support::{ + traits::{Currency, Get, IsSubType}, + BoundedVec, EqNoBound, PartialEqNoBound, RuntimeDebugNoBound, +}; +use pallet_nomination_pools::PoolId; +use scale_info::TypeInfo; +use sp_runtime::transaction_validity::{InvalidTransaction, TransactionValidityError}; +use sp_staking::EraIndex; +use sp_std::{fmt::Debug, prelude::*}; + +pub type BalanceOf = <::Currency as Currency< + ::AccountId, +>>::Balance; + +/// An unstake request. +#[derive( + Encode, Decode, EqNoBound, PartialEqNoBound, Clone, TypeInfo, RuntimeDebugNoBound, MaxEncodedLen, +)] +pub struct UnstakeRequest> { + /// Their stash account. + pub(crate) stash: AccountId, + /// The list of eras for which they have been checked. + pub(crate) checked: BoundedVec, + /// The pool they wish to join, if any. + pub(crate) maybe_pool_id: Option, +} + +#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo, RuntimeDebugNoBound)] +#[scale_info(skip_type_params(T))] +pub struct PreventStakingOpsIfUnbonding(sp_std::marker::PhantomData); + +#[cfg(test)] +impl PreventStakingOpsIfUnbonding { + pub fn new() -> Self { + Self(Default::default()) + } +} + +impl sp_runtime::traits::SignedExtension + for PreventStakingOpsIfUnbonding +where + ::RuntimeCall: IsSubType>, +{ + type AccountId = T::AccountId; + type Call = ::RuntimeCall; + type AdditionalSigned = (); + type Pre = (); + const IDENTIFIER: &'static str = "PreventStakingOpsIfUnbonding"; + + fn additional_signed(&self) -> Result { + Ok(()) + } + + fn pre_dispatch( + self, + // NOTE: we want to prevent this stash-controller pair from doing anything in the + // staking system as long as they are registered here. + stash_or_controller: &Self::AccountId, + call: &Self::Call, + _info: &sp_runtime::traits::DispatchInfoOf, + _len: usize, + ) -> Result { + // we don't check this in the tx-pool as it requires a storage read. + if >>::is_sub_type(call).is_some() { + let check_stash = |stash: &T::AccountId| { + if Queue::::contains_key(&stash) || + Head::::get().map_or(false, |u| &u.stash == stash) + { + Err(TransactionValidityError::Invalid(InvalidTransaction::Call)) + } else { + Ok(()) + } + }; + match ( + // mapped from controller. + pallet_staking::Ledger::::get(&stash_or_controller), + // mapped from stash. + pallet_staking::Bonded::::get(&stash_or_controller), + ) { + (Some(ledger), None) => { + // it is a controller. + check_stash(&ledger.stash) + }, + (_, Some(_)) => { + // it's a stash. + let stash = stash_or_controller; + check_stash(stash) + }, + (None, None) => { + // They are not a staker -- let them execute. + Ok(()) + }, + } + } else { + Ok(()) + } + } +} diff --git a/frame/fast-unstake/src/weights.rs b/frame/fast-unstake/src/weights.rs new file mode 100644 index 0000000000000..04857d0dcc865 --- /dev/null +++ b/frame/fast-unstake/src/weights.rs @@ -0,0 +1,210 @@ +// This file is part of Substrate. + +// Copyright (C) 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. + +//! Autogenerated weights for pallet_fast_unstake +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-09-07, STEPS: `10`, REPEAT: 1, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `Kians-MacBook-Pro-2.local`, CPU: `` +//! EXECUTION: Some(Native), WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024 + +// Executed Command: +// target/release/substrate +// benchmark +// pallet +// --steps=10 +// --repeat=1 +// --pallet=pallet_fast_unstake +// --extrinsic=* +// --execution=native +// --output +// weight.rs +// --template +// ./.maintain/frame-weight-template.hbs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use sp_std::marker::PhantomData; + +/// Weight functions needed for pallet_fast_unstake. +pub trait WeightInfo { + fn on_idle_unstake() -> Weight; + fn on_idle_check(x: u32, ) -> Weight; + fn register_fast_unstake() -> Weight; + fn deregister() -> Weight; + fn control() -> Weight; +} + +/// Weights for pallet_fast_unstake using the Substrate node and recommended hardware. +pub struct SubstrateWeight(PhantomData); +impl WeightInfo for SubstrateWeight { + // Storage: FastUnstake ErasToCheckPerBlock (r:1 w:0) + // Storage: Staking ValidatorCount (r:1 w:0) + // Storage: ElectionProviderMultiPhase CurrentPhase (r:1 w:0) + // Storage: FastUnstake Head (r:1 w:1) + // Storage: Staking CurrentEra (r:1 w:0) + // Storage: Staking SlashingSpans (r:1 w:0) + // Storage: Staking Bonded (r:2 w:1) + // Storage: Staking Ledger (r:2 w:2) + // Storage: Staking Validators (r:1 w:0) + // Storage: Staking Nominators (r:1 w:0) + // Storage: System Account (r:3 w:2) + // Storage: Balances Locks (r:2 w:2) + // Storage: NominationPools MinJoinBond (r:1 w:0) + // Storage: NominationPools PoolMembers (r:1 w:1) + // Storage: NominationPools BondedPools (r:1 w:1) + // Storage: NominationPools RewardPools (r:1 w:1) + // Storage: NominationPools MaxPoolMembersPerPool (r:1 w:0) + // Storage: NominationPools MaxPoolMembers (r:1 w:0) + // Storage: NominationPools CounterForPoolMembers (r:1 w:1) + // Storage: BagsList ListNodes (r:1 w:0) + // Storage: Staking Payee (r:0 w:1) + fn on_idle_unstake() -> Weight { + Weight::from_ref_time(102_000_000 as u64) + .saturating_add(T::DbWeight::get().reads(25 as u64)) + .saturating_add(T::DbWeight::get().writes(13 as u64)) + } + // Storage: FastUnstake ErasToCheckPerBlock (r:1 w:0) + // Storage: Staking ValidatorCount (r:1 w:0) + // Storage: ElectionProviderMultiPhase CurrentPhase (r:1 w:0) + // Storage: FastUnstake Head (r:1 w:1) + // Storage: FastUnstake Queue (r:2 w:1) + // Storage: FastUnstake CounterForQueue (r:1 w:1) + // Storage: Staking CurrentEra (r:1 w:0) + // Storage: Staking ErasStakers (r:1344 w:0) + /// The range of component `x` is `[672, 86016]`. + fn on_idle_check(x: u32, ) -> Weight { + Weight::from_ref_time(0 as u64) + // Standard Error: 244_000 + .saturating_add(Weight::from_ref_time(13_913_000 as u64).saturating_mul(x as u64)) + .saturating_add(T::DbWeight::get().reads(585 as u64)) + .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(x as u64))) + .saturating_add(T::DbWeight::get().writes(3 as u64)) + } + // Storage: Staking Ledger (r:1 w:1) + // Storage: Staking Nominators (r:1 w:1) + // Storage: FastUnstake Queue (r:1 w:1) + // Storage: FastUnstake Head (r:1 w:0) + // Storage: Staking Validators (r:1 w:0) + // Storage: Staking CounterForNominators (r:1 w:1) + // Storage: BagsList ListNodes (r:1 w:1) + // Storage: BagsList ListBags (r:1 w:1) + // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: Staking CurrentEra (r:1 w:0) + // Storage: Balances Locks (r:1 w:1) + // Storage: FastUnstake CounterForQueue (r:1 w:1) + fn register_fast_unstake() -> Weight { + Weight::from_ref_time(57_000_000 as u64) + .saturating_add(T::DbWeight::get().reads(12 as u64)) + .saturating_add(T::DbWeight::get().writes(9 as u64)) + } + // Storage: Staking Ledger (r:1 w:0) + // Storage: FastUnstake Queue (r:1 w:1) + // Storage: FastUnstake Head (r:1 w:0) + // Storage: FastUnstake CounterForQueue (r:1 w:1) + fn deregister() -> Weight { + Weight::from_ref_time(15_000_000 as u64) + .saturating_add(T::DbWeight::get().reads(4 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) + } + // Storage: FastUnstake ErasToCheckPerBlock (r:0 w:1) + fn control() -> Weight { + Weight::from_ref_time(3_000_000 as u64) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } +} + +// For backwards compatibility and tests +impl WeightInfo for () { + // Storage: FastUnstake ErasToCheckPerBlock (r:1 w:0) + // Storage: Staking ValidatorCount (r:1 w:0) + // Storage: ElectionProviderMultiPhase CurrentPhase (r:1 w:0) + // Storage: FastUnstake Head (r:1 w:1) + // Storage: Staking CurrentEra (r:1 w:0) + // Storage: Staking SlashingSpans (r:1 w:0) + // Storage: Staking Bonded (r:2 w:1) + // Storage: Staking Ledger (r:2 w:2) + // Storage: Staking Validators (r:1 w:0) + // Storage: Staking Nominators (r:1 w:0) + // Storage: System Account (r:3 w:2) + // Storage: Balances Locks (r:2 w:2) + // Storage: NominationPools MinJoinBond (r:1 w:0) + // Storage: NominationPools PoolMembers (r:1 w:1) + // Storage: NominationPools BondedPools (r:1 w:1) + // Storage: NominationPools RewardPools (r:1 w:1) + // Storage: NominationPools MaxPoolMembersPerPool (r:1 w:0) + // Storage: NominationPools MaxPoolMembers (r:1 w:0) + // Storage: NominationPools CounterForPoolMembers (r:1 w:1) + // Storage: BagsList ListNodes (r:1 w:0) + // Storage: Staking Payee (r:0 w:1) + fn on_idle_unstake() -> Weight { + Weight::from_ref_time(102_000_000 as u64) + .saturating_add(RocksDbWeight::get().reads(25 as u64)) + .saturating_add(RocksDbWeight::get().writes(13 as u64)) + } + // Storage: FastUnstake ErasToCheckPerBlock (r:1 w:0) + // Storage: Staking ValidatorCount (r:1 w:0) + // Storage: ElectionProviderMultiPhase CurrentPhase (r:1 w:0) + // Storage: FastUnstake Head (r:1 w:1) + // Storage: FastUnstake Queue (r:2 w:1) + // Storage: FastUnstake CounterForQueue (r:1 w:1) + // Storage: Staking CurrentEra (r:1 w:0) + // Storage: Staking ErasStakers (r:1344 w:0) + /// The range of component `x` is `[672, 86016]`. + fn on_idle_check(x: u32, ) -> Weight { + Weight::from_ref_time(0 as u64) + // Standard Error: 244_000 + .saturating_add(Weight::from_ref_time(13_913_000 as u64).saturating_mul(x as u64)) + .saturating_add(RocksDbWeight::get().reads(585 as u64)) + .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(x as u64))) + .saturating_add(RocksDbWeight::get().writes(3 as u64)) + } + // Storage: Staking Ledger (r:1 w:1) + // Storage: Staking Nominators (r:1 w:1) + // Storage: FastUnstake Queue (r:1 w:1) + // Storage: FastUnstake Head (r:1 w:0) + // Storage: Staking Validators (r:1 w:0) + // Storage: Staking CounterForNominators (r:1 w:1) + // Storage: BagsList ListNodes (r:1 w:1) + // Storage: BagsList ListBags (r:1 w:1) + // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: Staking CurrentEra (r:1 w:0) + // Storage: Balances Locks (r:1 w:1) + // Storage: FastUnstake CounterForQueue (r:1 w:1) + fn register_fast_unstake() -> Weight { + Weight::from_ref_time(57_000_000 as u64) + .saturating_add(RocksDbWeight::get().reads(12 as u64)) + .saturating_add(RocksDbWeight::get().writes(9 as u64)) + } + // Storage: Staking Ledger (r:1 w:0) + // Storage: FastUnstake Queue (r:1 w:1) + // Storage: FastUnstake Head (r:1 w:0) + // Storage: FastUnstake CounterForQueue (r:1 w:1) + fn deregister() -> Weight { + Weight::from_ref_time(15_000_000 as u64) + .saturating_add(RocksDbWeight::get().reads(4 as u64)) + .saturating_add(RocksDbWeight::get().writes(2 as u64)) + } + // Storage: FastUnstake ErasToCheckPerBlock (r:0 w:1) + fn control() -> Weight { + Weight::from_ref_time(3_000_000 as u64) + .saturating_add(RocksDbWeight::get().writes(1 as u64)) + } +} diff --git a/frame/gilt/src/benchmarking.rs b/frame/gilt/src/benchmarking.rs index 3df08372f499b..1767a8da4def0 100644 --- a/frame/gilt/src/benchmarking.rs +++ b/frame/gilt/src/benchmarking.rs @@ -77,7 +77,7 @@ benchmarks! { set_target { let origin = T::AdminOrigin::successful_origin(); - }: _(origin, Default::default()) + }: _(origin, Default::default()) verify {} thaw { diff --git a/frame/gilt/src/lib.rs b/frame/gilt/src/lib.rs index 157aa8284f2f1..28a0f5fd56e67 100644 --- a/frame/gilt/src/lib.rs +++ b/frame/gilt/src/lib.rs @@ -116,7 +116,7 @@ pub mod pallet { + MaxEncodedLen; /// Origin required for setting the target proportion to be under gilt. - type AdminOrigin: EnsureOrigin; + type AdminOrigin: EnsureOrigin; /// Unbalanced handler to account for funds created (in case of a higher total issuance over /// freezing period). diff --git a/frame/gilt/src/mock.rs b/frame/gilt/src/mock.rs index a9cca0ff22780..e1cdf6507ef58 100644 --- a/frame/gilt/src/mock.rs +++ b/frame/gilt/src/mock.rs @@ -49,7 +49,7 @@ impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); type BlockLength = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = u64; diff --git a/frame/gilt/src/tests.rs b/frame/gilt/src/tests.rs index 486601b5b2f21..2ac369dd3b8b3 100644 --- a/frame/gilt/src/tests.rs +++ b/frame/gilt/src/tests.rs @@ -49,8 +49,8 @@ fn set_target_works() { new_test_ext().execute_with(|| { run_to_block(1); let e = DispatchError::BadOrigin; - assert_noop!(Gilt::set_target(Origin::signed(2), Perquintill::from_percent(50)), e); - assert_ok!(Gilt::set_target(Origin::signed(1), Perquintill::from_percent(50))); + assert_noop!(Gilt::set_target(RuntimeOrigin::signed(2), Perquintill::from_percent(50)), e); + assert_ok!(Gilt::set_target(RuntimeOrigin::signed(1), Perquintill::from_percent(50))); assert_eq!( ActiveTotal::::get(), @@ -68,13 +68,19 @@ fn set_target_works() { fn place_bid_works() { new_test_ext().execute_with(|| { run_to_block(1); - assert_noop!(Gilt::place_bid(Origin::signed(1), 1, 2), Error::::AmountTooSmall); assert_noop!( - Gilt::place_bid(Origin::signed(1), 101, 2), + Gilt::place_bid(RuntimeOrigin::signed(1), 1, 2), + Error::::AmountTooSmall + ); + assert_noop!( + Gilt::place_bid(RuntimeOrigin::signed(1), 101, 2), BalancesError::::InsufficientBalance ); - assert_noop!(Gilt::place_bid(Origin::signed(1), 10, 4), Error::::DurationTooBig); - assert_ok!(Gilt::place_bid(Origin::signed(1), 10, 2)); + assert_noop!( + Gilt::place_bid(RuntimeOrigin::signed(1), 10, 4), + Error::::DurationTooBig + ); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 10, 2)); assert_eq!(Balances::reserved_balance(1), 10); assert_eq!(Queues::::get(2), vec![GiltBid { amount: 10, who: 1 }]); assert_eq!(QueueTotals::::get(), vec![(0, 0), (1, 10), (0, 0)]); @@ -85,16 +91,16 @@ fn place_bid_works() { fn place_bid_queuing_works() { new_test_ext().execute_with(|| { run_to_block(1); - assert_ok!(Gilt::place_bid(Origin::signed(1), 20, 2)); - assert_ok!(Gilt::place_bid(Origin::signed(1), 10, 2)); - assert_ok!(Gilt::place_bid(Origin::signed(1), 5, 2)); - assert_noop!(Gilt::place_bid(Origin::signed(1), 5, 2), Error::::BidTooLow); - assert_ok!(Gilt::place_bid(Origin::signed(1), 15, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 20, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 10, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 5, 2)); + assert_noop!(Gilt::place_bid(RuntimeOrigin::signed(1), 5, 2), Error::::BidTooLow); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 15, 2)); assert_eq!(Balances::reserved_balance(1), 45); - assert_ok!(Gilt::place_bid(Origin::signed(1), 25, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 25, 2)); assert_eq!(Balances::reserved_balance(1), 60); - assert_noop!(Gilt::place_bid(Origin::signed(1), 10, 2), Error::::BidTooLow); + assert_noop!(Gilt::place_bid(RuntimeOrigin::signed(1), 10, 2), Error::::BidTooLow); assert_eq!( Queues::::get(2), vec![ @@ -111,11 +117,11 @@ fn place_bid_queuing_works() { fn place_bid_fails_when_queue_full() { new_test_ext().execute_with(|| { run_to_block(1); - assert_ok!(Gilt::place_bid(Origin::signed(1), 10, 2)); - assert_ok!(Gilt::place_bid(Origin::signed(2), 10, 2)); - assert_ok!(Gilt::place_bid(Origin::signed(3), 10, 2)); - assert_noop!(Gilt::place_bid(Origin::signed(4), 10, 2), Error::::BidTooLow); - assert_ok!(Gilt::place_bid(Origin::signed(4), 10, 3)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 10, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(2), 10, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(3), 10, 2)); + assert_noop!(Gilt::place_bid(RuntimeOrigin::signed(4), 10, 2), Error::::BidTooLow); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(4), 10, 3)); }); } @@ -123,11 +129,11 @@ fn place_bid_fails_when_queue_full() { fn multiple_place_bids_works() { new_test_ext().execute_with(|| { run_to_block(1); - assert_ok!(Gilt::place_bid(Origin::signed(1), 10, 1)); - assert_ok!(Gilt::place_bid(Origin::signed(1), 10, 2)); - assert_ok!(Gilt::place_bid(Origin::signed(1), 10, 2)); - assert_ok!(Gilt::place_bid(Origin::signed(1), 10, 3)); - assert_ok!(Gilt::place_bid(Origin::signed(2), 10, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 10, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 10, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 10, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 10, 3)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(2), 10, 2)); assert_eq!(Balances::reserved_balance(1), 40); assert_eq!(Balances::reserved_balance(2), 10); @@ -149,9 +155,9 @@ fn multiple_place_bids_works() { fn retract_single_item_queue_works() { new_test_ext().execute_with(|| { run_to_block(1); - assert_ok!(Gilt::place_bid(Origin::signed(1), 10, 1)); - assert_ok!(Gilt::place_bid(Origin::signed(1), 10, 2)); - assert_ok!(Gilt::retract_bid(Origin::signed(1), 10, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 10, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 10, 2)); + assert_ok!(Gilt::retract_bid(RuntimeOrigin::signed(1), 10, 1)); assert_eq!(Balances::reserved_balance(1), 10); assert_eq!(Queues::::get(1), vec![]); @@ -164,12 +170,12 @@ fn retract_single_item_queue_works() { fn retract_with_other_and_duplicate_works() { new_test_ext().execute_with(|| { run_to_block(1); - assert_ok!(Gilt::place_bid(Origin::signed(1), 10, 1)); - assert_ok!(Gilt::place_bid(Origin::signed(1), 10, 2)); - assert_ok!(Gilt::place_bid(Origin::signed(1), 10, 2)); - assert_ok!(Gilt::place_bid(Origin::signed(2), 10, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 10, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 10, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 10, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(2), 10, 2)); - assert_ok!(Gilt::retract_bid(Origin::signed(1), 10, 2)); + assert_ok!(Gilt::retract_bid(RuntimeOrigin::signed(1), 10, 2)); assert_eq!(Balances::reserved_balance(1), 20); assert_eq!(Balances::reserved_balance(2), 10); assert_eq!(Queues::::get(1), vec![GiltBid { amount: 10, who: 1 },]); @@ -185,11 +191,11 @@ fn retract_with_other_and_duplicate_works() { fn retract_non_existent_item_fails() { new_test_ext().execute_with(|| { run_to_block(1); - assert_noop!(Gilt::retract_bid(Origin::signed(1), 10, 1), Error::::NotFound); - assert_ok!(Gilt::place_bid(Origin::signed(1), 10, 1)); - assert_noop!(Gilt::retract_bid(Origin::signed(1), 20, 1), Error::::NotFound); - assert_noop!(Gilt::retract_bid(Origin::signed(1), 10, 2), Error::::NotFound); - assert_noop!(Gilt::retract_bid(Origin::signed(2), 10, 1), Error::::NotFound); + assert_noop!(Gilt::retract_bid(RuntimeOrigin::signed(1), 10, 1), Error::::NotFound); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 10, 1)); + assert_noop!(Gilt::retract_bid(RuntimeOrigin::signed(1), 20, 1), Error::::NotFound); + assert_noop!(Gilt::retract_bid(RuntimeOrigin::signed(1), 10, 2), Error::::NotFound); + assert_noop!(Gilt::retract_bid(RuntimeOrigin::signed(2), 10, 1), Error::::NotFound); }); } @@ -197,8 +203,8 @@ fn retract_non_existent_item_fails() { fn basic_enlarge_works() { new_test_ext().execute_with(|| { run_to_block(1); - assert_ok!(Gilt::place_bid(Origin::signed(1), 40, 1)); - assert_ok!(Gilt::place_bid(Origin::signed(2), 40, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 40, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(2), 40, 2)); Gilt::enlarge(40, 2); // Takes 2/2, then stopped because it reaches its max amount @@ -228,10 +234,10 @@ fn basic_enlarge_works() { fn enlarge_respects_bids_limit() { new_test_ext().execute_with(|| { run_to_block(1); - assert_ok!(Gilt::place_bid(Origin::signed(1), 40, 1)); - assert_ok!(Gilt::place_bid(Origin::signed(2), 40, 2)); - assert_ok!(Gilt::place_bid(Origin::signed(3), 40, 2)); - assert_ok!(Gilt::place_bid(Origin::signed(4), 40, 3)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 40, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(2), 40, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(3), 40, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(4), 40, 3)); Gilt::enlarge(100, 2); // Should have taken 4/3 and 2/2, then stopped because it's only allowed 2. @@ -269,7 +275,7 @@ fn enlarge_respects_bids_limit() { fn enlarge_respects_amount_limit_and_will_split() { new_test_ext().execute_with(|| { run_to_block(1); - assert_ok!(Gilt::place_bid(Origin::signed(1), 80, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 80, 1)); Gilt::enlarge(40, 2); // Takes 2/2, then stopped because it reaches its max amount @@ -296,14 +302,14 @@ fn enlarge_respects_amount_limit_and_will_split() { fn basic_thaw_works() { new_test_ext().execute_with(|| { run_to_block(1); - assert_ok!(Gilt::place_bid(Origin::signed(1), 40, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 40, 1)); Gilt::enlarge(40, 1); run_to_block(3); - assert_noop!(Gilt::thaw(Origin::signed(1), 0), Error::::NotExpired); + assert_noop!(Gilt::thaw(RuntimeOrigin::signed(1), 0), Error::::NotExpired); run_to_block(4); - assert_noop!(Gilt::thaw(Origin::signed(1), 1), Error::::Unknown); - assert_noop!(Gilt::thaw(Origin::signed(2), 0), Error::::NotOwner); - assert_ok!(Gilt::thaw(Origin::signed(1), 0)); + assert_noop!(Gilt::thaw(RuntimeOrigin::signed(1), 1), Error::::Unknown); + assert_noop!(Gilt::thaw(RuntimeOrigin::signed(2), 0), Error::::NotOwner); + assert_ok!(Gilt::thaw(RuntimeOrigin::signed(1), 0)); assert_eq!( ActiveTotal::::get(), @@ -324,7 +330,7 @@ fn basic_thaw_works() { fn thaw_when_issuance_higher_works() { new_test_ext().execute_with(|| { run_to_block(1); - assert_ok!(Gilt::place_bid(Origin::signed(1), 100, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 100, 1)); Gilt::enlarge(100, 1); // Everybody else's balances goes up by 50% @@ -333,7 +339,7 @@ fn thaw_when_issuance_higher_works() { Balances::make_free_balance_be(&4, 150); run_to_block(4); - assert_ok!(Gilt::thaw(Origin::signed(1), 0)); + assert_ok!(Gilt::thaw(RuntimeOrigin::signed(1), 0)); assert_eq!(Balances::free_balance(1), 150); assert_eq!(Balances::reserved_balance(1), 0); @@ -347,16 +353,16 @@ fn thaw_with_ignored_issuance_works() { // Give account zero some balance. Balances::make_free_balance_be(&0, 200); - assert_ok!(Gilt::place_bid(Origin::signed(1), 100, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 100, 1)); Gilt::enlarge(100, 1); // Account zero transfers 50 into everyone else's accounts. - assert_ok!(Balances::transfer(Origin::signed(0), 2, 50)); - assert_ok!(Balances::transfer(Origin::signed(0), 3, 50)); - assert_ok!(Balances::transfer(Origin::signed(0), 4, 50)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(0), 2, 50)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(0), 3, 50)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(0), 4, 50)); run_to_block(4); - assert_ok!(Gilt::thaw(Origin::signed(1), 0)); + assert_ok!(Gilt::thaw(RuntimeOrigin::signed(1), 0)); // Account zero changes have been ignored. assert_eq!(Balances::free_balance(1), 150); @@ -368,7 +374,7 @@ fn thaw_with_ignored_issuance_works() { fn thaw_when_issuance_lower_works() { new_test_ext().execute_with(|| { run_to_block(1); - assert_ok!(Gilt::place_bid(Origin::signed(1), 100, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 100, 1)); Gilt::enlarge(100, 1); // Everybody else's balances goes down by 25% @@ -377,7 +383,7 @@ fn thaw_when_issuance_lower_works() { Balances::make_free_balance_be(&4, 75); run_to_block(4); - assert_ok!(Gilt::thaw(Origin::signed(1), 0)); + assert_ok!(Gilt::thaw(RuntimeOrigin::signed(1), 0)); assert_eq!(Balances::free_balance(1), 75); assert_eq!(Balances::reserved_balance(1), 0); @@ -388,9 +394,9 @@ fn thaw_when_issuance_lower_works() { fn multiple_thaws_works() { new_test_ext().execute_with(|| { run_to_block(1); - assert_ok!(Gilt::place_bid(Origin::signed(1), 40, 1)); - assert_ok!(Gilt::place_bid(Origin::signed(1), 60, 1)); - assert_ok!(Gilt::place_bid(Origin::signed(2), 50, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 40, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 60, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(2), 50, 1)); Gilt::enlarge(200, 3); // Double everyone's free balances. @@ -399,9 +405,9 @@ fn multiple_thaws_works() { Balances::make_free_balance_be(&4, 200); run_to_block(4); - assert_ok!(Gilt::thaw(Origin::signed(1), 0)); - assert_ok!(Gilt::thaw(Origin::signed(1), 1)); - assert_ok!(Gilt::thaw(Origin::signed(2), 2)); + assert_ok!(Gilt::thaw(RuntimeOrigin::signed(1), 0)); + assert_ok!(Gilt::thaw(RuntimeOrigin::signed(1), 1)); + assert_ok!(Gilt::thaw(RuntimeOrigin::signed(2), 2)); assert_eq!(Balances::free_balance(1), 200); assert_eq!(Balances::free_balance(2), 200); @@ -412,9 +418,9 @@ fn multiple_thaws_works() { fn multiple_thaws_works_in_alternative_thaw_order() { new_test_ext().execute_with(|| { run_to_block(1); - assert_ok!(Gilt::place_bid(Origin::signed(1), 40, 1)); - assert_ok!(Gilt::place_bid(Origin::signed(1), 60, 1)); - assert_ok!(Gilt::place_bid(Origin::signed(2), 50, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 40, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 60, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(2), 50, 1)); Gilt::enlarge(200, 3); // Double everyone's free balances. @@ -423,9 +429,9 @@ fn multiple_thaws_works_in_alternative_thaw_order() { Balances::make_free_balance_be(&4, 200); run_to_block(4); - assert_ok!(Gilt::thaw(Origin::signed(2), 2)); - assert_ok!(Gilt::thaw(Origin::signed(1), 1)); - assert_ok!(Gilt::thaw(Origin::signed(1), 0)); + assert_ok!(Gilt::thaw(RuntimeOrigin::signed(2), 2)); + assert_ok!(Gilt::thaw(RuntimeOrigin::signed(1), 1)); + assert_ok!(Gilt::thaw(RuntimeOrigin::signed(1), 0)); assert_eq!(Balances::free_balance(1), 200); assert_eq!(Balances::free_balance(2), 200); @@ -436,12 +442,12 @@ fn multiple_thaws_works_in_alternative_thaw_order() { fn enlargement_to_target_works() { new_test_ext().execute_with(|| { run_to_block(2); - assert_ok!(Gilt::place_bid(Origin::signed(1), 40, 1)); - assert_ok!(Gilt::place_bid(Origin::signed(1), 40, 2)); - assert_ok!(Gilt::place_bid(Origin::signed(2), 40, 2)); - assert_ok!(Gilt::place_bid(Origin::signed(2), 40, 3)); - assert_ok!(Gilt::place_bid(Origin::signed(3), 40, 3)); - assert_ok!(Gilt::set_target(Origin::signed(1), Perquintill::from_percent(40))); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 40, 1)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(1), 40, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(2), 40, 2)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(2), 40, 3)); + assert_ok!(Gilt::place_bid(RuntimeOrigin::signed(3), 40, 3)); + assert_ok!(Gilt::set_target(RuntimeOrigin::signed(1), Perquintill::from_percent(40))); run_to_block(3); assert_eq!(Queues::::get(1), vec![GiltBid { amount: 40, who: 1 },]); @@ -540,7 +546,7 @@ fn enlargement_to_target_works() { ); // Set target a bit higher to use up the remaining bid. - assert_ok!(Gilt::set_target(Origin::signed(1), Perquintill::from_percent(60))); + assert_ok!(Gilt::set_target(RuntimeOrigin::signed(1), Perquintill::from_percent(60))); run_to_block(10); // Two new gilts should have been issued to 1 & 2 for 40 each & duration of 2. diff --git a/frame/grandpa/src/mock.rs b/frame/grandpa/src/mock.rs index 19caf0766a3e0..573a74d2bfae8 100644 --- a/frame/grandpa/src/mock.rs +++ b/frame/grandpa/src/mock.rs @@ -79,7 +79,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; @@ -208,6 +208,7 @@ impl pallet_staking::Config for Test { type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; + type HistoryDepth = ConstU32<84>; type OnStakerSlash = (); type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; type WeightInfo = (); diff --git a/frame/grandpa/src/tests.rs b/frame/grandpa/src/tests.rs index baf71dfff71dc..775eda58c03e0 100644 --- a/frame/grandpa/src/tests.rs +++ b/frame/grandpa/src/tests.rs @@ -359,7 +359,7 @@ fn report_equivocation_current_set_works() { // report the equivocation and the tx should be dispatched successfully assert_ok!(Grandpa::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof), key_owner_proof, ),); @@ -437,7 +437,7 @@ fn report_equivocation_old_set_works() { // report the equivocation using the key ownership proof generated on // the old set, the tx should be dispatched successfully assert_ok!(Grandpa::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof), key_owner_proof, ),); @@ -500,7 +500,7 @@ fn report_equivocation_invalid_set_id() { // the call for reporting the equivocation should error assert_err!( Grandpa::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof), key_owner_proof, ), @@ -541,7 +541,7 @@ fn report_equivocation_invalid_session() { // proof from the previous set, the session should be invalid. assert_err!( Grandpa::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof), key_owner_proof, ), @@ -586,7 +586,7 @@ fn report_equivocation_invalid_key_owner_proof() { // proof for a different key than the one in the equivocation proof. assert_err!( Grandpa::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof), invalid_key_owner_proof, ), @@ -617,7 +617,7 @@ fn report_equivocation_invalid_equivocation_proof() { let assert_invalid_equivocation_proof = |equivocation_proof| { assert_err!( Grandpa::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof), key_owner_proof.clone(), ), @@ -723,7 +723,7 @@ fn report_equivocation_validate_unsigned_prevents_duplicates() { // we submit the report Grandpa::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof), key_owner_proof, ) @@ -861,7 +861,7 @@ fn valid_equivocation_reports_dont_pay_fees() { // report the equivocation. let post_info = Grandpa::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof.clone()), key_owner_proof.clone(), ) @@ -875,7 +875,7 @@ fn valid_equivocation_reports_dont_pay_fees() { // report the equivocation again which is invalid now since it is // duplicate. let post_info = Grandpa::report_equivocation_unsigned( - Origin::none(), + RuntimeOrigin::none(), Box::new(equivocation_proof), key_owner_proof, ) diff --git a/frame/identity/src/benchmarking.rs b/frame/identity/src/benchmarking.rs index 7ab5d416eb533..c66658b92b0d2 100644 --- a/frame/identity/src/benchmarking.rs +++ b/frame/identity/src/benchmarking.rs @@ -123,7 +123,7 @@ benchmarks! { ensure!(Registrars::::get().len() as u32 == r, "Registrars not set up correctly."); let origin = T::RegistrarOrigin::successful_origin(); let account = T::Lookup::unlookup(account("registrar", r + 1, SEED)); - }: _(origin, account) + }: _(origin, account) verify { ensure!(Registrars::::get().len() as u32 == r + 1, "Registrars not added."); } @@ -135,7 +135,7 @@ benchmarks! { // The target user let caller: T::AccountId = whitelisted_caller(); let caller_lookup = T::Lookup::unlookup(caller.clone()); - let caller_origin: ::Origin = RawOrigin::Signed(caller.clone()).into(); + let caller_origin: ::RuntimeOrigin = RawOrigin::Signed(caller.clone()).into(); let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); // Add an initial identity @@ -193,7 +193,7 @@ benchmarks! { clear_identity { let caller: T::AccountId = whitelisted_caller(); - let caller_origin = ::Origin::from(RawOrigin::Signed(caller.clone())); + let caller_origin = ::RuntimeOrigin::from(RawOrigin::Signed(caller.clone())); let caller_lookup = ::unlookup(caller.clone()); let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); @@ -208,7 +208,7 @@ benchmarks! { // Create their main identity with x additional fields let info = create_identity_info::(x); let caller: T::AccountId = whitelisted_caller(); - let caller_origin = ::Origin::from(RawOrigin::Signed(caller.clone())); + let caller_origin = ::RuntimeOrigin::from(RawOrigin::Signed(caller.clone())); Identity::::set_identity(caller_origin.clone(), Box::new(info.clone()))?; // User requests judgement from all the registrars, and they approve @@ -237,7 +237,7 @@ benchmarks! { // Create their main identity with x additional fields let info = create_identity_info::(x); let caller: T::AccountId = whitelisted_caller(); - let caller_origin = ::Origin::from(RawOrigin::Signed(caller)); + let caller_origin = ::RuntimeOrigin::from(RawOrigin::Signed(caller)); Identity::::set_identity(caller_origin, Box::new(info))?; }; }: _(RawOrigin::Signed(caller.clone()), r - 1, 10u32.into()) @@ -247,7 +247,7 @@ benchmarks! { cancel_request { let caller: T::AccountId = whitelisted_caller(); - let caller_origin = ::Origin::from(RawOrigin::Signed(caller.clone())); + let caller_origin = ::RuntimeOrigin::from(RawOrigin::Signed(caller.clone())); let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); let r in 1 .. T::MaxRegistrars::get() => add_registrars::(r)?; @@ -255,7 +255,7 @@ benchmarks! { // Create their main identity with x additional fields let info = create_identity_info::(x); let caller: T::AccountId = whitelisted_caller(); - let caller_origin = ::Origin::from(RawOrigin::Signed(caller)); + let caller_origin = ::RuntimeOrigin::from(RawOrigin::Signed(caller)); Identity::::set_identity(caller_origin, Box::new(info))?; }; @@ -323,7 +323,7 @@ benchmarks! { provide_judgement { // The user let user: T::AccountId = account("user", r, SEED); - let user_origin = ::Origin::from(RawOrigin::Signed(user.clone())); + let user_origin = ::RuntimeOrigin::from(RawOrigin::Signed(user.clone())); let user_lookup = ::unlookup(user.clone()); let _ = T::Currency::make_free_balance_be(&user, BalanceOf::::max_value()); @@ -352,7 +352,7 @@ benchmarks! { let x in 1 .. T::MaxAdditionalFields::get(); let target: T::AccountId = account("target", 0, SEED); - let target_origin: ::Origin = RawOrigin::Signed(target.clone()).into(); + let target_origin: ::RuntimeOrigin = RawOrigin::Signed(target.clone()).into(); let target_lookup = T::Lookup::unlookup(target.clone()); let _ = T::Currency::make_free_balance_be(&target, BalanceOf::::max_value()); @@ -373,7 +373,7 @@ benchmarks! { } ensure!(IdentityOf::::contains_key(&target), "Identity not set"); let origin = T::ForceOrigin::successful_origin(); - }: _(origin, target_lookup) + }: _(origin, target_lookup) verify { ensure!(!IdentityOf::::contains_key(&target), "Identity not removed"); } diff --git a/frame/identity/src/lib.rs b/frame/identity/src/lib.rs index c4f35a06e830a..8b22ecedaec19 100644 --- a/frame/identity/src/lib.rs +++ b/frame/identity/src/lib.rs @@ -142,10 +142,10 @@ pub mod pallet { type Slashed: OnUnbalanced>; /// The origin which may forcibly set or remove a name. Root can always do this. - type ForceOrigin: EnsureOrigin; + type ForceOrigin: EnsureOrigin; /// The origin which may add or remove registrars. Root can always do this. - type RegistrarOrigin: EnsureOrigin; + type RegistrarOrigin: EnsureOrigin; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; diff --git a/frame/identity/src/tests.rs b/frame/identity/src/tests.rs index 0fb5d4587af16..747d1e9f27106 100644 --- a/frame/identity/src/tests.rs +++ b/frame/identity/src/tests.rs @@ -56,7 +56,7 @@ impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); type BlockLength = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = H256; @@ -148,41 +148,44 @@ fn editing_subaccounts_should_work() { new_test_ext().execute_with(|| { let data = |x| Data::Raw(vec![x; 1].try_into().unwrap()); - assert_noop!(Identity::add_sub(Origin::signed(10), 20, data(1)), Error::::NoIdentity); + assert_noop!( + Identity::add_sub(RuntimeOrigin::signed(10), 20, data(1)), + Error::::NoIdentity + ); - assert_ok!(Identity::set_identity(Origin::signed(10), Box::new(ten()))); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten()))); // first sub account - assert_ok!(Identity::add_sub(Origin::signed(10), 1, data(1))); + assert_ok!(Identity::add_sub(RuntimeOrigin::signed(10), 1, data(1))); assert_eq!(SuperOf::::get(1), Some((10, data(1)))); assert_eq!(Balances::free_balance(10), 80); // second sub account - assert_ok!(Identity::add_sub(Origin::signed(10), 2, data(2))); + assert_ok!(Identity::add_sub(RuntimeOrigin::signed(10), 2, data(2))); assert_eq!(SuperOf::::get(1), Some((10, data(1)))); assert_eq!(SuperOf::::get(2), Some((10, data(2)))); assert_eq!(Balances::free_balance(10), 70); // third sub account is too many assert_noop!( - Identity::add_sub(Origin::signed(10), 3, data(3)), + Identity::add_sub(RuntimeOrigin::signed(10), 3, data(3)), Error::::TooManySubAccounts ); // rename first sub account - assert_ok!(Identity::rename_sub(Origin::signed(10), 1, data(11))); + assert_ok!(Identity::rename_sub(RuntimeOrigin::signed(10), 1, data(11))); assert_eq!(SuperOf::::get(1), Some((10, data(11)))); assert_eq!(SuperOf::::get(2), Some((10, data(2)))); assert_eq!(Balances::free_balance(10), 70); // remove first sub account - assert_ok!(Identity::remove_sub(Origin::signed(10), 1)); + assert_ok!(Identity::remove_sub(RuntimeOrigin::signed(10), 1)); assert_eq!(SuperOf::::get(1), None); assert_eq!(SuperOf::::get(2), Some((10, data(2)))); assert_eq!(Balances::free_balance(10), 80); // add third sub account - assert_ok!(Identity::add_sub(Origin::signed(10), 3, data(3))); + assert_ok!(Identity::add_sub(RuntimeOrigin::signed(10), 3, data(3))); assert_eq!(SuperOf::::get(1), None); assert_eq!(SuperOf::::get(2), Some((10, data(2)))); assert_eq!(SuperOf::::get(3), Some((10, data(3)))); @@ -195,27 +198,27 @@ fn resolving_subaccount_ownership_works() { new_test_ext().execute_with(|| { let data = |x| Data::Raw(vec![x; 1].try_into().unwrap()); - assert_ok!(Identity::set_identity(Origin::signed(10), Box::new(ten()))); - assert_ok!(Identity::set_identity(Origin::signed(20), Box::new(twenty()))); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten()))); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(20), Box::new(twenty()))); // 10 claims 1 as a subaccount - assert_ok!(Identity::add_sub(Origin::signed(10), 1, data(1))); + assert_ok!(Identity::add_sub(RuntimeOrigin::signed(10), 1, data(1))); assert_eq!(Balances::free_balance(1), 10); assert_eq!(Balances::free_balance(10), 80); assert_eq!(Balances::reserved_balance(10), 20); // 20 cannot claim 1 now assert_noop!( - Identity::add_sub(Origin::signed(20), 1, data(1)), + Identity::add_sub(RuntimeOrigin::signed(20), 1, data(1)), Error::::AlreadyClaimed ); // 1 wants to be with 20 so it quits from 10 - assert_ok!(Identity::quit_sub(Origin::signed(1))); + assert_ok!(Identity::quit_sub(RuntimeOrigin::signed(1))); // 1 gets the 10 that 10 paid. assert_eq!(Balances::free_balance(1), 20); assert_eq!(Balances::free_balance(10), 80); assert_eq!(Balances::reserved_balance(10), 10); // 20 can claim 1 now - assert_ok!(Identity::add_sub(Origin::signed(20), 1, data(1))); + assert_ok!(Identity::add_sub(RuntimeOrigin::signed(20), 1, data(1))); }); } @@ -232,10 +235,10 @@ fn trailing_zeros_decodes_into_default_data() { #[test] fn adding_registrar_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Identity::add_registrar(Origin::signed(1), 3)); - assert_ok!(Identity::set_fee(Origin::signed(3), 0, 10)); + assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), 3)); + assert_ok!(Identity::set_fee(RuntimeOrigin::signed(3), 0, 10)); let fields = IdentityFields(IdentityField::Display | IdentityField::Legal); - assert_ok!(Identity::set_fields(Origin::signed(3), 0, fields)); + assert_ok!(Identity::set_fields(RuntimeOrigin::signed(3), 0, fields)); assert_eq!( Identity::registrars(), vec![Some(RegistrarInfo { account: 3, fee: 10, fields })] @@ -247,11 +250,11 @@ fn adding_registrar_should_work() { fn amount_of_registrars_is_limited() { new_test_ext().execute_with(|| { for i in 1..MaxRegistrars::get() + 1 { - assert_ok!(Identity::add_registrar(Origin::signed(1), i as u64)); + assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), i as u64)); } let last_registrar = MaxRegistrars::get() as u64 + 1; assert_noop!( - Identity::add_registrar(Origin::signed(1), last_registrar), + Identity::add_registrar(RuntimeOrigin::signed(1), last_registrar), Error::::TooManyRegistrars ); }); @@ -260,18 +263,18 @@ fn amount_of_registrars_is_limited() { #[test] fn registration_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Identity::add_registrar(Origin::signed(1), 3)); - assert_ok!(Identity::set_fee(Origin::signed(3), 0, 10)); + assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), 3)); + assert_ok!(Identity::set_fee(RuntimeOrigin::signed(3), 0, 10)); let mut three_fields = ten(); three_fields.additional.try_push(Default::default()).unwrap(); three_fields.additional.try_push(Default::default()).unwrap(); assert_eq!(three_fields.additional.try_push(Default::default()), Err(())); - assert_ok!(Identity::set_identity(Origin::signed(10), Box::new(ten()))); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten()))); assert_eq!(Identity::identity(10).unwrap().info, ten()); assert_eq!(Balances::free_balance(10), 90); - assert_ok!(Identity::clear_identity(Origin::signed(10))); + assert_ok!(Identity::clear_identity(RuntimeOrigin::signed(10))); assert_eq!(Balances::free_balance(10), 100); - assert_noop!(Identity::clear_identity(Origin::signed(10)), Error::::NotNamed); + assert_noop!(Identity::clear_identity(RuntimeOrigin::signed(10)), Error::::NotNamed); }); } @@ -280,7 +283,7 @@ fn uninvited_judgement_should_work() { new_test_ext().execute_with(|| { assert_noop!( Identity::provide_judgement( - Origin::signed(3), + RuntimeOrigin::signed(3), 0, 10, Judgement::Reasonable, @@ -289,10 +292,10 @@ fn uninvited_judgement_should_work() { Error::::InvalidIndex ); - assert_ok!(Identity::add_registrar(Origin::signed(1), 3)); + assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), 3)); assert_noop!( Identity::provide_judgement( - Origin::signed(3), + RuntimeOrigin::signed(3), 0, 10, Judgement::Reasonable, @@ -301,10 +304,10 @@ fn uninvited_judgement_should_work() { Error::::InvalidTarget ); - assert_ok!(Identity::set_identity(Origin::signed(10), Box::new(ten()))); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten()))); assert_noop!( Identity::provide_judgement( - Origin::signed(3), + RuntimeOrigin::signed(3), 0, 10, Judgement::Reasonable, @@ -317,7 +320,7 @@ fn uninvited_judgement_should_work() { assert_noop!( Identity::provide_judgement( - Origin::signed(10), + RuntimeOrigin::signed(10), 0, 10, Judgement::Reasonable, @@ -327,7 +330,7 @@ fn uninvited_judgement_should_work() { ); assert_noop!( Identity::provide_judgement( - Origin::signed(3), + RuntimeOrigin::signed(3), 0, 10, Judgement::FeePaid(1), @@ -337,7 +340,7 @@ fn uninvited_judgement_should_work() { ); assert_ok!(Identity::provide_judgement( - Origin::signed(3), + RuntimeOrigin::signed(3), 0, 10, Judgement::Reasonable, @@ -350,16 +353,16 @@ fn uninvited_judgement_should_work() { #[test] fn clearing_judgement_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Identity::add_registrar(Origin::signed(1), 3)); - assert_ok!(Identity::set_identity(Origin::signed(10), Box::new(ten()))); + assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), 3)); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten()))); assert_ok!(Identity::provide_judgement( - Origin::signed(3), + RuntimeOrigin::signed(3), 0, 10, Judgement::Reasonable, BlakeTwo256::hash_of(&ten()) )); - assert_ok!(Identity::clear_identity(Origin::signed(10))); + assert_ok!(Identity::clear_identity(RuntimeOrigin::signed(10))); assert_eq!(Identity::identity(10), None); }); } @@ -367,12 +370,15 @@ fn clearing_judgement_should_work() { #[test] fn killing_slashing_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Identity::set_identity(Origin::signed(10), Box::new(ten()))); - assert_noop!(Identity::kill_identity(Origin::signed(1), 10), BadOrigin); - assert_ok!(Identity::kill_identity(Origin::signed(2), 10)); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten()))); + assert_noop!(Identity::kill_identity(RuntimeOrigin::signed(1), 10), BadOrigin); + assert_ok!(Identity::kill_identity(RuntimeOrigin::signed(2), 10)); assert_eq!(Identity::identity(10), None); assert_eq!(Balances::free_balance(10), 90); - assert_noop!(Identity::kill_identity(Origin::signed(2), 10), Error::::NotNamed); + assert_noop!( + Identity::kill_identity(RuntimeOrigin::signed(2), 10), + Error::::NotNamed + ); }); } @@ -380,17 +386,20 @@ fn killing_slashing_should_work() { fn setting_subaccounts_should_work() { new_test_ext().execute_with(|| { let mut subs = vec![(20, Data::Raw(vec![40; 1].try_into().unwrap()))]; - assert_noop!(Identity::set_subs(Origin::signed(10), subs.clone()), Error::::NotFound); + assert_noop!( + Identity::set_subs(RuntimeOrigin::signed(10), subs.clone()), + Error::::NotFound + ); - assert_ok!(Identity::set_identity(Origin::signed(10), Box::new(ten()))); - assert_ok!(Identity::set_subs(Origin::signed(10), subs.clone())); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten()))); + assert_ok!(Identity::set_subs(RuntimeOrigin::signed(10), subs.clone())); assert_eq!(Balances::free_balance(10), 80); assert_eq!(Identity::subs_of(10), (10, vec![20].try_into().unwrap())); assert_eq!(Identity::super_of(20), Some((10, Data::Raw(vec![40; 1].try_into().unwrap())))); // push another item and re-set it. subs.push((30, Data::Raw(vec![50; 1].try_into().unwrap()))); - assert_ok!(Identity::set_subs(Origin::signed(10), subs.clone())); + assert_ok!(Identity::set_subs(RuntimeOrigin::signed(10), subs.clone())); assert_eq!(Balances::free_balance(10), 70); assert_eq!(Identity::subs_of(10), (20, vec![20, 30].try_into().unwrap())); assert_eq!(Identity::super_of(20), Some((10, Data::Raw(vec![40; 1].try_into().unwrap())))); @@ -398,7 +407,7 @@ fn setting_subaccounts_should_work() { // switch out one of the items and re-set. subs[0] = (40, Data::Raw(vec![60; 1].try_into().unwrap())); - assert_ok!(Identity::set_subs(Origin::signed(10), subs.clone())); + assert_ok!(Identity::set_subs(RuntimeOrigin::signed(10), subs.clone())); assert_eq!(Balances::free_balance(10), 70); // no change in the balance assert_eq!(Identity::subs_of(10), (20, vec![40, 30].try_into().unwrap())); assert_eq!(Identity::super_of(20), None); @@ -406,7 +415,7 @@ fn setting_subaccounts_should_work() { assert_eq!(Identity::super_of(40), Some((10, Data::Raw(vec![60; 1].try_into().unwrap())))); // clear - assert_ok!(Identity::set_subs(Origin::signed(10), vec![])); + assert_ok!(Identity::set_subs(RuntimeOrigin::signed(10), vec![])); assert_eq!(Balances::free_balance(10), 90); assert_eq!(Identity::subs_of(10), (0, BoundedVec::default())); assert_eq!(Identity::super_of(30), None); @@ -414,7 +423,7 @@ fn setting_subaccounts_should_work() { subs.push((20, Data::Raw(vec![40; 1].try_into().unwrap()))); assert_noop!( - Identity::set_subs(Origin::signed(10), subs.clone()), + Identity::set_subs(RuntimeOrigin::signed(10), subs.clone()), Error::::TooManySubAccounts ); }); @@ -423,12 +432,12 @@ fn setting_subaccounts_should_work() { #[test] fn clearing_account_should_remove_subaccounts_and_refund() { new_test_ext().execute_with(|| { - assert_ok!(Identity::set_identity(Origin::signed(10), Box::new(ten()))); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten()))); assert_ok!(Identity::set_subs( - Origin::signed(10), + RuntimeOrigin::signed(10), vec![(20, Data::Raw(vec![40; 1].try_into().unwrap()))] )); - assert_ok!(Identity::clear_identity(Origin::signed(10))); + assert_ok!(Identity::clear_identity(RuntimeOrigin::signed(10))); assert_eq!(Balances::free_balance(10), 100); assert!(Identity::super_of(20).is_none()); }); @@ -437,12 +446,12 @@ fn clearing_account_should_remove_subaccounts_and_refund() { #[test] fn killing_account_should_remove_subaccounts_and_not_refund() { new_test_ext().execute_with(|| { - assert_ok!(Identity::set_identity(Origin::signed(10), Box::new(ten()))); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten()))); assert_ok!(Identity::set_subs( - Origin::signed(10), + RuntimeOrigin::signed(10), vec![(20, Data::Raw(vec![40; 1].try_into().unwrap()))] )); - assert_ok!(Identity::kill_identity(Origin::signed(2), 10)); + assert_ok!(Identity::kill_identity(RuntimeOrigin::signed(2), 10)); assert_eq!(Balances::free_balance(10), 80); assert!(Identity::super_of(20).is_none()); }); @@ -451,24 +460,30 @@ fn killing_account_should_remove_subaccounts_and_not_refund() { #[test] fn cancelling_requested_judgement_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Identity::add_registrar(Origin::signed(1), 3)); - assert_ok!(Identity::set_fee(Origin::signed(3), 0, 10)); - assert_noop!(Identity::cancel_request(Origin::signed(10), 0), Error::::NoIdentity); - assert_ok!(Identity::set_identity(Origin::signed(10), Box::new(ten()))); - assert_ok!(Identity::request_judgement(Origin::signed(10), 0, 10)); - assert_ok!(Identity::cancel_request(Origin::signed(10), 0)); + assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), 3)); + assert_ok!(Identity::set_fee(RuntimeOrigin::signed(3), 0, 10)); + assert_noop!( + Identity::cancel_request(RuntimeOrigin::signed(10), 0), + Error::::NoIdentity + ); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten()))); + assert_ok!(Identity::request_judgement(RuntimeOrigin::signed(10), 0, 10)); + assert_ok!(Identity::cancel_request(RuntimeOrigin::signed(10), 0)); assert_eq!(Balances::free_balance(10), 90); - assert_noop!(Identity::cancel_request(Origin::signed(10), 0), Error::::NotFound); + assert_noop!( + Identity::cancel_request(RuntimeOrigin::signed(10), 0), + Error::::NotFound + ); assert_ok!(Identity::provide_judgement( - Origin::signed(3), + RuntimeOrigin::signed(3), 0, 10, Judgement::Reasonable, BlakeTwo256::hash_of(&ten()) )); assert_noop!( - Identity::cancel_request(Origin::signed(10), 0), + Identity::cancel_request(RuntimeOrigin::signed(10), 0), Error::::JudgementGiven ); }); @@ -477,24 +492,24 @@ fn cancelling_requested_judgement_should_work() { #[test] fn requesting_judgement_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Identity::add_registrar(Origin::signed(1), 3)); - assert_ok!(Identity::set_fee(Origin::signed(3), 0, 10)); - assert_ok!(Identity::set_identity(Origin::signed(10), Box::new(ten()))); + assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), 3)); + assert_ok!(Identity::set_fee(RuntimeOrigin::signed(3), 0, 10)); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten()))); assert_noop!( - Identity::request_judgement(Origin::signed(10), 0, 9), + Identity::request_judgement(RuntimeOrigin::signed(10), 0, 9), Error::::FeeChanged ); - assert_ok!(Identity::request_judgement(Origin::signed(10), 0, 10)); + assert_ok!(Identity::request_judgement(RuntimeOrigin::signed(10), 0, 10)); // 10 for the judgement request, 10 for the identity. assert_eq!(Balances::free_balance(10), 80); // Re-requesting won't work as we already paid. assert_noop!( - Identity::request_judgement(Origin::signed(10), 0, 10), + Identity::request_judgement(RuntimeOrigin::signed(10), 0, 10), Error::::StickyJudgement ); assert_ok!(Identity::provide_judgement( - Origin::signed(3), + RuntimeOrigin::signed(3), 0, 10, Judgement::Erroneous, @@ -505,33 +520,33 @@ fn requesting_judgement_should_work() { // Re-requesting still won't work as it's erroneous. assert_noop!( - Identity::request_judgement(Origin::signed(10), 0, 10), + Identity::request_judgement(RuntimeOrigin::signed(10), 0, 10), Error::::StickyJudgement ); // Requesting from a second registrar still works. - assert_ok!(Identity::add_registrar(Origin::signed(1), 4)); - assert_ok!(Identity::request_judgement(Origin::signed(10), 1, 10)); + assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), 4)); + assert_ok!(Identity::request_judgement(RuntimeOrigin::signed(10), 1, 10)); // Re-requesting after the judgement has been reduced works. assert_ok!(Identity::provide_judgement( - Origin::signed(3), + RuntimeOrigin::signed(3), 0, 10, Judgement::OutOfDate, BlakeTwo256::hash_of(&ten()) )); - assert_ok!(Identity::request_judgement(Origin::signed(10), 0, 10)); + assert_ok!(Identity::request_judgement(RuntimeOrigin::signed(10), 0, 10)); }); } #[test] fn field_deposit_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Identity::add_registrar(Origin::signed(1), 3)); - assert_ok!(Identity::set_fee(Origin::signed(3), 0, 10)); + assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), 3)); + assert_ok!(Identity::set_fee(RuntimeOrigin::signed(3), 0, 10)); assert_ok!(Identity::set_identity( - Origin::signed(10), + RuntimeOrigin::signed(10), Box::new(IdentityInfo { additional: vec![ ( @@ -555,23 +570,23 @@ fn field_deposit_should_work() { #[test] fn setting_account_id_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Identity::add_registrar(Origin::signed(1), 3)); + assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), 3)); // account 4 cannot change the first registrar's identity since it's owned by 3. assert_noop!( - Identity::set_account_id(Origin::signed(4), 0, 3), + Identity::set_account_id(RuntimeOrigin::signed(4), 0, 3), Error::::InvalidIndex ); // account 3 can, because that's the registrar's current account. - assert_ok!(Identity::set_account_id(Origin::signed(3), 0, 4)); + assert_ok!(Identity::set_account_id(RuntimeOrigin::signed(3), 0, 4)); // account 4 can now, because that's their new ID. - assert_ok!(Identity::set_account_id(Origin::signed(4), 0, 3)); + assert_ok!(Identity::set_account_id(RuntimeOrigin::signed(4), 0, 3)); }); } #[test] fn test_has_identity() { new_test_ext().execute_with(|| { - assert_ok!(Identity::set_identity(Origin::signed(10), Box::new(ten()))); + assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten()))); assert!(Identity::has_identity(&10, IdentityField::Display as u64)); assert!(Identity::has_identity(&10, IdentityField::Legal as u64)); assert!(Identity::has_identity( diff --git a/frame/im-online/src/mock.rs b/frame/im-online/src/mock.rs index a193843a3d661..5782e1a615b8e 100644 --- a/frame/im-online/src/mock.rs +++ b/frame/im-online/src/mock.rs @@ -111,7 +111,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { result.execute_with(|| { for i in 1..=6 { System::inc_providers(&i); - assert_eq!(Session::set_keys(Origin::signed(i), (i - 1).into(), vec![]), Ok(())); + assert_eq!(Session::set_keys(RuntimeOrigin::signed(i), (i - 1).into(), vec![]), Ok(())); } }); result @@ -127,7 +127,7 @@ impl frame_system::Config for Runtime { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; diff --git a/frame/im-online/src/tests.rs b/frame/im-online/src/tests.rs index e6154a634f4a4..366119278d836 100644 --- a/frame/im-online/src/tests.rs +++ b/frame/im-online/src/tests.rs @@ -141,7 +141,7 @@ fn heartbeat( "invalid validators len", e @ _ => <&'static str>::from(e), })?; - ImOnline::heartbeat(Origin::none(), heartbeat, signature) + ImOnline::heartbeat(RuntimeOrigin::none(), heartbeat, signature) } #[test] diff --git a/frame/indices/src/mock.rs b/frame/indices/src/mock.rs index 255080f345eee..fd2e9fff16885 100644 --- a/frame/indices/src/mock.rs +++ b/frame/indices/src/mock.rs @@ -52,7 +52,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = u64; diff --git a/frame/indices/src/tests.rs b/frame/indices/src/tests.rs index 4e6c59703ca36..bed6cfffaa825 100644 --- a/frame/indices/src/tests.rs +++ b/frame/indices/src/tests.rs @@ -104,7 +104,7 @@ fn transfer_index_on_accounts_should_work() { fn force_transfer_index_on_preowned_should_work() { new_test_ext().execute_with(|| { assert_ok!(Indices::claim(Some(1).into(), 0)); - assert_ok!(Indices::force_transfer(Origin::root(), Id(3), 0, false)); + assert_ok!(Indices::force_transfer(RuntimeOrigin::root(), Id(3), 0, false)); assert_eq!(Balances::reserved_balance(1), 0); assert_eq!(Balances::reserved_balance(3), 0); assert_eq!(Indices::lookup_index(0), Some(3)); @@ -114,7 +114,7 @@ fn force_transfer_index_on_preowned_should_work() { #[test] fn force_transfer_index_on_free_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Indices::force_transfer(Origin::root(), Id(3), 0, false)); + assert_ok!(Indices::force_transfer(RuntimeOrigin::root(), Id(3), 0, false)); assert_eq!(Balances::reserved_balance(3), 0); assert_eq!(Indices::lookup_index(0), Some(3)); }); diff --git a/frame/lottery/src/benchmarking.rs b/frame/lottery/src/benchmarking.rs index 1c850e66f9c6e..fba722a07fabd 100644 --- a/frame/lottery/src/benchmarking.rs +++ b/frame/lottery/src/benchmarking.rs @@ -78,7 +78,7 @@ benchmarks! { let calls = vec![frame_system::Call::::remark { remark: vec![] }.into(); n as usize]; let origin = T::ManagerOrigin::successful_origin(); assert!(CallIndices::::get().is_empty()); - }: _(origin, calls) + }: _(origin, calls) verify { if !n.is_zero() { assert!(!CallIndices::::get().is_empty()); @@ -90,7 +90,7 @@ benchmarks! { let end = 10u32.into(); let payout = 5u32.into(); let origin = T::ManagerOrigin::successful_origin(); - }: _(origin, price, end, payout, true) + }: _(origin, price, end, payout, true) verify { assert!(crate::Lottery::::get().is_some()); } @@ -99,7 +99,7 @@ benchmarks! { setup_lottery::(true)?; assert_eq!(crate::Lottery::::get().unwrap().repeat, true); let origin = T::ManagerOrigin::successful_origin(); - }: _(origin) + }: _(origin) verify { assert_eq!(crate::Lottery::::get().unwrap().repeat, false); } diff --git a/frame/lottery/src/lib.rs b/frame/lottery/src/lib.rs index 505dd1bb98caa..c501a30ef5f4a 100644 --- a/frame/lottery/src/lib.rs +++ b/frame/lottery/src/lib.rs @@ -135,7 +135,7 @@ pub mod pallet { /// A dispatchable call. type RuntimeCall: Parameter - + Dispatchable + + Dispatchable + GetDispatchInfo + From>; @@ -149,7 +149,7 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// The manager origin. - type ManagerOrigin: EnsureOrigin; + type ManagerOrigin: EnsureOrigin; /// The max number of calls available in a single lottery. #[pallet::constant] diff --git a/frame/lottery/src/mock.rs b/frame/lottery/src/mock.rs index b521b83e7ce2b..1977da5959d39 100644 --- a/frame/lottery/src/mock.rs +++ b/frame/lottery/src/mock.rs @@ -57,7 +57,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type RuntimeCall = RuntimeCall; type BlockNumber = u64; diff --git a/frame/lottery/src/tests.rs b/frame/lottery/src/tests.rs index ff3111b52db77..0eaf080564008 100644 --- a/frame/lottery/src/tests.rs +++ b/frame/lottery/src/tests.rs @@ -20,8 +20,8 @@ use super::*; use frame_support::{assert_noop, assert_ok, assert_storage_noop}; use mock::{ - new_test_ext, run_to_block, Balances, BalancesCall, Lottery, Origin, RuntimeCall, SystemCall, - Test, + new_test_ext, run_to_block, Balances, BalancesCall, Lottery, RuntimeCall, RuntimeOrigin, + SystemCall, Test, }; use pallet_balances::Error as BalancesError; use sp_runtime::traits::BadOrigin; @@ -49,15 +49,15 @@ fn basic_end_to_end_works() { ]; // Set calls for the lottery - assert_ok!(Lottery::set_calls(Origin::root(), calls)); + assert_ok!(Lottery::set_calls(RuntimeOrigin::root(), calls)); // Start lottery, it repeats - assert_ok!(Lottery::start_lottery(Origin::root(), price, length, delay, true)); + assert_ok!(Lottery::start_lottery(RuntimeOrigin::root(), price, length, delay, true)); assert!(crate::Lottery::::get().is_some()); assert_eq!(Balances::free_balance(&1), 100); let call = Box::new(RuntimeCall::Balances(BalancesCall::transfer { dest: 2, value: 20 })); - assert_ok!(Lottery::buy_ticket(Origin::signed(1), call.clone())); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(1), call.clone())); // 20 from the transfer, 10 from buying a ticket assert_eq!(Balances::free_balance(&1), 100 - 20 - 10); assert_eq!(Participants::::get(&1).1.len(), 1); @@ -66,14 +66,14 @@ fn basic_end_to_end_works() { assert_eq!(Tickets::::get(0), Some(1)); // More ticket purchases - assert_ok!(Lottery::buy_ticket(Origin::signed(2), call.clone())); - assert_ok!(Lottery::buy_ticket(Origin::signed(3), call.clone())); - assert_ok!(Lottery::buy_ticket(Origin::signed(4), call.clone())); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(2), call.clone())); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(3), call.clone())); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(4), call.clone())); assert_eq!(TicketsCount::::get(), 4); // Go to end run_to_block(20); - assert_ok!(Lottery::buy_ticket(Origin::signed(5), call.clone())); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(5), call.clone())); // Ticket isn't bought assert_eq!(TicketsCount::::get(), 4); @@ -100,15 +100,15 @@ fn stop_repeat_works() { let delay = 5; // Set no calls for the lottery. - assert_ok!(Lottery::set_calls(Origin::root(), vec![])); + assert_ok!(Lottery::set_calls(RuntimeOrigin::root(), vec![])); // Start lottery, it repeats. - assert_ok!(Lottery::start_lottery(Origin::root(), price, length, delay, true)); + assert_ok!(Lottery::start_lottery(RuntimeOrigin::root(), price, length, delay, true)); // Non-manager fails to `stop_repeat`. - assert_noop!(Lottery::stop_repeat(Origin::signed(1)), DispatchError::BadOrigin); + assert_noop!(Lottery::stop_repeat(RuntimeOrigin::signed(1)), DispatchError::BadOrigin); // Manager can `stop_repeat`, even twice. - assert_ok!(Lottery::stop_repeat(Origin::root())); - assert_ok!(Lottery::stop_repeat(Origin::root())); + assert_ok!(Lottery::stop_repeat(RuntimeOrigin::root())); + assert_ok!(Lottery::stop_repeat(RuntimeOrigin::root())); // Lottery still exists. assert!(crate::Lottery::::get().is_some()); @@ -132,7 +132,7 @@ fn set_calls_works() { RuntimeCall::Balances(BalancesCall::transfer { dest: 0, value: 0 }), ]; - assert_ok!(Lottery::set_calls(Origin::root(), calls)); + assert_ok!(Lottery::set_calls(RuntimeOrigin::root(), calls)); assert!(CallIndices::::exists()); let too_many_calls = vec![ @@ -142,12 +142,12 @@ fn set_calls_works() { ]; assert_noop!( - Lottery::set_calls(Origin::root(), too_many_calls), + Lottery::set_calls(RuntimeOrigin::root(), too_many_calls), Error::::TooManyCalls, ); // Clear calls - assert_ok!(Lottery::set_calls(Origin::root(), vec![])); + assert_ok!(Lottery::set_calls(RuntimeOrigin::root(), vec![])); assert!(CallIndices::::get().is_empty()); }); } @@ -182,16 +182,16 @@ fn start_lottery_works() { // Setup ignores bad origin assert_noop!( - Lottery::start_lottery(Origin::signed(1), price, length, delay, false), + Lottery::start_lottery(RuntimeOrigin::signed(1), price, length, delay, false), BadOrigin, ); // All good - assert_ok!(Lottery::start_lottery(Origin::root(), price, length, delay, false)); + assert_ok!(Lottery::start_lottery(RuntimeOrigin::root(), price, length, delay, false)); // Can't open another one if lottery is already present assert_noop!( - Lottery::start_lottery(Origin::root(), price, length, delay, false), + Lottery::start_lottery(RuntimeOrigin::root(), price, length, delay, false), Error::::InProgress, ); }); @@ -205,7 +205,7 @@ fn buy_ticket_works_as_simple_passthrough() { // No lottery set up let call = Box::new(RuntimeCall::Balances(BalancesCall::transfer { dest: 2, value: 20 })); // This is just a basic transfer then - assert_ok!(Lottery::buy_ticket(Origin::signed(1), call.clone())); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(1), call.clone())); assert_eq!(Balances::free_balance(&1), 100 - 20); assert_eq!(TicketsCount::::get(), 0); @@ -214,11 +214,11 @@ fn buy_ticket_works_as_simple_passthrough() { RuntimeCall::Balances(BalancesCall::force_transfer { source: 0, dest: 0, value: 0 }), RuntimeCall::Balances(BalancesCall::transfer { dest: 0, value: 0 }), ]; - assert_ok!(Lottery::set_calls(Origin::root(), calls)); + assert_ok!(Lottery::set_calls(RuntimeOrigin::root(), calls)); // Ticket price of 60 would kill the user's account - assert_ok!(Lottery::start_lottery(Origin::root(), 60, 10, 5, false)); - assert_ok!(Lottery::buy_ticket(Origin::signed(1), call.clone())); + assert_ok!(Lottery::start_lottery(RuntimeOrigin::root(), 60, 10, 5, false)); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(1), call.clone())); assert_eq!(Balances::free_balance(&1), 100 - 20 - 20); assert_eq!(TicketsCount::::get(), 0); @@ -226,7 +226,7 @@ fn buy_ticket_works_as_simple_passthrough() { let fail_call = Box::new(RuntimeCall::Balances(BalancesCall::transfer { dest: 2, value: 1000 })); assert_noop!( - Lottery::buy_ticket(Origin::signed(1), fail_call), + Lottery::buy_ticket(RuntimeOrigin::signed(1), fail_call), BalancesError::::InsufficientBalance, ); @@ -235,17 +235,17 @@ fn buy_ticket_works_as_simple_passthrough() { dest: 0, value: 0, })); - assert_noop!(Lottery::buy_ticket(Origin::signed(1), bad_origin_call), BadOrigin,); + assert_noop!(Lottery::buy_ticket(RuntimeOrigin::signed(1), bad_origin_call), BadOrigin,); // User can call other txs, but doesn't get a ticket let remark_call = Box::new(RuntimeCall::System(SystemCall::remark { remark: b"hello, world!".to_vec() })); - assert_ok!(Lottery::buy_ticket(Origin::signed(2), remark_call)); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(2), remark_call)); assert_eq!(TicketsCount::::get(), 0); let successful_call = Box::new(RuntimeCall::Balances(BalancesCall::transfer { dest: 2, value: 1 })); - assert_ok!(Lottery::buy_ticket(Origin::signed(2), successful_call)); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(2), successful_call)); assert_eq!(TicketsCount::::get(), 1); }); } @@ -258,40 +258,40 @@ fn buy_ticket_works() { RuntimeCall::System(SystemCall::remark { remark: vec![] }), RuntimeCall::Balances(BalancesCall::transfer { dest: 0, value: 0 }), ]; - assert_ok!(Lottery::set_calls(Origin::root(), calls)); + assert_ok!(Lottery::set_calls(RuntimeOrigin::root(), calls)); // Can't buy ticket before start let call = Box::new(RuntimeCall::Balances(BalancesCall::transfer { dest: 2, value: 1 })); - assert_ok!(Lottery::buy_ticket(Origin::signed(1), call.clone())); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(1), call.clone())); assert_eq!(TicketsCount::::get(), 0); // Start lottery - assert_ok!(Lottery::start_lottery(Origin::root(), 1, 20, 5, false)); + assert_ok!(Lottery::start_lottery(RuntimeOrigin::root(), 1, 20, 5, false)); // Go to start, buy ticket for transfer run_to_block(5); - assert_ok!(Lottery::buy_ticket(Origin::signed(1), call)); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(1), call)); assert_eq!(TicketsCount::::get(), 1); // Can't buy another of the same ticket (even if call is slightly changed) let call = Box::new(RuntimeCall::Balances(BalancesCall::transfer { dest: 3, value: 30 })); - assert_ok!(Lottery::buy_ticket(Origin::signed(1), call)); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(1), call)); assert_eq!(TicketsCount::::get(), 1); // Buy ticket for remark let call = Box::new(RuntimeCall::System(SystemCall::remark { remark: b"hello, world!".to_vec() })); - assert_ok!(Lottery::buy_ticket(Origin::signed(1), call.clone())); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(1), call.clone())); assert_eq!(TicketsCount::::get(), 2); // Go to end, can't buy tickets anymore run_to_block(20); - assert_ok!(Lottery::buy_ticket(Origin::signed(2), call.clone())); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(2), call.clone())); assert_eq!(TicketsCount::::get(), 2); // Go to payout, can't buy tickets when there is no lottery open run_to_block(25); - assert_ok!(Lottery::buy_ticket(Origin::signed(2), call.clone())); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(2), call.clone())); assert_eq!(TicketsCount::::get(), 0); assert_eq!(LotteryIndex::::get(), 1); }); @@ -303,8 +303,8 @@ fn buy_ticket_works() { fn do_buy_ticket_already_participating() { new_test_ext().execute_with(|| { let calls = vec![RuntimeCall::Balances(BalancesCall::transfer { dest: 0, value: 0 })]; - assert_ok!(Lottery::set_calls(Origin::root(), calls.clone())); - assert_ok!(Lottery::start_lottery(Origin::root(), 1, 10, 10, false)); + assert_ok!(Lottery::set_calls(RuntimeOrigin::root(), calls.clone())); + assert_ok!(Lottery::start_lottery(RuntimeOrigin::root(), 1, 10, 10, false)); // Buying once works. assert_ok!(Lottery::do_buy_ticket(&1, &calls[0])); @@ -318,15 +318,15 @@ fn do_buy_ticket_already_participating() { fn buy_ticket_already_participating() { new_test_ext().execute_with(|| { let calls = vec![RuntimeCall::Balances(BalancesCall::transfer { dest: 0, value: 0 })]; - assert_ok!(Lottery::set_calls(Origin::root(), calls.clone())); - assert_ok!(Lottery::start_lottery(Origin::root(), 1, 10, 10, false)); + assert_ok!(Lottery::set_calls(RuntimeOrigin::root(), calls.clone())); + assert_ok!(Lottery::start_lottery(RuntimeOrigin::root(), 1, 10, 10, false)); // Buying once works. let call = Box::new(calls[0].clone()); - assert_ok!(Lottery::buy_ticket(Origin::signed(1), call.clone())); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(1), call.clone())); // Buying the same ticket again returns Ok, but changes nothing. - assert_storage_noop!(Lottery::buy_ticket(Origin::signed(1), call).unwrap()); + assert_storage_noop!(Lottery::buy_ticket(RuntimeOrigin::signed(1), call).unwrap()); // Exactly one ticket exists. assert_eq!(TicketsCount::::get(), 1); @@ -338,13 +338,13 @@ fn buy_ticket_already_participating() { fn buy_ticket_insufficient_balance() { new_test_ext().execute_with(|| { let calls = vec![RuntimeCall::Balances(BalancesCall::transfer { dest: 0, value: 0 })]; - assert_ok!(Lottery::set_calls(Origin::root(), calls.clone())); + assert_ok!(Lottery::set_calls(RuntimeOrigin::root(), calls.clone())); // Price set to 100. - assert_ok!(Lottery::start_lottery(Origin::root(), 100, 10, 10, false)); + assert_ok!(Lottery::start_lottery(RuntimeOrigin::root(), 100, 10, 10, false)); let call = Box::new(calls[0].clone()); // Buying a ticket returns Ok, but changes nothing. - assert_storage_noop!(Lottery::buy_ticket(Origin::signed(1), call).unwrap()); + assert_storage_noop!(Lottery::buy_ticket(RuntimeOrigin::signed(1), call).unwrap()); assert!(TicketsCount::::get().is_zero()); }); } @@ -353,9 +353,9 @@ fn buy_ticket_insufficient_balance() { fn do_buy_ticket_insufficient_balance() { new_test_ext().execute_with(|| { let calls = vec![RuntimeCall::Balances(BalancesCall::transfer { dest: 0, value: 0 })]; - assert_ok!(Lottery::set_calls(Origin::root(), calls.clone())); + assert_ok!(Lottery::set_calls(RuntimeOrigin::root(), calls.clone())); // Price set to 101. - assert_ok!(Lottery::start_lottery(Origin::root(), 101, 10, 10, false)); + assert_ok!(Lottery::start_lottery(RuntimeOrigin::root(), 101, 10, 10, false)); // Buying fails with InsufficientBalance. assert_noop!( @@ -370,9 +370,9 @@ fn do_buy_ticket_insufficient_balance() { fn do_buy_ticket_keep_alive() { new_test_ext().execute_with(|| { let calls = vec![RuntimeCall::Balances(BalancesCall::transfer { dest: 0, value: 0 })]; - assert_ok!(Lottery::set_calls(Origin::root(), calls.clone())); + assert_ok!(Lottery::set_calls(RuntimeOrigin::root(), calls.clone())); // Price set to 100. - assert_ok!(Lottery::start_lottery(Origin::root(), 100, 10, 10, false)); + assert_ok!(Lottery::start_lottery(RuntimeOrigin::root(), 100, 10, 10, false)); // Buying fails with KeepAlive. assert_noop!(Lottery::do_buy_ticket(&1, &calls[0]), BalancesError::::KeepAlive); @@ -388,9 +388,9 @@ fn no_participants_works() { let delay = 5; // Set no calls for the lottery. - assert_ok!(Lottery::set_calls(Origin::root(), vec![])); + assert_ok!(Lottery::set_calls(RuntimeOrigin::root(), vec![])); // Start lottery. - assert_ok!(Lottery::start_lottery(Origin::root(), 10, length, delay, false)); + assert_ok!(Lottery::start_lottery(RuntimeOrigin::root(), 10, length, delay, false)); // End the lottery, no one wins. run_to_block(length + delay); @@ -405,7 +405,7 @@ fn start_lottery_will_create_account() { let delay = 5; assert_eq!(Balances::total_balance(&Lottery::account_id()), 0); - assert_ok!(Lottery::start_lottery(Origin::root(), price, length, delay, false)); + assert_ok!(Lottery::start_lottery(RuntimeOrigin::root(), price, length, delay, false)); assert_eq!(Balances::total_balance(&Lottery::account_id()), 1); }); } @@ -422,12 +422,12 @@ fn choose_ticket_trivial_cases() { fn choose_account_one_participant() { new_test_ext().execute_with(|| { let calls = vec![RuntimeCall::Balances(BalancesCall::transfer { dest: 0, value: 0 })]; - assert_ok!(Lottery::set_calls(Origin::root(), calls.clone())); - assert_ok!(Lottery::start_lottery(Origin::root(), 10, 10, 10, false)); + assert_ok!(Lottery::set_calls(RuntimeOrigin::root(), calls.clone())); + assert_ok!(Lottery::start_lottery(RuntimeOrigin::root(), 10, 10, 10, false)); let call = Box::new(calls[0].clone()); // Buy one ticket with account 1. - assert_ok!(Lottery::buy_ticket(Origin::signed(1), call)); + assert_ok!(Lottery::buy_ticket(RuntimeOrigin::signed(1), call)); // Account 1 is always the winner. assert_eq!(Lottery::choose_account().unwrap(), 1); }); diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index a3f79ab2052e9..af2f2ddcf42f0 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -59,19 +59,19 @@ pub mod pallet { + IsType<::RuntimeEvent>; /// Required origin for adding a member (though can always be Root). - type AddOrigin: EnsureOrigin; + type AddOrigin: EnsureOrigin; /// Required origin for removing a member (though can always be Root). - type RemoveOrigin: EnsureOrigin; + type RemoveOrigin: EnsureOrigin; /// Required origin for adding and removing a member in a single action. - type SwapOrigin: EnsureOrigin; + type SwapOrigin: EnsureOrigin; /// Required origin for resetting membership. - type ResetOrigin: EnsureOrigin; + type ResetOrigin: EnsureOrigin; /// Required origin for setting or resetting the prime member. - type PrimeOrigin: EnsureOrigin; + type PrimeOrigin: EnsureOrigin; /// The receiver of the signal for when the membership has been initialized. This happens /// pre-genesis and will usually be the same as `MembershipChanged`. If you need to do @@ -543,7 +543,7 @@ mod tests { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = H256; @@ -647,13 +647,16 @@ mod tests { #[test] fn prime_member_works() { new_test_ext().execute_with(|| { - assert_noop!(Membership::set_prime(Origin::signed(4), 20), BadOrigin); - assert_noop!(Membership::set_prime(Origin::signed(5), 15), Error::::NotMember); - assert_ok!(Membership::set_prime(Origin::signed(5), 20)); + assert_noop!(Membership::set_prime(RuntimeOrigin::signed(4), 20), BadOrigin); + assert_noop!( + Membership::set_prime(RuntimeOrigin::signed(5), 15), + Error::::NotMember + ); + assert_ok!(Membership::set_prime(RuntimeOrigin::signed(5), 20)); assert_eq!(Membership::prime(), Some(20)); assert_eq!(PRIME.with(|m| *m.borrow()), Membership::prime()); - assert_ok!(Membership::clear_prime(Origin::signed(5))); + assert_ok!(Membership::clear_prime(RuntimeOrigin::signed(5))); assert_eq!(Membership::prime(), None); assert_eq!(PRIME.with(|m| *m.borrow()), Membership::prime()); }); @@ -662,12 +665,12 @@ mod tests { #[test] fn add_member_works() { new_test_ext().execute_with(|| { - assert_noop!(Membership::add_member(Origin::signed(5), 15), BadOrigin); + assert_noop!(Membership::add_member(RuntimeOrigin::signed(5), 15), BadOrigin); assert_noop!( - Membership::add_member(Origin::signed(1), 10), + Membership::add_member(RuntimeOrigin::signed(1), 10), Error::::AlreadyMember ); - assert_ok!(Membership::add_member(Origin::signed(1), 15)); + assert_ok!(Membership::add_member(RuntimeOrigin::signed(1), 15)); assert_eq!(Membership::members(), vec![10, 15, 20, 30]); assert_eq!(MEMBERS.with(|m| m.borrow().clone()), Membership::members().to_vec()); }); @@ -676,13 +679,13 @@ mod tests { #[test] fn remove_member_works() { new_test_ext().execute_with(|| { - assert_noop!(Membership::remove_member(Origin::signed(5), 20), BadOrigin); + assert_noop!(Membership::remove_member(RuntimeOrigin::signed(5), 20), BadOrigin); assert_noop!( - Membership::remove_member(Origin::signed(2), 15), + Membership::remove_member(RuntimeOrigin::signed(2), 15), Error::::NotMember ); - assert_ok!(Membership::set_prime(Origin::signed(5), 20)); - assert_ok!(Membership::remove_member(Origin::signed(2), 20)); + assert_ok!(Membership::set_prime(RuntimeOrigin::signed(5), 20)); + assert_ok!(Membership::remove_member(RuntimeOrigin::signed(2), 20)); assert_eq!(Membership::members(), vec![10, 30]); assert_eq!(MEMBERS.with(|m| m.borrow().clone()), Membership::members().to_vec()); assert_eq!(Membership::prime(), None); @@ -693,24 +696,24 @@ mod tests { #[test] fn swap_member_works() { new_test_ext().execute_with(|| { - assert_noop!(Membership::swap_member(Origin::signed(5), 10, 25), BadOrigin); + assert_noop!(Membership::swap_member(RuntimeOrigin::signed(5), 10, 25), BadOrigin); assert_noop!( - Membership::swap_member(Origin::signed(3), 15, 25), + Membership::swap_member(RuntimeOrigin::signed(3), 15, 25), Error::::NotMember ); assert_noop!( - Membership::swap_member(Origin::signed(3), 10, 30), + Membership::swap_member(RuntimeOrigin::signed(3), 10, 30), Error::::AlreadyMember ); - assert_ok!(Membership::set_prime(Origin::signed(5), 20)); - assert_ok!(Membership::swap_member(Origin::signed(3), 20, 20)); + assert_ok!(Membership::set_prime(RuntimeOrigin::signed(5), 20)); + assert_ok!(Membership::swap_member(RuntimeOrigin::signed(3), 20, 20)); assert_eq!(Membership::members(), vec![10, 20, 30]); assert_eq!(Membership::prime(), Some(20)); assert_eq!(PRIME.with(|m| *m.borrow()), Membership::prime()); - assert_ok!(Membership::set_prime(Origin::signed(5), 10)); - assert_ok!(Membership::swap_member(Origin::signed(3), 10, 25)); + assert_ok!(Membership::set_prime(RuntimeOrigin::signed(5), 10)); + assert_ok!(Membership::swap_member(RuntimeOrigin::signed(3), 10, 25)); assert_eq!(Membership::members(), vec![20, 25, 30]); assert_eq!(MEMBERS.with(|m| m.borrow().clone()), Membership::members().to_vec()); assert_eq!(Membership::prime(), None); @@ -721,7 +724,7 @@ mod tests { #[test] fn swap_member_works_that_does_not_change_order() { new_test_ext().execute_with(|| { - assert_ok!(Membership::swap_member(Origin::signed(3), 10, 5)); + assert_ok!(Membership::swap_member(RuntimeOrigin::signed(3), 10, 5)); assert_eq!(Membership::members(), vec![5, 20, 30]); assert_eq!(MEMBERS.with(|m| m.borrow().clone()), Membership::members().to_vec()); }); @@ -730,16 +733,16 @@ mod tests { #[test] fn change_key_works() { new_test_ext().execute_with(|| { - assert_ok!(Membership::set_prime(Origin::signed(5), 10)); + assert_ok!(Membership::set_prime(RuntimeOrigin::signed(5), 10)); assert_noop!( - Membership::change_key(Origin::signed(3), 25), + Membership::change_key(RuntimeOrigin::signed(3), 25), Error::::NotMember ); assert_noop!( - Membership::change_key(Origin::signed(10), 20), + Membership::change_key(RuntimeOrigin::signed(10), 20), Error::::AlreadyMember ); - assert_ok!(Membership::change_key(Origin::signed(10), 40)); + assert_ok!(Membership::change_key(RuntimeOrigin::signed(10), 40)); assert_eq!(Membership::members(), vec![20, 30, 40]); assert_eq!(MEMBERS.with(|m| m.borrow().clone()), Membership::members().to_vec()); assert_eq!(Membership::prime(), Some(40)); @@ -750,7 +753,7 @@ mod tests { #[test] fn change_key_works_that_does_not_change_order() { new_test_ext().execute_with(|| { - assert_ok!(Membership::change_key(Origin::signed(10), 5)); + assert_ok!(Membership::change_key(RuntimeOrigin::signed(10), 5)); assert_eq!(Membership::members(), vec![5, 20, 30]); assert_eq!(MEMBERS.with(|m| m.borrow().clone()), Membership::members().to_vec()); }); @@ -759,19 +762,19 @@ mod tests { #[test] fn reset_members_works() { new_test_ext().execute_with(|| { - assert_ok!(Membership::set_prime(Origin::signed(5), 20)); + assert_ok!(Membership::set_prime(RuntimeOrigin::signed(5), 20)); assert_noop!( - Membership::reset_members(Origin::signed(1), bounded_vec![20, 40, 30]), + Membership::reset_members(RuntimeOrigin::signed(1), bounded_vec![20, 40, 30]), BadOrigin ); - assert_ok!(Membership::reset_members(Origin::signed(4), vec![20, 40, 30])); + assert_ok!(Membership::reset_members(RuntimeOrigin::signed(4), vec![20, 40, 30])); assert_eq!(Membership::members(), vec![20, 30, 40]); assert_eq!(MEMBERS.with(|m| m.borrow().clone()), Membership::members().to_vec()); assert_eq!(Membership::prime(), Some(20)); assert_eq!(PRIME.with(|m| *m.borrow()), Membership::prime()); - assert_ok!(Membership::reset_members(Origin::signed(4), vec![10, 40, 30])); + assert_ok!(Membership::reset_members(RuntimeOrigin::signed(4), vec![10, 40, 30])); assert_eq!(Membership::members(), vec![10, 30, 40]); assert_eq!(MEMBERS.with(|m| m.borrow().clone()), Membership::members().to_vec()); assert_eq!(Membership::prime(), None); diff --git a/frame/merkle-mountain-range/Cargo.toml b/frame/merkle-mountain-range/Cargo.toml index 43d7d6ba2eed7..91ec19d731094 100644 --- a/frame/merkle-mountain-range/Cargo.toml +++ b/frame/merkle-mountain-range/Cargo.toml @@ -25,8 +25,8 @@ sp-runtime = { version = "6.0.0", default-features = false, path = "../../primit sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } [dev-dependencies] +array-bytes = "4.1" env_logger = "0.9" -hex-literal = "0.3" itertools = "0.10.3" [features] diff --git a/frame/merkle-mountain-range/src/mock.rs b/frame/merkle-mountain-range/src/mock.rs index abaa7b106d539..16f0922633088 100644 --- a/frame/merkle-mountain-range/src/mock.rs +++ b/frame/merkle-mountain-range/src/mock.rs @@ -47,7 +47,7 @@ frame_support::construct_runtime!( impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = u64; diff --git a/frame/multisig/src/lib.rs b/frame/multisig/src/lib.rs index 0c7e931e5ea2e..3bdb47ffc4568 100644 --- a/frame/multisig/src/lib.rs +++ b/frame/multisig/src/lib.rs @@ -122,7 +122,7 @@ pub mod pallet { /// The overarching call type. type RuntimeCall: Parameter - + Dispatchable + + Dispatchable + GetDispatchInfo + From>; diff --git a/frame/multisig/src/tests.rs b/frame/multisig/src/tests.rs index 7eb9a9c3aae32..b24a06f454368 100644 --- a/frame/multisig/src/tests.rs +++ b/frame/multisig/src/tests.rs @@ -57,7 +57,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = H256; @@ -138,15 +138,15 @@ fn call_transfer(dest: u64, value: u64) -> RuntimeCall { fn multisig_deposit_is_taken_and_returned() { new_test_ext().execute_with(|| { let multi = Multisig::multi_account_id(&[1, 2, 3][..], 2); - assert_ok!(Balances::transfer(Origin::signed(1), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(2), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(3), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(1), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(2), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(3), multi, 5)); let call = call_transfer(6, 15); let call_weight = call.get_dispatch_info().weight; let data = call.encode(); assert_ok!(Multisig::as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, vec![2, 3], None, @@ -158,7 +158,7 @@ fn multisig_deposit_is_taken_and_returned() { assert_eq!(Balances::reserved_balance(1), 3); assert_ok!(Multisig::as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 2, vec![1, 3], Some(now()), @@ -175,16 +175,16 @@ fn multisig_deposit_is_taken_and_returned() { fn multisig_deposit_is_taken_and_returned_with_call_storage() { new_test_ext().execute_with(|| { let multi = Multisig::multi_account_id(&[1, 2, 3][..], 2); - assert_ok!(Balances::transfer(Origin::signed(1), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(2), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(3), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(1), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(2), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(3), multi, 5)); let call = call_transfer(6, 15); let call_weight = call.get_dispatch_info().weight; let data = call.encode(); let hash = blake2_256(&data); assert_ok!(Multisig::as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, vec![2, 3], None, @@ -196,7 +196,7 @@ fn multisig_deposit_is_taken_and_returned_with_call_storage() { assert_eq!(Balances::reserved_balance(1), 5); assert_ok!(Multisig::approve_as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 2, vec![1, 3], Some(now()), @@ -212,9 +212,9 @@ fn multisig_deposit_is_taken_and_returned_with_call_storage() { fn multisig_deposit_is_taken_and_returned_with_alt_call_storage() { new_test_ext().execute_with(|| { let multi = Multisig::multi_account_id(&[1, 2, 3][..], 3); - assert_ok!(Balances::transfer(Origin::signed(1), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(2), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(3), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(1), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(2), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(3), multi, 5)); let call = call_transfer(6, 15); let call_weight = call.get_dispatch_info().weight; @@ -222,7 +222,7 @@ fn multisig_deposit_is_taken_and_returned_with_alt_call_storage() { let hash = blake2_256(&data); assert_ok!(Multisig::approve_as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, vec![2, 3], None, @@ -233,7 +233,7 @@ fn multisig_deposit_is_taken_and_returned_with_alt_call_storage() { assert_eq!(Balances::reserved_balance(1), 4); assert_ok!(Multisig::as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 3, vec![1, 3], Some(now()), @@ -247,7 +247,7 @@ fn multisig_deposit_is_taken_and_returned_with_alt_call_storage() { assert_eq!(Balances::reserved_balance(1), 4); assert_ok!(Multisig::approve_as_multi( - Origin::signed(3), + RuntimeOrigin::signed(3), 3, vec![1, 2], Some(now()), @@ -267,7 +267,7 @@ fn cancel_multisig_returns_deposit() { let call = call_transfer(6, 15).encode(); let hash = blake2_256(&call); assert_ok!(Multisig::approve_as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, vec![2, 3], None, @@ -275,7 +275,7 @@ fn cancel_multisig_returns_deposit() { Weight::zero() )); assert_ok!(Multisig::approve_as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 3, vec![1, 3], Some(now()), @@ -284,7 +284,7 @@ fn cancel_multisig_returns_deposit() { )); assert_eq!(Balances::free_balance(1), 6); assert_eq!(Balances::reserved_balance(1), 4); - assert_ok!(Multisig::cancel_as_multi(Origin::signed(1), 3, vec![2, 3], now(), hash)); + assert_ok!(Multisig::cancel_as_multi(RuntimeOrigin::signed(1), 3, vec![2, 3], now(), hash)); assert_eq!(Balances::free_balance(1), 10); assert_eq!(Balances::reserved_balance(1), 0); }); @@ -294,16 +294,16 @@ fn cancel_multisig_returns_deposit() { fn timepoint_checking_works() { new_test_ext().execute_with(|| { let multi = Multisig::multi_account_id(&[1, 2, 3][..], 2); - assert_ok!(Balances::transfer(Origin::signed(1), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(2), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(3), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(1), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(2), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(3), multi, 5)); let call = call_transfer(6, 15).encode(); let hash = blake2_256(&call); assert_noop!( Multisig::approve_as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 2, vec![1, 3], Some(now()), @@ -314,7 +314,7 @@ fn timepoint_checking_works() { ); assert_ok!(Multisig::approve_as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, vec![2, 3], None, @@ -324,7 +324,7 @@ fn timepoint_checking_works() { assert_noop!( Multisig::as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 2, vec![1, 3], None, @@ -337,7 +337,7 @@ fn timepoint_checking_works() { let later = Timepoint { index: 1, ..now() }; assert_noop!( Multisig::as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 2, vec![1, 3], Some(later), @@ -354,16 +354,16 @@ fn timepoint_checking_works() { fn multisig_2_of_3_works_with_call_storing() { new_test_ext().execute_with(|| { let multi = Multisig::multi_account_id(&[1, 2, 3][..], 2); - assert_ok!(Balances::transfer(Origin::signed(1), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(2), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(3), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(1), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(2), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(3), multi, 5)); let call = call_transfer(6, 15); let call_weight = call.get_dispatch_info().weight; let data = call.encode(); let hash = blake2_256(&data); assert_ok!(Multisig::as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, vec![2, 3], None, @@ -374,7 +374,7 @@ fn multisig_2_of_3_works_with_call_storing() { assert_eq!(Balances::free_balance(6), 0); assert_ok!(Multisig::approve_as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 2, vec![1, 3], Some(now()), @@ -389,16 +389,16 @@ fn multisig_2_of_3_works_with_call_storing() { fn multisig_2_of_3_works() { new_test_ext().execute_with(|| { let multi = Multisig::multi_account_id(&[1, 2, 3][..], 2); - assert_ok!(Balances::transfer(Origin::signed(1), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(2), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(3), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(1), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(2), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(3), multi, 5)); let call = call_transfer(6, 15); let call_weight = call.get_dispatch_info().weight; let data = call.encode(); let hash = blake2_256(&data); assert_ok!(Multisig::approve_as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, vec![2, 3], None, @@ -408,7 +408,7 @@ fn multisig_2_of_3_works() { assert_eq!(Balances::free_balance(6), 0); assert_ok!(Multisig::as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 2, vec![1, 3], Some(now()), @@ -424,16 +424,16 @@ fn multisig_2_of_3_works() { fn multisig_3_of_3_works() { new_test_ext().execute_with(|| { let multi = Multisig::multi_account_id(&[1, 2, 3][..], 3); - assert_ok!(Balances::transfer(Origin::signed(1), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(2), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(3), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(1), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(2), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(3), multi, 5)); let call = call_transfer(6, 15); let call_weight = call.get_dispatch_info().weight; let data = call.encode(); let hash = blake2_256(&data); assert_ok!(Multisig::approve_as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, vec![2, 3], None, @@ -441,7 +441,7 @@ fn multisig_3_of_3_works() { Weight::zero() )); assert_ok!(Multisig::approve_as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 3, vec![1, 3], Some(now()), @@ -451,7 +451,7 @@ fn multisig_3_of_3_works() { assert_eq!(Balances::free_balance(6), 0); assert_ok!(Multisig::as_multi( - Origin::signed(3), + RuntimeOrigin::signed(3), 3, vec![1, 2], Some(now()), @@ -469,7 +469,7 @@ fn cancel_multisig_works() { let call = call_transfer(6, 15).encode(); let hash = blake2_256(&call); assert_ok!(Multisig::approve_as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, vec![2, 3], None, @@ -477,7 +477,7 @@ fn cancel_multisig_works() { Weight::zero() )); assert_ok!(Multisig::approve_as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 3, vec![1, 3], Some(now()), @@ -485,10 +485,10 @@ fn cancel_multisig_works() { Weight::zero() )); assert_noop!( - Multisig::cancel_as_multi(Origin::signed(2), 3, vec![1, 3], now(), hash), + Multisig::cancel_as_multi(RuntimeOrigin::signed(2), 3, vec![1, 3], now(), hash), Error::::NotOwner, ); - assert_ok!(Multisig::cancel_as_multi(Origin::signed(1), 3, vec![2, 3], now(), hash),); + assert_ok!(Multisig::cancel_as_multi(RuntimeOrigin::signed(1), 3, vec![2, 3], now(), hash),); }); } @@ -498,7 +498,7 @@ fn cancel_multisig_with_call_storage_works() { let call = call_transfer(6, 15).encode(); let hash = blake2_256(&call); assert_ok!(Multisig::as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, vec![2, 3], None, @@ -508,7 +508,7 @@ fn cancel_multisig_with_call_storage_works() { )); assert_eq!(Balances::free_balance(1), 4); assert_ok!(Multisig::approve_as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 3, vec![1, 3], Some(now()), @@ -516,10 +516,10 @@ fn cancel_multisig_with_call_storage_works() { Weight::zero() )); assert_noop!( - Multisig::cancel_as_multi(Origin::signed(2), 3, vec![1, 3], now(), hash), + Multisig::cancel_as_multi(RuntimeOrigin::signed(2), 3, vec![1, 3], now(), hash), Error::::NotOwner, ); - assert_ok!(Multisig::cancel_as_multi(Origin::signed(1), 3, vec![2, 3], now(), hash),); + assert_ok!(Multisig::cancel_as_multi(RuntimeOrigin::signed(1), 3, vec![2, 3], now(), hash),); assert_eq!(Balances::free_balance(1), 10); }); } @@ -530,7 +530,7 @@ fn cancel_multisig_with_alt_call_storage_works() { let call = call_transfer(6, 15).encode(); let hash = blake2_256(&call); assert_ok!(Multisig::approve_as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, vec![2, 3], None, @@ -539,7 +539,7 @@ fn cancel_multisig_with_alt_call_storage_works() { )); assert_eq!(Balances::free_balance(1), 6); assert_ok!(Multisig::as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 3, vec![1, 3], Some(now()), @@ -548,7 +548,7 @@ fn cancel_multisig_with_alt_call_storage_works() { Weight::zero() )); assert_eq!(Balances::free_balance(2), 8); - assert_ok!(Multisig::cancel_as_multi(Origin::signed(1), 3, vec![2, 3], now(), hash)); + assert_ok!(Multisig::cancel_as_multi(RuntimeOrigin::signed(1), 3, vec![2, 3], now(), hash)); assert_eq!(Balances::free_balance(1), 10); assert_eq!(Balances::free_balance(2), 10); }); @@ -558,15 +558,15 @@ fn cancel_multisig_with_alt_call_storage_works() { fn multisig_2_of_3_as_multi_works() { new_test_ext().execute_with(|| { let multi = Multisig::multi_account_id(&[1, 2, 3][..], 2); - assert_ok!(Balances::transfer(Origin::signed(1), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(2), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(3), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(1), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(2), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(3), multi, 5)); let call = call_transfer(6, 15); let call_weight = call.get_dispatch_info().weight; let data = call.encode(); assert_ok!(Multisig::as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, vec![2, 3], None, @@ -577,7 +577,7 @@ fn multisig_2_of_3_as_multi_works() { assert_eq!(Balances::free_balance(6), 0); assert_ok!(Multisig::as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 2, vec![1, 3], Some(now()), @@ -593,9 +593,9 @@ fn multisig_2_of_3_as_multi_works() { fn multisig_2_of_3_as_multi_with_many_calls_works() { new_test_ext().execute_with(|| { let multi = Multisig::multi_account_id(&[1, 2, 3][..], 2); - assert_ok!(Balances::transfer(Origin::signed(1), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(2), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(3), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(1), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(2), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(3), multi, 5)); let call1 = call_transfer(6, 10); let call1_weight = call1.get_dispatch_info().weight; @@ -605,7 +605,7 @@ fn multisig_2_of_3_as_multi_with_many_calls_works() { let data2 = call2.encode(); assert_ok!(Multisig::as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, vec![2, 3], None, @@ -614,7 +614,7 @@ fn multisig_2_of_3_as_multi_with_many_calls_works() { Weight::zero() )); assert_ok!(Multisig::as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 2, vec![1, 3], None, @@ -623,7 +623,7 @@ fn multisig_2_of_3_as_multi_with_many_calls_works() { Weight::zero() )); assert_ok!(Multisig::as_multi( - Origin::signed(3), + RuntimeOrigin::signed(3), 2, vec![1, 2], Some(now()), @@ -632,7 +632,7 @@ fn multisig_2_of_3_as_multi_with_many_calls_works() { call1_weight )); assert_ok!(Multisig::as_multi( - Origin::signed(3), + RuntimeOrigin::signed(3), 2, vec![1, 2], Some(now()), @@ -650,16 +650,16 @@ fn multisig_2_of_3_as_multi_with_many_calls_works() { fn multisig_2_of_3_cannot_reissue_same_call() { new_test_ext().execute_with(|| { let multi = Multisig::multi_account_id(&[1, 2, 3][..], 2); - assert_ok!(Balances::transfer(Origin::signed(1), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(2), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(3), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(1), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(2), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(3), multi, 5)); let call = call_transfer(6, 10); let call_weight = call.get_dispatch_info().weight; let data = call.encode(); let hash = blake2_256(&data); assert_ok!(Multisig::as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, vec![2, 3], None, @@ -668,7 +668,7 @@ fn multisig_2_of_3_cannot_reissue_same_call() { Weight::zero() )); assert_ok!(Multisig::as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 2, vec![1, 3], Some(now()), @@ -679,7 +679,7 @@ fn multisig_2_of_3_cannot_reissue_same_call() { assert_eq!(Balances::free_balance(multi), 5); assert_ok!(Multisig::as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, vec![2, 3], None, @@ -688,7 +688,7 @@ fn multisig_2_of_3_cannot_reissue_same_call() { Weight::zero() )); assert_ok!(Multisig::as_multi( - Origin::signed(3), + RuntimeOrigin::signed(3), 2, vec![1, 2], Some(now()), @@ -717,7 +717,7 @@ fn minimum_threshold_check_works() { let call = call_transfer(6, 15).encode(); assert_noop!( Multisig::as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 0, vec![2], None, @@ -729,7 +729,7 @@ fn minimum_threshold_check_works() { ); assert_noop!( Multisig::as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 1, vec![2], None, @@ -748,7 +748,7 @@ fn too_many_signatories_fails() { let call = call_transfer(6, 15).encode(); assert_noop!( Multisig::as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, vec![2, 3, 4], None, @@ -767,7 +767,7 @@ fn duplicate_approvals_are_ignored() { let call = call_transfer(6, 15).encode(); let hash = blake2_256(&call); assert_ok!(Multisig::approve_as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, vec![2, 3], None, @@ -776,7 +776,7 @@ fn duplicate_approvals_are_ignored() { )); assert_noop!( Multisig::approve_as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, vec![2, 3], Some(now()), @@ -786,7 +786,7 @@ fn duplicate_approvals_are_ignored() { Error::::AlreadyApproved, ); assert_ok!(Multisig::approve_as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 2, vec![1, 3], Some(now()), @@ -795,7 +795,7 @@ fn duplicate_approvals_are_ignored() { )); assert_noop!( Multisig::approve_as_multi( - Origin::signed(3), + RuntimeOrigin::signed(3), 2, vec![1, 2], Some(now()), @@ -811,15 +811,15 @@ fn duplicate_approvals_are_ignored() { fn multisig_1_of_3_works() { new_test_ext().execute_with(|| { let multi = Multisig::multi_account_id(&[1, 2, 3][..], 1); - assert_ok!(Balances::transfer(Origin::signed(1), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(2), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(3), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(1), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(2), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(3), multi, 5)); let call = call_transfer(6, 15).encode(); let hash = blake2_256(&call); assert_noop!( Multisig::approve_as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 1, vec![2, 3], None, @@ -830,7 +830,7 @@ fn multisig_1_of_3_works() { ); assert_noop!( Multisig::as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 1, vec![2, 3], None, @@ -841,7 +841,11 @@ fn multisig_1_of_3_works() { Error::::MinimumThreshold, ); let boxed_call = Box::new(call_transfer(6, 15)); - assert_ok!(Multisig::as_multi_threshold_1(Origin::signed(1), vec![2, 3], boxed_call)); + assert_ok!(Multisig::as_multi_threshold_1( + RuntimeOrigin::signed(1), + vec![2, 3], + boxed_call + )); assert_eq!(Balances::free_balance(6), 15); }); @@ -852,7 +856,7 @@ fn multisig_filters() { new_test_ext().execute_with(|| { let call = Box::new(RuntimeCall::System(frame_system::Call::set_code { code: vec![] })); assert_noop!( - Multisig::as_multi_threshold_1(Origin::signed(1), vec![2], call.clone()), + Multisig::as_multi_threshold_1(RuntimeOrigin::signed(1), vec![2], call.clone()), DispatchError::from(frame_system::Error::::CallFiltered), ); }); @@ -862,14 +866,14 @@ fn multisig_filters() { fn weight_check_works() { new_test_ext().execute_with(|| { let multi = Multisig::multi_account_id(&[1, 2, 3][..], 2); - assert_ok!(Balances::transfer(Origin::signed(1), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(2), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(3), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(1), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(2), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(3), multi, 5)); let call = call_transfer(6, 15); let data = call.encode(); assert_ok!(Multisig::as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, vec![2, 3], None, @@ -881,7 +885,7 @@ fn weight_check_works() { assert_noop!( Multisig::as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 2, vec![1, 3], Some(now()), @@ -901,16 +905,16 @@ fn multisig_handles_no_preimage_after_all_approve() { // the call will go through. new_test_ext().execute_with(|| { let multi = Multisig::multi_account_id(&[1, 2, 3][..], 3); - assert_ok!(Balances::transfer(Origin::signed(1), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(2), multi, 5)); - assert_ok!(Balances::transfer(Origin::signed(3), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(1), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(2), multi, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(3), multi, 5)); let call = call_transfer(6, 15); let call_weight = call.get_dispatch_info().weight; let data = call.encode(); let hash = blake2_256(&data); assert_ok!(Multisig::approve_as_multi( - Origin::signed(1), + RuntimeOrigin::signed(1), 3, vec![2, 3], None, @@ -918,7 +922,7 @@ fn multisig_handles_no_preimage_after_all_approve() { Weight::zero() )); assert_ok!(Multisig::approve_as_multi( - Origin::signed(2), + RuntimeOrigin::signed(2), 3, vec![1, 3], Some(now()), @@ -926,7 +930,7 @@ fn multisig_handles_no_preimage_after_all_approve() { Weight::zero() )); assert_ok!(Multisig::approve_as_multi( - Origin::signed(3), + RuntimeOrigin::signed(3), 3, vec![1, 2], Some(now()), @@ -936,7 +940,7 @@ fn multisig_handles_no_preimage_after_all_approve() { assert_eq!(Balances::free_balance(6), 0); assert_ok!(Multisig::as_multi( - Origin::signed(3), + RuntimeOrigin::signed(3), 3, vec![1, 2], Some(now()), diff --git a/frame/nicks/src/lib.rs b/frame/nicks/src/lib.rs index 0ab9a509a568f..953cf39cd12db 100644 --- a/frame/nicks/src/lib.rs +++ b/frame/nicks/src/lib.rs @@ -71,7 +71,7 @@ pub mod pallet { type Slashed: OnUnbalanced>; /// The origin which may forcibly set or remove a name. Root can always do this. - type ForceOrigin: EnsureOrigin; + type ForceOrigin: EnsureOrigin; /// The minimum length a name may be. #[pallet::constant] @@ -280,7 +280,7 @@ mod tests { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = H256; @@ -338,9 +338,9 @@ mod tests { #[test] fn kill_name_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Nicks::set_name(Origin::signed(2), b"Dave".to_vec())); + assert_ok!(Nicks::set_name(RuntimeOrigin::signed(2), b"Dave".to_vec())); assert_eq!(Balances::total_balance(&2), 10); - assert_ok!(Nicks::kill_name(Origin::signed(1), 2)); + assert_ok!(Nicks::kill_name(RuntimeOrigin::signed(1), 2)); assert_eq!(Balances::total_balance(&2), 8); assert_eq!(>::get(2), None); }); @@ -350,17 +350,21 @@ mod tests { fn force_name_should_work() { new_test_ext().execute_with(|| { assert_noop!( - Nicks::set_name(Origin::signed(2), b"Dr. David Brubeck, III".to_vec()), + Nicks::set_name(RuntimeOrigin::signed(2), b"Dr. David Brubeck, III".to_vec()), Error::::TooLong, ); - assert_ok!(Nicks::set_name(Origin::signed(2), b"Dave".to_vec())); + assert_ok!(Nicks::set_name(RuntimeOrigin::signed(2), b"Dave".to_vec())); assert_eq!(Balances::reserved_balance(2), 2); assert_noop!( - Nicks::force_name(Origin::signed(1), 2, b"Dr. David Brubeck, III".to_vec()), + Nicks::force_name(RuntimeOrigin::signed(1), 2, b"Dr. David Brubeck, III".to_vec()), Error::::TooLong, ); - assert_ok!(Nicks::force_name(Origin::signed(1), 2, b"Dr. Brubeck, III".to_vec())); + assert_ok!(Nicks::force_name( + RuntimeOrigin::signed(1), + 2, + b"Dr. Brubeck, III".to_vec() + )); assert_eq!(Balances::reserved_balance(2), 2); let (name, amount) = >::get(2).unwrap(); assert_eq!(name, b"Dr. Brubeck, III".to_vec()); @@ -371,17 +375,17 @@ mod tests { #[test] fn normal_operation_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Nicks::set_name(Origin::signed(1), b"Gav".to_vec())); + assert_ok!(Nicks::set_name(RuntimeOrigin::signed(1), b"Gav".to_vec())); assert_eq!(Balances::reserved_balance(1), 2); assert_eq!(Balances::free_balance(1), 8); assert_eq!(>::get(1).unwrap().0, b"Gav".to_vec()); - assert_ok!(Nicks::set_name(Origin::signed(1), b"Gavin".to_vec())); + assert_ok!(Nicks::set_name(RuntimeOrigin::signed(1), b"Gavin".to_vec())); assert_eq!(Balances::reserved_balance(1), 2); assert_eq!(Balances::free_balance(1), 8); assert_eq!(>::get(1).unwrap().0, b"Gavin".to_vec()); - assert_ok!(Nicks::clear_name(Origin::signed(1))); + assert_ok!(Nicks::clear_name(RuntimeOrigin::signed(1))); assert_eq!(Balances::reserved_balance(1), 0); assert_eq!(Balances::free_balance(1), 10); }); @@ -390,24 +394,27 @@ mod tests { #[test] fn error_catching_should_work() { new_test_ext().execute_with(|| { - assert_noop!(Nicks::clear_name(Origin::signed(1)), Error::::Unnamed); + assert_noop!(Nicks::clear_name(RuntimeOrigin::signed(1)), Error::::Unnamed); assert_noop!( - Nicks::set_name(Origin::signed(3), b"Dave".to_vec()), + Nicks::set_name(RuntimeOrigin::signed(3), b"Dave".to_vec()), pallet_balances::Error::::InsufficientBalance ); assert_noop!( - Nicks::set_name(Origin::signed(1), b"Ga".to_vec()), + Nicks::set_name(RuntimeOrigin::signed(1), b"Ga".to_vec()), Error::::TooShort ); assert_noop!( - Nicks::set_name(Origin::signed(1), b"Gavin James Wood, Esquire".to_vec()), + Nicks::set_name(RuntimeOrigin::signed(1), b"Gavin James Wood, Esquire".to_vec()), Error::::TooLong ); - assert_ok!(Nicks::set_name(Origin::signed(1), b"Dave".to_vec())); - assert_noop!(Nicks::kill_name(Origin::signed(2), 1), BadOrigin); - assert_noop!(Nicks::force_name(Origin::signed(2), 1, b"Whatever".to_vec()), BadOrigin); + assert_ok!(Nicks::set_name(RuntimeOrigin::signed(1), b"Dave".to_vec())); + assert_noop!(Nicks::kill_name(RuntimeOrigin::signed(2), 1), BadOrigin); + assert_noop!( + Nicks::force_name(RuntimeOrigin::signed(2), 1, b"Whatever".to_vec()), + BadOrigin + ); }); } } diff --git a/frame/node-authorization/src/lib.rs b/frame/node-authorization/src/lib.rs index 42f1fcf7b55e6..638a96eb3321a 100644 --- a/frame/node-authorization/src/lib.rs +++ b/frame/node-authorization/src/lib.rs @@ -78,16 +78,16 @@ pub mod pallet { type MaxPeerIdLength: Get; /// The origin which can add a well known node. - type AddOrigin: EnsureOrigin; + type AddOrigin: EnsureOrigin; /// The origin which can remove a well known node. - type RemoveOrigin: EnsureOrigin; + type RemoveOrigin: EnsureOrigin; /// The origin which can swap the well known nodes. - type SwapOrigin: EnsureOrigin; + type SwapOrigin: EnsureOrigin; /// The origin which can reset the well known nodes. - type ResetOrigin: EnsureOrigin; + type ResetOrigin: EnsureOrigin; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; diff --git a/frame/node-authorization/src/mock.rs b/frame/node-authorization/src/mock.rs index 448f8cef80e28..fcf7ff0189332 100644 --- a/frame/node-authorization/src/mock.rs +++ b/frame/node-authorization/src/mock.rs @@ -52,7 +52,7 @@ impl frame_system::Config for Test { type DbWeight = (); type BlockWeights = (); type BlockLength = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = H256; diff --git a/frame/node-authorization/src/tests.rs b/frame/node-authorization/src/tests.rs index ba78d14912133..d9db09db4f46f 100644 --- a/frame/node-authorization/src/tests.rs +++ b/frame/node-authorization/src/tests.rs @@ -26,19 +26,27 @@ use sp_runtime::traits::BadOrigin; fn add_well_known_node_works() { new_test_ext().execute_with(|| { assert_noop!( - NodeAuthorization::add_well_known_node(Origin::signed(2), test_node(15), 15), + NodeAuthorization::add_well_known_node(RuntimeOrigin::signed(2), test_node(15), 15), BadOrigin ); assert_noop!( - NodeAuthorization::add_well_known_node(Origin::signed(1), PeerId(vec![1, 2, 3]), 15), + NodeAuthorization::add_well_known_node( + RuntimeOrigin::signed(1), + PeerId(vec![1, 2, 3]), + 15 + ), Error::::PeerIdTooLong ); assert_noop!( - NodeAuthorization::add_well_known_node(Origin::signed(1), test_node(20), 20), + NodeAuthorization::add_well_known_node(RuntimeOrigin::signed(1), test_node(20), 20), Error::::AlreadyJoined ); - assert_ok!(NodeAuthorization::add_well_known_node(Origin::signed(1), test_node(15), 15)); + assert_ok!(NodeAuthorization::add_well_known_node( + RuntimeOrigin::signed(1), + test_node(15), + 15 + )); assert_eq!( WellKnownNodes::::get(), BTreeSet::from_iter(vec![test_node(10), test_node(15), test_node(20), test_node(30)]) @@ -49,7 +57,7 @@ fn add_well_known_node_works() { assert_eq!(Owners::::get(test_node(15)), Some(15)); assert_noop!( - NodeAuthorization::add_well_known_node(Origin::signed(1), test_node(25), 25), + NodeAuthorization::add_well_known_node(RuntimeOrigin::signed(1), test_node(25), 25), Error::::TooManyNodes ); }); @@ -59,15 +67,18 @@ fn add_well_known_node_works() { fn remove_well_known_node_works() { new_test_ext().execute_with(|| { assert_noop!( - NodeAuthorization::remove_well_known_node(Origin::signed(3), test_node(20)), + NodeAuthorization::remove_well_known_node(RuntimeOrigin::signed(3), test_node(20)), BadOrigin ); assert_noop!( - NodeAuthorization::remove_well_known_node(Origin::signed(2), PeerId(vec![1, 2, 3])), + NodeAuthorization::remove_well_known_node( + RuntimeOrigin::signed(2), + PeerId(vec![1, 2, 3]) + ), Error::::PeerIdTooLong ); assert_noop!( - NodeAuthorization::remove_well_known_node(Origin::signed(2), test_node(40)), + NodeAuthorization::remove_well_known_node(RuntimeOrigin::signed(2), test_node(40)), Error::::NotExist ); @@ -77,7 +88,10 @@ fn remove_well_known_node_works() { ); assert!(AdditionalConnections::::contains_key(test_node(20))); - assert_ok!(NodeAuthorization::remove_well_known_node(Origin::signed(2), test_node(20))); + assert_ok!(NodeAuthorization::remove_well_known_node( + RuntimeOrigin::signed(2), + test_node(20) + )); assert_eq!( WellKnownNodes::::get(), BTreeSet::from_iter(vec![test_node(10), test_node(30)]) @@ -91,12 +105,16 @@ fn remove_well_known_node_works() { fn swap_well_known_node_works() { new_test_ext().execute_with(|| { assert_noop!( - NodeAuthorization::swap_well_known_node(Origin::signed(4), test_node(20), test_node(5)), + NodeAuthorization::swap_well_known_node( + RuntimeOrigin::signed(4), + test_node(20), + test_node(5) + ), BadOrigin ); assert_noop!( NodeAuthorization::swap_well_known_node( - Origin::signed(3), + RuntimeOrigin::signed(3), PeerId(vec![1, 2, 3]), test_node(20) ), @@ -104,7 +122,7 @@ fn swap_well_known_node_works() { ); assert_noop!( NodeAuthorization::swap_well_known_node( - Origin::signed(3), + RuntimeOrigin::signed(3), test_node(20), PeerId(vec![1, 2, 3]) ), @@ -112,7 +130,7 @@ fn swap_well_known_node_works() { ); assert_ok!(NodeAuthorization::swap_well_known_node( - Origin::signed(3), + RuntimeOrigin::signed(3), test_node(20), test_node(20) )); @@ -122,12 +140,16 @@ fn swap_well_known_node_works() { ); assert_noop!( - NodeAuthorization::swap_well_known_node(Origin::signed(3), test_node(15), test_node(5)), + NodeAuthorization::swap_well_known_node( + RuntimeOrigin::signed(3), + test_node(15), + test_node(5) + ), Error::::NotExist ); assert_noop!( NodeAuthorization::swap_well_known_node( - Origin::signed(3), + RuntimeOrigin::signed(3), test_node(20), test_node(30) ), @@ -139,7 +161,7 @@ fn swap_well_known_node_works() { BTreeSet::from_iter(vec![test_node(15)]), ); assert_ok!(NodeAuthorization::swap_well_known_node( - Origin::signed(3), + RuntimeOrigin::signed(3), test_node(20), test_node(5) )); @@ -162,14 +184,14 @@ fn reset_well_known_nodes_works() { new_test_ext().execute_with(|| { assert_noop!( NodeAuthorization::reset_well_known_nodes( - Origin::signed(3), + RuntimeOrigin::signed(3), vec![(test_node(15), 15), (test_node(5), 5), (test_node(20), 20)] ), BadOrigin ); assert_noop!( NodeAuthorization::reset_well_known_nodes( - Origin::signed(4), + RuntimeOrigin::signed(4), vec![ (test_node(15), 15), (test_node(5), 5), @@ -181,7 +203,7 @@ fn reset_well_known_nodes_works() { ); assert_ok!(NodeAuthorization::reset_well_known_nodes( - Origin::signed(4), + RuntimeOrigin::signed(4), vec![(test_node(15), 15), (test_node(5), 5), (test_node(20), 20)] )); assert_eq!( @@ -198,15 +220,15 @@ fn reset_well_known_nodes_works() { fn claim_node_works() { new_test_ext().execute_with(|| { assert_noop!( - NodeAuthorization::claim_node(Origin::signed(1), PeerId(vec![1, 2, 3])), + NodeAuthorization::claim_node(RuntimeOrigin::signed(1), PeerId(vec![1, 2, 3])), Error::::PeerIdTooLong ); assert_noop!( - NodeAuthorization::claim_node(Origin::signed(1), test_node(20)), + NodeAuthorization::claim_node(RuntimeOrigin::signed(1), test_node(20)), Error::::AlreadyClaimed ); - assert_ok!(NodeAuthorization::claim_node(Origin::signed(15), test_node(15))); + assert_ok!(NodeAuthorization::claim_node(RuntimeOrigin::signed(15), test_node(15))); assert_eq!(Owners::::get(test_node(15)), Some(15)); }); } @@ -215,21 +237,21 @@ fn claim_node_works() { fn remove_claim_works() { new_test_ext().execute_with(|| { assert_noop!( - NodeAuthorization::remove_claim(Origin::signed(15), PeerId(vec![1, 2, 3])), + NodeAuthorization::remove_claim(RuntimeOrigin::signed(15), PeerId(vec![1, 2, 3])), Error::::PeerIdTooLong ); assert_noop!( - NodeAuthorization::remove_claim(Origin::signed(15), test_node(15)), + NodeAuthorization::remove_claim(RuntimeOrigin::signed(15), test_node(15)), Error::::NotClaimed ); assert_noop!( - NodeAuthorization::remove_claim(Origin::signed(15), test_node(20)), + NodeAuthorization::remove_claim(RuntimeOrigin::signed(15), test_node(20)), Error::::NotOwner ); assert_noop!( - NodeAuthorization::remove_claim(Origin::signed(20), test_node(20)), + NodeAuthorization::remove_claim(RuntimeOrigin::signed(20), test_node(20)), Error::::PermissionDenied ); @@ -238,7 +260,7 @@ fn remove_claim_works() { test_node(15), BTreeSet::from_iter(vec![test_node(20)]), ); - assert_ok!(NodeAuthorization::remove_claim(Origin::signed(15), test_node(15))); + assert_ok!(NodeAuthorization::remove_claim(RuntimeOrigin::signed(15), test_node(15))); assert!(!Owners::::contains_key(test_node(15))); assert!(!AdditionalConnections::::contains_key(test_node(15))); }); @@ -248,20 +270,20 @@ fn remove_claim_works() { fn transfer_node_works() { new_test_ext().execute_with(|| { assert_noop!( - NodeAuthorization::transfer_node(Origin::signed(15), PeerId(vec![1, 2, 3]), 10), + NodeAuthorization::transfer_node(RuntimeOrigin::signed(15), PeerId(vec![1, 2, 3]), 10), Error::::PeerIdTooLong ); assert_noop!( - NodeAuthorization::transfer_node(Origin::signed(15), test_node(15), 10), + NodeAuthorization::transfer_node(RuntimeOrigin::signed(15), test_node(15), 10), Error::::NotClaimed ); assert_noop!( - NodeAuthorization::transfer_node(Origin::signed(15), test_node(20), 10), + NodeAuthorization::transfer_node(RuntimeOrigin::signed(15), test_node(20), 10), Error::::NotOwner ); - assert_ok!(NodeAuthorization::transfer_node(Origin::signed(20), test_node(20), 15)); + assert_ok!(NodeAuthorization::transfer_node(RuntimeOrigin::signed(20), test_node(20), 15)); assert_eq!(Owners::::get(test_node(20)), Some(15)); }); } @@ -271,7 +293,7 @@ fn add_connections_works() { new_test_ext().execute_with(|| { assert_noop!( NodeAuthorization::add_connections( - Origin::signed(15), + RuntimeOrigin::signed(15), PeerId(vec![1, 2, 3]), vec![test_node(5)] ), @@ -279,7 +301,7 @@ fn add_connections_works() { ); assert_noop!( NodeAuthorization::add_connections( - Origin::signed(15), + RuntimeOrigin::signed(15), test_node(15), vec![test_node(5)] ), @@ -288,7 +310,7 @@ fn add_connections_works() { assert_noop!( NodeAuthorization::add_connections( - Origin::signed(15), + RuntimeOrigin::signed(15), test_node(20), vec![test_node(5)] ), @@ -296,7 +318,7 @@ fn add_connections_works() { ); assert_ok!(NodeAuthorization::add_connections( - Origin::signed(20), + RuntimeOrigin::signed(20), test_node(20), vec![test_node(15), test_node(5), test_node(25), test_node(20)] )); @@ -312,7 +334,7 @@ fn remove_connections_works() { new_test_ext().execute_with(|| { assert_noop!( NodeAuthorization::remove_connections( - Origin::signed(15), + RuntimeOrigin::signed(15), PeerId(vec![1, 2, 3]), vec![test_node(5)] ), @@ -320,7 +342,7 @@ fn remove_connections_works() { ); assert_noop!( NodeAuthorization::remove_connections( - Origin::signed(15), + RuntimeOrigin::signed(15), test_node(15), vec![test_node(5)] ), @@ -329,7 +351,7 @@ fn remove_connections_works() { assert_noop!( NodeAuthorization::remove_connections( - Origin::signed(15), + RuntimeOrigin::signed(15), test_node(20), vec![test_node(5)] ), @@ -341,7 +363,7 @@ fn remove_connections_works() { BTreeSet::from_iter(vec![test_node(5), test_node(15), test_node(25)]), ); assert_ok!(NodeAuthorization::remove_connections( - Origin::signed(20), + RuntimeOrigin::signed(20), test_node(20), vec![test_node(15), test_node(5)] )); diff --git a/frame/nomination-pools/benchmarking/src/lib.rs b/frame/nomination-pools/benchmarking/src/lib.rs index 18b081367d135..c31bcb1546ecd 100644 --- a/frame/nomination-pools/benchmarking/src/lib.rs +++ b/frame/nomination-pools/benchmarking/src/lib.rs @@ -26,7 +26,7 @@ mod mock; use frame_benchmarking::{account, frame_support::traits::Currency, vec, whitelist_account, Vec}; use frame_election_provider_support::SortedListProvider; use frame_support::{assert_ok, ensure, traits::Get}; -use frame_system::RawOrigin as Origin; +use frame_system::RawOrigin as RuntimeOrigin; use pallet_nomination_pools::{ BalanceOf, BondExtra, BondedPoolInner, BondedPools, ConfigOp, MaxPoolMembers, MaxPoolMembersPerPool, MaxPools, Metadata, MinCreateBond, MinJoinBond, Pallet as Pools, @@ -52,12 +52,6 @@ pub trait Config: pub struct Pallet(Pools); -fn min_create_bond() -> BalanceOf { - MinCreateBond::::get() - .max(T::StakingInterface::minimum_bond()) - .max(CurrencyOf::::minimum_balance()) -} - fn create_funded_user_with_balance( string: &'static str, n: u32, @@ -80,7 +74,7 @@ fn create_pool_account( let pool_creator_lookup = T::Lookup::unlookup(pool_creator.clone()); Pools::::create( - Origin::Signed(pool_creator.clone()).into(), + RuntimeOrigin::Signed(pool_creator.clone()).into(), balance, pool_creator_lookup.clone(), pool_creator_lookup.clone(), @@ -203,7 +197,7 @@ impl ListScenario { maybe_pool.as_mut().map(|pool| pool.points -= amount) }); - Pools::::join(Origin::Signed(joiner.clone()).into(), amount, 1).unwrap(); + Pools::::join(RuntimeOrigin::Signed(joiner.clone()).into(), amount, 1).unwrap(); // check that the vote weight is still the same as the original bonded let weight_of = pallet_staking::Pallet::::weight_of_fn(); @@ -220,7 +214,7 @@ impl ListScenario { frame_benchmarking::benchmarks! { join { - let origin_weight = min_create_bond::() * 2u32.into(); + let origin_weight = Pools::::depositor_min_bond() * 2u32.into(); // setup the worst case list scenario. let scenario = ListScenario::::new(origin_weight, true)?; @@ -236,7 +230,7 @@ frame_benchmarking::benchmarks! { = create_funded_user_with_balance::("joiner", 0, joiner_free); whitelist_account!(joiner); - }: _(Origin::Signed(joiner.clone()), max_additional, 1) + }: _(RuntimeOrigin::Signed(joiner.clone()), max_additional, 1) verify { assert_eq!(CurrencyOf::::free_balance(&joiner), joiner_free - max_additional); assert_eq!( @@ -246,13 +240,13 @@ frame_benchmarking::benchmarks! { } bond_extra_transfer { - let origin_weight = min_create_bond::() * 2u32.into(); + let origin_weight = Pools::::depositor_min_bond() * 2u32.into(); let scenario = ListScenario::::new(origin_weight, true)?; let extra = scenario.dest_weight - origin_weight; // creator of the src pool will bond-extra, bumping itself to dest bag. - }: bond_extra(Origin::Signed(scenario.creator1.clone()), BondExtra::FreeBalance(extra)) + }: bond_extra(RuntimeOrigin::Signed(scenario.creator1.clone()), BondExtra::FreeBalance(extra)) verify { assert!( T::StakingInterface::active_stake(&scenario.origin1).unwrap() >= @@ -261,7 +255,7 @@ frame_benchmarking::benchmarks! { } bond_extra_reward { - let origin_weight = min_create_bond::() * 2u32.into(); + let origin_weight = Pools::::depositor_min_bond() * 2u32.into(); let scenario = ListScenario::::new(origin_weight, true)?; let extra = (scenario.dest_weight - origin_weight).max(CurrencyOf::::minimum_balance()); @@ -270,7 +264,7 @@ frame_benchmarking::benchmarks! { assert!(extra >= CurrencyOf::::minimum_balance()); CurrencyOf::::deposit_creating(&reward_account1, extra); - }: bond_extra(Origin::Signed(scenario.creator1.clone()), BondExtra::Rewards) + }: bond_extra(RuntimeOrigin::Signed(scenario.creator1.clone()), BondExtra::Rewards) verify { assert!( T::StakingInterface::active_stake(&scenario.origin1).unwrap() >= @@ -279,7 +273,7 @@ frame_benchmarking::benchmarks! { } claim_payout { - let origin_weight = min_create_bond::() * 2u32.into(); + let origin_weight = Pools::::depositor_min_bond() * 2u32.into(); let ed = CurrencyOf::::minimum_balance(); let (depositor, pool_account) = create_pool_account::(0, origin_weight); let reward_account = Pools::::create_reward_account(1); @@ -294,7 +288,7 @@ frame_benchmarking::benchmarks! { ); whitelist_account!(depositor); - }:_(Origin::Signed(depositor.clone())) + }:_(RuntimeOrigin::Signed(depositor.clone())) verify { assert_eq!( CurrencyOf::::free_balance(&depositor), @@ -309,7 +303,7 @@ frame_benchmarking::benchmarks! { unbond { // The weight the nominator will start at. The value used here is expected to be // significantly higher than the first position in a list (e.g. the first bag threshold). - let origin_weight = min_create_bond::() * 200u32.into(); + let origin_weight = Pools::::depositor_min_bond() * 200u32.into(); let scenario = ListScenario::::new(origin_weight, false)?; let amount = origin_weight - scenario.dest_weight; @@ -318,7 +312,7 @@ frame_benchmarking::benchmarks! { let member_id_lookup = T::Lookup::unlookup(member_id.clone()); let all_points = PoolMembers::::get(&member_id).unwrap().points; whitelist_account!(member_id); - }: _(Origin::Signed(member_id.clone()), member_id_lookup, all_points) + }: _(RuntimeOrigin::Signed(member_id.clone()), member_id_lookup, all_points) verify { let bonded_after = T::StakingInterface::active_stake(&scenario.origin1).unwrap(); // We at least went down to the destination bag @@ -340,13 +334,13 @@ frame_benchmarking::benchmarks! { pool_withdraw_unbonded { let s in 0 .. MAX_SPANS; - let min_create_bond = min_create_bond::(); + let min_create_bond = Pools::::depositor_min_bond(); let (depositor, pool_account) = create_pool_account::(0, min_create_bond); // Add a new member let min_join_bond = MinJoinBond::::get().max(CurrencyOf::::minimum_balance()); let joiner = create_funded_user_with_balance::("joiner", 0, min_join_bond * 2u32.into()); - Pools::::join(Origin::Signed(joiner.clone()).into(), min_join_bond, 1) + Pools::::join(RuntimeOrigin::Signed(joiner.clone()).into(), min_join_bond, 1) .unwrap(); // Sanity check join worked @@ -357,7 +351,7 @@ frame_benchmarking::benchmarks! { assert_eq!(CurrencyOf::::free_balance(&joiner), min_join_bond); // Unbond the new member - Pools::::fully_unbond(Origin::Signed(joiner.clone()).into(), joiner.clone()).unwrap(); + Pools::::fully_unbond(RuntimeOrigin::Signed(joiner.clone()).into(), joiner.clone()).unwrap(); // Sanity check that unbond worked assert_eq!( @@ -371,7 +365,7 @@ frame_benchmarking::benchmarks! { // Add `s` count of slashing spans to storage. pallet_staking::benchmarking::add_slashing_spans::(&pool_account, s); whitelist_account!(pool_account); - }: _(Origin::Signed(pool_account.clone()), 1, s) + }: _(RuntimeOrigin::Signed(pool_account.clone()), 1, s) verify { // The joiners funds didn't change assert_eq!(CurrencyOf::::free_balance(&joiner), min_join_bond); @@ -382,14 +376,14 @@ frame_benchmarking::benchmarks! { withdraw_unbonded_update { let s in 0 .. MAX_SPANS; - let min_create_bond = min_create_bond::(); + let min_create_bond = Pools::::depositor_min_bond(); let (depositor, pool_account) = create_pool_account::(0, min_create_bond); // Add a new member let min_join_bond = MinJoinBond::::get().max(CurrencyOf::::minimum_balance()); let joiner = create_funded_user_with_balance::("joiner", 0, min_join_bond * 2u32.into()); let joiner_lookup = T::Lookup::unlookup(joiner.clone()); - Pools::::join(Origin::Signed(joiner.clone()).into(), min_join_bond, 1) + Pools::::join(RuntimeOrigin::Signed(joiner.clone()).into(), min_join_bond, 1) .unwrap(); // Sanity check join worked @@ -401,7 +395,7 @@ frame_benchmarking::benchmarks! { // Unbond the new member pallet_staking::CurrentEra::::put(0); - Pools::::fully_unbond(Origin::Signed(joiner.clone()).into(), joiner.clone()).unwrap(); + Pools::::fully_unbond(RuntimeOrigin::Signed(joiner.clone()).into(), joiner.clone()).unwrap(); // Sanity check that unbond worked assert_eq!( @@ -415,7 +409,7 @@ frame_benchmarking::benchmarks! { pallet_staking::benchmarking::add_slashing_spans::(&pool_account, s); whitelist_account!(joiner); - }: withdraw_unbonded(Origin::Signed(joiner.clone()), joiner_lookup, s) + }: withdraw_unbonded(RuntimeOrigin::Signed(joiner.clone()), joiner_lookup, s) verify { assert_eq!( CurrencyOf::::free_balance(&joiner), @@ -428,7 +422,7 @@ frame_benchmarking::benchmarks! { withdraw_unbonded_kill { let s in 0 .. MAX_SPANS; - let min_create_bond = min_create_bond::(); + let min_create_bond = Pools::::depositor_min_bond(); let (depositor, pool_account) = create_pool_account::(0, min_create_bond); let depositor_lookup = T::Lookup::unlookup(depositor.clone()); @@ -448,7 +442,7 @@ frame_benchmarking::benchmarks! { // up when unbonding. let reward_account = Pools::::create_reward_account(1); assert!(frame_system::Account::::contains_key(&reward_account)); - Pools::::fully_unbond(Origin::Signed(depositor.clone()).into(), depositor.clone()).unwrap(); + Pools::::fully_unbond(RuntimeOrigin::Signed(depositor.clone()).into(), depositor.clone()).unwrap(); // Sanity check that unbond worked assert_eq!( @@ -473,7 +467,7 @@ frame_benchmarking::benchmarks! { assert!(frame_system::Account::::contains_key(&reward_account)); whitelist_account!(depositor); - }: withdraw_unbonded(Origin::Signed(depositor.clone()), depositor_lookup, s) + }: withdraw_unbonded(RuntimeOrigin::Signed(depositor.clone()), depositor_lookup, s) verify { // Pool removal worked assert!(!pallet_staking::Ledger::::contains_key(&pool_account)); @@ -493,20 +487,20 @@ frame_benchmarking::benchmarks! { } create { - let min_create_bond = min_create_bond::(); + let min_create_bond = Pools::::depositor_min_bond(); let depositor: T::AccountId = account("depositor", USER_SEED, 0); let depositor_lookup = T::Lookup::unlookup(depositor.clone()); // Give the depositor some balance to bond CurrencyOf::::make_free_balance_be(&depositor, min_create_bond * 2u32.into()); - // Make sure no pools exist as a pre-condition for our verify checks + // Make sure no Pools exist at a pre-condition for our verify checks assert_eq!(RewardPools::::count(), 0); assert_eq!(BondedPools::::count(), 0); whitelist_account!(depositor); }: _( - Origin::Signed(depositor.clone()), + RuntimeOrigin::Signed(depositor.clone()), min_create_bond, depositor_lookup.clone(), depositor_lookup.clone(), @@ -540,7 +534,7 @@ frame_benchmarking::benchmarks! { let n in 1 .. T::MaxNominations::get(); // Create a pool - let min_create_bond = min_create_bond::() * 2u32.into(); + let min_create_bond = Pools::::depositor_min_bond() * 2u32.into(); let (depositor, pool_account) = create_pool_account::(0, min_create_bond); // Create some accounts to nominate. For the sake of benchmarking they don't need to be @@ -550,7 +544,7 @@ frame_benchmarking::benchmarks! { .collect(); whitelist_account!(depositor); - }:_(Origin::Signed(depositor.clone()), 1, validators) + }:_(RuntimeOrigin::Signed(depositor.clone()), 1, validators) verify { assert_eq!(RewardPools::::count(), 1); assert_eq!(BondedPools::::count(), 1); @@ -577,7 +571,7 @@ frame_benchmarking::benchmarks! { set_state { // Create a pool - let min_create_bond = min_create_bond::(); + let min_create_bond = Pools::::depositor_min_bond(); let (depositor, pool_account) = create_pool_account::(0, min_create_bond); BondedPools::::mutate(&1, |maybe_pool| { // Force the pool into an invalid state @@ -586,7 +580,7 @@ frame_benchmarking::benchmarks! { let caller = account("caller", 0, USER_SEED); whitelist_account!(caller); - }:_(Origin::Signed(caller), 1, PoolState::Destroying) + }:_(RuntimeOrigin::Signed(caller), 1, PoolState::Destroying) verify { assert_eq!(BondedPools::::get(1).unwrap().state, PoolState::Destroying); } @@ -595,20 +589,20 @@ frame_benchmarking::benchmarks! { let n in 1 .. ::MaxMetadataLen::get(); // Create a pool - let (depositor, pool_account) = create_pool_account::(0, min_create_bond::() * 2u32.into()); + let (depositor, pool_account) = create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into()); // Create metadata of the max possible size let metadata: Vec = (0..n).map(|_| 42).collect(); whitelist_account!(depositor); - }:_(Origin::Signed(depositor), 1, metadata.clone()) + }:_(RuntimeOrigin::Signed(depositor), 1, metadata.clone()) verify { assert_eq!(Metadata::::get(&1), metadata); } set_configs { }:_( - Origin::Root, + RuntimeOrigin::Root, ConfigOp::Set(BalanceOf::::max_value()), ConfigOp::Set(BalanceOf::::max_value()), ConfigOp::Set(u32::MAX), @@ -624,10 +618,10 @@ frame_benchmarking::benchmarks! { update_roles { let first_id = pallet_nomination_pools::LastPoolId::::get() + 1; - let (root, _) = create_pool_account::(0, min_create_bond::() * 2u32.into()); + let (root, _) = create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into()); let random: T::AccountId = account("but is anything really random in computers..?", 0, USER_SEED); }:_( - Origin::Signed(root.clone()), + RuntimeOrigin::Signed(root.clone()), first_id, ConfigOp::Set(random.clone()), ConfigOp::Set(random.clone()), @@ -646,18 +640,18 @@ frame_benchmarking::benchmarks! { chill { // Create a pool - let (depositor, pool_account) = create_pool_account::(0, min_create_bond::() * 2u32.into()); + let (depositor, pool_account) = create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into()); // Nominate with the pool. let validators: Vec<_> = (0..T::MaxNominations::get()) .map(|i| account("stash", USER_SEED, i)) .collect(); - assert_ok!(Pools::::nominate(Origin::Signed(depositor.clone()).into(), 1, validators)); + assert_ok!(Pools::::nominate(RuntimeOrigin::Signed(depositor.clone()).into(), 1, validators)); assert!(T::StakingInterface::nominations(Pools::::create_bonded_account(1)).is_some()); whitelist_account!(depositor); - }:_(Origin::Signed(depositor.clone()), 1) + }:_(RuntimeOrigin::Signed(depositor.clone()), 1) verify { assert!(T::StakingInterface::nominations(Pools::::create_bonded_account(1)).is_none()); } diff --git a/frame/nomination-pools/benchmarking/src/mock.rs b/frame/nomination-pools/benchmarking/src/mock.rs index 2dcac34d39a11..0f617f0bf6f4b 100644 --- a/frame/nomination-pools/benchmarking/src/mock.rs +++ b/frame/nomination-pools/benchmarking/src/mock.rs @@ -33,7 +33,7 @@ impl frame_system::Config for Runtime { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; @@ -115,6 +115,7 @@ impl pallet_staking::Config for Runtime { type VoterList = VoterList; type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; + type HistoryDepth = ConstU32<84>; type OnStakerSlash = 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 dfe4bf1931068..28d10ce573401 100644 --- a/frame/nomination-pools/src/lib.rs +++ b/frame/nomination-pools/src/lib.rs @@ -2184,10 +2184,11 @@ impl Pallet { /// /// It is essentially `max { MinNominatorBond, MinCreateBond, MinJoinBond }`, where the former /// is coming from the staking pallet and the latter two are configured in this pallet. - fn depositor_min_bond() -> BalanceOf { + pub fn depositor_min_bond() -> BalanceOf { T::StakingInterface::minimum_bond() .max(MinCreateBond::::get()) .max(MinJoinBond::::get()) + .max(T::Currency::minimum_balance()) } /// Remove everything related to the given bonded pool. /// diff --git a/frame/nomination-pools/src/migration.rs b/frame/nomination-pools/src/migration.rs index 4d78f2fa76c96..b73141c95f72c 100644 --- a/frame/nomination-pools/src/migration.rs +++ b/frame/nomination-pools/src/migration.rs @@ -119,7 +119,7 @@ pub mod v2 { ExtBuilder::default().build_and_execute(|| { let join = |x| { Balances::make_free_balance_be(&x, Balances::minimum_balance() + 10); - frame_support::assert_ok!(Pools::join(Origin::signed(x), 10, 1)); + frame_support::assert_ok!(Pools::join(RuntimeOrigin::signed(x), 10, 1)); }; assert_eq!(BondedPool::::get(1).unwrap().points, 10); diff --git a/frame/nomination-pools/src/mock.rs b/frame/nomination-pools/src/mock.rs index 13df09c47fa92..1b3372dae56ee 100644 --- a/frame/nomination-pools/src/mock.rs +++ b/frame/nomination-pools/src/mock.rs @@ -128,7 +128,7 @@ impl sp_staking::StakingInterface for StakingMock { impl frame_system::Config for Runtime { type SS58Prefix = (); type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; @@ -291,7 +291,7 @@ impl ExtBuilder { let amount_to_bond = Pools::depositor_min_bond(); Balances::make_free_balance_be(&10, amount_to_bond * 5); assert_ok!(Pools::create(RawOrigin::Signed(10).into(), amount_to_bond, 900, 901, 902)); - assert_ok!(Pools::set_metadata(Origin::signed(900), 1, vec![1, 1])); + assert_ok!(Pools::set_metadata(RuntimeOrigin::signed(900), 1, vec![1, 1])); let last_pool = LastPoolId::::get(); for (account_id, bonded) in self.members { Balances::make_free_balance_be(&account_id, bonded * 2); @@ -353,7 +353,7 @@ pub fn fully_unbond_permissioned(member: AccountId) -> DispatchResult { let points = PoolMembers::::get(&member) .map(|d| d.active_points()) .unwrap_or_default(); - Pools::unbond(Origin::signed(member), member, points) + Pools::unbond(RuntimeOrigin::signed(member), member, points) } #[cfg(test)] diff --git a/frame/nomination-pools/src/tests.rs b/frame/nomination-pools/src/tests.rs index bcc735a9cef99..5074a7ffa695a 100644 --- a/frame/nomination-pools/src/tests.rs +++ b/frame/nomination-pools/src/tests.rs @@ -443,7 +443,7 @@ mod join { assert!(!PoolMembers::::contains_key(&11)); // When - assert_ok!(Pools::join(Origin::signed(11), 2, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(11), 2, 1)); // Then @@ -471,7 +471,7 @@ mod join { assert!(!PoolMembers::::contains_key(&12)); // When - assert_ok!(Pools::join(Origin::signed(12), 12, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(12), 12, 1)); // Then assert_eq!( @@ -494,15 +494,21 @@ mod join { assert_eq!(PoolMembers::::get(&10).unwrap().pool_id, 1); assert_noop!( - Pools::join(Origin::signed(10), 420, 123), + Pools::join(RuntimeOrigin::signed(10), 420, 123), Error::::AccountBelongsToOtherPool ); - assert_noop!(Pools::join(Origin::signed(11), 420, 123), Error::::PoolNotFound); + assert_noop!( + Pools::join(RuntimeOrigin::signed(11), 420, 123), + Error::::PoolNotFound + ); // Force the pools bonded balance to 0, simulating a 100% slash StakingMock::set_bonded_balance(Pools::create_bonded_account(1), 0); - assert_noop!(Pools::join(Origin::signed(11), 420, 1), Error::::OverflowRisk); + assert_noop!( + Pools::join(RuntimeOrigin::signed(11), 420, 1), + Error::::OverflowRisk + ); // Given a mocked bonded pool BondedPool:: { @@ -527,27 +533,33 @@ mod join { Pools::create_bonded_account(123), max_points_to_balance, ); - assert_noop!(Pools::join(Origin::signed(11), 420, 123), Error::::OverflowRisk); + assert_noop!( + Pools::join(RuntimeOrigin::signed(11), 420, 123), + Error::::OverflowRisk + ); StakingMock::set_bonded_balance( Pools::create_bonded_account(123), Balance::MAX / max_points_to_balance, ); // Balance needs to be gt Balance::MAX / `MaxPointsToBalance` - assert_noop!(Pools::join(Origin::signed(11), 5, 123), Error::::OverflowRisk); + assert_noop!( + Pools::join(RuntimeOrigin::signed(11), 5, 123), + Error::::OverflowRisk + ); StakingMock::set_bonded_balance(Pools::create_bonded_account(1), max_points_to_balance); // Cannot join a pool that isn't open unsafe_set_state(123, PoolState::Blocked); assert_noop!( - Pools::join(Origin::signed(11), max_points_to_balance, 123), + Pools::join(RuntimeOrigin::signed(11), max_points_to_balance, 123), Error::::NotOpen ); unsafe_set_state(123, PoolState::Destroying); assert_noop!( - Pools::join(Origin::signed(11), max_points_to_balance, 123), + Pools::join(RuntimeOrigin::signed(11), max_points_to_balance, 123), Error::::NotOpen ); @@ -556,7 +568,7 @@ mod join { // Then assert_noop!( - Pools::join(Origin::signed(11), 99, 123), + Pools::join(RuntimeOrigin::signed(11), 99, 123), Error::::MinimumBondNotMet ); }); @@ -578,7 +590,7 @@ mod join { }, } .put(); - let _ = Pools::join(Origin::signed(11), 420, 123); + let _ = Pools::join(RuntimeOrigin::signed(11), 420, 123); }); } @@ -591,7 +603,7 @@ mod join { let account = i + 100; Balances::make_free_balance_be(&account, 100 + Balances::minimum_balance()); - assert_ok!(Pools::join(Origin::signed(account), 100, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(account), 100, 1)); } Balances::make_free_balance_be(&103, 100 + Balances::minimum_balance()); @@ -608,7 +620,7 @@ mod join { ); assert_noop!( - Pools::join(Origin::signed(103), 100, 1), + Pools::join(RuntimeOrigin::signed(103), 100, 1), Error::::MaxPoolMembers ); @@ -617,7 +629,7 @@ mod join { assert_eq!(MaxPoolMembers::::get(), Some(4)); Balances::make_free_balance_be(&104, 100 + Balances::minimum_balance()); - assert_ok!(Pools::create(Origin::signed(104), 100, 104, 104, 104)); + assert_ok!(Pools::create(RuntimeOrigin::signed(104), 100, 104, 104, 104)); let pool_account = BondedPools::::iter() .find(|(_, bonded_pool)| bonded_pool.roles.depositor == 104) @@ -634,7 +646,7 @@ mod join { ); assert_noop!( - Pools::join(Origin::signed(103), 100, pool_account), + Pools::join(RuntimeOrigin::signed(103), 100, pool_account), Error::::MaxPoolMembers ); }); @@ -692,7 +704,7 @@ mod claim_payout { let _ = pool_events_since_last_call(); // When - assert_ok!(Pools::claim_payout(Origin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); // Then assert_eq!( @@ -708,7 +720,7 @@ mod claim_payout { assert_eq!(Balances::free_balance(&default_reward_account()), ed + 90); // When - assert_ok!(Pools::claim_payout(Origin::signed(40))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(40))); // Then assert_eq!( @@ -721,7 +733,7 @@ mod claim_payout { assert_eq!(Balances::free_balance(&default_reward_account()), ed + 50); // When - assert_ok!(Pools::claim_payout(Origin::signed(50))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(50))); // Then assert_eq!( @@ -737,7 +749,7 @@ mod claim_payout { assert_ok!(Balances::mutate_account(&default_reward_account(), |a| a.free += 50)); // When - assert_ok!(Pools::claim_payout(Origin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); // Then assert_eq!( @@ -750,7 +762,7 @@ mod claim_payout { assert_eq!(Balances::free_balance(&default_reward_account()), ed + 45); // When - assert_ok!(Pools::claim_payout(Origin::signed(40))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(40))); // Then assert_eq!( @@ -767,7 +779,7 @@ mod claim_payout { assert_eq!(Balances::free_balance(&default_reward_account()), ed + 75); // When - assert_ok!(Pools::claim_payout(Origin::signed(50))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(50))); // Then assert_eq!( @@ -780,7 +792,7 @@ mod claim_payout { assert_eq!(Balances::free_balance(&default_reward_account()), ed + 25); // When - assert_ok!(Pools::claim_payout(Origin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); // Then assert_eq!( @@ -797,7 +809,7 @@ mod claim_payout { assert_eq!(Balances::free_balance(&default_reward_account()), ed + 420); // When - assert_ok!(Pools::claim_payout(Origin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); // Then assert_eq!( @@ -816,7 +828,7 @@ mod claim_payout { assert_eq!(Balances::free_balance(&default_reward_account()), ed + 400); // When - assert_ok!(Pools::claim_payout(Origin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); // Then assert_eq!( @@ -829,7 +841,7 @@ mod claim_payout { assert_eq!(Balances::free_balance(&default_reward_account()), ed + 398); // When - assert_ok!(Pools::claim_payout(Origin::signed(40))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(40))); // Then assert_eq!( @@ -842,7 +854,7 @@ mod claim_payout { assert_eq!(Balances::free_balance(&default_reward_account()), ed + 210); // When - assert_ok!(Pools::claim_payout(Origin::signed(50))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(50))); // Then assert_eq!( @@ -862,7 +874,10 @@ mod claim_payout { // fully unbond the member. assert_ok!(fully_unbond_permissioned(11)); - assert_noop!(Pools::claim_payout(Origin::signed(11)), Error::::FullyUnbonding); + assert_noop!( + Pools::claim_payout(RuntimeOrigin::signed(11)), + Error::::FullyUnbonding + ); assert_eq!( pool_events_since_last_call(), @@ -1141,14 +1156,14 @@ mod claim_payout { // 20 joins afterwards. Balances::make_free_balance_be(&20, Balances::minimum_balance() + 10); - assert_ok!(Pools::join(Origin::signed(20), 10, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(20), 10, 1)); // reward by another 20 Balances::mutate_account(&default_reward_account(), |f| f.free += 20).unwrap(); // 10 should claim 10 + 10, 20 should claim 20 / 2. - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); assert_eq!( pool_events_since_last_call(), vec![ @@ -1163,8 +1178,8 @@ mod claim_payout { // any upcoming rewards are shared equally. Balances::mutate_account(&default_reward_account(), |f| f.free += 20).unwrap(); - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); assert_eq!( pool_events_since_last_call(), @@ -1184,13 +1199,13 @@ mod claim_payout { Balances::mutate_account(&default_reward_account(), |f| f.free += 3).unwrap(); Balances::make_free_balance_be(&20, Balances::minimum_balance() + 10); - assert_ok!(Pools::join(Origin::signed(20), 10, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(20), 10, 1)); Balances::mutate_account(&default_reward_account(), |f| f.free += 6).unwrap(); // 10 should claim 3, 20 should claim 3 + 3. - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); assert_eq!( pool_events_since_last_call(), @@ -1206,8 +1221,8 @@ mod claim_payout { // any upcoming rewards are shared equally. Balances::mutate_account(&default_reward_account(), |f| f.free += 8).unwrap(); - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); assert_eq!( pool_events_since_last_call(), @@ -1220,8 +1235,8 @@ mod claim_payout { // uneven upcoming rewards are shared equally, rounded down. Balances::mutate_account(&default_reward_account(), |f| f.free += 7).unwrap(); - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); assert_eq!( pool_events_since_last_call(), @@ -1241,19 +1256,19 @@ mod claim_payout { Balances::mutate_account(&default_reward_account(), |f| f.free += 30).unwrap(); Balances::make_free_balance_be(&20, ed + 10); - assert_ok!(Pools::join(Origin::signed(20), 10, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(20), 10, 1)); Balances::mutate_account(&default_reward_account(), |f| f.free += 100).unwrap(); Balances::make_free_balance_be(&30, ed + 10); - assert_ok!(Pools::join(Origin::signed(30), 10, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(30), 10, 1)); Balances::mutate_account(&default_reward_account(), |f| f.free += 60).unwrap(); // 10 should claim 10, 20 should claim nothing. - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); - assert_ok!(Pools::claim_payout(Origin::signed(30))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(30))); assert_eq!( pool_events_since_last_call(), @@ -1271,9 +1286,9 @@ mod claim_payout { // any upcoming rewards are shared equally. Balances::mutate_account(&default_reward_account(), |f| f.free += 30).unwrap(); - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); - assert_ok!(Pools::claim_payout(Origin::signed(30))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(30))); assert_eq!( pool_events_since_last_call(), @@ -1297,7 +1312,7 @@ mod claim_payout { assert_eq!(Pools::pending_rewards(20), None); Balances::make_free_balance_be(&20, ed + 10); - assert_ok!(Pools::join(Origin::signed(20), 10, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(20), 10, 1)); assert_eq!(Pools::pending_rewards(10), Some(30)); assert_eq!(Pools::pending_rewards(20), Some(0)); @@ -1309,7 +1324,7 @@ mod claim_payout { assert_eq!(Pools::pending_rewards(30), None); Balances::make_free_balance_be(&30, ed + 10); - assert_ok!(Pools::join(Origin::signed(30), 10, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(30), 10, 1)); assert_eq!(Pools::pending_rewards(10), Some(30 + 50)); assert_eq!(Pools::pending_rewards(20), Some(50)); @@ -1322,17 +1337,17 @@ mod claim_payout { assert_eq!(Pools::pending_rewards(30), Some(20)); // 10 should claim 10, 20 should claim nothing. - assert_ok!(Pools::claim_payout(Origin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); assert_eq!(Pools::pending_rewards(10), Some(0)); assert_eq!(Pools::pending_rewards(20), Some(50 + 20)); assert_eq!(Pools::pending_rewards(30), Some(20)); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); assert_eq!(Pools::pending_rewards(10), Some(0)); assert_eq!(Pools::pending_rewards(20), Some(0)); assert_eq!(Pools::pending_rewards(30), Some(20)); - assert_ok!(Pools::claim_payout(Origin::signed(30))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(30))); assert_eq!(Pools::pending_rewards(10), Some(0)); assert_eq!(Pools::pending_rewards(20), Some(0)); assert_eq!(Pools::pending_rewards(30), Some(0)); @@ -1345,16 +1360,16 @@ mod claim_payout { let ed = Balances::minimum_balance(); Balances::make_free_balance_be(&20, ed + 20); - assert_ok!(Pools::join(Origin::signed(20), 20, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(20), 20, 1)); Balances::make_free_balance_be(&30, ed + 20); - assert_ok!(Pools::join(Origin::signed(30), 10, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(30), 10, 1)); Balances::mutate_account(&default_reward_account(), |f| f.free += 40).unwrap(); // everyone claims. - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); - assert_ok!(Pools::claim_payout(Origin::signed(30))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(30))); assert_eq!( pool_events_since_last_call(), @@ -1370,14 +1385,14 @@ mod claim_payout { ); // 30 now bumps itself to be like 20. - assert_ok!(Pools::bond_extra(Origin::signed(30), BondExtra::FreeBalance(10))); + assert_ok!(Pools::bond_extra(RuntimeOrigin::signed(30), BondExtra::FreeBalance(10))); // more rewards come in. Balances::mutate_account(&default_reward_account(), |f| f.free += 100).unwrap(); - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); - assert_ok!(Pools::claim_payout(Origin::signed(30))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(30))); assert_eq!( pool_events_since_last_call(), @@ -1397,13 +1412,13 @@ mod claim_payout { let ed = Balances::minimum_balance(); Balances::make_free_balance_be(&20, ed + 20); - assert_ok!(Pools::join(Origin::signed(20), 20, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(20), 20, 1)); Balances::mutate_account(&default_reward_account(), |f| f.free += 30).unwrap(); // everyone claims. - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); assert_eq!( pool_events_since_last_call(), @@ -1417,13 +1432,13 @@ mod claim_payout { ); // 20 unbonds to be equal to 10 (10 points each). - assert_ok!(Pools::unbond(Origin::signed(20), 20, 10)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 10)); // more rewards come in. Balances::mutate_account(&default_reward_account(), |f| f.free += 100).unwrap(); - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); assert_eq!( pool_events_since_last_call(), @@ -1442,16 +1457,16 @@ mod claim_payout { let ed = Balances::minimum_balance(); Balances::make_free_balance_be(&20, ed + 20); - assert_ok!(Pools::join(Origin::signed(20), 20, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(20), 20, 1)); Balances::make_free_balance_be(&30, ed + 20); - assert_ok!(Pools::join(Origin::signed(30), 10, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(30), 10, 1)); // 10 gets 10, 20 gets 20, 30 gets 10 Balances::mutate_account(&default_reward_account(), |f| f.free += 40).unwrap(); // some claim. - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); assert_eq!( pool_events_since_last_call(), @@ -1469,8 +1484,8 @@ mod claim_payout { Balances::mutate_account(&default_reward_account(), |f| f.free += 80).unwrap(); // some claim. - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); assert_eq!( pool_events_since_last_call(), @@ -1484,8 +1499,8 @@ mod claim_payout { Balances::mutate_account(&default_reward_account(), |f| f.free += 80).unwrap(); // some claim. - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); assert_eq!( pool_events_since_last_call(), @@ -1496,7 +1511,7 @@ mod claim_payout { ); // now 30 claims all at once - assert_ok!(Pools::claim_payout(Origin::signed(30))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(30))); assert_eq!( pool_events_since_last_call(), @@ -1511,13 +1526,13 @@ mod claim_payout { let ed = Balances::minimum_balance(); Balances::make_free_balance_be(&20, ed + 200); - assert_ok!(Pools::join(Origin::signed(20), 20, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(20), 20, 1)); // 10 gets 10, 20 gets 20, 30 gets 10 Balances::mutate_account(&default_reward_account(), |f| f.free += 30).unwrap(); // some claim. - assert_ok!(Pools::claim_payout(Origin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); assert_eq!( pool_events_since_last_call(), @@ -1533,11 +1548,11 @@ mod claim_payout { Balances::mutate_account(&default_reward_account(), |f| f.free += 60).unwrap(); // and 20 bonds more -- they should not have more share of this reward. - assert_ok!(Pools::bond_extra(Origin::signed(20), BondExtra::FreeBalance(10))); + assert_ok!(Pools::bond_extra(RuntimeOrigin::signed(20), BondExtra::FreeBalance(10))); // everyone claim. - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); assert_eq!( pool_events_since_last_call(), @@ -1553,8 +1568,8 @@ mod claim_payout { Balances::mutate_account(&default_reward_account(), |f| f.free += 60).unwrap(); // everyone claim. - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); assert_eq!( pool_events_since_last_call(), @@ -1584,7 +1599,7 @@ mod claim_payout { // create pool 2 Balances::make_free_balance_be(&20, 100); - assert_ok!(Pools::create(Origin::signed(20), 10, 20, 20, 20)); + assert_ok!(Pools::create(RuntimeOrigin::signed(20), 10, 20, 20, 20)); // has no impact -- initial let (member_20, _, reward_pool_20) = Pools::get_member_with_pools(&20).unwrap(); @@ -1600,7 +1615,7 @@ mod claim_payout { // create pool 3 Balances::make_free_balance_be(&30, 100); - assert_ok!(Pools::create(Origin::signed(30), 10, 30, 30, 30)); + assert_ok!(Pools::create(RuntimeOrigin::signed(30), 10, 30, 30, 30)); // reward counter is still the same. let (member_30, _, reward_pool_30) = Pools::get_member_with_pools(&30).unwrap(); @@ -1616,7 +1631,7 @@ mod claim_payout { assert_eq!(member_30.last_recorded_reward_counter, 0.into()); // and 30 can claim the reward now. - assert_ok!(Pools::claim_payout(Origin::signed(30))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(30))); assert_eq!( pool_events_since_last_call(), @@ -1640,7 +1655,7 @@ mod claim_payout { MaxPoolMembersPerPool::::set(None); let join = |x, y| { Balances::make_free_balance_be(&x, y + Balances::minimum_balance()); - assert_ok!(Pools::join(Origin::signed(x), y, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(x), y, 1)); }; { @@ -1722,7 +1737,10 @@ mod claim_payout { // 10 bonds extra without any rewards. { - assert_ok!(Pools::bond_extra(Origin::signed(10), BondExtra::FreeBalance(10))); + assert_ok!(Pools::bond_extra( + RuntimeOrigin::signed(10), + BondExtra::FreeBalance(10) + )); let (member, _, reward_pool) = Pools::get_member_with_pools(&10).unwrap(); assert_eq!(member.last_recorded_reward_counter, 0.into()); assert_eq!(reward_pool.last_recorded_total_payouts, 0); @@ -1734,7 +1752,10 @@ mod claim_payout { Balances::mutate_account(&default_reward_account(), |f| f.free += 30).unwrap(); { - assert_ok!(Pools::bond_extra(Origin::signed(10), BondExtra::FreeBalance(10))); + assert_ok!(Pools::bond_extra( + RuntimeOrigin::signed(10), + BondExtra::FreeBalance(10) + )); let (member, _, reward_pool) = Pools::get_member_with_pools(&10).unwrap(); // explanation: before bond_extra takes place, there is 40 points and 30 balance in // the system, RewardCounter is therefore 7.5 @@ -1748,7 +1769,10 @@ mod claim_payout { // 20 bonds extra again, without further rewards. { - assert_ok!(Pools::bond_extra(Origin::signed(20), BondExtra::FreeBalance(10))); + assert_ok!(Pools::bond_extra( + RuntimeOrigin::signed(20), + BondExtra::FreeBalance(10) + )); let (member, _, reward_pool) = Pools::get_member_with_pools(&20).unwrap(); assert_eq!(member.last_recorded_reward_counter, RewardCounter::from_float(0.75)); assert_eq!( @@ -1786,7 +1810,7 @@ mod claim_payout { // 10 cashes it out, and bonds it. { - assert_ok!(Pools::claim_payout(Origin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); let (member, _, reward_pool) = Pools::get_member_with_pools(&10).unwrap(); // there is 30 points and 30 reward points in the system RC is 1. assert_eq!(member.last_recorded_reward_counter, 1.into()); @@ -1803,7 +1827,7 @@ mod claim_payout { // 20 re-bonds it. { - assert_ok!(Pools::bond_extra(Origin::signed(20), BondExtra::Rewards)); + assert_ok!(Pools::bond_extra(RuntimeOrigin::signed(20), BondExtra::Rewards)); let (member, _, reward_pool) = Pools::get_member_with_pools(&10).unwrap(); assert_eq!(member.last_recorded_reward_counter, 1.into()); assert_eq!(reward_pool.total_rewards_claimed, 30); @@ -1843,7 +1867,7 @@ mod claim_payout { // 20 unbonds without any rewards. { - assert_ok!(Pools::unbond(Origin::signed(20), 20, 10)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 10)); let (member, _, reward_pool) = Pools::get_member_with_pools(&20).unwrap(); assert_eq!(member.last_recorded_reward_counter, 0.into()); assert_eq!(reward_pool.last_recorded_total_payouts, 0); @@ -1855,7 +1879,7 @@ mod claim_payout { // and 30 also unbonds half. { - assert_ok!(Pools::unbond(Origin::signed(30), 30, 10)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(30), 30, 10)); let (member, _, reward_pool) = Pools::get_member_with_pools(&30).unwrap(); // 30 reward in the system, and 40 points before this unbond to collect it, // RewardCounter is 3/4. @@ -1872,7 +1896,7 @@ mod claim_payout { // 30 unbonds again, not change this time. { - assert_ok!(Pools::unbond(Origin::signed(30), 30, 5)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(30), 30, 5)); let (member, _, reward_pool) = Pools::get_member_with_pools(&30).unwrap(); assert_eq!( member.last_recorded_reward_counter, @@ -1887,7 +1911,7 @@ mod claim_payout { // 20 unbonds again, not change this time, just collecting their reward. { - assert_ok!(Pools::unbond(Origin::signed(20), 20, 5)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 5)); let (member, _, reward_pool) = Pools::get_member_with_pools(&20).unwrap(); assert_eq!( member.last_recorded_reward_counter, @@ -1901,7 +1925,7 @@ mod claim_payout { } // trigger 10's reward as well to see all of the payouts. - assert_ok!(Pools::claim_payout(Origin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); assert_eq!( pool_events_since_last_call(), @@ -1937,8 +1961,8 @@ mod claim_payout { Balances::mutate_account(&default_reward_account(), |f| f.free += 40).unwrap(); // everyone claims - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); // some dust (1) remains in the reward account. assert_eq!( @@ -1953,15 +1977,15 @@ mod claim_payout { ); // start dismantling the pool. - assert_ok!(Pools::set_state(Origin::signed(902), 1, PoolState::Destroying)); + assert_ok!(Pools::set_state(RuntimeOrigin::signed(902), 1, PoolState::Destroying)); assert_ok!(fully_unbond_permissioned(20)); CurrentEra::set(3); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(20), 20, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(20), 20, 0)); assert_ok!(fully_unbond_permissioned(10)); CurrentEra::set(6); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(10), 10, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(10), 10, 0)); assert_eq!( pool_events_since_last_call(), @@ -2000,10 +2024,10 @@ mod claim_payout { .unwrap(); // everyone claims - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); - assert_ok!(Pools::claim_payout(Origin::signed(21))); - assert_ok!(Pools::claim_payout(Origin::signed(22))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(21))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(22))); assert_eq!( pool_events_since_last_call(), @@ -2057,18 +2081,18 @@ mod unbond { .add_members(vec![(20, 20)]) .build_and_execute(|| { // can unbond to above limit - assert_ok!(Pools::unbond(Origin::signed(20), 20, 5)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 5)); assert_eq!(PoolMembers::::get(20).unwrap().active_points(), 15); assert_eq!(PoolMembers::::get(20).unwrap().unbonding_points(), 5); // cannot go to below 10: assert_noop!( - Pools::unbond(Origin::signed(20), 20, 10), + Pools::unbond(RuntimeOrigin::signed(20), 20, 10), Error::::MinimumBondNotMet ); // but can go to 0 - assert_ok!(Pools::unbond(Origin::signed(20), 20, 15)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 15)); assert_eq!(PoolMembers::::get(20).unwrap().active_points(), 0); assert_eq!(PoolMembers::::get(20).unwrap().unbonding_points(), 20); }) @@ -2089,23 +2113,23 @@ mod unbond { // cannot be kicked to above the limit. assert_noop!( - Pools::unbond(Origin::signed(kicker), 20, 5), + Pools::unbond(RuntimeOrigin::signed(kicker), 20, 5), Error::::PartialUnbondNotAllowedPermissionlessly ); // cannot go to below 10: assert_noop!( - Pools::unbond(Origin::signed(kicker), 20, 15), + Pools::unbond(RuntimeOrigin::signed(kicker), 20, 15), Error::::PartialUnbondNotAllowedPermissionlessly ); // but they themselves can do an unbond - assert_ok!(Pools::unbond(Origin::signed(20), 20, 2)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 2)); assert_eq!(PoolMembers::::get(20).unwrap().active_points(), 18); assert_eq!(PoolMembers::::get(20).unwrap().unbonding_points(), 2); // can be kicked to 0. - assert_ok!(Pools::unbond(Origin::signed(kicker), 20, 18)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(kicker), 20, 18)); assert_eq!(PoolMembers::::get(20).unwrap().active_points(), 0); assert_eq!(PoolMembers::::get(20).unwrap().unbonding_points(), 20); }) @@ -2126,23 +2150,23 @@ mod unbond { // cannot be kicked to above the limit. assert_noop!( - Pools::unbond(Origin::signed(random), 20, 5), + Pools::unbond(RuntimeOrigin::signed(random), 20, 5), Error::::PartialUnbondNotAllowedPermissionlessly ); // cannot go to below 10: assert_noop!( - Pools::unbond(Origin::signed(random), 20, 15), + Pools::unbond(RuntimeOrigin::signed(random), 20, 15), Error::::PartialUnbondNotAllowedPermissionlessly ); // but they themselves can do an unbond - assert_ok!(Pools::unbond(Origin::signed(20), 20, 2)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 2)); assert_eq!(PoolMembers::::get(20).unwrap().active_points(), 18); assert_eq!(PoolMembers::::get(20).unwrap().unbonding_points(), 2); // but can go to 0 - assert_ok!(Pools::unbond(Origin::signed(random), 20, 18)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(random), 20, 18)); assert_eq!(PoolMembers::::get(20).unwrap().active_points(), 0); assert_eq!(PoolMembers::::get(20).unwrap().unbonding_points(), 20); }) @@ -2155,19 +2179,25 @@ mod unbond { // - depositor cannot unbond to below limit or 0 ExtBuilder::default().min_join_bond(10).build_and_execute(|| { // give the depositor some extra funds. - assert_ok!(Pools::bond_extra(Origin::signed(10), BondExtra::FreeBalance(10))); + assert_ok!(Pools::bond_extra(RuntimeOrigin::signed(10), BondExtra::FreeBalance(10))); assert_eq!(PoolMembers::::get(10).unwrap().points, 20); // can unbond to above the limit. - assert_ok!(Pools::unbond(Origin::signed(10), 10, 5)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 5)); assert_eq!(PoolMembers::::get(10).unwrap().active_points(), 15); assert_eq!(PoolMembers::::get(10).unwrap().unbonding_points(), 5); // cannot go to below 10: - assert_noop!(Pools::unbond(Origin::signed(10), 10, 10), Error::::MinimumBondNotMet); + assert_noop!( + Pools::unbond(RuntimeOrigin::signed(10), 10, 10), + Error::::MinimumBondNotMet + ); // cannot go to 0 either. - assert_noop!(Pools::unbond(Origin::signed(10), 10, 15), Error::::MinimumBondNotMet); + assert_noop!( + Pools::unbond(RuntimeOrigin::signed(10), 10, 15), + Error::::MinimumBondNotMet + ); }) } @@ -2177,7 +2207,7 @@ mod unbond { // - depositor can never be kicked. ExtBuilder::default().min_join_bond(10).build_and_execute(|| { // give the depositor some extra funds. - assert_ok!(Pools::bond_extra(Origin::signed(10), BondExtra::FreeBalance(10))); + assert_ok!(Pools::bond_extra(RuntimeOrigin::signed(10), BondExtra::FreeBalance(10))); assert_eq!(PoolMembers::::get(10).unwrap().points, 20); // set the stage @@ -2186,24 +2216,27 @@ mod unbond { // cannot be kicked to above limit. assert_noop!( - Pools::unbond(Origin::signed(kicker), 10, 5), + Pools::unbond(RuntimeOrigin::signed(kicker), 10, 5), Error::::PartialUnbondNotAllowedPermissionlessly ); // or below the limit assert_noop!( - Pools::unbond(Origin::signed(kicker), 10, 15), + Pools::unbond(RuntimeOrigin::signed(kicker), 10, 15), Error::::PartialUnbondNotAllowedPermissionlessly ); // or 0. assert_noop!( - Pools::unbond(Origin::signed(kicker), 10, 20), + Pools::unbond(RuntimeOrigin::signed(kicker), 10, 20), Error::::DoesNotHavePermission ); // they themselves cannot do it either - assert_noop!(Pools::unbond(Origin::signed(10), 10, 20), Error::::MinimumBondNotMet); + assert_noop!( + Pools::unbond(RuntimeOrigin::signed(10), 10, 20), + Error::::MinimumBondNotMet + ); }) } @@ -2212,7 +2245,7 @@ mod unbond { // depositor can never be permissionlessly unbonded. ExtBuilder::default().min_join_bond(10).build_and_execute(|| { // give the depositor some extra funds. - assert_ok!(Pools::bond_extra(Origin::signed(10), BondExtra::FreeBalance(10))); + assert_ok!(Pools::bond_extra(RuntimeOrigin::signed(10), BondExtra::FreeBalance(10))); assert_eq!(PoolMembers::::get(10).unwrap().points, 20); // set the stage @@ -2221,24 +2254,24 @@ mod unbond { // cannot be kicked to above limit. assert_noop!( - Pools::unbond(Origin::signed(random), 10, 5), + Pools::unbond(RuntimeOrigin::signed(random), 10, 5), Error::::PartialUnbondNotAllowedPermissionlessly ); // or below the limit assert_noop!( - Pools::unbond(Origin::signed(random), 10, 15), + Pools::unbond(RuntimeOrigin::signed(random), 10, 15), Error::::PartialUnbondNotAllowedPermissionlessly ); // or 0. assert_noop!( - Pools::unbond(Origin::signed(random), 10, 20), + Pools::unbond(RuntimeOrigin::signed(random), 10, 20), Error::::DoesNotHavePermission ); // they themselves can do it in this case though. - assert_ok!(Pools::unbond(Origin::signed(10), 10, 20)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 20)); }) } @@ -2251,26 +2284,29 @@ mod unbond { .add_members(vec![(20, 20)]) .build_and_execute(|| { // give the depositor some extra funds. - assert_ok!(Pools::bond_extra(Origin::signed(10), BondExtra::FreeBalance(10))); + assert_ok!(Pools::bond_extra( + RuntimeOrigin::signed(10), + BondExtra::FreeBalance(10) + )); assert_eq!(PoolMembers::::get(10).unwrap().points, 20); // set the stage unsafe_set_state(1, PoolState::Destroying); // can go above the limit - assert_ok!(Pools::unbond(Origin::signed(10), 10, 5)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 5)); assert_eq!(PoolMembers::::get(10).unwrap().active_points(), 15); assert_eq!(PoolMembers::::get(10).unwrap().unbonding_points(), 5); // but not below the limit assert_noop!( - Pools::unbond(Origin::signed(10), 10, 10), + Pools::unbond(RuntimeOrigin::signed(10), 10, 10), Error::::MinimumBondNotMet ); // and certainly not zero assert_noop!( - Pools::unbond(Origin::signed(10), 10, 15), + Pools::unbond(RuntimeOrigin::signed(10), 10, 15), Error::::MinimumBondNotMet ); }) @@ -2284,22 +2320,25 @@ mod unbond { // - depositor can unbond to 0 if last and destroying. ExtBuilder::default().min_join_bond(10).build_and_execute(|| { // give the depositor some extra funds. - assert_ok!(Pools::bond_extra(Origin::signed(10), BondExtra::FreeBalance(10))); + assert_ok!(Pools::bond_extra(RuntimeOrigin::signed(10), BondExtra::FreeBalance(10))); assert_eq!(PoolMembers::::get(10).unwrap().points, 20); // set the stage unsafe_set_state(1, PoolState::Destroying); // can unbond to above the limit. - assert_ok!(Pools::unbond(Origin::signed(10), 10, 5)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 5)); assert_eq!(PoolMembers::::get(10).unwrap().active_points(), 15); assert_eq!(PoolMembers::::get(10).unwrap().unbonding_points(), 5); // still cannot go to below limit - assert_noop!(Pools::unbond(Origin::signed(10), 10, 10), Error::::MinimumBondNotMet); + assert_noop!( + Pools::unbond(RuntimeOrigin::signed(10), 10, 10), + Error::::MinimumBondNotMet + ); // can go to 0 too. - assert_ok!(Pools::unbond(Origin::signed(10), 10, 15)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 15)); assert_eq!(PoolMembers::::get(10).unwrap().active_points(), 0); assert_eq!(PoolMembers::::get(10).unwrap().unbonding_points(), 20); }) @@ -2426,8 +2465,8 @@ mod unbond { // When CurrentEra::set(3); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(10), 40, 0)); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(10), 550, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(10), 40, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(10), 550, 0)); assert_ok!(fully_unbond_permissioned(10)); // Then @@ -2525,12 +2564,12 @@ mod unbond { // When the nominator tries to kick, then its a noop assert_noop!( - Pools::fully_unbond(Origin::signed(901), 100), + Pools::fully_unbond(RuntimeOrigin::signed(901), 100), Error::::NotKickerOrDestroying ); // When the root kicks then its ok - assert_ok!(Pools::fully_unbond(Origin::signed(900), 100)); + assert_ok!(Pools::fully_unbond(RuntimeOrigin::signed(900), 100)); assert_eq!( pool_events_since_last_call(), @@ -2550,7 +2589,7 @@ mod unbond { ); // When the state toggler kicks then its ok - assert_ok!(Pools::fully_unbond(Origin::signed(902), 200)); + assert_ok!(Pools::fully_unbond(RuntimeOrigin::signed(902), 200)); assert_eq!( pool_events_since_last_call(), @@ -2601,13 +2640,13 @@ mod unbond { // A permissionless unbond attempt errors assert_noop!( - Pools::fully_unbond(Origin::signed(420), 100), + Pools::fully_unbond(RuntimeOrigin::signed(420), 100), Error::::NotKickerOrDestroying ); // permissionless unbond must be full assert_noop!( - Pools::unbond(Origin::signed(420), 100, 80), + Pools::unbond(RuntimeOrigin::signed(420), 100, 80), Error::::PartialUnbondNotAllowedPermissionlessly, ); @@ -2616,12 +2655,12 @@ mod unbond { // The depositor cannot be fully unbonded until they are the last member assert_noop!( - Pools::fully_unbond(Origin::signed(10), 10), + Pools::fully_unbond(RuntimeOrigin::signed(10), 10), Error::::MinimumBondNotMet, ); // Any account can unbond a member that is not the depositor - assert_ok!(Pools::fully_unbond(Origin::signed(420), 100)); + assert_ok!(Pools::fully_unbond(RuntimeOrigin::signed(420), 100)); assert_eq!( pool_events_since_last_call(), @@ -2635,7 +2674,7 @@ mod unbond { // still permissionless unbond must be full assert_noop!( - Pools::unbond(Origin::signed(420), 100, 80), + Pools::unbond(RuntimeOrigin::signed(420), 100, 80), Error::::PartialUnbondNotAllowedPermissionlessly, ); @@ -2644,7 +2683,7 @@ mod unbond { // The depositor cannot be unbonded assert_noop!( - Pools::fully_unbond(Origin::signed(420), 10), + Pools::fully_unbond(RuntimeOrigin::signed(420), 10), Error::::DoesNotHavePermission ); @@ -2653,27 +2692,27 @@ mod unbond { // The depositor cannot be unbonded yet. assert_noop!( - Pools::fully_unbond(Origin::signed(420), 10), + Pools::fully_unbond(RuntimeOrigin::signed(420), 10), Error::::DoesNotHavePermission, ); // but when everyone is unbonded it can.. CurrentEra::set(3); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(10), 100, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(10), 100, 0)); // still permissionless unbond must be full. assert_noop!( - Pools::unbond(Origin::signed(420), 10, 5), + Pools::unbond(RuntimeOrigin::signed(420), 10, 5), Error::::PartialUnbondNotAllowedPermissionlessly, ); // depositor can never be unbonded permissionlessly . assert_noop!( - Pools::fully_unbond(Origin::signed(420), 10), + Pools::fully_unbond(RuntimeOrigin::signed(420), 10), Error::::DoesNotHavePermission ); // but depositor itself can do it. - assert_ok!(Pools::fully_unbond(Origin::signed(10), 10)); + assert_ok!(Pools::fully_unbond(RuntimeOrigin::signed(10), 10)); assert_eq!(BondedPools::::get(1).unwrap().points, 0); assert_eq!( @@ -2696,7 +2735,7 @@ mod unbond { fn unbond_errors_correctly() { ExtBuilder::default().build_and_execute(|| { assert_noop!( - Pools::fully_unbond(Origin::signed(11), 11), + Pools::fully_unbond(RuntimeOrigin::signed(11), 11), Error::::PoolMemberNotFound ); @@ -2704,7 +2743,7 @@ mod unbond { let member = PoolMember { pool_id: 2, points: 10, ..Default::default() }; PoolMembers::::insert(11, member); - let _ = Pools::fully_unbond(Origin::signed(11), 11); + let _ = Pools::fully_unbond(RuntimeOrigin::signed(11), 11); }); } @@ -2726,13 +2765,13 @@ mod unbond { } .put(); - let _ = Pools::fully_unbond(Origin::signed(11), 11); + let _ = Pools::fully_unbond(RuntimeOrigin::signed(11), 11); }); } #[test] fn partial_unbond_era_tracking() { - ExtBuilder::default().build_and_execute(|| { + ExtBuilder::default().ed(1).build_and_execute(|| { // to make the depositor capable of withdrawing. StakingMinBond::set(1); MinCreateBond::::set(1); @@ -2756,7 +2795,7 @@ mod unbond { unsafe_set_state(1, PoolState::Destroying); // when: casual unbond - assert_ok!(Pools::unbond(Origin::signed(10), 10, 1)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 1)); // then assert_eq!(PoolMembers::::get(10).unwrap().active_points(), 9); @@ -2785,7 +2824,7 @@ mod unbond { ); // when: casual further unbond, same era. - assert_ok!(Pools::unbond(Origin::signed(10), 10, 5)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 5)); // then assert_eq!(PoolMembers::::get(10).unwrap().active_points(), 4); @@ -2811,7 +2850,7 @@ mod unbond { // when: casual further unbond, next era. CurrentEra::set(1); - assert_ok!(Pools::unbond(Origin::signed(10), 10, 1)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 1)); // then assert_eq!(PoolMembers::::get(10).unwrap().active_points(), 3); @@ -2839,14 +2878,14 @@ mod unbond { // when: unbonding more than our active: error assert_noop!( frame_support::storage::with_storage_layer(|| Pools::unbond( - Origin::signed(10), + RuntimeOrigin::signed(10), 10, 5 )), Error::::MinimumBondNotMet ); // instead: - assert_ok!(Pools::unbond(Origin::signed(10), 10, 3)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 3)); // then assert_eq!(PoolMembers::::get(10).unwrap().active_points(), 0); @@ -2879,9 +2918,9 @@ mod unbond { MaxUnbonding::set(2); // given - assert_ok!(Pools::unbond(Origin::signed(20), 20, 2)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 2)); CurrentEra::set(1); - assert_ok!(Pools::unbond(Origin::signed(20), 20, 3)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 3)); assert_eq!( PoolMembers::::get(20).unwrap().unbonding_eras, member_unbonding_eras!(3 => 2, 4 => 3) @@ -2891,7 +2930,7 @@ mod unbond { CurrentEra::set(2); assert_noop!( frame_support::storage::with_storage_layer(|| Pools::unbond( - Origin::signed(20), + RuntimeOrigin::signed(20), 20, 4 )), @@ -2900,7 +2939,7 @@ mod unbond { // when MaxUnbonding::set(3); - assert_ok!(Pools::unbond(Origin::signed(20), 20, 1)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 1)); assert_eq!( PoolMembers::::get(20).unwrap().unbonding_eras, @@ -2933,13 +2972,13 @@ mod unbond { assert_eq!(PoolMembers::::get(10).unwrap().unbonding_points(), 0); // can unbond a bit.. - assert_ok!(Pools::unbond(Origin::signed(10), 10, 3)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 3)); assert_eq!(PoolMembers::::get(10).unwrap().active_points(), 7); assert_eq!(PoolMembers::::get(10).unwrap().unbonding_points(), 3); // but not less than 2 assert_noop!( - Pools::unbond(Origin::signed(10), 10, 6), + Pools::unbond(RuntimeOrigin::signed(10), 10, 6), Error::::MinimumBondNotMet ); @@ -2967,7 +3006,7 @@ mod unbond { // cannot unbond even 7, because the value of shares is now less. assert_noop!( - Pools::unbond(Origin::signed(10), 10, 7), + Pools::unbond(RuntimeOrigin::signed(10), 10, 7), Error::::MinimumBondNotMet ); }); @@ -2985,7 +3024,7 @@ mod unbond { 4 * Balances::minimum_balance(), ); - assert_ok!(Pools::unbond(Origin::signed(20), 20, 2)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 2)); assert_eq!( pool_events_since_last_call(), vec![ @@ -3004,7 +3043,7 @@ mod unbond { 4 * Balances::minimum_balance(), ); - assert_ok!(Pools::unbond(Origin::signed(20), 20, 3)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 3)); assert_eq!( pool_events_since_last_call(), vec![ @@ -3020,7 +3059,7 @@ mod unbond { 4 * Balances::minimum_balance(), ); - assert_ok!(Pools::unbond(Origin::signed(20), 20, 5)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 5)); assert_eq!( pool_events_since_last_call(), vec![ @@ -3051,7 +3090,7 @@ mod pool_withdraw_unbonded { assert_eq!(Balances::free_balance(&default_bonded_account()), 10); // When - assert_ok!(Pools::pool_withdraw_unbonded(Origin::signed(10), 1, 0)); + assert_ok!(Pools::pool_withdraw_unbonded(RuntimeOrigin::signed(10), 1, 0)); // Then there unbonding balance is no longer locked assert_eq!(StakingMock::active_stake(&default_bonded_account()), Some(5)); @@ -3075,8 +3114,8 @@ mod withdraw_unbonded { // Given assert_eq!(StakingMock::bonding_duration(), 3); - assert_ok!(Pools::fully_unbond(Origin::signed(550), 550)); - assert_ok!(Pools::fully_unbond(Origin::signed(40), 40)); + assert_ok!(Pools::fully_unbond(RuntimeOrigin::signed(550), 550)); + assert_ok!(Pools::fully_unbond(RuntimeOrigin::signed(40), 40)); assert_eq!(Balances::free_balance(&default_bonded_account()), 600); let mut current_era = 1; @@ -3151,7 +3190,7 @@ mod withdraw_unbonded { ); // When - assert_ok!(Pools::withdraw_unbonded(Origin::signed(550), 550, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(550), 550, 0)); // Then assert_eq!( @@ -3171,7 +3210,7 @@ mod withdraw_unbonded { ); // When - assert_ok!(Pools::withdraw_unbonded(Origin::signed(40), 40, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(40), 40, 0)); // Then assert_eq!( @@ -3199,7 +3238,7 @@ mod withdraw_unbonded { CurrentEra::set(current_era); // when - assert_ok!(Pools::withdraw_unbonded(Origin::signed(10), 10, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(10), 10, 0)); assert_eq!( pool_events_since_last_call(), vec![ @@ -3271,7 +3310,7 @@ mod withdraw_unbonded { CurrentEra::set(StakingMock::bonding_duration()); // When - assert_ok!(Pools::withdraw_unbonded(Origin::signed(40), 40, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(40), 40, 0)); // Then assert_eq!( @@ -3292,7 +3331,7 @@ mod withdraw_unbonded { ); // When - assert_ok!(Pools::withdraw_unbonded(Origin::signed(550), 550, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(550), 550, 0)); // Then assert_eq!( @@ -3321,11 +3360,11 @@ mod withdraw_unbonded { CurrentEra::set(CurrentEra::get() + 3); // set metadata to check that it's being removed on dissolve - assert_ok!(Pools::set_metadata(Origin::signed(900), 1, vec![1, 1])); + assert_ok!(Pools::set_metadata(RuntimeOrigin::signed(900), 1, vec![1, 1])); assert!(Metadata::::contains_key(1)); // when - assert_ok!(Pools::withdraw_unbonded(Origin::signed(10), 10, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(10), 10, 0)); // then assert_eq!(Balances::free_balance(&10), 10 + 35); @@ -3361,7 +3400,7 @@ mod withdraw_unbonded { assert_eq!(Balances::free_balance(&10), 35); assert_eq!(Balances::free_balance(&default_bonded_account()), 10); unsafe_set_state(1, PoolState::Destroying); - assert_ok!(Pools::fully_unbond(Origin::signed(10), 10)); + assert_ok!(Pools::fully_unbond(RuntimeOrigin::signed(10), 10)); // Simulate a slash that is not accounted for in the sub pools. Balances::make_free_balance_be(&default_bonded_account(), 5); @@ -3374,7 +3413,7 @@ mod withdraw_unbonded { CurrentEra::set(0 + 3); // When - assert_ok!(Pools::withdraw_unbonded(Origin::signed(10), 10, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(10), 10, 0)); // Then assert_eq!(Balances::free_balance(10), 10 + 35); @@ -3393,7 +3432,7 @@ mod withdraw_unbonded { SubPoolsStorage::::insert(1, sub_pools.clone()); assert_noop!( - Pools::withdraw_unbonded(Origin::signed(11), 11, 0), + Pools::withdraw_unbonded(RuntimeOrigin::signed(11), 11, 0), Error::::PoolMemberNotFound ); @@ -3406,7 +3445,7 @@ mod withdraw_unbonded { // We are still in the bonding duration assert_noop!( - Pools::withdraw_unbonded(Origin::signed(11), 11, 0), + Pools::withdraw_unbonded(RuntimeOrigin::signed(11), 11, 0), Error::::CannotWithdrawAny ); @@ -3423,8 +3462,8 @@ mod withdraw_unbonded { .add_members(vec![(100, 100), (200, 200)]) .build_and_execute(|| { // Given - assert_ok!(Pools::fully_unbond(Origin::signed(100), 100)); - assert_ok!(Pools::fully_unbond(Origin::signed(200), 200)); + assert_ok!(Pools::fully_unbond(RuntimeOrigin::signed(100), 100)); + assert_ok!(Pools::fully_unbond(RuntimeOrigin::signed(200), 200)); assert_eq!( BondedPool::::get(1).unwrap(), BondedPool { @@ -3441,7 +3480,7 @@ mod withdraw_unbonded { // Cannot kick when pool is open assert_noop!( - Pools::withdraw_unbonded(Origin::signed(902), 100, 0), + Pools::withdraw_unbonded(RuntimeOrigin::signed(902), 100, 0), Error::::NotKickerOrDestroying ); assert_eq!( @@ -3473,15 +3512,15 @@ mod withdraw_unbonded { // Cannot kick as a nominator assert_noop!( - Pools::withdraw_unbonded(Origin::signed(901), 100, 0), + Pools::withdraw_unbonded(RuntimeOrigin::signed(901), 100, 0), Error::::NotKickerOrDestroying ); // Can kick as root - assert_ok!(Pools::withdraw_unbonded(Origin::signed(900), 100, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(900), 100, 0)); // Can kick as state toggler - assert_ok!(Pools::withdraw_unbonded(Origin::signed(900), 200, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(900), 200, 0)); assert_eq!(Balances::free_balance(100), 100 + 100); assert_eq!(Balances::free_balance(200), 200 + 200); @@ -3504,7 +3543,7 @@ mod withdraw_unbonded { fn withdraw_unbonded_destroying_permissionless() { ExtBuilder::default().add_members(vec![(100, 100)]).build_and_execute(|| { // Given - assert_ok!(Pools::fully_unbond(Origin::signed(100), 100)); + assert_ok!(Pools::fully_unbond(RuntimeOrigin::signed(100), 100)); assert_eq!( BondedPool::::get(1).unwrap(), BondedPool { @@ -3522,7 +3561,7 @@ mod withdraw_unbonded { // Cannot permissionlessly withdraw assert_noop!( - Pools::fully_unbond(Origin::signed(420), 100), + Pools::fully_unbond(RuntimeOrigin::signed(420), 100), Error::::NotKickerOrDestroying ); @@ -3530,7 +3569,7 @@ mod withdraw_unbonded { unsafe_set_state(1, PoolState::Destroying); // Can permissionlesly withdraw a member that is not the depositor - assert_ok!(Pools::withdraw_unbonded(Origin::signed(420), 100, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(420), 100, 0)); assert_eq!(SubPoolsStorage::::get(1).unwrap(), Default::default(),); assert_eq!(Balances::free_balance(100), 100 + 100); @@ -3552,13 +3591,13 @@ mod withdraw_unbonded { #[test] fn partial_withdraw_unbonded_depositor() { ExtBuilder::default().ed(1).build_and_execute(|| { - assert_ok!(Pools::bond_extra(Origin::signed(10), BondExtra::FreeBalance(10))); + assert_ok!(Pools::bond_extra(RuntimeOrigin::signed(10), BondExtra::FreeBalance(10))); unsafe_set_state(1, PoolState::Destroying); // given - assert_ok!(Pools::unbond(Origin::signed(10), 10, 6)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 6)); CurrentEra::set(1); - assert_ok!(Pools::unbond(Origin::signed(10), 10, 1)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 1)); assert_eq!( PoolMembers::::get(10).unwrap().unbonding_eras, member_unbonding_eras!(3 => 6, 4 => 1) @@ -3589,13 +3628,13 @@ mod withdraw_unbonded { // when CurrentEra::set(2); assert_noop!( - Pools::withdraw_unbonded(Origin::signed(10), 10, 0), + Pools::withdraw_unbonded(RuntimeOrigin::signed(10), 10, 0), Error::::CannotWithdrawAny ); // when CurrentEra::set(3); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(10), 10, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(10), 10, 0)); // then assert_eq!( @@ -3618,7 +3657,7 @@ mod withdraw_unbonded { // when CurrentEra::set(4); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(10), 10, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(10), 10, 0)); // then assert_eq!( @@ -3633,7 +3672,7 @@ mod withdraw_unbonded { // when repeating: assert_noop!( - Pools::withdraw_unbonded(Origin::signed(10), 10, 0), + Pools::withdraw_unbonded(RuntimeOrigin::signed(10), 10, 0), Error::::CannotWithdrawAny ); }); @@ -3643,9 +3682,9 @@ mod withdraw_unbonded { fn partial_withdraw_unbonded_non_depositor() { ExtBuilder::default().add_members(vec![(11, 10)]).build_and_execute(|| { // given - assert_ok!(Pools::unbond(Origin::signed(11), 11, 6)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(11), 11, 6)); CurrentEra::set(1); - assert_ok!(Pools::unbond(Origin::signed(11), 11, 1)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(11), 11, 1)); assert_eq!( PoolMembers::::get(11).unwrap().unbonding_eras, member_unbonding_eras!(3 => 6, 4 => 1) @@ -3676,13 +3715,13 @@ mod withdraw_unbonded { // when CurrentEra::set(2); assert_noop!( - Pools::withdraw_unbonded(Origin::signed(11), 11, 0), + Pools::withdraw_unbonded(RuntimeOrigin::signed(11), 11, 0), Error::::CannotWithdrawAny ); // when CurrentEra::set(3); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(11), 11, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(11), 11, 0)); // then assert_eq!( @@ -3705,7 +3744,7 @@ mod withdraw_unbonded { // when CurrentEra::set(4); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(11), 11, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(11), 11, 0)); // then assert_eq!( @@ -3720,7 +3759,7 @@ mod withdraw_unbonded { // when repeating: assert_noop!( - Pools::withdraw_unbonded(Origin::signed(11), 11, 0), + Pools::withdraw_unbonded(RuntimeOrigin::signed(11), 11, 0), Error::::CannotWithdrawAny ); }); @@ -3730,7 +3769,7 @@ mod withdraw_unbonded { fn full_multi_step_withdrawing_non_depositor() { ExtBuilder::default().add_members(vec![(100, 100)]).build_and_execute(|| { // given - assert_ok!(Pools::unbond(Origin::signed(100), 100, 75)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(100), 100, 75)); assert_eq!( PoolMembers::::get(100).unwrap().unbonding_eras, member_unbonding_eras!(3 => 75) @@ -3738,20 +3777,20 @@ mod withdraw_unbonded { // progress one era and unbond the leftover. CurrentEra::set(1); - assert_ok!(Pools::unbond(Origin::signed(100), 100, 25)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(100), 100, 25)); assert_eq!( PoolMembers::::get(100).unwrap().unbonding_eras, member_unbonding_eras!(3 => 75, 4 => 25) ); assert_noop!( - Pools::withdraw_unbonded(Origin::signed(100), 100, 0), + Pools::withdraw_unbonded(RuntimeOrigin::signed(100), 100, 0), Error::::CannotWithdrawAny ); // now the 75 should be free. CurrentEra::set(3); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(100), 100, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(100), 100, 0)); assert_eq!( pool_events_since_last_call(), vec![ @@ -3770,7 +3809,7 @@ mod withdraw_unbonded { // the 25 should be free now, and the member removed. CurrentEra::set(4); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(100), 100, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(100), 100, 0)); assert_eq!( pool_events_since_last_call(), vec![ @@ -3793,8 +3832,8 @@ mod withdraw_unbonded { System::reset_events(); // when - assert_ok!(Pools::unbond(Origin::signed(20), 20, 5)); - assert_ok!(Pools::unbond(Origin::signed(30), 30, 5)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 5)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(30), 30, 5)); // then member-local unbonding is pretty much in sync with the global pools. assert_eq!( @@ -3824,7 +3863,7 @@ mod withdraw_unbonded { // when CurrentEra::set(1); - assert_ok!(Pools::unbond(Origin::signed(20), 20, 5)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 5)); // then still member-local unbonding is pretty much in sync with the global pools. assert_eq!( @@ -3848,7 +3887,7 @@ mod withdraw_unbonded { // when CurrentEra::set(2); - assert_ok!(Pools::unbond(Origin::signed(20), 20, 5)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 5)); // then still member-local unbonding is pretty much in sync with the global pools. assert_eq!( @@ -3873,7 +3912,7 @@ mod withdraw_unbonded { // when CurrentEra::set(5); - assert_ok!(Pools::unbond(Origin::signed(20), 20, 5)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 5)); // then assert_eq!( @@ -3900,7 +3939,7 @@ mod withdraw_unbonded { // now we start withdrawing unlocked bonds. // when - assert_ok!(Pools::withdraw_unbonded(Origin::signed(20), 20, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(20), 20, 0)); // then assert_eq!( PoolMembers::::get(20).unwrap().unbonding_eras, @@ -3922,7 +3961,7 @@ mod withdraw_unbonded { ); // when - assert_ok!(Pools::withdraw_unbonded(Origin::signed(30), 30, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(30), 30, 0)); // then assert_eq!( PoolMembers::::get(30).unwrap().unbonding_eras, @@ -3950,14 +3989,14 @@ mod withdraw_unbonded { ExtBuilder::default().ed(1).build_and_execute(|| { // depositor now has 20, they can unbond to 10. assert_eq!(Pools::depositor_min_bond(), 10); - assert_ok!(Pools::bond_extra(Origin::signed(10), BondExtra::FreeBalance(10))); + assert_ok!(Pools::bond_extra(RuntimeOrigin::signed(10), BondExtra::FreeBalance(10))); // now they can. - assert_ok!(Pools::unbond(Origin::signed(10), 10, 7)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 7)); // progress one era and unbond the leftover. CurrentEra::set(1); - assert_ok!(Pools::unbond(Origin::signed(10), 10, 3)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 3)); assert_eq!( PoolMembers::::get(10).unwrap().unbonding_eras, @@ -3966,27 +4005,27 @@ mod withdraw_unbonded { // they can't unbond to a value below 10 other than 0.. assert_noop!( - Pools::unbond(Origin::signed(10), 10, 5), + Pools::unbond(RuntimeOrigin::signed(10), 10, 5), Error::::MinimumBondNotMet ); // but not even full, because they pool is not yet destroying. assert_noop!( - Pools::unbond(Origin::signed(10), 10, 10), + Pools::unbond(RuntimeOrigin::signed(10), 10, 10), Error::::MinimumBondNotMet ); // but now they can. unsafe_set_state(1, PoolState::Destroying); assert_noop!( - Pools::unbond(Origin::signed(10), 10, 5), + Pools::unbond(RuntimeOrigin::signed(10), 10, 5), Error::::MinimumBondNotMet ); - assert_ok!(Pools::unbond(Origin::signed(10), 10, 10)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 10)); // now the 7 should be free. CurrentEra::set(3); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(10), 10, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(10), 10, 0)); assert_eq!( pool_events_since_last_call(), @@ -4007,7 +4046,7 @@ mod withdraw_unbonded { // the 13 should be free now, and the member removed. CurrentEra::set(4); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(10), 10, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(10), 10, 0)); assert_eq!( pool_events_since_last_call(), @@ -4039,7 +4078,7 @@ mod create { Balances::make_free_balance_be(&11, StakingMock::minimum_bond() + ed); assert_ok!(Pools::create( - Origin::signed(11), + RuntimeOrigin::signed(11), StakingMock::minimum_bond(), 123, 456, @@ -4097,7 +4136,7 @@ mod create { fn create_errors_correctly() { ExtBuilder::default().with_check(0).build_and_execute(|| { assert_noop!( - Pools::create(Origin::signed(10), 420, 123, 456, 789), + Pools::create(RuntimeOrigin::signed(10), 420, 123, 456, 789), Error::::AccountBelongsToOtherPool ); @@ -4107,7 +4146,7 @@ mod create { // Then assert_noop!( - Pools::create(Origin::signed(11), 9, 123, 456, 789), + Pools::create(RuntimeOrigin::signed(11), 9, 123, 456, 789), Error::::MinimumBondNotMet ); @@ -4116,7 +4155,7 @@ mod create { // Then assert_noop!( - Pools::create(Origin::signed(11), 19, 123, 456, 789), + Pools::create(RuntimeOrigin::signed(11), 19, 123, 456, 789), Error::::MinimumBondNotMet ); @@ -4136,7 +4175,7 @@ mod create { // Then assert_noop!( - Pools::create(Origin::signed(11), 20, 123, 456, 789), + Pools::create(RuntimeOrigin::signed(11), 20, 123, 456, 789), Error::::MaxPools ); @@ -4153,7 +4192,10 @@ mod create { nominator: 11, state_toggler: 11, }); - assert_noop!(create.dispatch(Origin::signed(11)), Error::::MaxPoolMembers); + assert_noop!( + create.dispatch(RuntimeOrigin::signed(11)), + Error::::MaxPoolMembers + ); }); } } @@ -4166,27 +4208,27 @@ mod nominate { ExtBuilder::default().build_and_execute(|| { // Depositor can't nominate assert_noop!( - Pools::nominate(Origin::signed(10), 1, vec![21]), + Pools::nominate(RuntimeOrigin::signed(10), 1, vec![21]), Error::::NotNominator ); // State toggler can't nominate assert_noop!( - Pools::nominate(Origin::signed(902), 1, vec![21]), + Pools::nominate(RuntimeOrigin::signed(902), 1, vec![21]), Error::::NotNominator ); // Root can nominate - assert_ok!(Pools::nominate(Origin::signed(900), 1, vec![21])); + assert_ok!(Pools::nominate(RuntimeOrigin::signed(900), 1, vec![21])); assert_eq!(Nominations::get().unwrap(), vec![21]); // Nominator can nominate - assert_ok!(Pools::nominate(Origin::signed(901), 1, vec![31])); + assert_ok!(Pools::nominate(RuntimeOrigin::signed(901), 1, vec![31])); assert_eq!(Nominations::get().unwrap(), vec![31]); // Can't nominate for a pool that doesn't exist assert_noop!( - Pools::nominate(Origin::signed(902), 123, vec![21]), + Pools::nominate(RuntimeOrigin::signed(902), 123, vec![21]), Error::::PoolNotFound ); }); @@ -4204,16 +4246,16 @@ mod set_state { // Only the root and state toggler can change the state when the pool is ok to be open. assert_noop!( - Pools::set_state(Origin::signed(10), 1, PoolState::Blocked), + Pools::set_state(RuntimeOrigin::signed(10), 1, PoolState::Blocked), Error::::CanNotChangeState ); assert_noop!( - Pools::set_state(Origin::signed(901), 1, PoolState::Blocked), + Pools::set_state(RuntimeOrigin::signed(901), 1, PoolState::Blocked), Error::::CanNotChangeState ); // Root can change state - assert_ok!(Pools::set_state(Origin::signed(900), 1, PoolState::Blocked)); + assert_ok!(Pools::set_state(RuntimeOrigin::signed(900), 1, PoolState::Blocked)); assert_eq!( pool_events_since_last_call(), @@ -4227,16 +4269,16 @@ mod set_state { assert_eq!(BondedPool::::get(1).unwrap().state, PoolState::Blocked); // State toggler can change state - assert_ok!(Pools::set_state(Origin::signed(902), 1, PoolState::Destroying)); + assert_ok!(Pools::set_state(RuntimeOrigin::signed(902), 1, PoolState::Destroying)); assert_eq!(BondedPool::::get(1).unwrap().state, PoolState::Destroying); // If the pool is destroying, then no one can set state assert_noop!( - Pools::set_state(Origin::signed(900), 1, PoolState::Blocked), + Pools::set_state(RuntimeOrigin::signed(900), 1, PoolState::Blocked), Error::::CanNotChangeState ); assert_noop!( - Pools::set_state(Origin::signed(902), 1, PoolState::Blocked), + Pools::set_state(RuntimeOrigin::signed(902), 1, PoolState::Blocked), Error::::CanNotChangeState ); @@ -4248,7 +4290,7 @@ mod set_state { bonded_pool.points = 100; bonded_pool.put(); // When - assert_ok!(Pools::set_state(Origin::signed(11), 1, PoolState::Destroying)); + assert_ok!(Pools::set_state(RuntimeOrigin::signed(11), 1, PoolState::Destroying)); // Then assert_eq!(BondedPool::::get(1).unwrap().state, PoolState::Destroying); @@ -4256,7 +4298,7 @@ mod set_state { Balances::make_free_balance_be(&default_bonded_account(), Balance::max_value() / 10); unsafe_set_state(1, PoolState::Open); // When - assert_ok!(Pools::set_state(Origin::signed(11), 1, PoolState::Destroying)); + assert_ok!(Pools::set_state(RuntimeOrigin::signed(11), 1, PoolState::Destroying)); // Then assert_eq!(BondedPool::::get(1).unwrap().state, PoolState::Destroying); @@ -4264,7 +4306,7 @@ mod set_state { // isn't destroying unsafe_set_state(1, PoolState::Open); assert_noop!( - Pools::set_state(Origin::signed(11), 1, PoolState::Blocked), + Pools::set_state(RuntimeOrigin::signed(11), 1, PoolState::Blocked), Error::::CanNotChangeState ); @@ -4287,28 +4329,28 @@ mod set_metadata { fn set_metadata_works() { ExtBuilder::default().build_and_execute(|| { // Root can set metadata - assert_ok!(Pools::set_metadata(Origin::signed(900), 1, vec![1, 1])); + assert_ok!(Pools::set_metadata(RuntimeOrigin::signed(900), 1, vec![1, 1])); assert_eq!(Metadata::::get(1), vec![1, 1]); // State toggler can set metadata - assert_ok!(Pools::set_metadata(Origin::signed(902), 1, vec![2, 2])); + assert_ok!(Pools::set_metadata(RuntimeOrigin::signed(902), 1, vec![2, 2])); assert_eq!(Metadata::::get(1), vec![2, 2]); // Depositor can't set metadata assert_noop!( - Pools::set_metadata(Origin::signed(10), 1, vec![3, 3]), + Pools::set_metadata(RuntimeOrigin::signed(10), 1, vec![3, 3]), Error::::DoesNotHavePermission ); // Nominator can't set metadata assert_noop!( - Pools::set_metadata(Origin::signed(901), 1, vec![3, 3]), + Pools::set_metadata(RuntimeOrigin::signed(901), 1, vec![3, 3]), Error::::DoesNotHavePermission ); // Metadata cannot be longer than `MaxMetadataLen` assert_noop!( - Pools::set_metadata(Origin::signed(900), 1, vec![1, 1, 1]), + Pools::set_metadata(RuntimeOrigin::signed(900), 1, vec![1, 1, 1]), Error::::MetadataExceedsMaxLen ); }); @@ -4323,7 +4365,7 @@ mod set_configs { ExtBuilder::default().build_and_execute(|| { // Setting works assert_ok!(Pools::set_configs( - Origin::root(), + RuntimeOrigin::root(), ConfigOp::Set(1 as Balance), ConfigOp::Set(2 as Balance), ConfigOp::Set(3u32), @@ -4338,7 +4380,7 @@ mod set_configs { // Noop does nothing assert_storage_noop!(assert_ok!(Pools::set_configs( - Origin::root(), + RuntimeOrigin::root(), ConfigOp::Noop, ConfigOp::Noop, ConfigOp::Noop, @@ -4348,7 +4390,7 @@ mod set_configs { // Removing works assert_ok!(Pools::set_configs( - Origin::root(), + RuntimeOrigin::root(), ConfigOp::Remove, ConfigOp::Remove, ConfigOp::Remove, @@ -4380,7 +4422,7 @@ mod bond_extra { assert_eq!(Balances::free_balance(10), 100); // when - assert_ok!(Pools::bond_extra(Origin::signed(10), BondExtra::FreeBalance(10))); + assert_ok!(Pools::bond_extra(RuntimeOrigin::signed(10), BondExtra::FreeBalance(10))); // then assert_eq!(Balances::free_balance(10), 90); @@ -4397,7 +4439,7 @@ mod bond_extra { ); // when - assert_ok!(Pools::bond_extra(Origin::signed(10), BondExtra::FreeBalance(20))); + assert_ok!(Pools::bond_extra(RuntimeOrigin::signed(10), BondExtra::FreeBalance(20))); // then assert_eq!(Balances::free_balance(10), 70); @@ -4426,7 +4468,7 @@ mod bond_extra { assert_eq!(Balances::free_balance(10), 35); // when - assert_ok!(Pools::bond_extra(Origin::signed(10), BondExtra::Rewards)); + assert_ok!(Pools::bond_extra(RuntimeOrigin::signed(10), BondExtra::Rewards)); // then assert_eq!(Balances::free_balance(10), 35); @@ -4469,7 +4511,7 @@ mod bond_extra { assert_eq!(Balances::free_balance(20), 20); // when - assert_ok!(Pools::bond_extra(Origin::signed(10), BondExtra::Rewards)); + assert_ok!(Pools::bond_extra(RuntimeOrigin::signed(10), BondExtra::Rewards)); // then assert_eq!(Balances::free_balance(10), 35); @@ -4478,7 +4520,7 @@ mod bond_extra { assert_eq!(BondedPools::::get(1).unwrap().points, 30 + 1); // when - assert_ok!(Pools::bond_extra(Origin::signed(20), BondExtra::Rewards)); + assert_ok!(Pools::bond_extra(RuntimeOrigin::signed(20), BondExtra::Rewards)); // then assert_eq!(Balances::free_balance(20), 20); @@ -4522,7 +4564,7 @@ mod update_roles { // non-existent pools assert_noop!( Pools::update_roles( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, ConfigOp::Set(5), ConfigOp::Set(6), @@ -4534,7 +4576,7 @@ mod update_roles { // depositor cannot change roles. assert_noop!( Pools::update_roles( - Origin::signed(1), + RuntimeOrigin::signed(1), 1, ConfigOp::Set(5), ConfigOp::Set(6), @@ -4546,7 +4588,7 @@ mod update_roles { // nominator cannot change roles. assert_noop!( Pools::update_roles( - Origin::signed(901), + RuntimeOrigin::signed(901), 1, ConfigOp::Set(5), ConfigOp::Set(6), @@ -4557,7 +4599,7 @@ mod update_roles { // state-toggler assert_noop!( Pools::update_roles( - Origin::signed(902), + RuntimeOrigin::signed(902), 1, ConfigOp::Set(5), ConfigOp::Set(6), @@ -4568,7 +4610,7 @@ mod update_roles { // but root can assert_ok!(Pools::update_roles( - Origin::signed(900), + RuntimeOrigin::signed(900), 1, ConfigOp::Set(5), ConfigOp::Set(6), @@ -4599,7 +4641,7 @@ mod update_roles { // also root origin can assert_ok!(Pools::update_roles( - Origin::root(), + RuntimeOrigin::root(), 1, ConfigOp::Set(1), ConfigOp::Set(2), @@ -4626,7 +4668,7 @@ mod update_roles { // Noop works assert_ok!(Pools::update_roles( - Origin::root(), + RuntimeOrigin::root(), 1, ConfigOp::Set(11), ConfigOp::Noop, @@ -4654,7 +4696,7 @@ mod update_roles { // Remove works assert_ok!(Pools::update_roles( - Origin::root(), + RuntimeOrigin::root(), 1, ConfigOp::Set(69), ConfigOp::Remove, @@ -4730,7 +4772,7 @@ mod reward_counter_precision { // tad bit less. cannot be paid out. assert_ok!(Balances::mutate_account(&default_reward_account(), |a| a.free += expected_smallest_reward - 1)); - assert_ok!(Pools::claim_payout(Origin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); assert_eq!(pool_events_since_last_call(), vec![]); // revert it. @@ -4740,7 +4782,7 @@ mod reward_counter_precision { // tad bit more. can be claimed. assert_ok!(Balances::mutate_account(&default_reward_account(), |a| a.free += expected_smallest_reward + 1)); - assert_ok!(Pools::claim_payout(Origin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); assert_eq!( pool_events_since_last_call(), vec![Event::PaidOut { member: 10, pool_id: 1, payout: 1173 }] @@ -4776,7 +4818,7 @@ mod reward_counter_precision { // some whale now joins with the other half ot the total issuance. This will bloat all // the calculation regarding current reward counter. Balances::make_free_balance_be(&20, pool_bond * 2); - assert_ok!(Pools::join(Origin::signed(20), pool_bond, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(20), pool_bond, 1)); assert_eq!( pool_events_since_last_call(), @@ -4788,8 +4830,8 @@ mod reward_counter_precision { }] ); - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); assert_eq!( pool_events_since_last_call(), @@ -4798,12 +4840,12 @@ mod reward_counter_precision { // now let a small member join with 10 DOTs. Balances::make_free_balance_be(&30, 20 * DOT); - assert_ok!(Pools::join(Origin::signed(30), 10 * DOT, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(30), 10 * DOT, 1)); // and give a reasonably small reward to the pool. assert_ok!(Balances::mutate_account(&default_reward_account(), |a| a.free += DOT)); - assert_ok!(Pools::claim_payout(Origin::signed(30))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(30))); assert_eq!( pool_events_since_last_call(), vec![ @@ -4841,7 +4883,10 @@ mod reward_counter_precision { // set to zero. In other tests that we want to assert a scenario won't fail, we should // also set the reward counters to some large value. Balances::make_free_balance_be(&20, pool_bond * 2); - assert_err!(Pools::join(Origin::signed(20), pool_bond, 1), Error::::OverflowRisk); + assert_err!( + Pools::join(RuntimeOrigin::signed(20), pool_bond, 1), + Error::::OverflowRisk + ); }) } @@ -4867,7 +4912,7 @@ mod reward_counter_precision { // and have a tiny fish join the pool as well.. Balances::make_free_balance_be(&20, 20 * DOT); - assert_ok!(Pools::join(Origin::signed(20), 10 * DOT, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(20), 10 * DOT, 1)); // earn some small rewards assert_ok!( @@ -4876,7 +4921,7 @@ mod reward_counter_precision { // no point in claiming for 20 (nonetheless, it should be harmless) assert!(pending_rewards(20).unwrap().is_zero()); - assert_ok!(Pools::claim_payout(Origin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); assert_eq!( pool_events_since_last_call(), vec![ @@ -4896,7 +4941,7 @@ mod reward_counter_precision { Balances::mutate_account(&default_reward_account(), |a| a.free += DOT / 1000) ); assert!(pending_rewards(20).unwrap().is_zero()); - assert_ok!(Pools::claim_payout(Origin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); assert_eq!( pool_events_since_last_call(), vec![Event::PaidOut { member: 10, pool_id: 1, payout: 10000000 }] @@ -4907,8 +4952,8 @@ mod reward_counter_precision { Balances::mutate_account(&default_reward_account(), |a| a.free += DOT / 1000) ); assert_eq!(pending_rewards(20).unwrap(), 1); - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); assert_eq!( pool_events_since_last_call(), vec![ @@ -4941,7 +4986,7 @@ mod reward_counter_precision { // and have a tiny fish join the pool as well.. Balances::make_free_balance_be(&20, 20 * DOT); - assert_ok!(Pools::join(Origin::signed(20), 10 * DOT, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(20), 10 * DOT, 1)); // earn some small rewards assert_ok!( @@ -4951,8 +4996,8 @@ mod reward_counter_precision { // if 20 claims now, their reward counter should stay the same, so that they have a // chance of claiming this if they let it accumulate. Also see // `if_small_member_waits_long_enough_they_will_earn_rewards` - assert_ok!(Pools::claim_payout(Origin::signed(10))); - assert_ok!(Pools::claim_payout(Origin::signed(20))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(20))); assert_eq!( pool_events_since_last_call(), vec![ @@ -4998,7 +5043,7 @@ mod fuzz_test { const REWARD_AGENT_ACCOUNT: AccountId = 42; /// Grab random accounts, either known ones, or new ones. - fn random_signed_origin(rng: &mut R) -> (Origin, AccountId) { + fn random_signed_origin(rng: &mut R) -> (RuntimeOrigin, AccountId) { let count = PoolMembers::::count(); if rng.gen::() && count > 0 { // take an existing account. @@ -5011,11 +5056,11 @@ mod fuzz_test { let acc = if candidate == REWARD_AGENT_ACCOUNT { rng.gen::() } else { candidate }; - (Origin::signed(acc), acc) + (RuntimeOrigin::signed(acc), acc) } else { // create a new account let acc = rng.gen::(); - (Origin::signed(acc), acc) + (RuntimeOrigin::signed(acc), acc) } } @@ -5036,7 +5081,7 @@ mod fuzz_test { BondedPools::::iter_keys().collect::>().choose(&mut rng).map(|x| *x) } - fn random_call(mut rng: &mut R) -> (crate::pallet::Call, Origin) { + fn random_call(mut rng: &mut R) -> (crate::pallet::Call, RuntimeOrigin) { let op = rng.gen::(); let mut op_count = as frame_support::dispatch::GetCallName>::get_call_names() @@ -5133,7 +5178,7 @@ mod fuzz_test { } let pool_id = LastPoolId::::get(); let amount = 10 * ExistentialDeposit::get(); - let origin = Origin::signed(self.who); + let origin = RuntimeOrigin::signed(self.who); let _ = Balances::deposit_creating(&self.who, 10 * amount); self.pool_id = Some(pool_id); log::info!(target: "reward-agent", "🤖 reward agent joining in {} with {}", pool_id, amount); @@ -5148,7 +5193,7 @@ mod fuzz_test { return } let pre = Balances::free_balance(&42); - let origin = Origin::signed(42); + let origin = RuntimeOrigin::signed(42); assert_ok!(PoolsCall::::claim_payout {}.dispatch_bypass_filter(origin)); let post = Balances::free_balance(&42); diff --git a/frame/nomination-pools/test-staking/src/lib.rs b/frame/nomination-pools/test-staking/src/lib.rs index 8c6ecae937063..7d848e98174b4 100644 --- a/frame/nomination-pools/test-staking/src/lib.rs +++ b/frame/nomination-pools/test-staking/src/lib.rs @@ -35,11 +35,11 @@ fn pool_lifecycle_e2e() { assert_eq!(Staking::current_era(), None); // create the pool, we know this has id 1. - assert_ok!(Pools::create(Origin::signed(10), 50, 10, 10, 10)); + assert_ok!(Pools::create(RuntimeOrigin::signed(10), 50, 10, 10, 10)); assert_eq!(LastPoolId::::get(), 1); // have the pool nominate. - assert_ok!(Pools::nominate(Origin::signed(10), 1, vec![1, 2, 3])); + assert_ok!(Pools::nominate(RuntimeOrigin::signed(10), 1, vec![1, 2, 3])); assert_eq!(staking_events_since_last_call(), vec![StakingEvent::Bonded(POOL1_BONDED, 50),]); assert_eq!( @@ -51,8 +51,8 @@ fn pool_lifecycle_e2e() { ); // have two members join - assert_ok!(Pools::join(Origin::signed(20), 10, 1)); - assert_ok!(Pools::join(Origin::signed(21), 10, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(20), 10, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(21), 10, 1)); assert_eq!( staking_events_since_last_call(), @@ -67,17 +67,17 @@ fn pool_lifecycle_e2e() { ); // pool goes into destroying - assert_ok!(Pools::set_state(Origin::signed(10), 1, PoolState::Destroying)); + assert_ok!(Pools::set_state(RuntimeOrigin::signed(10), 1, PoolState::Destroying)); // depositor cannot unbond yet. assert_noop!( - Pools::unbond(Origin::signed(10), 10, 50), + Pools::unbond(RuntimeOrigin::signed(10), 10, 50), PoolsError::::MinimumBondNotMet, ); // now the members want to unbond. - assert_ok!(Pools::unbond(Origin::signed(20), 20, 10)); - assert_ok!(Pools::unbond(Origin::signed(21), 21, 10)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 10)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(21), 21, 10)); assert_eq!(PoolMembers::::get(20).unwrap().unbonding_eras.len(), 1); assert_eq!(PoolMembers::::get(20).unwrap().points, 0); @@ -102,14 +102,14 @@ fn pool_lifecycle_e2e() { // depositor cannot still unbond assert_noop!( - Pools::unbond(Origin::signed(10), 10, 50), + Pools::unbond(RuntimeOrigin::signed(10), 10, 50), PoolsError::::MinimumBondNotMet, ); for e in 1..BondingDuration::get() { CurrentEra::::set(Some(e)); assert_noop!( - Pools::withdraw_unbonded(Origin::signed(20), 20, 0), + Pools::withdraw_unbonded(RuntimeOrigin::signed(20), 20, 0), PoolsError::::CannotWithdrawAny ); } @@ -119,13 +119,13 @@ fn pool_lifecycle_e2e() { // depositor cannot still unbond assert_noop!( - Pools::unbond(Origin::signed(10), 10, 50), + Pools::unbond(RuntimeOrigin::signed(10), 10, 50), PoolsError::::MinimumBondNotMet, ); // but members can now withdraw. - assert_ok!(Pools::withdraw_unbonded(Origin::signed(20), 20, 0)); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(21), 21, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(20), 20, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(21), 21, 0)); assert!(PoolMembers::::get(20).is_none()); assert!(PoolMembers::::get(21).is_none()); @@ -146,12 +146,12 @@ fn pool_lifecycle_e2e() { // as soon as all members have left, the depositor can try to unbond, but since the // min-nominator intention is set, they must chill first. assert_noop!( - Pools::unbond(Origin::signed(10), 10, 50), + Pools::unbond(RuntimeOrigin::signed(10), 10, 50), pallet_staking::Error::::InsufficientBond ); - assert_ok!(Pools::chill(Origin::signed(10), 1)); - assert_ok!(Pools::unbond(Origin::signed(10), 10, 50)); + assert_ok!(Pools::chill(RuntimeOrigin::signed(10), 1)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 50)); assert_eq!( staking_events_since_last_call(), @@ -164,7 +164,7 @@ fn pool_lifecycle_e2e() { // waiting another bonding duration: CurrentEra::::set(Some(BondingDuration::get() * 2)); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(10), 10, 1)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(10), 10, 1)); // pools is fully destroyed now. assert_eq!( @@ -190,7 +190,7 @@ fn pool_slash_e2e() { assert_eq!(Staking::current_era(), None); // create the pool, we know this has id 1. - assert_ok!(Pools::create(Origin::signed(10), 40, 10, 10, 10)); + assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); assert_eq!(LastPoolId::::get(), 1); assert_eq!(staking_events_since_last_call(), vec![StakingEvent::Bonded(POOL1_BONDED, 40)]); @@ -205,8 +205,8 @@ fn pool_slash_e2e() { assert_eq!(Payee::::get(POOL1_BONDED), RewardDestination::Account(POOL1_REWARD)); // have two members join - assert_ok!(Pools::join(Origin::signed(20), 20, 1)); - assert_ok!(Pools::join(Origin::signed(21), 20, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(20), 20, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(21), 20, 1)); assert_eq!( staking_events_since_last_call(), @@ -224,8 +224,8 @@ fn pool_slash_e2e() { CurrentEra::::set(Some(1)); // 20 / 80 of the total funds are unlocked, and safe from any further slash. - assert_ok!(Pools::unbond(Origin::signed(10), 10, 10)); - assert_ok!(Pools::unbond(Origin::signed(20), 20, 10)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 10)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 10)); assert_eq!( staking_events_since_last_call(), @@ -246,9 +246,9 @@ fn pool_slash_e2e() { // note: depositor cannot fully unbond at this point. // these funds will still get slashed. - assert_ok!(Pools::unbond(Origin::signed(10), 10, 10)); - assert_ok!(Pools::unbond(Origin::signed(20), 20, 10)); - assert_ok!(Pools::unbond(Origin::signed(21), 21, 10)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 10)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, 10)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(21), 21, 10)); assert_eq!( staking_events_since_last_call(), @@ -290,7 +290,7 @@ fn pool_slash_e2e() { ); CurrentEra::::set(Some(3)); - assert_ok!(Pools::unbond(Origin::signed(21), 21, 10)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(21), 21, 10)); assert_eq!( PoolMembers::::get(21).unwrap(), @@ -310,8 +310,8 @@ fn pool_slash_e2e() { // now we start withdrawing. we do it all at once, at era 6 where 20 and 21 are fully free. CurrentEra::::set(Some(6)); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(20), 20, 0)); - assert_ok!(Pools::withdraw_unbonded(Origin::signed(21), 21, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(20), 20, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(21), 21, 0)); assert_eq!( pool_events_since_last_call(), @@ -331,8 +331,8 @@ fn pool_slash_e2e() { ); // now, finally, we can unbond the depositor further than their current limit. - assert_ok!(Pools::set_state(Origin::signed(10), 1, PoolState::Destroying)); - assert_ok!(Pools::unbond(Origin::signed(10), 10, 20)); + assert_ok!(Pools::set_state(RuntimeOrigin::signed(10), 1, PoolState::Destroying)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(10), 10, 20)); assert_eq!( staking_events_since_last_call(), @@ -357,7 +357,7 @@ fn pool_slash_e2e() { } ); // withdraw the depositor, they should lose 12 balance in total due to slash. - assert_ok!(Pools::withdraw_unbonded(Origin::signed(10), 10, 0)); + assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(10), 10, 0)); assert_eq!( staking_events_since_last_call(), @@ -385,7 +385,7 @@ fn pool_slash_proportional() { assert_eq!(Staking::current_era(), None); // create the pool, we know this has id 1. - assert_ok!(Pools::create(Origin::signed(10), 40, 10, 10, 10)); + assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); assert_eq!(LastPoolId::::get(), 1); assert_eq!(staking_events_since_last_call(), vec![StakingEvent::Bonded(POOL1_BONDED, 40)]); @@ -399,9 +399,9 @@ fn pool_slash_proportional() { // have two members join let bond = 20; - assert_ok!(Pools::join(Origin::signed(20), bond, 1)); - assert_ok!(Pools::join(Origin::signed(21), bond, 1)); - assert_ok!(Pools::join(Origin::signed(22), bond, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(20), bond, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(21), bond, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(22), bond, 1)); assert_eq!( staking_events_since_last_call(), @@ -424,7 +424,7 @@ fn pool_slash_proportional() { CurrentEra::::set(Some(99)); // and unbond - assert_ok!(Pools::unbond(Origin::signed(20), 20, bond)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, bond)); assert_eq!( staking_events_since_last_call(), @@ -442,7 +442,7 @@ fn pool_slash_proportional() { ); CurrentEra::::set(Some(100)); - assert_ok!(Pools::unbond(Origin::signed(21), 21, bond)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(21), 21, bond)); assert_eq!( staking_events_since_last_call(), vec![StakingEvent::Unbonded(POOL1_BONDED, bond),] @@ -459,7 +459,7 @@ fn pool_slash_proportional() { ); CurrentEra::::set(Some(101)); - assert_ok!(Pools::unbond(Origin::signed(22), 22, bond)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(22), 22, bond)); assert_eq!( staking_events_since_last_call(), vec![StakingEvent::Unbonded(POOL1_BONDED, bond),] @@ -516,7 +516,7 @@ fn pool_slash_non_proportional_only_bonded_pool() { assert_eq!(Staking::current_era(), None); // create the pool, we know this has id 1. - assert_ok!(Pools::create(Origin::signed(10), 40, 10, 10, 10)); + assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); assert_eq!(staking_events_since_last_call(), vec![StakingEvent::Bonded(POOL1_BONDED, 40)]); assert_eq!( pool_events_since_last_call(), @@ -528,7 +528,7 @@ fn pool_slash_non_proportional_only_bonded_pool() { // have two members join let bond = 20; - assert_ok!(Pools::join(Origin::signed(20), bond, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(20), bond, 1)); assert_eq!( staking_events_since_last_call(), vec![StakingEvent::Bonded(POOL1_BONDED, bond)] @@ -540,7 +540,7 @@ fn pool_slash_non_proportional_only_bonded_pool() { // progress and unbond. CurrentEra::::set(Some(99)); - assert_ok!(Pools::unbond(Origin::signed(20), 20, bond)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, bond)); assert_eq!( staking_events_since_last_call(), vec![StakingEvent::Unbonded(POOL1_BONDED, bond)] @@ -589,7 +589,7 @@ fn pool_slash_non_proportional_bonded_pool_and_chunks() { assert_eq!(Staking::current_era(), None); // create the pool, we know this has id 1. - assert_ok!(Pools::create(Origin::signed(10), 40, 10, 10, 10)); + assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); assert_eq!(staking_events_since_last_call(), vec![StakingEvent::Bonded(POOL1_BONDED, 40)]); assert_eq!( pool_events_since_last_call(), @@ -601,7 +601,7 @@ fn pool_slash_non_proportional_bonded_pool_and_chunks() { // have two members join let bond = 20; - assert_ok!(Pools::join(Origin::signed(20), bond, 1)); + assert_ok!(Pools::join(RuntimeOrigin::signed(20), bond, 1)); assert_eq!( staking_events_since_last_call(), vec![StakingEvent::Bonded(POOL1_BONDED, bond)] @@ -613,7 +613,7 @@ fn pool_slash_non_proportional_bonded_pool_and_chunks() { // progress and unbond. CurrentEra::::set(Some(99)); - assert_ok!(Pools::unbond(Origin::signed(20), 20, bond)); + assert_ok!(Pools::unbond(RuntimeOrigin::signed(20), 20, bond)); assert_eq!( staking_events_since_last_call(), vec![StakingEvent::Unbonded(POOL1_BONDED, bond)] diff --git a/frame/nomination-pools/test-staking/src/mock.rs b/frame/nomination-pools/test-staking/src/mock.rs index cb63ad04d1a38..8c04e40d71df4 100644 --- a/frame/nomination-pools/test-staking/src/mock.rs +++ b/frame/nomination-pools/test-staking/src/mock.rs @@ -43,7 +43,7 @@ impl frame_system::Config for Runtime { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; @@ -129,6 +129,7 @@ impl pallet_staking::Config for Runtime { type VoterList = VoterList; type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; + type HistoryDepth = ConstU32<84>; type OnStakerSlash = Pools; type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; type WeightInfo = (); @@ -227,7 +228,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { // set some limit for nominations. assert_ok!(Staking::set_staking_configs( - Origin::root(), + RuntimeOrigin::root(), pallet_staking::ConfigOp::Set(10), // minimum nominator bond pallet_staking::ConfigOp::Noop, pallet_staking::ConfigOp::Noop, diff --git a/frame/offences/benchmarking/src/mock.rs b/frame/offences/benchmarking/src/mock.rs index 43c248a09a0b8..c4c1d2aca8d07 100644 --- a/frame/offences/benchmarking/src/mock.rs +++ b/frame/offences/benchmarking/src/mock.rs @@ -50,7 +50,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; @@ -182,6 +182,7 @@ impl pallet_staking::Config for Test { type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; + type HistoryDepth = ConstU32<84>; type OnStakerSlash = (); type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; type WeightInfo = (); diff --git a/frame/offences/src/mock.rs b/frame/offences/src/mock.rs index 5b07aab5bd85e..31dac8d51d3b1 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -92,7 +92,7 @@ impl frame_system::Config for Runtime { type BlockWeights = (); type BlockLength = (); type DbWeight = RocksDbWeight; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; diff --git a/frame/preimage/src/benchmarking.rs b/frame/preimage/src/benchmarking.rs index e0d7e9614abbc..3c7be9db573f4 100644 --- a/frame/preimage/src/benchmarking.rs +++ b/frame/preimage/src/benchmarking.rs @@ -72,7 +72,7 @@ benchmarks! { let s in 0 .. T::MaxSize::get(); let (preimage, hash) = sized_preimage_and_hash::(s); assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash)); - }: note_preimage(T::ManagerOrigin::successful_origin(), preimage) + }: note_preimage(T::ManagerOrigin::successful_origin(), preimage) verify { assert!(Preimage::::have_preimage(&hash)); } @@ -91,7 +91,7 @@ benchmarks! { unnote_no_deposit_preimage { let (preimage, hash) = preimage_and_hash::(); assert_ok!(Preimage::::note_preimage(T::ManagerOrigin::successful_origin(), preimage)); - }: unnote_preimage(T::ManagerOrigin::successful_origin(), hash) + }: unnote_preimage(T::ManagerOrigin::successful_origin(), hash) verify { assert!(!Preimage::::have_preimage(&hash)); } @@ -102,7 +102,7 @@ benchmarks! { let noter = funded_account::("noter", 0); whitelist_account!(noter); assert_ok!(Preimage::::note_preimage(RawOrigin::Signed(noter).into(), preimage)); - }: _(T::ManagerOrigin::successful_origin(), hash) + }: _(T::ManagerOrigin::successful_origin(), hash) verify { assert_eq!(StatusFor::::get(&hash), Some(RequestStatus::Requested(1))); } @@ -110,14 +110,14 @@ benchmarks! { request_no_deposit_preimage { let (preimage, hash) = preimage_and_hash::(); assert_ok!(Preimage::::note_preimage(T::ManagerOrigin::successful_origin(), preimage)); - }: request_preimage(T::ManagerOrigin::successful_origin(), hash) + }: request_preimage(T::ManagerOrigin::successful_origin(), hash) verify { assert_eq!(StatusFor::::get(&hash), Some(RequestStatus::Requested(1))); } // Cheap request - the preimage is not yet noted, so deposit to unreserve. request_unnoted_preimage { let (_, hash) = preimage_and_hash::(); - }: request_preimage(T::ManagerOrigin::successful_origin(), hash) + }: request_preimage(T::ManagerOrigin::successful_origin(), hash) verify { assert_eq!(StatusFor::::get(&hash), Some(RequestStatus::Requested(1))); } @@ -125,7 +125,7 @@ benchmarks! { request_requested_preimage { let (_, hash) = preimage_and_hash::(); assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash)); - }: request_preimage(T::ManagerOrigin::successful_origin(), hash) + }: request_preimage(T::ManagerOrigin::successful_origin(), hash) verify { assert_eq!(StatusFor::::get(&hash), Some(RequestStatus::Requested(2))); } @@ -135,7 +135,7 @@ benchmarks! { let (preimage, hash) = preimage_and_hash::(); assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash)); assert_ok!(Preimage::::note_preimage(T::ManagerOrigin::successful_origin(), preimage)); - }: _(T::ManagerOrigin::successful_origin(), hash) + }: _(T::ManagerOrigin::successful_origin(), hash) verify { assert_eq!(StatusFor::::get(&hash), None); } @@ -143,7 +143,7 @@ benchmarks! { unrequest_unnoted_preimage { let (_, hash) = preimage_and_hash::(); assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash)); - }: unrequest_preimage(T::ManagerOrigin::successful_origin(), hash) + }: unrequest_preimage(T::ManagerOrigin::successful_origin(), hash) verify { assert_eq!(StatusFor::::get(&hash), None); } @@ -152,7 +152,7 @@ benchmarks! { let (_, hash) = preimage_and_hash::(); assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash)); assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash)); - }: unrequest_preimage(T::ManagerOrigin::successful_origin(), hash) + }: unrequest_preimage(T::ManagerOrigin::successful_origin(), hash) verify { assert_eq!(StatusFor::::get(&hash), Some(RequestStatus::Requested(1))); } diff --git a/frame/preimage/src/lib.rs b/frame/preimage/src/lib.rs index 749e5924cc885..90f5ac175f540 100644 --- a/frame/preimage/src/lib.rs +++ b/frame/preimage/src/lib.rs @@ -86,7 +86,7 @@ pub mod pallet { /// An origin that can request a preimage be placed on-chain without a deposit or fee, or /// manage existing preimages. - type ManagerOrigin: EnsureOrigin; + type ManagerOrigin: EnsureOrigin; /// Max size allowed for a preimage. type MaxSize: Get; @@ -191,7 +191,9 @@ pub mod pallet { impl Pallet { /// Ensure that the origin is either the `ManagerOrigin` or a signed origin. - fn ensure_signed_or_manager(origin: T::Origin) -> Result, BadOrigin> { + fn ensure_signed_or_manager( + origin: T::RuntimeOrigin, + ) -> Result, BadOrigin> { if T::ManagerOrigin::ensure_origin(origin.clone()).is_ok() { return Ok(None) } diff --git a/frame/preimage/src/mock.rs b/frame/preimage/src/mock.rs index 75e8767f3e59f..e12598a35b4bb 100644 --- a/frame/preimage/src/mock.rs +++ b/frame/preimage/src/mock.rs @@ -57,7 +57,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = RocksDbWeight; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = u64; diff --git a/frame/preimage/src/tests.rs b/frame/preimage/src/tests.rs index 721bb128de239..e6b64ae16dd8c 100644 --- a/frame/preimage/src/tests.rs +++ b/frame/preimage/src/tests.rs @@ -26,7 +26,7 @@ use pallet_balances::Error as BalancesError; #[test] fn user_note_preimage_works() { new_test_ext().execute_with(|| { - assert_ok!(Preimage::note_preimage(Origin::signed(2), vec![1])); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::signed(2), vec![1])); assert_eq!(Balances::reserved_balance(2), 3); assert_eq!(Balances::free_balance(2), 97); @@ -35,11 +35,11 @@ fn user_note_preimage_works() { assert_eq!(Preimage::get_preimage(&h), Some(vec![1])); assert_noop!( - Preimage::note_preimage(Origin::signed(2), vec![1]), + Preimage::note_preimage(RuntimeOrigin::signed(2), vec![1]), Error::::AlreadyNoted ); assert_noop!( - Preimage::note_preimage(Origin::signed(0), vec![2]), + Preimage::note_preimage(RuntimeOrigin::signed(0), vec![2]), BalancesError::::InsufficientBalance ); }); @@ -48,7 +48,7 @@ fn user_note_preimage_works() { #[test] fn manager_note_preimage_works() { new_test_ext().execute_with(|| { - assert_ok!(Preimage::note_preimage(Origin::signed(1), vec![1])); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::signed(1), vec![1])); assert_eq!(Balances::reserved_balance(1), 0); assert_eq!(Balances::free_balance(1), 100); @@ -57,7 +57,7 @@ fn manager_note_preimage_works() { assert_eq!(Preimage::get_preimage(&h), Some(vec![1])); assert_noop!( - Preimage::note_preimage(Origin::signed(1), vec![1]), + Preimage::note_preimage(RuntimeOrigin::signed(1), vec![1]), Error::::AlreadyNoted ); }); @@ -66,19 +66,19 @@ fn manager_note_preimage_works() { #[test] fn user_unnote_preimage_works() { new_test_ext().execute_with(|| { - assert_ok!(Preimage::note_preimage(Origin::signed(2), vec![1])); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::signed(2), vec![1])); assert_noop!( - Preimage::unnote_preimage(Origin::signed(3), hashed([1])), + Preimage::unnote_preimage(RuntimeOrigin::signed(3), hashed([1])), Error::::NotAuthorized ); assert_noop!( - Preimage::unnote_preimage(Origin::signed(2), hashed([2])), + Preimage::unnote_preimage(RuntimeOrigin::signed(2), hashed([2])), Error::::NotNoted ); - assert_ok!(Preimage::unnote_preimage(Origin::signed(2), hashed([1]))); + assert_ok!(Preimage::unnote_preimage(RuntimeOrigin::signed(2), hashed([1]))); assert_noop!( - Preimage::unnote_preimage(Origin::signed(2), hashed([1])), + Preimage::unnote_preimage(RuntimeOrigin::signed(2), hashed([1])), Error::::NotNoted ); @@ -91,10 +91,10 @@ fn user_unnote_preimage_works() { #[test] fn manager_unnote_preimage_works() { new_test_ext().execute_with(|| { - assert_ok!(Preimage::note_preimage(Origin::signed(1), vec![1])); - assert_ok!(Preimage::unnote_preimage(Origin::signed(1), hashed([1]))); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::signed(1), vec![1])); + assert_ok!(Preimage::unnote_preimage(RuntimeOrigin::signed(1), hashed([1]))); assert_noop!( - Preimage::unnote_preimage(Origin::signed(1), hashed([1])), + Preimage::unnote_preimage(RuntimeOrigin::signed(1), hashed([1])), Error::::NotNoted ); @@ -107,17 +107,17 @@ fn manager_unnote_preimage_works() { #[test] fn manager_unnote_user_preimage_works() { new_test_ext().execute_with(|| { - assert_ok!(Preimage::note_preimage(Origin::signed(2), vec![1])); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::signed(2), vec![1])); assert_noop!( - Preimage::unnote_preimage(Origin::signed(3), hashed([1])), + Preimage::unnote_preimage(RuntimeOrigin::signed(3), hashed([1])), Error::::NotAuthorized ); assert_noop!( - Preimage::unnote_preimage(Origin::signed(2), hashed([2])), + Preimage::unnote_preimage(RuntimeOrigin::signed(2), hashed([2])), Error::::NotNoted ); - assert_ok!(Preimage::unnote_preimage(Origin::signed(1), hashed([1]))); + assert_ok!(Preimage::unnote_preimage(RuntimeOrigin::signed(1), hashed([1]))); let h = hashed([1]); assert!(!Preimage::have_preimage(&h)); @@ -128,10 +128,10 @@ fn manager_unnote_user_preimage_works() { #[test] fn requested_then_noted_preimage_cannot_be_unnoted() { new_test_ext().execute_with(|| { - assert_ok!(Preimage::note_preimage(Origin::signed(1), vec![1])); - assert_ok!(Preimage::request_preimage(Origin::signed(1), hashed([1]))); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::signed(1), vec![1])); + assert_ok!(Preimage::request_preimage(RuntimeOrigin::signed(1), hashed([1]))); assert_noop!( - Preimage::unnote_preimage(Origin::signed(1), hashed([1])), + Preimage::unnote_preimage(RuntimeOrigin::signed(1), hashed([1])), Error::::Requested ); @@ -144,16 +144,16 @@ fn requested_then_noted_preimage_cannot_be_unnoted() { #[test] fn request_note_order_makes_no_difference() { let one_way = new_test_ext().execute_with(|| { - assert_ok!(Preimage::request_preimage(Origin::signed(1), hashed([1]))); - assert_ok!(Preimage::note_preimage(Origin::signed(1), vec![1])); + assert_ok!(Preimage::request_preimage(RuntimeOrigin::signed(1), hashed([1]))); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::signed(1), vec![1])); ( StatusFor::::iter().collect::>(), PreimageFor::::iter().collect::>(), ) }); new_test_ext().execute_with(|| { - assert_ok!(Preimage::note_preimage(Origin::signed(1), vec![1])); - assert_ok!(Preimage::request_preimage(Origin::signed(1), hashed([1]))); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::signed(1), vec![1])); + assert_ok!(Preimage::request_preimage(RuntimeOrigin::signed(1), hashed([1]))); let other_way = ( StatusFor::::iter().collect::>(), PreimageFor::::iter().collect::>(), @@ -165,8 +165,8 @@ fn request_note_order_makes_no_difference() { #[test] fn requested_then_user_noted_preimage_is_free() { new_test_ext().execute_with(|| { - assert_ok!(Preimage::request_preimage(Origin::signed(1), hashed([1]))); - assert_ok!(Preimage::note_preimage(Origin::signed(2), vec![1])); + assert_ok!(Preimage::request_preimage(RuntimeOrigin::signed(1), hashed([1]))); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::signed(2), vec![1])); assert_eq!(Balances::reserved_balance(2), 0); assert_eq!(Balances::free_balance(2), 100); @@ -179,16 +179,16 @@ fn requested_then_user_noted_preimage_is_free() { #[test] fn request_user_note_order_makes_no_difference() { let one_way = new_test_ext().execute_with(|| { - assert_ok!(Preimage::request_preimage(Origin::signed(1), hashed([1]))); - assert_ok!(Preimage::note_preimage(Origin::signed(2), vec![1])); + assert_ok!(Preimage::request_preimage(RuntimeOrigin::signed(1), hashed([1]))); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::signed(2), vec![1])); ( StatusFor::::iter().collect::>(), PreimageFor::::iter().collect::>(), ) }); new_test_ext().execute_with(|| { - assert_ok!(Preimage::note_preimage(Origin::signed(2), vec![1])); - assert_ok!(Preimage::request_preimage(Origin::signed(1), hashed([1]))); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::signed(2), vec![1])); + assert_ok!(Preimage::request_preimage(RuntimeOrigin::signed(1), hashed([1]))); let other_way = ( StatusFor::::iter().collect::>(), PreimageFor::::iter().collect::>(), @@ -200,20 +200,20 @@ fn request_user_note_order_makes_no_difference() { #[test] fn unrequest_preimage_works() { new_test_ext().execute_with(|| { - assert_ok!(Preimage::request_preimage(Origin::signed(1), hashed([1]))); - assert_ok!(Preimage::request_preimage(Origin::signed(1), hashed([1]))); - assert_ok!(Preimage::note_preimage(Origin::signed(2), vec![1])); + assert_ok!(Preimage::request_preimage(RuntimeOrigin::signed(1), hashed([1]))); + assert_ok!(Preimage::request_preimage(RuntimeOrigin::signed(1), hashed([1]))); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::signed(2), vec![1])); assert_noop!( - Preimage::unrequest_preimage(Origin::signed(1), hashed([2])), + Preimage::unrequest_preimage(RuntimeOrigin::signed(1), hashed([2])), Error::::NotRequested ); - assert_ok!(Preimage::unrequest_preimage(Origin::signed(1), hashed([1]))); + assert_ok!(Preimage::unrequest_preimage(RuntimeOrigin::signed(1), hashed([1]))); assert!(Preimage::have_preimage(&hashed([1]))); - assert_ok!(Preimage::unrequest_preimage(Origin::signed(1), hashed([1]))); + assert_ok!(Preimage::unrequest_preimage(RuntimeOrigin::signed(1), hashed([1]))); assert_noop!( - Preimage::unrequest_preimage(Origin::signed(1), hashed([1])), + Preimage::unrequest_preimage(RuntimeOrigin::signed(1), hashed([1])), Error::::NotRequested ); }); @@ -222,10 +222,10 @@ fn unrequest_preimage_works() { #[test] fn user_noted_then_requested_preimage_is_refunded_once_only() { new_test_ext().execute_with(|| { - assert_ok!(Preimage::note_preimage(Origin::signed(2), vec![1; 3])); - assert_ok!(Preimage::note_preimage(Origin::signed(2), vec![1])); - assert_ok!(Preimage::request_preimage(Origin::signed(1), hashed([1]))); - assert_ok!(Preimage::unrequest_preimage(Origin::signed(1), hashed([1]))); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::signed(2), vec![1; 3])); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::signed(2), vec![1])); + assert_ok!(Preimage::request_preimage(RuntimeOrigin::signed(1), hashed([1]))); + assert_ok!(Preimage::unrequest_preimage(RuntimeOrigin::signed(1), hashed([1]))); // Still have reserve from `vec[1; 3]`. assert_eq!(Balances::reserved_balance(2), 5); assert_eq!(Balances::free_balance(2), 95); diff --git a/frame/proxy/src/benchmarking.rs b/frame/proxy/src/benchmarking.rs index f7e440d1f7d6f..58c0cb73011df 100644 --- a/frame/proxy/src/benchmarking.rs +++ b/frame/proxy/src/benchmarking.rs @@ -98,7 +98,7 @@ benchmarks! { let a in 0 .. T::MaxPending::get() - 1; let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::(p, None)?; // In this case the caller is the "target" proxy - let caller: T::AccountId = account("anonymous", 0, SEED); + let caller: T::AccountId = account("pure", 0, SEED); let delegate: T::AccountId = account("target", p - 1, SEED); let delegate_lookup = T::Lookup::unlookup(delegate.clone()); T::Currency::make_free_balance_be(&delegate, BalanceOf::::max_value() / 2u32.into()); @@ -218,7 +218,7 @@ benchmarks! { assert_eq!(proxies.len() as u32, 0); } - anonymous { + create_pure { let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::(p, None)?; let caller: T::AccountId = whitelisted_caller(); }: _( @@ -228,22 +228,22 @@ benchmarks! { 0 ) verify { - let anon_account = Pallet::::anonymous_account(&caller, &T::ProxyType::default(), 0, None); - assert_last_event::(Event::AnonymousCreated { - anonymous: anon_account, + let pure_account = Pallet::::pure_account(&caller, &T::ProxyType::default(), 0, None); + assert_last_event::(Event::PureCreated { + pure: pure_account, who: caller, proxy_type: T::ProxyType::default(), disambiguation_index: 0, }.into()); } - kill_anonymous { + kill_pure { let p in 0 .. (T::MaxProxies::get() - 2); let caller: T::AccountId = whitelisted_caller(); let caller_lookup = T::Lookup::unlookup(caller.clone()); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); - Pallet::::anonymous( + Pallet::::create_pure( RawOrigin::Signed(whitelisted_caller()).into(), T::ProxyType::default(), T::BlockNumber::zero(), @@ -251,13 +251,13 @@ benchmarks! { )?; let height = system::Pallet::::block_number(); let ext_index = system::Pallet::::extrinsic_index().unwrap_or(0); - let anon = Pallet::::anonymous_account(&caller, &T::ProxyType::default(), 0, None); + let pure_account = Pallet::::pure_account(&caller, &T::ProxyType::default(), 0, None); - add_proxies::(p, Some(anon.clone()))?; - ensure!(Proxies::::contains_key(&anon), "anon proxy not created"); - }: _(RawOrigin::Signed(anon.clone()), caller_lookup, T::ProxyType::default(), 0, height, ext_index) + add_proxies::(p, Some(pure_account.clone()))?; + ensure!(Proxies::::contains_key(&pure_account), "pure proxy not created"); + }: _(RawOrigin::Signed(pure_account.clone()), caller_lookup, T::ProxyType::default(), 0, height, ext_index) verify { - assert!(!Proxies::::contains_key(&anon)); + assert!(!Proxies::::contains_key(&pure_account)); } impl_benchmark_test_suite!(Proxy, crate::tests::new_test_ext(), crate::tests::Test); diff --git a/frame/proxy/src/lib.rs b/frame/proxy/src/lib.rs index dcc19e85085f8..5c07a2b012243 100644 --- a/frame/proxy/src/lib.rs +++ b/frame/proxy/src/lib.rs @@ -113,7 +113,7 @@ pub mod pallet { /// The overarching call type. type RuntimeCall: Parameter - + Dispatchable + + Dispatchable + GetDispatchInfo + From> + IsSubType> @@ -191,10 +191,6 @@ pub mod pallet { /// - `real`: The account that the proxy will make a call on behalf of. /// - `force_proxy_type`: Specify the exact proxy type to be used and checked for this call. /// - `call`: The call to be made by the `real` account. - /// - /// # - /// Weight is a function of the number of proxies the user has (P). - /// # #[pallet::weight({ let di = call.get_dispatch_info(); (T::WeightInfo::proxy(T::MaxProxies::get()) @@ -228,10 +224,6 @@ pub mod pallet { /// - `proxy_type`: The permissions allowed for this proxy account. /// - `delay`: The announcement period required of the initial proxy. Will generally be /// zero. - /// - /// # - /// Weight is a function of the number of proxies the user has (P). - /// # #[pallet::weight(T::WeightInfo::add_proxy(T::MaxProxies::get()))] pub fn add_proxy( origin: OriginFor, @@ -251,10 +243,6 @@ pub mod pallet { /// Parameters: /// - `proxy`: The account that the `caller` would like to remove as a proxy. /// - `proxy_type`: The permissions currently enabled for the removed proxy account. - /// - /// # - /// Weight is a function of the number of proxies the user has (P). - /// # #[pallet::weight(T::WeightInfo::remove_proxy(T::MaxProxies::get()))] pub fn remove_proxy( origin: OriginFor, @@ -271,12 +259,8 @@ pub mod pallet { /// /// The dispatch origin for this call must be _Signed_. /// - /// WARNING: This may be called on accounts created by `anonymous`, however if done, then + /// WARNING: This may be called on accounts created by `pure`, however if done, then /// the unreserved fees will be inaccessible. **All access to this account will be lost.** - /// - /// # - /// Weight is a function of the number of proxies the user has (P). - /// # #[pallet::weight(T::WeightInfo::remove_proxies(T::MaxProxies::get()))] pub fn remove_proxies(origin: OriginFor) -> DispatchResult { let who = ensure_signed(origin)?; @@ -304,13 +288,8 @@ pub mod pallet { /// same sender, with the same parameters. /// /// Fails if there are insufficient funds to pay for deposit. - /// - /// # - /// Weight is a function of the number of proxies the user has (P). - /// # - /// TODO: Might be over counting 1 read - #[pallet::weight(T::WeightInfo::anonymous(T::MaxProxies::get()))] - pub fn anonymous( + #[pallet::weight(T::WeightInfo::create_pure(T::MaxProxies::get()))] + pub fn create_pure( origin: OriginFor, proxy_type: T::ProxyType, delay: T::BlockNumber, @@ -318,8 +297,8 @@ pub mod pallet { ) -> DispatchResult { let who = ensure_signed(origin)?; - let anonymous = Self::anonymous_account(&who, &proxy_type, index, None); - ensure!(!Proxies::::contains_key(&anonymous), Error::::Duplicate); + let pure = Self::pure_account(&who, &proxy_type, index, None); + ensure!(!Proxies::::contains_key(&pure), Error::::Duplicate); let proxy_def = ProxyDefinition { delegate: who.clone(), proxy_type: proxy_type.clone(), delay }; @@ -329,9 +308,9 @@ pub mod pallet { let deposit = T::ProxyDepositBase::get() + T::ProxyDepositFactor::get(); T::Currency::reserve(&who, deposit)?; - Proxies::::insert(&anonymous, (bounded_proxies, deposit)); - Self::deposit_event(Event::AnonymousCreated { - anonymous, + Proxies::::insert(&pure, (bounded_proxies, deposit)); + Self::deposit_event(Event::PureCreated { + pure, who, proxy_type, disambiguation_index: index, @@ -340,28 +319,24 @@ pub mod pallet { Ok(()) } - /// Removes a previously spawned anonymous proxy. + /// Removes a previously spawned pure proxy. /// /// WARNING: **All access to this account will be lost.** Any funds held in it will be /// inaccessible. /// /// Requires a `Signed` origin, and the sender account must have been created by a call to - /// `anonymous` with corresponding parameters. - /// - /// - `spawner`: The account that originally called `anonymous` to create this account. - /// - `index`: The disambiguation index originally passed to `anonymous`. Probably `0`. - /// - `proxy_type`: The proxy type originally passed to `anonymous`. - /// - `height`: The height of the chain when the call to `anonymous` was processed. - /// - `ext_index`: The extrinsic index in which the call to `anonymous` was processed. - /// - /// Fails with `NoPermission` in case the caller is not a previously created anonymous - /// account whose `anonymous` call has corresponding parameters. - /// - /// # - /// Weight is a function of the number of proxies the user has (P). - /// # - #[pallet::weight(T::WeightInfo::kill_anonymous(T::MaxProxies::get()))] - pub fn kill_anonymous( + /// `pure` with corresponding parameters. + /// + /// - `spawner`: The account that originally called `pure` to create this account. + /// - `index`: The disambiguation index originally passed to `pure`. Probably `0`. + /// - `proxy_type`: The proxy type originally passed to `pure`. + /// - `height`: The height of the chain when the call to `pure` was processed. + /// - `ext_index`: The extrinsic index in which the call to `pure` was processed. + /// + /// Fails with `NoPermission` in case the caller is not a previously created pure + /// account whose `pure` call has corresponding parameters. + #[pallet::weight(T::WeightInfo::kill_pure(T::MaxProxies::get()))] + pub fn kill_pure( origin: OriginFor, spawner: AccountIdLookupOf, proxy_type: T::ProxyType, @@ -373,7 +348,7 @@ pub mod pallet { let spawner = T::Lookup::lookup(spawner)?; let when = (height, ext_index); - let proxy = Self::anonymous_account(&spawner, &proxy_type, index, Some(when)); + let proxy = Self::pure_account(&spawner, &proxy_type, index, Some(when)); ensure!(proxy == who, Error::::NoPermission); let (_, deposit) = Proxies::::take(&who); @@ -397,12 +372,6 @@ pub mod pallet { /// Parameters: /// - `real`: The account that the proxy will make a call on behalf of. /// - `call_hash`: The hash of the call to be made by the `real` account. - /// - /// # - /// Weight is a function of: - /// - A: the number of announcements made. - /// - P: the number of proxies the user has. - /// # #[pallet::weight(T::WeightInfo::announce(T::MaxPending::get(), T::MaxProxies::get()))] pub fn announce( origin: OriginFor, @@ -452,12 +421,6 @@ pub mod pallet { /// Parameters: /// - `real`: The account that the proxy will make a call on behalf of. /// - `call_hash`: The hash of the call to be made by the `real` account. - /// - /// # - /// Weight is a function of: - /// - A: the number of announcements made. - /// - P: the number of proxies the user has. - /// # #[pallet::weight(T::WeightInfo::remove_announcement( T::MaxPending::get(), T::MaxProxies::get() @@ -484,12 +447,6 @@ pub mod pallet { /// Parameters: /// - `delegate`: The account that previously announced the call. /// - `call_hash`: The hash of the call to be made. - /// - /// # - /// Weight is a function of: - /// - A: the number of announcements made. - /// - P: the number of proxies the user has. - /// # #[pallet::weight(T::WeightInfo::reject_announcement( T::MaxPending::get(), T::MaxProxies::get() @@ -519,12 +476,6 @@ pub mod pallet { /// - `real`: The account that the proxy will make a call on behalf of. /// - `force_proxy_type`: Specify the exact proxy type to be used and checked for this call. /// - `call`: The call to be made by the `real` account. - /// - /// # - /// Weight is a function of: - /// - A: the number of announcements made. - /// - P: the number of proxies the user has. - /// # #[pallet::weight({ let di = call.get_dispatch_info(); (T::WeightInfo::proxy_announced(T::MaxPending::get(), T::MaxProxies::get()) @@ -565,10 +516,10 @@ pub mod pallet { pub enum Event { /// A proxy was executed correctly, with the given. ProxyExecuted { result: DispatchResult }, - /// Anonymous account has been created by new proxy with given + /// A pure account has been created by new proxy with given /// disambiguation index and proxy type. - AnonymousCreated { - anonymous: T::AccountId, + PureCreated { + pure: T::AccountId, who: T::AccountId, proxy_type: T::ProxyType, disambiguation_index: u16, @@ -642,7 +593,7 @@ pub mod pallet { } impl Pallet { - /// Calculate the address of an anonymous account. + /// Calculate the address of an pure account. /// /// - `who`: The spawner account. /// - `proxy_type`: The type of the proxy that the sender will be registered as over the @@ -651,9 +602,9 @@ impl Pallet { /// - `index`: A disambiguation index, in case this is called multiple times in the same /// transaction (e.g. with `utility::batch`). Unless you're using `batch` you probably just /// want to use `0`. - /// - `maybe_when`: The block height and extrinsic index of when the anonymous account was + /// - `maybe_when`: The block height and extrinsic index of when the pure account was /// created. None to use current block height and extrinsic index. - pub fn anonymous_account( + pub fn pure_account( who: &T::AccountId, proxy_type: &T::ProxyType, index: u16, @@ -819,7 +770,7 @@ impl Pallet { call: ::RuntimeCall, ) { // This is a freshly authenticated new account, the origin restrictions doesn't apply. - let mut origin: T::Origin = frame_system::RawOrigin::Signed(real).into(); + let mut origin: T::RuntimeOrigin = frame_system::RawOrigin::Signed(real).into(); origin.add_filter(move |c: &::RuntimeCall| { let c = ::RuntimeCall::from_ref(c); // We make sure the proxy call does access this pallet to change modify proxies. @@ -830,9 +781,9 @@ impl Pallet { Some(Call::remove_proxy { ref proxy_type, .. }) if !def.proxy_type.is_superset(proxy_type) => false, - // Proxy call cannot remove all proxies or kill anonymous proxies unless it has full + // Proxy call cannot remove all proxies or kill pure proxies unless it has full // permissions. - Some(Call::remove_proxies { .. }) | Some(Call::kill_anonymous { .. }) + Some(Call::remove_proxies { .. }) | Some(Call::kill_pure { .. }) if def.proxy_type != T::ProxyType::default() => false, _ => def.proxy_type.filter(c), diff --git a/frame/proxy/src/tests.rs b/frame/proxy/src/tests.rs index 0025b1510526e..17bc7bcb92ee1 100644 --- a/frame/proxy/src/tests.rs +++ b/frame/proxy/src/tests.rs @@ -61,7 +61,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = H256; @@ -204,7 +204,7 @@ fn call_transfer(dest: u64, value: u64) -> RuntimeCall { #[test] fn announcement_works() { new_test_ext().execute_with(|| { - assert_ok!(Proxy::add_proxy(Origin::signed(1), 3, ProxyType::Any, 1)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(1), 3, ProxyType::Any, 1)); System::assert_last_event( ProxyEvent::ProxyAdded { delegator: 1, @@ -214,10 +214,10 @@ fn announcement_works() { } .into(), ); - assert_ok!(Proxy::add_proxy(Origin::signed(2), 3, ProxyType::Any, 1)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(2), 3, ProxyType::Any, 1)); assert_eq!(Balances::reserved_balance(3), 0); - assert_ok!(Proxy::announce(Origin::signed(3), 1, [1; 32].into())); + assert_ok!(Proxy::announce(RuntimeOrigin::signed(3), 1, [1; 32].into())); let announcements = Announcements::::get(3); assert_eq!( announcements.0, @@ -225,7 +225,7 @@ fn announcement_works() { ); assert_eq!(Balances::reserved_balance(3), announcements.1); - assert_ok!(Proxy::announce(Origin::signed(3), 2, [2; 32].into())); + assert_ok!(Proxy::announce(RuntimeOrigin::signed(3), 2, [2; 32].into())); let announcements = Announcements::::get(3); assert_eq!( announcements.0, @@ -236,20 +236,23 @@ fn announcement_works() { ); assert_eq!(Balances::reserved_balance(3), announcements.1); - assert_noop!(Proxy::announce(Origin::signed(3), 2, [3; 32].into()), Error::::TooMany); + assert_noop!( + Proxy::announce(RuntimeOrigin::signed(3), 2, [3; 32].into()), + Error::::TooMany + ); }); } #[test] fn remove_announcement_works() { new_test_ext().execute_with(|| { - assert_ok!(Proxy::add_proxy(Origin::signed(1), 3, ProxyType::Any, 1)); - assert_ok!(Proxy::add_proxy(Origin::signed(2), 3, ProxyType::Any, 1)); - assert_ok!(Proxy::announce(Origin::signed(3), 1, [1; 32].into())); - assert_ok!(Proxy::announce(Origin::signed(3), 2, [2; 32].into())); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(1), 3, ProxyType::Any, 1)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(2), 3, ProxyType::Any, 1)); + assert_ok!(Proxy::announce(RuntimeOrigin::signed(3), 1, [1; 32].into())); + assert_ok!(Proxy::announce(RuntimeOrigin::signed(3), 2, [2; 32].into())); let e = Error::::NotFound; - assert_noop!(Proxy::remove_announcement(Origin::signed(3), 1, [0; 32].into()), e); - assert_ok!(Proxy::remove_announcement(Origin::signed(3), 1, [1; 32].into())); + assert_noop!(Proxy::remove_announcement(RuntimeOrigin::signed(3), 1, [0; 32].into()), e); + assert_ok!(Proxy::remove_announcement(RuntimeOrigin::signed(3), 1, [1; 32].into())); let announcements = Announcements::::get(3); assert_eq!( announcements.0, @@ -262,15 +265,15 @@ fn remove_announcement_works() { #[test] fn reject_announcement_works() { new_test_ext().execute_with(|| { - assert_ok!(Proxy::add_proxy(Origin::signed(1), 3, ProxyType::Any, 1)); - assert_ok!(Proxy::add_proxy(Origin::signed(2), 3, ProxyType::Any, 1)); - assert_ok!(Proxy::announce(Origin::signed(3), 1, [1; 32].into())); - assert_ok!(Proxy::announce(Origin::signed(3), 2, [2; 32].into())); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(1), 3, ProxyType::Any, 1)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(2), 3, ProxyType::Any, 1)); + assert_ok!(Proxy::announce(RuntimeOrigin::signed(3), 1, [1; 32].into())); + assert_ok!(Proxy::announce(RuntimeOrigin::signed(3), 2, [2; 32].into())); let e = Error::::NotFound; - assert_noop!(Proxy::reject_announcement(Origin::signed(1), 3, [0; 32].into()), e); + assert_noop!(Proxy::reject_announcement(RuntimeOrigin::signed(1), 3, [0; 32].into()), e); let e = Error::::NotFound; - assert_noop!(Proxy::reject_announcement(Origin::signed(4), 3, [1; 32].into()), e); - assert_ok!(Proxy::reject_announcement(Origin::signed(1), 3, [1; 32].into())); + assert_noop!(Proxy::reject_announcement(RuntimeOrigin::signed(4), 3, [1; 32].into()), e); + assert_ok!(Proxy::reject_announcement(RuntimeOrigin::signed(1), 3, [1; 32].into())); let announcements = Announcements::::get(3); assert_eq!( announcements.0, @@ -283,41 +286,44 @@ fn reject_announcement_works() { #[test] fn announcer_must_be_proxy() { new_test_ext().execute_with(|| { - assert_noop!(Proxy::announce(Origin::signed(2), 1, H256::zero()), Error::::NotProxy); + assert_noop!( + Proxy::announce(RuntimeOrigin::signed(2), 1, H256::zero()), + Error::::NotProxy + ); }); } #[test] fn delayed_requires_pre_announcement() { new_test_ext().execute_with(|| { - assert_ok!(Proxy::add_proxy(Origin::signed(1), 2, ProxyType::Any, 1)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(1), 2, ProxyType::Any, 1)); let call = Box::new(call_transfer(6, 1)); let e = Error::::Unannounced; - assert_noop!(Proxy::proxy(Origin::signed(2), 1, None, call.clone()), e); + assert_noop!(Proxy::proxy(RuntimeOrigin::signed(2), 1, None, call.clone()), e); let e = Error::::Unannounced; - assert_noop!(Proxy::proxy_announced(Origin::signed(0), 2, 1, None, call.clone()), e); + assert_noop!(Proxy::proxy_announced(RuntimeOrigin::signed(0), 2, 1, None, call.clone()), e); let call_hash = BlakeTwo256::hash_of(&call); - assert_ok!(Proxy::announce(Origin::signed(2), 1, call_hash)); + assert_ok!(Proxy::announce(RuntimeOrigin::signed(2), 1, call_hash)); system::Pallet::::set_block_number(2); - assert_ok!(Proxy::proxy_announced(Origin::signed(0), 2, 1, None, call.clone())); + assert_ok!(Proxy::proxy_announced(RuntimeOrigin::signed(0), 2, 1, None, call.clone())); }); } #[test] fn proxy_announced_removes_announcement_and_returns_deposit() { new_test_ext().execute_with(|| { - assert_ok!(Proxy::add_proxy(Origin::signed(1), 3, ProxyType::Any, 1)); - assert_ok!(Proxy::add_proxy(Origin::signed(2), 3, ProxyType::Any, 1)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(1), 3, ProxyType::Any, 1)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(2), 3, ProxyType::Any, 1)); let call = Box::new(call_transfer(6, 1)); let call_hash = BlakeTwo256::hash_of(&call); - assert_ok!(Proxy::announce(Origin::signed(3), 1, call_hash)); - assert_ok!(Proxy::announce(Origin::signed(3), 2, call_hash)); + assert_ok!(Proxy::announce(RuntimeOrigin::signed(3), 1, call_hash)); + assert_ok!(Proxy::announce(RuntimeOrigin::signed(3), 2, call_hash)); // Too early to execute announced call let e = Error::::Unannounced; - assert_noop!(Proxy::proxy_announced(Origin::signed(0), 3, 1, None, call.clone()), e); + assert_noop!(Proxy::proxy_announced(RuntimeOrigin::signed(0), 3, 1, None, call.clone()), e); system::Pallet::::set_block_number(2); - assert_ok!(Proxy::proxy_announced(Origin::signed(0), 3, 1, None, call.clone())); + assert_ok!(Proxy::proxy_announced(RuntimeOrigin::signed(0), 3, 1, None, call.clone())); let announcements = Announcements::::get(3); assert_eq!(announcements.0, vec![Announcement { real: 2, call_hash, height: 1 }]); assert_eq!(Balances::reserved_balance(3), announcements.1); @@ -328,16 +334,16 @@ fn proxy_announced_removes_announcement_and_returns_deposit() { fn filtering_works() { new_test_ext().execute_with(|| { assert!(Balances::mutate_account(&1, |a| a.free = 1000).is_ok()); - assert_ok!(Proxy::add_proxy(Origin::signed(1), 2, ProxyType::Any, 0)); - assert_ok!(Proxy::add_proxy(Origin::signed(1), 3, ProxyType::JustTransfer, 0)); - assert_ok!(Proxy::add_proxy(Origin::signed(1), 4, ProxyType::JustUtility, 0)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(1), 2, ProxyType::Any, 0)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(1), 3, ProxyType::JustTransfer, 0)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(1), 4, ProxyType::JustUtility, 0)); let call = Box::new(call_transfer(6, 1)); - assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(2), 1, None, call.clone())); System::assert_last_event(ProxyEvent::ProxyExecuted { result: Ok(()) }.into()); - assert_ok!(Proxy::proxy(Origin::signed(3), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(3), 1, None, call.clone())); System::assert_last_event(ProxyEvent::ProxyExecuted { result: Ok(()) }.into()); - assert_ok!(Proxy::proxy(Origin::signed(4), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(4), 1, None, call.clone())); System::assert_last_event( ProxyEvent::ProxyExecuted { result: Err(SystemError::CallFiltered.into()) }.into(), ); @@ -350,28 +356,28 @@ fn filtering_works() { index: 0, call: inner.clone(), })); - assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(2), 1, None, call.clone())); System::assert_last_event(ProxyEvent::ProxyExecuted { result: Ok(()) }.into()); - assert_ok!(Proxy::proxy(Origin::signed(3), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(3), 1, None, call.clone())); System::assert_last_event( ProxyEvent::ProxyExecuted { result: Err(SystemError::CallFiltered.into()) }.into(), ); - assert_ok!(Proxy::proxy(Origin::signed(4), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(4), 1, None, call.clone())); System::assert_last_event( ProxyEvent::ProxyExecuted { result: Err(SystemError::CallFiltered.into()) }.into(), ); let call = Box::new(RuntimeCall::Utility(UtilityCall::batch { calls: vec![*inner] })); - assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(2), 1, None, call.clone())); expect_events(vec![ UtilityEvent::BatchCompleted.into(), ProxyEvent::ProxyExecuted { result: Ok(()) }.into(), ]); - assert_ok!(Proxy::proxy(Origin::signed(3), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(3), 1, None, call.clone())); System::assert_last_event( ProxyEvent::ProxyExecuted { result: Err(SystemError::CallFiltered.into()) }.into(), ); - assert_ok!(Proxy::proxy(Origin::signed(4), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(4), 1, None, call.clone())); expect_events(vec![ UtilityEvent::BatchInterrupted { index: 0, error: SystemError::CallFiltered.into() } .into(), @@ -384,16 +390,16 @@ fn filtering_works() { 0, ))); let call = Box::new(RuntimeCall::Utility(UtilityCall::batch { calls: vec![*inner] })); - assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(2), 1, None, call.clone())); expect_events(vec![ UtilityEvent::BatchCompleted.into(), ProxyEvent::ProxyExecuted { result: Ok(()) }.into(), ]); - assert_ok!(Proxy::proxy(Origin::signed(3), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(3), 1, None, call.clone())); System::assert_last_event( ProxyEvent::ProxyExecuted { result: Err(SystemError::CallFiltered.into()) }.into(), ); - assert_ok!(Proxy::proxy(Origin::signed(4), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(4), 1, None, call.clone())); expect_events(vec![ UtilityEvent::BatchInterrupted { index: 0, error: SystemError::CallFiltered.into() } .into(), @@ -401,15 +407,15 @@ fn filtering_works() { ]); let call = Box::new(RuntimeCall::Proxy(ProxyCall::remove_proxies {})); - assert_ok!(Proxy::proxy(Origin::signed(3), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(3), 1, None, call.clone())); System::assert_last_event( ProxyEvent::ProxyExecuted { result: Err(SystemError::CallFiltered.into()) }.into(), ); - assert_ok!(Proxy::proxy(Origin::signed(4), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(4), 1, None, call.clone())); System::assert_last_event( ProxyEvent::ProxyExecuted { result: Err(SystemError::CallFiltered.into()) }.into(), ); - assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(2), 1, None, call.clone())); expect_events(vec![ BalancesEvent::::Unreserved { who: 1, amount: 5 }.into(), ProxyEvent::ProxyExecuted { result: Ok(()) }.into(), @@ -420,27 +426,27 @@ fn filtering_works() { #[test] fn add_remove_proxies_works() { new_test_ext().execute_with(|| { - assert_ok!(Proxy::add_proxy(Origin::signed(1), 2, ProxyType::Any, 0)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(1), 2, ProxyType::Any, 0)); assert_noop!( - Proxy::add_proxy(Origin::signed(1), 2, ProxyType::Any, 0), + Proxy::add_proxy(RuntimeOrigin::signed(1), 2, ProxyType::Any, 0), Error::::Duplicate ); assert_eq!(Balances::reserved_balance(1), 2); - assert_ok!(Proxy::add_proxy(Origin::signed(1), 2, ProxyType::JustTransfer, 0)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(1), 2, ProxyType::JustTransfer, 0)); assert_eq!(Balances::reserved_balance(1), 3); - assert_ok!(Proxy::add_proxy(Origin::signed(1), 3, ProxyType::Any, 0)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(1), 3, ProxyType::Any, 0)); assert_eq!(Balances::reserved_balance(1), 4); - assert_ok!(Proxy::add_proxy(Origin::signed(1), 4, ProxyType::JustUtility, 0)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(1), 4, ProxyType::JustUtility, 0)); assert_eq!(Balances::reserved_balance(1), 5); assert_noop!( - Proxy::add_proxy(Origin::signed(1), 4, ProxyType::Any, 0), + Proxy::add_proxy(RuntimeOrigin::signed(1), 4, ProxyType::Any, 0), Error::::TooMany ); assert_noop!( - Proxy::remove_proxy(Origin::signed(1), 3, ProxyType::JustTransfer, 0), + Proxy::remove_proxy(RuntimeOrigin::signed(1), 3, ProxyType::JustTransfer, 0), Error::::NotFound ); - assert_ok!(Proxy::remove_proxy(Origin::signed(1), 4, ProxyType::JustUtility, 0)); + assert_ok!(Proxy::remove_proxy(RuntimeOrigin::signed(1), 4, ProxyType::JustUtility, 0)); System::assert_last_event( ProxyEvent::ProxyRemoved { delegator: 1, @@ -451,7 +457,7 @@ fn add_remove_proxies_works() { .into(), ); assert_eq!(Balances::reserved_balance(1), 4); - assert_ok!(Proxy::remove_proxy(Origin::signed(1), 3, ProxyType::Any, 0)); + assert_ok!(Proxy::remove_proxy(RuntimeOrigin::signed(1), 3, ProxyType::Any, 0)); assert_eq!(Balances::reserved_balance(1), 3); System::assert_last_event( ProxyEvent::ProxyRemoved { @@ -462,7 +468,7 @@ fn add_remove_proxies_works() { } .into(), ); - assert_ok!(Proxy::remove_proxy(Origin::signed(1), 2, ProxyType::Any, 0)); + assert_ok!(Proxy::remove_proxy(RuntimeOrigin::signed(1), 2, ProxyType::Any, 0)); assert_eq!(Balances::reserved_balance(1), 2); System::assert_last_event( ProxyEvent::ProxyRemoved { @@ -473,7 +479,7 @@ fn add_remove_proxies_works() { } .into(), ); - assert_ok!(Proxy::remove_proxy(Origin::signed(1), 2, ProxyType::JustTransfer, 0)); + assert_ok!(Proxy::remove_proxy(RuntimeOrigin::signed(1), 2, ProxyType::JustTransfer, 0)); assert_eq!(Balances::reserved_balance(1), 0); System::assert_last_event( ProxyEvent::ProxyRemoved { @@ -485,7 +491,7 @@ fn add_remove_proxies_works() { .into(), ); assert_noop!( - Proxy::add_proxy(Origin::signed(1), 1, ProxyType::Any, 0), + Proxy::add_proxy(RuntimeOrigin::signed(1), 1, ProxyType::Any, 0), Error::::NoSelfProxy ); }); @@ -494,10 +500,10 @@ fn add_remove_proxies_works() { #[test] fn cannot_add_proxy_without_balance() { new_test_ext().execute_with(|| { - assert_ok!(Proxy::add_proxy(Origin::signed(5), 3, ProxyType::Any, 0)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(5), 3, ProxyType::Any, 0)); assert_eq!(Balances::reserved_balance(5), 2); assert_noop!( - Proxy::add_proxy(Origin::signed(5), 4, ProxyType::Any, 0), + Proxy::add_proxy(RuntimeOrigin::signed(5), 4, ProxyType::Any, 0), BalancesError::::InsufficientBalance ); }); @@ -506,24 +512,24 @@ fn cannot_add_proxy_without_balance() { #[test] fn proxying_works() { new_test_ext().execute_with(|| { - assert_ok!(Proxy::add_proxy(Origin::signed(1), 2, ProxyType::JustTransfer, 0)); - assert_ok!(Proxy::add_proxy(Origin::signed(1), 3, ProxyType::Any, 0)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(1), 2, ProxyType::JustTransfer, 0)); + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(1), 3, ProxyType::Any, 0)); let call = Box::new(call_transfer(6, 1)); assert_noop!( - Proxy::proxy(Origin::signed(4), 1, None, call.clone()), + Proxy::proxy(RuntimeOrigin::signed(4), 1, None, call.clone()), Error::::NotProxy ); assert_noop!( - Proxy::proxy(Origin::signed(2), 1, Some(ProxyType::Any), call.clone()), + Proxy::proxy(RuntimeOrigin::signed(2), 1, Some(ProxyType::Any), call.clone()), Error::::NotProxy ); - assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(2), 1, None, call.clone())); System::assert_last_event(ProxyEvent::ProxyExecuted { result: Ok(()) }.into()); assert_eq!(Balances::free_balance(6), 1); let call = Box::new(RuntimeCall::System(SystemCall::set_code { code: vec![] })); - assert_ok!(Proxy::proxy(Origin::signed(3), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(3), 1, None, call.clone())); System::assert_last_event( ProxyEvent::ProxyExecuted { result: Err(SystemError::CallFiltered.into()) }.into(), ); @@ -533,24 +539,24 @@ fn proxying_works() { value: 1, })); assert_ok!(RuntimeCall::Proxy(super::Call::new_call_variant_proxy(1, None, call.clone())) - .dispatch(Origin::signed(2))); + .dispatch(RuntimeOrigin::signed(2))); System::assert_last_event( ProxyEvent::ProxyExecuted { result: Err(SystemError::CallFiltered.into()) }.into(), ); - assert_ok!(Proxy::proxy(Origin::signed(3), 1, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(3), 1, None, call.clone())); System::assert_last_event(ProxyEvent::ProxyExecuted { result: Ok(()) }.into()); assert_eq!(Balances::free_balance(6), 2); }); } #[test] -fn anonymous_works() { +fn pure_works() { new_test_ext().execute_with(|| { - assert_ok!(Proxy::anonymous(Origin::signed(1), ProxyType::Any, 0, 0)); - let anon = Proxy::anonymous_account(&1, &ProxyType::Any, 0, None); + assert_ok!(Proxy::create_pure(RuntimeOrigin::signed(1), ProxyType::Any, 0, 0)); + let anon = Proxy::pure_account(&1, &ProxyType::Any, 0, None); System::assert_last_event( - ProxyEvent::AnonymousCreated { - anonymous: anon, + ProxyEvent::PureCreated { + pure: anon, who: 1, proxy_type: ProxyType::Any, disambiguation_index: 0, @@ -558,46 +564,46 @@ fn anonymous_works() { .into(), ); - // other calls to anonymous allowed as long as they're not exactly the same. - assert_ok!(Proxy::anonymous(Origin::signed(1), ProxyType::JustTransfer, 0, 0)); - assert_ok!(Proxy::anonymous(Origin::signed(1), ProxyType::Any, 0, 1)); - let anon2 = Proxy::anonymous_account(&2, &ProxyType::Any, 0, None); - assert_ok!(Proxy::anonymous(Origin::signed(2), ProxyType::Any, 0, 0)); + // other calls to pure allowed as long as they're not exactly the same. + assert_ok!(Proxy::create_pure(RuntimeOrigin::signed(1), ProxyType::JustTransfer, 0, 0)); + assert_ok!(Proxy::create_pure(RuntimeOrigin::signed(1), ProxyType::Any, 0, 1)); + let anon2 = Proxy::pure_account(&2, &ProxyType::Any, 0, None); + assert_ok!(Proxy::create_pure(RuntimeOrigin::signed(2), ProxyType::Any, 0, 0)); assert_noop!( - Proxy::anonymous(Origin::signed(1), ProxyType::Any, 0, 0), + Proxy::create_pure(RuntimeOrigin::signed(1), ProxyType::Any, 0, 0), Error::::Duplicate ); System::set_extrinsic_index(1); - assert_ok!(Proxy::anonymous(Origin::signed(1), ProxyType::Any, 0, 0)); + assert_ok!(Proxy::create_pure(RuntimeOrigin::signed(1), ProxyType::Any, 0, 0)); System::set_extrinsic_index(0); System::set_block_number(2); - assert_ok!(Proxy::anonymous(Origin::signed(1), ProxyType::Any, 0, 0)); + assert_ok!(Proxy::create_pure(RuntimeOrigin::signed(1), ProxyType::Any, 0, 0)); let call = Box::new(call_transfer(6, 1)); - assert_ok!(Balances::transfer(Origin::signed(3), anon, 5)); - assert_ok!(Proxy::proxy(Origin::signed(1), anon, None, call)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(3), anon, 5)); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(1), anon, None, call)); System::assert_last_event(ProxyEvent::ProxyExecuted { result: Ok(()) }.into()); assert_eq!(Balances::free_balance(6), 1); - let call = Box::new(RuntimeCall::Proxy(ProxyCall::new_call_variant_kill_anonymous( + let call = Box::new(RuntimeCall::Proxy(ProxyCall::new_call_variant_kill_pure( 1, ProxyType::Any, 0, 1, 0, ))); - assert_ok!(Proxy::proxy(Origin::signed(2), anon2, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(2), anon2, None, call.clone())); let de = DispatchError::from(Error::::NoPermission).stripped(); System::assert_last_event(ProxyEvent::ProxyExecuted { result: Err(de) }.into()); assert_noop!( - Proxy::kill_anonymous(Origin::signed(1), 1, ProxyType::Any, 0, 1, 0), + Proxy::kill_pure(RuntimeOrigin::signed(1), 1, ProxyType::Any, 0, 1, 0), Error::::NoPermission ); assert_eq!(Balances::free_balance(1), 0); - assert_ok!(Proxy::proxy(Origin::signed(1), anon, None, call.clone())); + assert_ok!(Proxy::proxy(RuntimeOrigin::signed(1), anon, None, call.clone())); assert_eq!(Balances::free_balance(1), 2); assert_noop!( - Proxy::proxy(Origin::signed(1), anon, None, call.clone()), + Proxy::proxy(RuntimeOrigin::signed(1), anon, None, call.clone()), Error::::NotProxy ); }); diff --git a/frame/proxy/src/weights.rs b/frame/proxy/src/weights.rs index 2d409d977f875..25457d52f4391 100644 --- a/frame/proxy/src/weights.rs +++ b/frame/proxy/src/weights.rs @@ -52,8 +52,8 @@ pub trait WeightInfo { fn add_proxy(p: u32, ) -> Weight; fn remove_proxy(p: u32, ) -> Weight; fn remove_proxies(p: u32, ) -> Weight; - fn anonymous(p: u32, ) -> Weight; - fn kill_anonymous(p: u32, ) -> Weight; + fn create_pure(p: u32, ) -> Weight; + fn kill_pure(p: u32, ) -> Weight; } /// Weights for pallet_proxy using the Substrate node and recommended hardware. @@ -138,7 +138,7 @@ impl WeightInfo for SubstrateWeight { } // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) // Storage: Proxy Proxies (r:1 w:1) - fn anonymous(p: u32, ) -> Weight { + fn create_pure(p: u32, ) -> Weight { Weight::from_ref_time(31_077_000 as u64) // Standard Error: 3_000 .saturating_add(Weight::from_ref_time(37_000 as u64).saturating_mul(p as u64)) @@ -146,7 +146,7 @@ impl WeightInfo for SubstrateWeight { .saturating_add(T::DbWeight::get().writes(1 as u64)) } // Storage: Proxy Proxies (r:1 w:1) - fn kill_anonymous(p: u32, ) -> Weight { + fn kill_pure(p: u32, ) -> Weight { Weight::from_ref_time(24_657_000 as u64) // Standard Error: 2_000 .saturating_add(Weight::from_ref_time(87_000 as u64).saturating_mul(p as u64)) @@ -236,7 +236,7 @@ impl WeightInfo for () { } // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) // Storage: Proxy Proxies (r:1 w:1) - fn anonymous(p: u32, ) -> Weight { + fn create_pure(p: u32, ) -> Weight { Weight::from_ref_time(31_077_000 as u64) // Standard Error: 3_000 .saturating_add(Weight::from_ref_time(37_000 as u64).saturating_mul(p as u64)) @@ -244,7 +244,7 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().writes(1 as u64)) } // Storage: Proxy Proxies (r:1 w:1) - fn kill_anonymous(p: u32, ) -> Weight { + fn kill_pure(p: u32, ) -> Weight { Weight::from_ref_time(24_657_000 as u64) // Standard Error: 2_000 .saturating_add(Weight::from_ref_time(87_000 as u64).saturating_mul(p as u64)) diff --git a/frame/randomness-collective-flip/src/lib.rs b/frame/randomness-collective-flip/src/lib.rs index bd86cc0d4029d..be970ba2a8422 100644 --- a/frame/randomness-collective-flip/src/lib.rs +++ b/frame/randomness-collective-flip/src/lib.rs @@ -197,7 +197,7 @@ mod tests { type BlockWeights = (); type BlockLength = BlockLength; type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; diff --git a/frame/ranked-collective/src/lib.rs b/frame/ranked-collective/src/lib.rs index 44b942d000012..bdd5d26373980 100644 --- a/frame/ranked-collective/src/lib.rs +++ b/frame/ranked-collective/src/lib.rs @@ -241,12 +241,12 @@ impl, I: 'static> GetMaxVoters for Pallet { /// Guard to ensure that the given origin is a member of the collective. The rank of the member is /// the `Success` value. pub struct EnsureRanked(PhantomData<(T, I)>); -impl, I: 'static, const MIN_RANK: u16> EnsureOrigin +impl, I: 'static, const MIN_RANK: u16> EnsureOrigin for EnsureRanked { type Success = Rank; - fn try_origin(o: T::Origin) -> Result { + fn try_origin(o: T::RuntimeOrigin) -> Result { let who = frame_system::EnsureSigned::try_origin(o)?; match Members::::get(&who) { Some(MemberRecord { rank, .. }) if rank >= MIN_RANK => Ok(rank), @@ -255,13 +255,13 @@ impl, I: 'static, const MIN_RANK: u16> EnsureOrigin } #[cfg(feature = "runtime-benchmarks")] - fn try_successful_origin() -> Result { + fn try_successful_origin() -> Result { let who = IndexToId::::get(MIN_RANK, 0).ok_or(())?; Ok(frame_system::RawOrigin::Signed(who).into()) } #[cfg(feature = "runtime-benchmarks")] - fn successful_origin() -> T::Origin { + fn successful_origin() -> T::RuntimeOrigin { match Self::try_successful_origin() { Ok(o) => o, Err(()) => { @@ -277,12 +277,12 @@ impl, I: 'static, const MIN_RANK: u16> EnsureOrigin /// Guard to ensure that the given origin is a member of the collective. The account ID of the /// member is the `Success` value. pub struct EnsureMember(PhantomData<(T, I)>); -impl, I: 'static, const MIN_RANK: u16> EnsureOrigin +impl, I: 'static, const MIN_RANK: u16> EnsureOrigin for EnsureMember { type Success = T::AccountId; - fn try_origin(o: T::Origin) -> Result { + fn try_origin(o: T::RuntimeOrigin) -> Result { let who = frame_system::EnsureSigned::try_origin(o)?; match Members::::get(&who) { Some(MemberRecord { rank, .. }) if rank >= MIN_RANK => Ok(who), @@ -291,13 +291,13 @@ impl, I: 'static, const MIN_RANK: u16> EnsureOrigin } #[cfg(feature = "runtime-benchmarks")] - fn try_successful_origin() -> Result { + fn try_successful_origin() -> Result { let who = IndexToId::::get(MIN_RANK, 0).ok_or(())?; Ok(frame_system::RawOrigin::Signed(who).into()) } #[cfg(feature = "runtime-benchmarks")] - fn successful_origin() -> T::Origin { + fn successful_origin() -> T::RuntimeOrigin { match Self::try_successful_origin() { Ok(o) => o, Err(()) => { @@ -313,12 +313,12 @@ impl, I: 'static, const MIN_RANK: u16> EnsureOrigin /// Guard to ensure that the given origin is a member of the collective. The pair of including both /// the account ID and the rank of the member is the `Success` value. pub struct EnsureRankedMember(PhantomData<(T, I)>); -impl, I: 'static, const MIN_RANK: u16> EnsureOrigin +impl, I: 'static, const MIN_RANK: u16> EnsureOrigin for EnsureRankedMember { type Success = (T::AccountId, Rank); - fn try_origin(o: T::Origin) -> Result { + fn try_origin(o: T::RuntimeOrigin) -> Result { let who = frame_system::EnsureSigned::try_origin(o)?; match Members::::get(&who) { Some(MemberRecord { rank, .. }) if rank >= MIN_RANK => Ok((who, rank)), @@ -327,13 +327,13 @@ impl, I: 'static, const MIN_RANK: u16> EnsureOrigin } #[cfg(feature = "runtime-benchmarks")] - fn try_successful_origin() -> Result { + fn try_successful_origin() -> Result { let who = IndexToId::::get(MIN_RANK, 0).ok_or(())?; Ok(frame_system::RawOrigin::Signed(who).into()) } #[cfg(feature = "runtime-benchmarks")] - fn successful_origin() -> T::Origin { + fn successful_origin() -> T::RuntimeOrigin { match Self::try_successful_origin() { Ok(o) => o, Err(()) => { @@ -367,11 +367,11 @@ pub mod pallet { /// The origin required to add or promote a mmember. The success value indicates the /// maximum rank *to which* the promotion may be. - type PromoteOrigin: EnsureOrigin; + type PromoteOrigin: EnsureOrigin; /// The origin required to demote or remove a member. The success value indicates the /// maximum rank *from which* the demotion/removal may be. - type DemoteOrigin: EnsureOrigin; + type DemoteOrigin: EnsureOrigin; /// The polling system used for our voting. type Polls: Polling, Votes = Votes, Moment = Self::BlockNumber>; diff --git a/frame/ranked-collective/src/tests.rs b/frame/ranked-collective/src/tests.rs index 25413b490483c..68bb79f3d07f7 100644 --- a/frame/ranked-collective/src/tests.rs +++ b/frame/ranked-collective/src/tests.rs @@ -58,7 +58,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; @@ -239,10 +239,10 @@ fn basic_stuff() { #[test] fn member_lifecycle_works() { new_test_ext().execute_with(|| { - assert_ok!(Club::add_member(Origin::root(), 1)); - assert_ok!(Club::promote_member(Origin::root(), 1)); - assert_ok!(Club::demote_member(Origin::root(), 1)); - assert_ok!(Club::demote_member(Origin::root(), 1)); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 1)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 1)); + assert_ok!(Club::demote_member(RuntimeOrigin::root(), 1)); + assert_ok!(Club::demote_member(RuntimeOrigin::root(), 1)); assert_eq!(member_count(0), 0); assert_eq!(member_count(1), 0); }); @@ -251,29 +251,29 @@ fn member_lifecycle_works() { #[test] fn add_remove_works() { new_test_ext().execute_with(|| { - assert_noop!(Club::add_member(Origin::signed(1), 1), DispatchError::BadOrigin); - assert_ok!(Club::add_member(Origin::root(), 1)); + assert_noop!(Club::add_member(RuntimeOrigin::signed(1), 1), DispatchError::BadOrigin); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 1)); assert_eq!(member_count(0), 1); - assert_ok!(Club::demote_member(Origin::root(), 1)); + assert_ok!(Club::demote_member(RuntimeOrigin::root(), 1)); assert_eq!(member_count(0), 0); - assert_ok!(Club::add_member(Origin::root(), 1)); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 1)); assert_eq!(member_count(0), 1); - assert_ok!(Club::add_member(Origin::root(), 2)); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 2)); assert_eq!(member_count(0), 2); - assert_ok!(Club::add_member(Origin::root(), 3)); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 3)); assert_eq!(member_count(0), 3); - assert_ok!(Club::demote_member(Origin::root(), 3)); + assert_ok!(Club::demote_member(RuntimeOrigin::root(), 3)); assert_eq!(member_count(0), 2); - assert_ok!(Club::demote_member(Origin::root(), 1)); + assert_ok!(Club::demote_member(RuntimeOrigin::root(), 1)); assert_eq!(member_count(0), 1); - assert_ok!(Club::demote_member(Origin::root(), 2)); + assert_ok!(Club::demote_member(RuntimeOrigin::root(), 2)); assert_eq!(member_count(0), 0); }); } @@ -281,29 +281,29 @@ fn add_remove_works() { #[test] fn promote_demote_works() { new_test_ext().execute_with(|| { - assert_noop!(Club::add_member(Origin::signed(1), 1), DispatchError::BadOrigin); - assert_ok!(Club::add_member(Origin::root(), 1)); + assert_noop!(Club::add_member(RuntimeOrigin::signed(1), 1), DispatchError::BadOrigin); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 1)); assert_eq!(member_count(0), 1); assert_eq!(member_count(1), 0); - assert_ok!(Club::add_member(Origin::root(), 2)); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 2)); assert_eq!(member_count(0), 2); assert_eq!(member_count(1), 0); - assert_ok!(Club::promote_member(Origin::root(), 1)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 1)); assert_eq!(member_count(0), 2); assert_eq!(member_count(1), 1); - assert_ok!(Club::promote_member(Origin::root(), 2)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 2)); assert_eq!(member_count(0), 2); assert_eq!(member_count(1), 2); - assert_ok!(Club::demote_member(Origin::root(), 1)); + assert_ok!(Club::demote_member(RuntimeOrigin::root(), 1)); assert_eq!(member_count(0), 2); assert_eq!(member_count(1), 1); - assert_noop!(Club::demote_member(Origin::signed(1), 1), DispatchError::BadOrigin); - assert_ok!(Club::demote_member(Origin::root(), 1)); + assert_noop!(Club::demote_member(RuntimeOrigin::signed(1), 1), DispatchError::BadOrigin); + assert_ok!(Club::demote_member(RuntimeOrigin::root(), 1)); assert_eq!(member_count(0), 1); assert_eq!(member_count(1), 1); }); @@ -312,88 +312,100 @@ fn promote_demote_works() { #[test] fn promote_demote_by_rank_works() { new_test_ext().execute_with(|| { - assert_ok!(Club::add_member(Origin::root(), 1)); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 1)); for _ in 0..7 { - assert_ok!(Club::promote_member(Origin::root(), 1)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 1)); } // #1 can add #2 and promote to rank 1 - assert_ok!(Club::add_member(Origin::signed(1), 2)); - assert_ok!(Club::promote_member(Origin::signed(1), 2)); + assert_ok!(Club::add_member(RuntimeOrigin::signed(1), 2)); + assert_ok!(Club::promote_member(RuntimeOrigin::signed(1), 2)); // #2 as rank 1 cannot do anything privileged - assert_noop!(Club::add_member(Origin::signed(2), 3), BadOrigin); + assert_noop!(Club::add_member(RuntimeOrigin::signed(2), 3), BadOrigin); - assert_ok!(Club::promote_member(Origin::signed(1), 2)); + assert_ok!(Club::promote_member(RuntimeOrigin::signed(1), 2)); // #2 as rank 2 can add #3. - assert_ok!(Club::add_member(Origin::signed(2), 3)); + assert_ok!(Club::add_member(RuntimeOrigin::signed(2), 3)); // #2 as rank 2 cannot promote #3 to rank 1 - assert_noop!(Club::promote_member(Origin::signed(2), 3), Error::::NoPermission); + assert_noop!( + Club::promote_member(RuntimeOrigin::signed(2), 3), + Error::::NoPermission + ); // #1 as rank 7 can promote #2 only up to rank 5 and once there cannot demote them. - assert_ok!(Club::promote_member(Origin::signed(1), 2)); - assert_ok!(Club::promote_member(Origin::signed(1), 2)); - assert_ok!(Club::promote_member(Origin::signed(1), 2)); - assert_noop!(Club::promote_member(Origin::signed(1), 2), Error::::NoPermission); - assert_noop!(Club::demote_member(Origin::signed(1), 2), Error::::NoPermission); + assert_ok!(Club::promote_member(RuntimeOrigin::signed(1), 2)); + assert_ok!(Club::promote_member(RuntimeOrigin::signed(1), 2)); + assert_ok!(Club::promote_member(RuntimeOrigin::signed(1), 2)); + assert_noop!( + Club::promote_member(RuntimeOrigin::signed(1), 2), + Error::::NoPermission + ); + assert_noop!(Club::demote_member(RuntimeOrigin::signed(1), 2), Error::::NoPermission); // #2 as rank 5 can promote #3 only up to rank 3 and once there cannot demote them. - assert_ok!(Club::promote_member(Origin::signed(2), 3)); - assert_ok!(Club::promote_member(Origin::signed(2), 3)); - assert_ok!(Club::promote_member(Origin::signed(2), 3)); - assert_noop!(Club::promote_member(Origin::signed(2), 3), Error::::NoPermission); - assert_noop!(Club::demote_member(Origin::signed(2), 3), Error::::NoPermission); + assert_ok!(Club::promote_member(RuntimeOrigin::signed(2), 3)); + assert_ok!(Club::promote_member(RuntimeOrigin::signed(2), 3)); + assert_ok!(Club::promote_member(RuntimeOrigin::signed(2), 3)); + assert_noop!( + Club::promote_member(RuntimeOrigin::signed(2), 3), + Error::::NoPermission + ); + assert_noop!(Club::demote_member(RuntimeOrigin::signed(2), 3), Error::::NoPermission); // #2 can add #4 & #5 as rank 0 and #6 & #7 as rank 1. - assert_ok!(Club::add_member(Origin::signed(2), 4)); - assert_ok!(Club::add_member(Origin::signed(2), 5)); - assert_ok!(Club::add_member(Origin::signed(2), 6)); - assert_ok!(Club::promote_member(Origin::signed(2), 6)); - assert_ok!(Club::add_member(Origin::signed(2), 7)); - assert_ok!(Club::promote_member(Origin::signed(2), 7)); + assert_ok!(Club::add_member(RuntimeOrigin::signed(2), 4)); + assert_ok!(Club::add_member(RuntimeOrigin::signed(2), 5)); + assert_ok!(Club::add_member(RuntimeOrigin::signed(2), 6)); + assert_ok!(Club::promote_member(RuntimeOrigin::signed(2), 6)); + assert_ok!(Club::add_member(RuntimeOrigin::signed(2), 7)); + assert_ok!(Club::promote_member(RuntimeOrigin::signed(2), 7)); // #3 as rank 3 can demote/remove #4 & #5 but not #6 & #7 - assert_ok!(Club::demote_member(Origin::signed(3), 4)); - assert_ok!(Club::remove_member(Origin::signed(3), 5, 0)); - assert_noop!(Club::demote_member(Origin::signed(3), 6), Error::::NoPermission); - assert_noop!(Club::remove_member(Origin::signed(3), 7, 1), Error::::NoPermission); + assert_ok!(Club::demote_member(RuntimeOrigin::signed(3), 4)); + assert_ok!(Club::remove_member(RuntimeOrigin::signed(3), 5, 0)); + assert_noop!(Club::demote_member(RuntimeOrigin::signed(3), 6), Error::::NoPermission); + assert_noop!( + Club::remove_member(RuntimeOrigin::signed(3), 7, 1), + Error::::NoPermission + ); // #2 as rank 5 can demote/remove #6 & #7 - assert_ok!(Club::demote_member(Origin::signed(2), 6)); - assert_ok!(Club::remove_member(Origin::signed(2), 7, 1)); + assert_ok!(Club::demote_member(RuntimeOrigin::signed(2), 6)); + assert_ok!(Club::remove_member(RuntimeOrigin::signed(2), 7, 1)); }); } #[test] fn voting_works() { new_test_ext().execute_with(|| { - assert_ok!(Club::add_member(Origin::root(), 0)); - assert_ok!(Club::add_member(Origin::root(), 1)); - assert_ok!(Club::promote_member(Origin::root(), 1)); - assert_ok!(Club::add_member(Origin::root(), 2)); - assert_ok!(Club::promote_member(Origin::root(), 2)); - assert_ok!(Club::promote_member(Origin::root(), 2)); - assert_ok!(Club::add_member(Origin::root(), 3)); - assert_ok!(Club::promote_member(Origin::root(), 3)); - assert_ok!(Club::promote_member(Origin::root(), 3)); - assert_ok!(Club::promote_member(Origin::root(), 3)); - - assert_noop!(Club::vote(Origin::signed(0), 3, true), Error::::RankTooLow); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 0)); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 1)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 1)); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 2)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 2)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 2)); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 3)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 3)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 3)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 3)); + + assert_noop!(Club::vote(RuntimeOrigin::signed(0), 3, true), Error::::RankTooLow); assert_eq!(tally(3), Tally::from_parts(0, 0, 0)); - assert_ok!(Club::vote(Origin::signed(1), 3, true)); + assert_ok!(Club::vote(RuntimeOrigin::signed(1), 3, true)); assert_eq!(tally(3), Tally::from_parts(1, 1, 0)); - assert_ok!(Club::vote(Origin::signed(1), 3, false)); + assert_ok!(Club::vote(RuntimeOrigin::signed(1), 3, false)); assert_eq!(tally(3), Tally::from_parts(0, 0, 1)); - assert_ok!(Club::vote(Origin::signed(2), 3, true)); + assert_ok!(Club::vote(RuntimeOrigin::signed(2), 3, true)); assert_eq!(tally(3), Tally::from_parts(1, 3, 1)); - assert_ok!(Club::vote(Origin::signed(2), 3, false)); + assert_ok!(Club::vote(RuntimeOrigin::signed(2), 3, false)); assert_eq!(tally(3), Tally::from_parts(0, 0, 4)); - assert_ok!(Club::vote(Origin::signed(3), 3, true)); + assert_ok!(Club::vote(RuntimeOrigin::signed(3), 3, true)); assert_eq!(tally(3), Tally::from_parts(1, 6, 4)); - assert_ok!(Club::vote(Origin::signed(3), 3, false)); + assert_ok!(Club::vote(RuntimeOrigin::signed(3), 3, false)); assert_eq!(tally(3), Tally::from_parts(0, 0, 10)); }); } @@ -401,59 +413,78 @@ fn voting_works() { #[test] fn cleanup_works() { new_test_ext().execute_with(|| { - assert_ok!(Club::add_member(Origin::root(), 1)); - assert_ok!(Club::promote_member(Origin::root(), 1)); - assert_ok!(Club::add_member(Origin::root(), 2)); - assert_ok!(Club::promote_member(Origin::root(), 2)); - assert_ok!(Club::add_member(Origin::root(), 3)); - assert_ok!(Club::promote_member(Origin::root(), 3)); - - assert_ok!(Club::vote(Origin::signed(1), 3, true)); - assert_ok!(Club::vote(Origin::signed(2), 3, false)); - assert_ok!(Club::vote(Origin::signed(3), 3, true)); - - assert_noop!(Club::cleanup_poll(Origin::signed(4), 3, 10), Error::::Ongoing); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 1)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 1)); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 2)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 2)); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 3)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 3)); + + assert_ok!(Club::vote(RuntimeOrigin::signed(1), 3, true)); + assert_ok!(Club::vote(RuntimeOrigin::signed(2), 3, false)); + assert_ok!(Club::vote(RuntimeOrigin::signed(3), 3, true)); + + assert_noop!(Club::cleanup_poll(RuntimeOrigin::signed(4), 3, 10), Error::::Ongoing); Polls::set( vec![(1, Completed(1, true)), (2, Completed(2, false)), (3, Completed(3, true))] .into_iter() .collect(), ); - assert_ok!(Club::cleanup_poll(Origin::signed(4), 3, 10)); + assert_ok!(Club::cleanup_poll(RuntimeOrigin::signed(4), 3, 10)); // NOTE: This will fail until #10016 is merged. - // assert_noop!(Club::cleanup_poll(Origin::signed(4), 3, 10), Error::::NoneRemaining); + // assert_noop!(Club::cleanup_poll(RuntimeOrigin::signed(4), 3, 10), + // Error::::NoneRemaining); }); } #[test] fn ensure_ranked_works() { new_test_ext().execute_with(|| { - assert_ok!(Club::add_member(Origin::root(), 1)); - assert_ok!(Club::promote_member(Origin::root(), 1)); - assert_ok!(Club::add_member(Origin::root(), 2)); - assert_ok!(Club::promote_member(Origin::root(), 2)); - assert_ok!(Club::promote_member(Origin::root(), 2)); - assert_ok!(Club::add_member(Origin::root(), 3)); - assert_ok!(Club::promote_member(Origin::root(), 3)); - assert_ok!(Club::promote_member(Origin::root(), 3)); - assert_ok!(Club::promote_member(Origin::root(), 3)); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 1)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 1)); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 2)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 2)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 2)); + assert_ok!(Club::add_member(RuntimeOrigin::root(), 3)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 3)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 3)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 3)); use frame_support::traits::OriginTrait; type Rank1 = EnsureRanked; type Rank2 = EnsureRanked; type Rank3 = EnsureRanked; type Rank4 = EnsureRanked; - assert_eq!(Rank1::try_origin(Origin::signed(1)).unwrap(), 1); - assert_eq!(Rank1::try_origin(Origin::signed(2)).unwrap(), 2); - assert_eq!(Rank1::try_origin(Origin::signed(3)).unwrap(), 3); - assert_eq!(Rank2::try_origin(Origin::signed(1)).unwrap_err().as_signed().unwrap(), 1); - assert_eq!(Rank2::try_origin(Origin::signed(2)).unwrap(), 2); - assert_eq!(Rank2::try_origin(Origin::signed(3)).unwrap(), 3); - assert_eq!(Rank3::try_origin(Origin::signed(1)).unwrap_err().as_signed().unwrap(), 1); - assert_eq!(Rank3::try_origin(Origin::signed(2)).unwrap_err().as_signed().unwrap(), 2); - assert_eq!(Rank3::try_origin(Origin::signed(3)).unwrap(), 3); - assert_eq!(Rank4::try_origin(Origin::signed(1)).unwrap_err().as_signed().unwrap(), 1); - assert_eq!(Rank4::try_origin(Origin::signed(2)).unwrap_err().as_signed().unwrap(), 2); - assert_eq!(Rank4::try_origin(Origin::signed(3)).unwrap_err().as_signed().unwrap(), 3); + assert_eq!(Rank1::try_origin(RuntimeOrigin::signed(1)).unwrap(), 1); + assert_eq!(Rank1::try_origin(RuntimeOrigin::signed(2)).unwrap(), 2); + assert_eq!(Rank1::try_origin(RuntimeOrigin::signed(3)).unwrap(), 3); + assert_eq!( + Rank2::try_origin(RuntimeOrigin::signed(1)).unwrap_err().as_signed().unwrap(), + 1 + ); + assert_eq!(Rank2::try_origin(RuntimeOrigin::signed(2)).unwrap(), 2); + assert_eq!(Rank2::try_origin(RuntimeOrigin::signed(3)).unwrap(), 3); + assert_eq!( + Rank3::try_origin(RuntimeOrigin::signed(1)).unwrap_err().as_signed().unwrap(), + 1 + ); + assert_eq!( + Rank3::try_origin(RuntimeOrigin::signed(2)).unwrap_err().as_signed().unwrap(), + 2 + ); + assert_eq!(Rank3::try_origin(RuntimeOrigin::signed(3)).unwrap(), 3); + assert_eq!( + Rank4::try_origin(RuntimeOrigin::signed(1)).unwrap_err().as_signed().unwrap(), + 1 + ); + assert_eq!( + Rank4::try_origin(RuntimeOrigin::signed(2)).unwrap_err().as_signed().unwrap(), + 2 + ); + assert_eq!( + Rank4::try_origin(RuntimeOrigin::signed(3)).unwrap_err().as_signed().unwrap(), + 3 + ); }); } diff --git a/frame/recovery/src/lib.rs b/frame/recovery/src/lib.rs index 7b85c119e68c5..0b6b7b0f51d9a 100644 --- a/frame/recovery/src/lib.rs +++ b/frame/recovery/src/lib.rs @@ -232,7 +232,7 @@ pub mod pallet { /// The overarching call type. type RuntimeCall: Parameter - + Dispatchable + + Dispatchable + GetDispatchInfo + From>; diff --git a/frame/recovery/src/mock.rs b/frame/recovery/src/mock.rs index 6496ceb253b77..2a29390fdd20f 100644 --- a/frame/recovery/src/mock.rs +++ b/frame/recovery/src/mock.rs @@ -55,7 +55,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = u64; diff --git a/frame/recovery/src/tests.rs b/frame/recovery/src/tests.rs index a3f19e5a61bc8..b037a8110147d 100644 --- a/frame/recovery/src/tests.rs +++ b/frame/recovery/src/tests.rs @@ -20,8 +20,8 @@ use super::*; use frame_support::{assert_noop, assert_ok, bounded_vec, traits::Currency}; use mock::{ - new_test_ext, run_to_block, Balances, BalancesCall, MaxFriends, Origin, Recovery, RecoveryCall, - RuntimeCall, Test, + new_test_ext, run_to_block, Balances, BalancesCall, MaxFriends, Recovery, RecoveryCall, + RuntimeCall, RuntimeOrigin, Test, }; use sp_runtime::traits::BadOrigin; @@ -41,12 +41,12 @@ fn basic_setup_works() { fn set_recovered_works() { new_test_ext().execute_with(|| { // Not accessible by a normal user - assert_noop!(Recovery::set_recovered(Origin::signed(1), 5, 1), BadOrigin); + assert_noop!(Recovery::set_recovered(RuntimeOrigin::signed(1), 5, 1), BadOrigin); // Root can set a recovered account though - assert_ok!(Recovery::set_recovered(Origin::root(), 5, 1)); + assert_ok!(Recovery::set_recovered(RuntimeOrigin::root(), 5, 1)); // Account 1 should now be able to make a call through account 5 let call = Box::new(RuntimeCall::Balances(BalancesCall::transfer { dest: 1, value: 100 })); - assert_ok!(Recovery::as_recovered(Origin::signed(1), 5, call)); + assert_ok!(Recovery::as_recovered(RuntimeOrigin::signed(1), 5, call)); // Account 1 has successfully drained the funds from account 5 assert_eq!(Balances::free_balance(1), 200); assert_eq!(Balances::free_balance(5), 0); @@ -60,38 +60,46 @@ fn recovery_life_cycle_works() { let threshold = 3; let delay_period = 10; // Account 5 sets up a recovery configuration on their account - assert_ok!(Recovery::create_recovery(Origin::signed(5), friends, threshold, delay_period)); + assert_ok!(Recovery::create_recovery( + RuntimeOrigin::signed(5), + friends, + threshold, + delay_period + )); // Some time has passed, and the user lost their keys! run_to_block(10); // Using account 1, the user begins the recovery process to recover the lost account - assert_ok!(Recovery::initiate_recovery(Origin::signed(1), 5)); + assert_ok!(Recovery::initiate_recovery(RuntimeOrigin::signed(1), 5)); // Off chain, the user contacts their friends and asks them to vouch for the recovery // attempt - assert_ok!(Recovery::vouch_recovery(Origin::signed(2), 5, 1)); - assert_ok!(Recovery::vouch_recovery(Origin::signed(3), 5, 1)); - assert_ok!(Recovery::vouch_recovery(Origin::signed(4), 5, 1)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(2), 5, 1)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(3), 5, 1)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(4), 5, 1)); // We met the threshold, lets try to recover the account...? - assert_noop!(Recovery::claim_recovery(Origin::signed(1), 5), Error::::DelayPeriod); + assert_noop!( + Recovery::claim_recovery(RuntimeOrigin::signed(1), 5), + Error::::DelayPeriod + ); // We need to wait at least the delay_period number of blocks before we can recover run_to_block(20); - assert_ok!(Recovery::claim_recovery(Origin::signed(1), 5)); + assert_ok!(Recovery::claim_recovery(RuntimeOrigin::signed(1), 5)); // Account 1 can use account 5 to close the active recovery process, claiming the deposited // funds used to initiate the recovery process into account 5. let call = Box::new(RuntimeCall::Recovery(RecoveryCall::close_recovery { rescuer: 1 })); - assert_ok!(Recovery::as_recovered(Origin::signed(1), 5, call)); + assert_ok!(Recovery::as_recovered(RuntimeOrigin::signed(1), 5, call)); // Account 1 can then use account 5 to remove the recovery configuration, claiming the // deposited funds used to create the recovery configuration into account 5. let call = Box::new(RuntimeCall::Recovery(RecoveryCall::remove_recovery {})); - assert_ok!(Recovery::as_recovered(Origin::signed(1), 5, call)); + assert_ok!(Recovery::as_recovered(RuntimeOrigin::signed(1), 5, call)); // Account 1 should now be able to make a call through account 5 to get all of their funds assert_eq!(Balances::free_balance(5), 110); let call = Box::new(RuntimeCall::Balances(BalancesCall::transfer { dest: 1, value: 110 })); - assert_ok!(Recovery::as_recovered(Origin::signed(1), 5, call)); + assert_ok!(Recovery::as_recovered(RuntimeOrigin::signed(1), 5, call)); // All funds have been fully recovered! assert_eq!(Balances::free_balance(1), 200); assert_eq!(Balances::free_balance(5), 0); // Remove the proxy link. - assert_ok!(Recovery::cancel_recovered(Origin::signed(1), 5)); + assert_ok!(Recovery::cancel_recovered(RuntimeOrigin::signed(1), 5)); // All storage items are removed from the module assert!(!>::contains_key(&5, &1)); @@ -107,38 +115,52 @@ fn malicious_recovery_fails() { let threshold = 3; let delay_period = 10; // Account 5 sets up a recovery configuration on their account - assert_ok!(Recovery::create_recovery(Origin::signed(5), friends, threshold, delay_period)); + assert_ok!(Recovery::create_recovery( + RuntimeOrigin::signed(5), + friends, + threshold, + delay_period + )); // Some time has passed, and account 1 wants to try and attack this account! run_to_block(10); // Using account 1, the malicious user begins the recovery process on account 5 - assert_ok!(Recovery::initiate_recovery(Origin::signed(1), 5)); + assert_ok!(Recovery::initiate_recovery(RuntimeOrigin::signed(1), 5)); // Off chain, the user **tricks** their friends and asks them to vouch for the recovery - assert_ok!(Recovery::vouch_recovery(Origin::signed(2), 5, 1)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(2), 5, 1)); // shame on you - assert_ok!(Recovery::vouch_recovery(Origin::signed(3), 5, 1)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(3), 5, 1)); // shame on you - assert_ok!(Recovery::vouch_recovery(Origin::signed(4), 5, 1)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(4), 5, 1)); // shame on you // We met the threshold, lets try to recover the account...? - assert_noop!(Recovery::claim_recovery(Origin::signed(1), 5), Error::::DelayPeriod); + assert_noop!( + Recovery::claim_recovery(RuntimeOrigin::signed(1), 5), + Error::::DelayPeriod + ); // Account 1 needs to wait... run_to_block(19); // One more block to wait! - assert_noop!(Recovery::claim_recovery(Origin::signed(1), 5), Error::::DelayPeriod); + assert_noop!( + Recovery::claim_recovery(RuntimeOrigin::signed(1), 5), + Error::::DelayPeriod + ); // Account 5 checks their account every `delay_period` and notices the malicious attack! // Account 5 can close the recovery process before account 1 can claim it - assert_ok!(Recovery::close_recovery(Origin::signed(5), 1)); + assert_ok!(Recovery::close_recovery(RuntimeOrigin::signed(5), 1)); // By doing so, account 5 has now claimed the deposit originally reserved by account 1 assert_eq!(Balances::total_balance(&1), 90); // Thanks for the free money! assert_eq!(Balances::total_balance(&5), 110); // The recovery process has been closed, so account 1 can't make the claim run_to_block(20); - assert_noop!(Recovery::claim_recovery(Origin::signed(1), 5), Error::::NotStarted); + assert_noop!( + Recovery::claim_recovery(RuntimeOrigin::signed(1), 5), + Error::::NotStarted + ); // Account 5 can remove their recovery config and pick some better friends - assert_ok!(Recovery::remove_recovery(Origin::signed(5))); + assert_ok!(Recovery::remove_recovery(RuntimeOrigin::signed(5))); assert_ok!(Recovery::create_recovery( - Origin::signed(5), + RuntimeOrigin::signed(5), vec![22, 33, 44], threshold, delay_period @@ -151,23 +173,23 @@ fn create_recovery_handles_basic_errors() { new_test_ext().execute_with(|| { // No friends assert_noop!( - Recovery::create_recovery(Origin::signed(5), vec![], 1, 0), + Recovery::create_recovery(RuntimeOrigin::signed(5), vec![], 1, 0), Error::::NotEnoughFriends ); // Zero threshold assert_noop!( - Recovery::create_recovery(Origin::signed(5), vec![2], 0, 0), + Recovery::create_recovery(RuntimeOrigin::signed(5), vec![2], 0, 0), Error::::ZeroThreshold ); // Threshold greater than friends length assert_noop!( - Recovery::create_recovery(Origin::signed(5), vec![2, 3, 4], 4, 0), + Recovery::create_recovery(RuntimeOrigin::signed(5), vec![2, 3, 4], 4, 0), Error::::NotEnoughFriends ); // Too many friends assert_noop!( Recovery::create_recovery( - Origin::signed(5), + RuntimeOrigin::signed(5), vec![1; (MaxFriends::get() + 1) as usize], 1, 0 @@ -176,18 +198,18 @@ fn create_recovery_handles_basic_errors() { ); // Unsorted friends assert_noop!( - Recovery::create_recovery(Origin::signed(5), vec![3, 2, 4], 3, 0), + Recovery::create_recovery(RuntimeOrigin::signed(5), vec![3, 2, 4], 3, 0), Error::::NotSorted ); // Duplicate friends assert_noop!( - Recovery::create_recovery(Origin::signed(5), vec![2, 2, 4], 3, 0), + Recovery::create_recovery(RuntimeOrigin::signed(5), vec![2, 2, 4], 3, 0), Error::::NotSorted ); // Already configured - assert_ok!(Recovery::create_recovery(Origin::signed(5), vec![2, 3, 4], 3, 10)); + assert_ok!(Recovery::create_recovery(RuntimeOrigin::signed(5), vec![2, 3, 4], 3, 10)); assert_noop!( - Recovery::create_recovery(Origin::signed(5), vec![2, 3, 4], 3, 10), + Recovery::create_recovery(RuntimeOrigin::signed(5), vec![2, 3, 4], 3, 10), Error::::AlreadyRecoverable ); }); @@ -201,7 +223,7 @@ fn create_recovery_works() { let delay_period = 10; // Account 5 sets up a recovery configuration on their account assert_ok!(Recovery::create_recovery( - Origin::signed(5), + RuntimeOrigin::signed(5), friends.clone(), threshold, delay_period @@ -225,7 +247,7 @@ fn initiate_recovery_handles_basic_errors() { new_test_ext().execute_with(|| { // No recovery process set up for the account assert_noop!( - Recovery::initiate_recovery(Origin::signed(1), 5), + Recovery::initiate_recovery(RuntimeOrigin::signed(1), 5), Error::::NotRecoverable ); // Create a recovery process for next test @@ -233,15 +255,15 @@ fn initiate_recovery_handles_basic_errors() { let threshold = 3; let delay_period = 10; assert_ok!(Recovery::create_recovery( - Origin::signed(5), + RuntimeOrigin::signed(5), friends.clone(), threshold, delay_period )); // Same user cannot recover same account twice - assert_ok!(Recovery::initiate_recovery(Origin::signed(1), 5)); + assert_ok!(Recovery::initiate_recovery(RuntimeOrigin::signed(1), 5)); assert_noop!( - Recovery::initiate_recovery(Origin::signed(1), 5), + Recovery::initiate_recovery(RuntimeOrigin::signed(1), 5), Error::::AlreadyStarted ); // No double deposit @@ -257,13 +279,13 @@ fn initiate_recovery_works() { let threshold = 3; let delay_period = 10; assert_ok!(Recovery::create_recovery( - Origin::signed(5), + RuntimeOrigin::signed(5), friends.clone(), threshold, delay_period )); // Recovery can be initiated - assert_ok!(Recovery::initiate_recovery(Origin::signed(1), 5)); + assert_ok!(Recovery::initiate_recovery(RuntimeOrigin::signed(1), 5)); // Deposit is reserved assert_eq!(Balances::reserved_balance(1), 10); // Recovery status object is created correctly @@ -271,7 +293,7 @@ fn initiate_recovery_works() { ActiveRecovery { created: 0, deposit: 10, friends: Default::default() }; assert_eq!(>::get(&5, &1), Some(recovery_status)); // Multiple users can attempt to recover the same account - assert_ok!(Recovery::initiate_recovery(Origin::signed(2), 5)); + assert_ok!(Recovery::initiate_recovery(RuntimeOrigin::signed(2), 5)); }); } @@ -280,7 +302,7 @@ fn vouch_recovery_handles_basic_errors() { new_test_ext().execute_with(|| { // Cannot vouch for non-recoverable account assert_noop!( - Recovery::vouch_recovery(Origin::signed(2), 5, 1), + Recovery::vouch_recovery(RuntimeOrigin::signed(2), 5, 1), Error::::NotRecoverable ); // Create a recovery process for next tests @@ -288,21 +310,27 @@ fn vouch_recovery_handles_basic_errors() { let threshold = 3; let delay_period = 10; assert_ok!(Recovery::create_recovery( - Origin::signed(5), + RuntimeOrigin::signed(5), friends.clone(), threshold, delay_period )); // Cannot vouch a recovery process that has not started - assert_noop!(Recovery::vouch_recovery(Origin::signed(2), 5, 1), Error::::NotStarted); + assert_noop!( + Recovery::vouch_recovery(RuntimeOrigin::signed(2), 5, 1), + Error::::NotStarted + ); // Initiate a recovery process - assert_ok!(Recovery::initiate_recovery(Origin::signed(1), 5)); + assert_ok!(Recovery::initiate_recovery(RuntimeOrigin::signed(1), 5)); // Cannot vouch if you are not a friend - assert_noop!(Recovery::vouch_recovery(Origin::signed(22), 5, 1), Error::::NotFriend); + assert_noop!( + Recovery::vouch_recovery(RuntimeOrigin::signed(22), 5, 1), + Error::::NotFriend + ); // Cannot vouch twice - assert_ok!(Recovery::vouch_recovery(Origin::signed(2), 5, 1)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(2), 5, 1)); assert_noop!( - Recovery::vouch_recovery(Origin::signed(2), 5, 1), + Recovery::vouch_recovery(RuntimeOrigin::signed(2), 5, 1), Error::::AlreadyVouched ); }); @@ -316,17 +344,17 @@ fn vouch_recovery_works() { let threshold = 3; let delay_period = 10; assert_ok!(Recovery::create_recovery( - Origin::signed(5), + RuntimeOrigin::signed(5), friends.clone(), threshold, delay_period )); - assert_ok!(Recovery::initiate_recovery(Origin::signed(1), 5)); + assert_ok!(Recovery::initiate_recovery(RuntimeOrigin::signed(1), 5)); // Vouching works - assert_ok!(Recovery::vouch_recovery(Origin::signed(2), 5, 1)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(2), 5, 1)); // Handles out of order vouches - assert_ok!(Recovery::vouch_recovery(Origin::signed(4), 5, 1)); - assert_ok!(Recovery::vouch_recovery(Origin::signed(3), 5, 1)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(4), 5, 1)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(3), 5, 1)); // Final recovery status object is updated correctly let recovery_status = ActiveRecovery { created: 0, deposit: 10, friends: bounded_vec![2, 3, 4] }; @@ -338,28 +366,40 @@ fn vouch_recovery_works() { fn claim_recovery_handles_basic_errors() { new_test_ext().execute_with(|| { // Cannot claim a non-recoverable account - assert_noop!(Recovery::claim_recovery(Origin::signed(1), 5), Error::::NotRecoverable); + assert_noop!( + Recovery::claim_recovery(RuntimeOrigin::signed(1), 5), + Error::::NotRecoverable + ); // Create a recovery process for the test let friends = vec![2, 3, 4]; let threshold = 3; let delay_period = 10; assert_ok!(Recovery::create_recovery( - Origin::signed(5), + RuntimeOrigin::signed(5), friends.clone(), threshold, delay_period )); // Cannot claim an account which has not started the recovery process - assert_noop!(Recovery::claim_recovery(Origin::signed(1), 5), Error::::NotStarted); - assert_ok!(Recovery::initiate_recovery(Origin::signed(1), 5)); + assert_noop!( + Recovery::claim_recovery(RuntimeOrigin::signed(1), 5), + Error::::NotStarted + ); + assert_ok!(Recovery::initiate_recovery(RuntimeOrigin::signed(1), 5)); // Cannot claim an account which has not passed the delay period - assert_noop!(Recovery::claim_recovery(Origin::signed(1), 5), Error::::DelayPeriod); + assert_noop!( + Recovery::claim_recovery(RuntimeOrigin::signed(1), 5), + Error::::DelayPeriod + ); run_to_block(11); // Cannot claim an account which has not passed the threshold number of votes - assert_ok!(Recovery::vouch_recovery(Origin::signed(2), 5, 1)); - assert_ok!(Recovery::vouch_recovery(Origin::signed(3), 5, 1)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(2), 5, 1)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(3), 5, 1)); // Only 2/3 is not good enough - assert_noop!(Recovery::claim_recovery(Origin::signed(1), 5), Error::::Threshold); + assert_noop!( + Recovery::claim_recovery(RuntimeOrigin::signed(1), 5), + Error::::Threshold + ); }); } @@ -371,32 +411,32 @@ fn claim_recovery_works() { let threshold = 3; let delay_period = 10; assert_ok!(Recovery::create_recovery( - Origin::signed(5), + RuntimeOrigin::signed(5), friends.clone(), threshold, delay_period )); - assert_ok!(Recovery::initiate_recovery(Origin::signed(1), 5)); - assert_ok!(Recovery::vouch_recovery(Origin::signed(2), 5, 1)); - assert_ok!(Recovery::vouch_recovery(Origin::signed(3), 5, 1)); - assert_ok!(Recovery::vouch_recovery(Origin::signed(4), 5, 1)); + assert_ok!(Recovery::initiate_recovery(RuntimeOrigin::signed(1), 5)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(2), 5, 1)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(3), 5, 1)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(4), 5, 1)); run_to_block(11); // Account can be recovered. - assert_ok!(Recovery::claim_recovery(Origin::signed(1), 5)); + assert_ok!(Recovery::claim_recovery(RuntimeOrigin::signed(1), 5)); // Recovered storage item is correctly created assert_eq!(>::get(&1), Some(5)); // Account could be re-recovered in the case that the recoverer account also gets lost. - assert_ok!(Recovery::initiate_recovery(Origin::signed(4), 5)); - assert_ok!(Recovery::vouch_recovery(Origin::signed(2), 5, 4)); - assert_ok!(Recovery::vouch_recovery(Origin::signed(3), 5, 4)); - assert_ok!(Recovery::vouch_recovery(Origin::signed(4), 5, 4)); + assert_ok!(Recovery::initiate_recovery(RuntimeOrigin::signed(4), 5)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(2), 5, 4)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(3), 5, 4)); + assert_ok!(Recovery::vouch_recovery(RuntimeOrigin::signed(4), 5, 4)); run_to_block(21); // Account is re-recovered. - assert_ok!(Recovery::claim_recovery(Origin::signed(4), 5)); + assert_ok!(Recovery::claim_recovery(RuntimeOrigin::signed(4), 5)); // Recovered storage item is correctly updated assert_eq!(>::get(&4), Some(5)); }); @@ -406,7 +446,10 @@ fn claim_recovery_works() { fn close_recovery_handles_basic_errors() { new_test_ext().execute_with(|| { // Cannot close a non-active recovery - assert_noop!(Recovery::close_recovery(Origin::signed(5), 1), Error::::NotStarted); + assert_noop!( + Recovery::close_recovery(RuntimeOrigin::signed(5), 1), + Error::::NotStarted + ); }); } @@ -414,26 +457,35 @@ fn close_recovery_handles_basic_errors() { fn remove_recovery_works() { new_test_ext().execute_with(|| { // Cannot remove an unrecoverable account - assert_noop!(Recovery::remove_recovery(Origin::signed(5)), Error::::NotRecoverable); + assert_noop!( + Recovery::remove_recovery(RuntimeOrigin::signed(5)), + Error::::NotRecoverable + ); // Create and initiate a recovery process for the test let friends = vec![2, 3, 4]; let threshold = 3; let delay_period = 10; assert_ok!(Recovery::create_recovery( - Origin::signed(5), + RuntimeOrigin::signed(5), friends.clone(), threshold, delay_period )); - assert_ok!(Recovery::initiate_recovery(Origin::signed(1), 5)); - assert_ok!(Recovery::initiate_recovery(Origin::signed(2), 5)); + assert_ok!(Recovery::initiate_recovery(RuntimeOrigin::signed(1), 5)); + assert_ok!(Recovery::initiate_recovery(RuntimeOrigin::signed(2), 5)); // Cannot remove a recovery when there are active recoveries. - assert_noop!(Recovery::remove_recovery(Origin::signed(5)), Error::::StillActive); - assert_ok!(Recovery::close_recovery(Origin::signed(5), 1)); + assert_noop!( + Recovery::remove_recovery(RuntimeOrigin::signed(5)), + Error::::StillActive + ); + assert_ok!(Recovery::close_recovery(RuntimeOrigin::signed(5), 1)); // Still need to remove one more! - assert_noop!(Recovery::remove_recovery(Origin::signed(5)), Error::::StillActive); - assert_ok!(Recovery::close_recovery(Origin::signed(5), 2)); + assert_noop!( + Recovery::remove_recovery(RuntimeOrigin::signed(5)), + Error::::StillActive + ); + assert_ok!(Recovery::close_recovery(RuntimeOrigin::signed(5), 2)); // Finally removed - assert_ok!(Recovery::remove_recovery(Origin::signed(5))); + assert_ok!(Recovery::remove_recovery(RuntimeOrigin::signed(5))); }); } diff --git a/frame/referenda/src/benchmarking.rs b/frame/referenda/src/benchmarking.rs index 2116d56f4647b..45ec894e2c2c0 100644 --- a/frame/referenda/src/benchmarking.rs +++ b/frame/referenda/src/benchmarking.rs @@ -42,8 +42,8 @@ fn funded_account, I: 'static>(name: &'static str, index: u32) -> T caller } -fn create_referendum, I: 'static>() -> (T::Origin, ReferendumIndex) { - let origin: T::Origin = T::SubmitOrigin::successful_origin(); +fn create_referendum, I: 'static>() -> (T::RuntimeOrigin, ReferendumIndex) { + let origin: T::RuntimeOrigin = T::SubmitOrigin::successful_origin(); if let Ok(caller) = frame_system::ensure_signed(origin.clone()) { T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); whitelist_account!(caller); @@ -188,12 +188,12 @@ fn is_not_confirming, I: 'static>(index: ReferendumIndex) -> bool { benchmarks_instance_pallet! { submit { - let origin: T::Origin = T::SubmitOrigin::successful_origin(); + let origin: T::RuntimeOrigin = T::SubmitOrigin::successful_origin(); if let Ok(caller) = frame_system::ensure_signed(origin.clone()) { T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); whitelist_account!(caller); } - }: _( + }: _( origin, Box::new(RawOrigin::Root.into()), T::Hashing::hash_of(&0), @@ -205,7 +205,7 @@ benchmarks_instance_pallet! { place_decision_deposit_preparing { let (origin, index) = create_referendum::(); - }: place_decision_deposit(origin, index) + }: place_decision_deposit(origin, index) verify { assert!(Referenda::::ensure_ongoing(index).unwrap().decision_deposit.is_some()); } @@ -213,7 +213,7 @@ benchmarks_instance_pallet! { place_decision_deposit_queued { let (origin, index) = create_referendum::(); fill_queue::(index, 1, 90); - }: place_decision_deposit(origin, index) + }: place_decision_deposit(origin, index) verify { let track = Referenda::::ensure_ongoing(index).unwrap().track; assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get()); @@ -226,7 +226,7 @@ benchmarks_instance_pallet! { let track = Referenda::::ensure_ongoing(index).unwrap().track; assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get()); assert!(TrackQueue::::get(&track).into_iter().all(|(i, _)| i != index)); - }: place_decision_deposit(origin, index) + }: place_decision_deposit(origin, index) verify { assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get()); assert!(TrackQueue::::get(&track).into_iter().all(|(i, _)| i != index)); @@ -236,7 +236,7 @@ benchmarks_instance_pallet! { let (origin, index) = create_referendum::(); skip_prepare_period::(index); make_passing::(index); - }: place_decision_deposit(origin, index) + }: place_decision_deposit(origin, index) verify { assert!(is_confirming::(index)); } @@ -244,7 +244,7 @@ benchmarks_instance_pallet! { place_decision_deposit_failing { let (origin, index) = create_referendum::(); skip_prepare_period::(index); - }: place_decision_deposit(origin, index) + }: place_decision_deposit(origin, index) verify { assert!(is_not_confirming::(index)); } @@ -253,7 +253,7 @@ benchmarks_instance_pallet! { let (origin, index) = create_referendum::(); place_deposit::(index); assert_ok!(Referenda::::cancel(T::CancelOrigin::successful_origin(), index)); - }: _(origin, index) + }: _(origin, index) verify { assert_matches!(ReferendumInfoFor::::get(index), Some(ReferendumInfo::Cancelled(_, _, None))); } @@ -261,7 +261,7 @@ benchmarks_instance_pallet! { cancel { let (_origin, index) = create_referendum::(); place_deposit::(index); - }: _(T::CancelOrigin::successful_origin(), index) + }: _(T::CancelOrigin::successful_origin(), index) verify { assert_matches!(ReferendumInfoFor::::get(index), Some(ReferendumInfo::Cancelled(..))); } @@ -269,7 +269,7 @@ benchmarks_instance_pallet! { kill { let (_origin, index) = create_referendum::(); place_deposit::(index); - }: _(T::KillOrigin::successful_origin(), index) + }: _(T::KillOrigin::successful_origin(), index) verify { assert_matches!(ReferendumInfoFor::::get(index), Some(ReferendumInfo::Killed(..))); } diff --git a/frame/referenda/src/lib.rs b/frame/referenda/src/lib.rs index a2a5aae4e617b..739f0dbc30ed4 100644 --- a/frame/referenda/src/lib.rs +++ b/frame/referenda/src/lib.rs @@ -147,7 +147,9 @@ pub mod pallet { #[pallet::config] pub trait Config: frame_system::Config + Sized { // System level stuff. - type RuntimeCall: Parameter + Dispatchable + From>; + type RuntimeCall: Parameter + + Dispatchable + + From>; type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// Weight information for extrinsics in this pallet. @@ -168,11 +170,11 @@ pub mod pallet { type Currency: ReservableCurrency; // Origins and unbalances. /// Origin from which proposals may be submitted. - type SubmitOrigin: EnsureOrigin; + type SubmitOrigin: EnsureOrigin; /// Origin from which any vote may be cancelled. - type CancelOrigin: EnsureOrigin; + type CancelOrigin: EnsureOrigin; /// Origin from which any vote may be killed. - type KillOrigin: EnsureOrigin; + type KillOrigin: EnsureOrigin; /// Handler for the unbalanced reduction when slashing a preimage deposit. type Slash: OnUnbalanced>; /// The counting type for votes. Usually just balance. @@ -217,7 +219,7 @@ pub mod pallet { > + TracksInfo< BalanceOf, Self::BlockNumber, - Origin = ::PalletsOrigin, + RuntimeOrigin = ::PalletsOrigin, >; } diff --git a/frame/referenda/src/mock.rs b/frame/referenda/src/mock.rs index 70ca304eed3cb..920e529bf05ca 100644 --- a/frame/referenda/src/mock.rs +++ b/frame/referenda/src/mock.rs @@ -71,7 +71,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; @@ -103,7 +103,7 @@ impl pallet_preimage::Config for Test { } impl pallet_scheduler::Config for Test { type RuntimeEvent = RuntimeEvent; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type PalletsOrigin = OriginCaller; type RuntimeCall = RuntimeCall; type MaximumWeight = MaxWeight; @@ -148,7 +148,7 @@ impl SortedMembers for OneToFive { pub struct TestTracksInfo; impl TracksInfo for TestTracksInfo { type Id = u8; - type Origin = ::PalletsOrigin; + type RuntimeOrigin = ::PalletsOrigin; fn tracks() -> &'static [(Self::Id, TrackInfo)] { static DATA: [(u8, TrackInfo); 2] = [ ( @@ -198,7 +198,7 @@ impl TracksInfo for TestTracksInfo { ]; &DATA[..] } - fn track_for(id: &Self::Origin) -> Result { + fn track_for(id: &Self::RuntimeOrigin) -> Result { if let Ok(system_origin) = frame_system::RawOrigin::try_from(id.clone()) { match system_origin { frame_system::RawOrigin::Root => Ok(0), @@ -319,7 +319,7 @@ pub fn set_balance_proposal_hash(value: u64) -> H256 { #[allow(dead_code)] pub fn propose_set_balance(who: u64, value: u64, delay: u64) -> DispatchResult { Referenda::submit( - Origin::signed(who), + RuntimeOrigin::signed(who), Box::new(frame_system::RawOrigin::Root.into()), set_balance_proposal_hash(value), DispatchTime::After(delay), @@ -447,12 +447,12 @@ pub enum RefState { impl RefState { pub fn create(self) -> ReferendumIndex { assert_ok!(Referenda::submit( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(frame_support::dispatch::RawOrigin::Root.into()), set_balance_proposal_hash(1), DispatchTime::At(10), )); - assert_ok!(Referenda::place_decision_deposit(Origin::signed(2), 0)); + assert_ok!(Referenda::place_decision_deposit(RuntimeOrigin::signed(2), 0)); if matches!(self, RefState::Confirming { immediate: true }) { set_tally(0, 100, 0); } diff --git a/frame/referenda/src/tests.rs b/frame/referenda/src/tests.rs index 69cd62f79159a..778d00e516693 100644 --- a/frame/referenda/src/tests.rs +++ b/frame/referenda/src/tests.rs @@ -42,14 +42,14 @@ fn basic_happy_path_works() { new_test_ext().execute_with(|| { // #1: submit assert_ok!(Referenda::submit( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(RawOrigin::Root.into()), set_balance_proposal_hash(1), DispatchTime::At(10), )); assert_eq!(Balances::reserved_balance(&1), 2); assert_eq!(ReferendumCount::::get(), 1); - assert_ok!(Referenda::place_decision_deposit(Origin::signed(2), 0)); + assert_ok!(Referenda::place_decision_deposit(RuntimeOrigin::signed(2), 0)); run_to(4); assert_eq!(DecidingCount::::get(0), 0); run_to(5); @@ -63,7 +63,7 @@ fn basic_happy_path_works() { run_to(9); // #8: Should be confirmed & ended. assert_eq!(approved_since(0), 9); - assert_ok!(Referenda::refund_decision_deposit(Origin::signed(2), 0)); + assert_ok!(Referenda::refund_decision_deposit(RuntimeOrigin::signed(2), 0)); run_to(12); // #9: Should not yet be enacted. assert_eq!(Balances::free_balance(&42), 0); @@ -78,7 +78,7 @@ fn insta_confirm_then_kill_works() { new_test_ext().execute_with(|| { let r = Confirming { immediate: true }.create(); run_to(6); - assert_ok!(Referenda::kill(Origin::root(), r)); + assert_ok!(Referenda::kill(RuntimeOrigin::root(), r)); assert_eq!(killed_since(r), 6); }); } @@ -173,24 +173,24 @@ fn queueing_works() { new_test_ext().execute_with(|| { // Submit a proposal into a track with a queue len of 1. assert_ok!(Referenda::submit( - Origin::signed(5), + RuntimeOrigin::signed(5), Box::new(RawOrigin::Root.into()), set_balance_proposal_hash(0), DispatchTime::After(0), )); - assert_ok!(Referenda::place_decision_deposit(Origin::signed(5), 0)); + assert_ok!(Referenda::place_decision_deposit(RuntimeOrigin::signed(5), 0)); run_to(2); // Submit 3 more proposals into the same queue. for i in 1..=4 { assert_ok!(Referenda::submit( - Origin::signed(i), + RuntimeOrigin::signed(i), Box::new(RawOrigin::Root.into()), set_balance_proposal_hash(i), DispatchTime::After(0), )); - assert_ok!(Referenda::place_decision_deposit(Origin::signed(i), i as u32)); + assert_ok!(Referenda::place_decision_deposit(RuntimeOrigin::signed(i), i as u32)); // TODO: decision deposit after some initial votes with a non-highest voted coming // first. } @@ -214,7 +214,7 @@ fn queueing_works() { println!("{:?}", Vec::<_>::from(TrackQueue::::get(0))); // Cancel the first. - assert_ok!(Referenda::cancel(Origin::signed(4), 0)); + assert_ok!(Referenda::cancel(RuntimeOrigin::signed(4), 0)); assert_eq!(cancelled_since(0), 6); // The other with the most approvals (#4) should be being decided. @@ -270,7 +270,7 @@ fn auto_timeout_should_happen_with_nothing_but_submit() { new_test_ext().execute_with(|| { // #1: submit assert_ok!(Referenda::submit( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(RawOrigin::Root.into()), set_balance_proposal_hash(1), DispatchTime::At(20), @@ -290,20 +290,20 @@ fn auto_timeout_should_happen_with_nothing_but_submit() { fn tracks_are_distinguished() { new_test_ext().execute_with(|| { assert_ok!(Referenda::submit( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(RawOrigin::Root.into()), set_balance_proposal_hash(1), DispatchTime::At(10), )); assert_ok!(Referenda::submit( - Origin::signed(2), + RuntimeOrigin::signed(2), Box::new(RawOrigin::None.into()), set_balance_proposal_hash(2), DispatchTime::At(20), )); - assert_ok!(Referenda::place_decision_deposit(Origin::signed(3), 0)); - assert_ok!(Referenda::place_decision_deposit(Origin::signed(4), 1)); + assert_ok!(Referenda::place_decision_deposit(RuntimeOrigin::signed(3), 0)); + assert_ok!(Referenda::place_decision_deposit(RuntimeOrigin::signed(4), 1)); let mut i = ReferendumInfoFor::::iter().collect::>(); i.sort_by_key(|x| x.0); @@ -354,7 +354,7 @@ fn submit_errors_work() { // No track for Signed origins. assert_noop!( Referenda::submit( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(RawOrigin::Signed(2).into()), h, DispatchTime::At(10), @@ -365,7 +365,7 @@ fn submit_errors_work() { // No funds for deposit assert_noop!( Referenda::submit( - Origin::signed(10), + RuntimeOrigin::signed(10), Box::new(RawOrigin::Root.into()), h, DispatchTime::At(10), @@ -379,21 +379,21 @@ fn submit_errors_work() { fn decision_deposit_errors_work() { new_test_ext().execute_with(|| { let e = Error::::NotOngoing; - assert_noop!(Referenda::place_decision_deposit(Origin::signed(2), 0), e); + assert_noop!(Referenda::place_decision_deposit(RuntimeOrigin::signed(2), 0), e); let h = set_balance_proposal_hash(1); assert_ok!(Referenda::submit( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(RawOrigin::Root.into()), h, DispatchTime::At(10), )); let e = BalancesError::::InsufficientBalance; - assert_noop!(Referenda::place_decision_deposit(Origin::signed(10), 0), e); + assert_noop!(Referenda::place_decision_deposit(RuntimeOrigin::signed(10), 0), e); - assert_ok!(Referenda::place_decision_deposit(Origin::signed(2), 0)); + assert_ok!(Referenda::place_decision_deposit(RuntimeOrigin::signed(2), 0)); let e = Error::::HasDeposit; - assert_noop!(Referenda::place_decision_deposit(Origin::signed(2), 0), e); + assert_noop!(Referenda::place_decision_deposit(RuntimeOrigin::signed(2), 0), e); }); } @@ -401,24 +401,24 @@ fn decision_deposit_errors_work() { fn refund_deposit_works() { new_test_ext().execute_with(|| { let e = Error::::BadReferendum; - assert_noop!(Referenda::refund_decision_deposit(Origin::signed(1), 0), e); + assert_noop!(Referenda::refund_decision_deposit(RuntimeOrigin::signed(1), 0), e); let h = set_balance_proposal_hash(1); assert_ok!(Referenda::submit( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(RawOrigin::Root.into()), h, DispatchTime::At(10), )); let e = Error::::NoDeposit; - assert_noop!(Referenda::refund_decision_deposit(Origin::signed(2), 0), e); + assert_noop!(Referenda::refund_decision_deposit(RuntimeOrigin::signed(2), 0), e); - assert_ok!(Referenda::place_decision_deposit(Origin::signed(2), 0)); + assert_ok!(Referenda::place_decision_deposit(RuntimeOrigin::signed(2), 0)); let e = Error::::Unfinished; - assert_noop!(Referenda::refund_decision_deposit(Origin::signed(3), 0), e); + assert_noop!(Referenda::refund_decision_deposit(RuntimeOrigin::signed(3), 0), e); run_to(11); - assert_ok!(Referenda::refund_decision_deposit(Origin::signed(3), 0)); + assert_ok!(Referenda::refund_decision_deposit(RuntimeOrigin::signed(3), 0)); }); } @@ -427,16 +427,16 @@ fn cancel_works() { new_test_ext().execute_with(|| { let h = set_balance_proposal_hash(1); assert_ok!(Referenda::submit( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(RawOrigin::Root.into()), h, DispatchTime::At(10), )); - assert_ok!(Referenda::place_decision_deposit(Origin::signed(2), 0)); + assert_ok!(Referenda::place_decision_deposit(RuntimeOrigin::signed(2), 0)); run_to(8); - assert_ok!(Referenda::cancel(Origin::signed(4), 0)); - assert_ok!(Referenda::refund_decision_deposit(Origin::signed(3), 0)); + assert_ok!(Referenda::cancel(RuntimeOrigin::signed(4), 0)); + assert_ok!(Referenda::refund_decision_deposit(RuntimeOrigin::signed(3), 0)); assert_eq!(cancelled_since(0), 8); }); } @@ -446,16 +446,16 @@ fn cancel_errors_works() { new_test_ext().execute_with(|| { let h = set_balance_proposal_hash(1); assert_ok!(Referenda::submit( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(RawOrigin::Root.into()), h, DispatchTime::At(10), )); - assert_ok!(Referenda::place_decision_deposit(Origin::signed(2), 0)); - assert_noop!(Referenda::cancel(Origin::signed(1), 0), BadOrigin); + assert_ok!(Referenda::place_decision_deposit(RuntimeOrigin::signed(2), 0)); + assert_noop!(Referenda::cancel(RuntimeOrigin::signed(1), 0), BadOrigin); run_to(11); - assert_noop!(Referenda::cancel(Origin::signed(4), 0), Error::::NotOngoing); + assert_noop!(Referenda::cancel(RuntimeOrigin::signed(4), 0), Error::::NotOngoing); }); } @@ -464,17 +464,17 @@ fn kill_works() { new_test_ext().execute_with(|| { let h = set_balance_proposal_hash(1); assert_ok!(Referenda::submit( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(RawOrigin::Root.into()), h, DispatchTime::At(10), )); - assert_ok!(Referenda::place_decision_deposit(Origin::signed(2), 0)); + assert_ok!(Referenda::place_decision_deposit(RuntimeOrigin::signed(2), 0)); run_to(8); - assert_ok!(Referenda::kill(Origin::root(), 0)); + assert_ok!(Referenda::kill(RuntimeOrigin::root(), 0)); let e = Error::::NoDeposit; - assert_noop!(Referenda::refund_decision_deposit(Origin::signed(3), 0), e); + assert_noop!(Referenda::refund_decision_deposit(RuntimeOrigin::signed(3), 0), e); assert_eq!(killed_since(0), 8); }); } @@ -484,16 +484,16 @@ fn kill_errors_works() { new_test_ext().execute_with(|| { let h = set_balance_proposal_hash(1); assert_ok!(Referenda::submit( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(RawOrigin::Root.into()), h, DispatchTime::At(10), )); - assert_ok!(Referenda::place_decision_deposit(Origin::signed(2), 0)); - assert_noop!(Referenda::kill(Origin::signed(4), 0), BadOrigin); + assert_ok!(Referenda::place_decision_deposit(RuntimeOrigin::signed(2), 0)); + assert_noop!(Referenda::kill(RuntimeOrigin::signed(4), 0), BadOrigin); run_to(11); - assert_noop!(Referenda::kill(Origin::root(), 0), Error::::NotOngoing); + assert_noop!(Referenda::kill(RuntimeOrigin::root(), 0), Error::::NotOngoing); }); } diff --git a/frame/referenda/src/types.rs b/frame/referenda/src/types.rs index 984bd0642d959..a6311e5f925be 100644 --- a/frame/referenda/src/types.rs +++ b/frame/referenda/src/types.rs @@ -33,7 +33,8 @@ pub type NegativeImbalanceOf = <>::Currency as Currency< pub type CallOf = >::RuntimeCall; pub type VotesOf = >::Votes; pub type TallyOf = >::Tally; -pub type PalletsOriginOf = <::Origin as OriginTrait>::PalletsOrigin; +pub type PalletsOriginOf = + <::RuntimeOrigin as OriginTrait>::PalletsOrigin; pub type ReferendumInfoOf = ReferendumInfo< TrackIdOf, PalletsOriginOf, @@ -139,13 +140,13 @@ pub trait TracksInfo { type Id: Copy + Parameter + Ord + PartialOrd + Send + Sync + 'static + MaxEncodedLen; /// The origin type from which a track is implied. - type Origin; + type RuntimeOrigin; /// Return the array of known tracks and their information. fn tracks() -> &'static [(Self::Id, TrackInfo)]; /// Determine the voting track for the given `origin`. - fn track_for(origin: &Self::Origin) -> Result; + fn track_for(origin: &Self::RuntimeOrigin) -> Result; /// Return the track info for track `id`, by default this just looks it up in `Self::tracks()`. fn info(id: Self::Id) -> Option<&'static TrackInfo> { @@ -157,7 +158,7 @@ pub trait TracksInfo { #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub struct ReferendumStatus< TrackId: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, - Origin: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + RuntimeOrigin: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, Moment: Parameter + Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone + EncodeLike, Hash: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, Balance: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, @@ -168,7 +169,7 @@ pub struct ReferendumStatus< /// The track of this referendum. pub(crate) track: TrackId, /// The origin for this referendum. - pub(crate) origin: Origin, + pub(crate) origin: RuntimeOrigin, /// The hash of the proposal up for referendum. pub(crate) proposal_hash: Hash, /// The time the proposal should be scheduled for enactment. @@ -194,7 +195,7 @@ pub struct ReferendumStatus< #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub enum ReferendumInfo< TrackId: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, - Origin: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + RuntimeOrigin: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, Moment: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone + EncodeLike, Hash: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, Balance: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, @@ -204,7 +205,16 @@ pub enum ReferendumInfo< > { /// Referendum has been submitted and is being voted on. Ongoing( - ReferendumStatus, + ReferendumStatus< + TrackId, + RuntimeOrigin, + Moment, + Hash, + Balance, + Tally, + AccountId, + ScheduleAddress, + >, ), /// Referendum finished with approval. Submission deposit is held. Approved(Moment, Deposit, Option>), @@ -220,14 +230,14 @@ pub enum ReferendumInfo< impl< TrackId: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, - Origin: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + RuntimeOrigin: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, Moment: Parameter + Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone + EncodeLike, Hash: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, Balance: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, Tally: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, AccountId: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, ScheduleAddress: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, - > ReferendumInfo + > ReferendumInfo { /// Take the Decision Deposit from `self`, if there is one. Returns an `Err` if `self` is not /// in a valid state for the Decision Deposit to be refunded. diff --git a/frame/remark/src/mock.rs b/frame/remark/src/mock.rs index 6ce7115345e57..22467796cf37b 100644 --- a/frame/remark/src/mock.rs +++ b/frame/remark/src/mock.rs @@ -45,7 +45,7 @@ impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); type BlockLength = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = u64; diff --git a/frame/scheduler/src/benchmarking.rs b/frame/scheduler/src/benchmarking.rs index fbd59555b5ebc..9397c66170425 100644 --- a/frame/scheduler/src/benchmarking.rs +++ b/frame/scheduler/src/benchmarking.rs @@ -31,7 +31,7 @@ use frame_system::Pallet as System; const BLOCK_NUMBER: u32 = 2; -type SystemOrigin = ::Origin; +type SystemOrigin = ::RuntimeOrigin; /// Add `n` named items to the schedule. /// diff --git a/frame/scheduler/src/lib.rs b/frame/scheduler/src/lib.rs index 7e9b8e1b92fb7..143fa37a9261d 100644 --- a/frame/scheduler/src/lib.rs +++ b/frame/scheduler/src/lib.rs @@ -202,17 +202,19 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// The aggregated origin which the dispatch will take. - type Origin: OriginTrait + type RuntimeOrigin: OriginTrait + From - + IsType<::Origin>; + + IsType<::RuntimeOrigin>; /// The caller origin, overarching type of all pallets origins. type PalletsOrigin: From> + Codec + Clone + Eq + TypeInfo; /// The aggregated call type. type RuntimeCall: Parameter - + Dispatchable::Origin, PostInfo = PostDispatchInfo> - + GetDispatchInfo + + Dispatchable< + RuntimeOrigin = ::RuntimeOrigin, + PostInfo = PostDispatchInfo, + > + GetDispatchInfo + From>; /// The maximum weight that may be scheduled per block for any dispatchables of less @@ -221,7 +223,7 @@ pub mod pallet { type MaximumWeight: Get; /// Required origin to schedule or cancel calls. - type ScheduleOrigin: EnsureOrigin<::Origin>; + type ScheduleOrigin: EnsureOrigin<::RuntimeOrigin>; /// Compare the privileges of origins. /// @@ -354,9 +356,10 @@ pub mod pallet { let periodic = s.maybe_periodic.is_some(); let call_weight = call.get_dispatch_info().weight; let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved)); - let origin = - <::Origin as From>::from(s.origin.clone()) - .into(); + let origin = <::RuntimeOrigin as From>::from( + s.origin.clone(), + ) + .into(); if ensure_signed(origin).is_ok() { // Weights of Signed dispatches expect their signing account to be whitelisted. item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1)); @@ -431,7 +434,7 @@ pub mod pallet { call: Box>, ) -> DispatchResult { T::ScheduleOrigin::ensure_origin(origin.clone())?; - let origin = ::Origin::from(origin); + let origin = ::RuntimeOrigin::from(origin); Self::do_schedule( DispatchTime::At(when), maybe_periodic, @@ -446,7 +449,7 @@ pub mod pallet { #[pallet::weight(::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))] pub fn cancel(origin: OriginFor, when: T::BlockNumber, index: u32) -> DispatchResult { T::ScheduleOrigin::ensure_origin(origin.clone())?; - let origin = ::Origin::from(origin); + let origin = ::RuntimeOrigin::from(origin); Self::do_cancel(Some(origin.caller().clone()), (when, index))?; Ok(()) } @@ -462,7 +465,7 @@ pub mod pallet { call: Box>, ) -> DispatchResult { T::ScheduleOrigin::ensure_origin(origin.clone())?; - let origin = ::Origin::from(origin); + let origin = ::RuntimeOrigin::from(origin); Self::do_schedule_named( id, DispatchTime::At(when), @@ -478,7 +481,7 @@ pub mod pallet { #[pallet::weight(::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))] pub fn cancel_named(origin: OriginFor, id: Vec) -> DispatchResult { T::ScheduleOrigin::ensure_origin(origin.clone())?; - let origin = ::Origin::from(origin); + let origin = ::RuntimeOrigin::from(origin); Self::do_cancel_named(Some(origin.caller().clone()), id)?; Ok(()) } @@ -497,7 +500,7 @@ pub mod pallet { call: Box>, ) -> DispatchResult { T::ScheduleOrigin::ensure_origin(origin.clone())?; - let origin = ::Origin::from(origin); + let origin = ::RuntimeOrigin::from(origin); Self::do_schedule( DispatchTime::After(after), maybe_periodic, @@ -523,7 +526,7 @@ pub mod pallet { call: Box>, ) -> DispatchResult { T::ScheduleOrigin::ensure_origin(origin.clone())?; - let origin = ::Origin::from(origin); + let origin = ::RuntimeOrigin::from(origin); Self::do_schedule_named( id, DispatchTime::After(after), diff --git a/frame/scheduler/src/mock.rs b/frame/scheduler/src/mock.rs index 6460d0f4c1cd1..6f6667590a6c3 100644 --- a/frame/scheduler/src/mock.rs +++ b/frame/scheduler/src/mock.rs @@ -70,7 +70,7 @@ pub mod logger { #[pallet::call] impl Pallet where - ::Origin: OriginTrait, + ::RuntimeOrigin: OriginTrait, { #[pallet::weight(*weight)] pub fn log(origin: OriginFor, i: u32, weight: Weight) -> DispatchResult { @@ -125,7 +125,7 @@ impl system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = RocksDbWeight; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = u64; @@ -169,7 +169,7 @@ impl pallet_preimage::Config for Test { impl Config for Test { type RuntimeEvent = RuntimeEvent; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type PalletsOrigin = OriginCaller; type RuntimeCall = RuntimeCall; type MaximumWeight = MaximumSchedulerWeight; diff --git a/frame/scheduler/src/tests.rs b/frame/scheduler/src/tests.rs index f1168e6e9d26f..f6db70ae42d49 100644 --- a/frame/scheduler/src/tests.rs +++ b/frame/scheduler/src/tests.rs @@ -52,7 +52,7 @@ fn scheduling_with_preimages_works() { RuntimeCall::Logger(LoggerCall::log { i: 42, weight: Weight::from_ref_time(1000) }); let hash = ::Hashing::hash_of(&call); let hashed = MaybeHashed::Hash(hash); - assert_ok!(Preimage::note_preimage(Origin::signed(0), call.encode())); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::signed(0), call.encode())); assert_ok!(Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), hashed)); assert!(Preimage::preimage_requested(&hash)); run_to_block(3); @@ -82,7 +82,7 @@ fn scheduling_with_preimage_postpones_correctly() { assert!(logger::log().is_empty()); // Register preimage. - assert_ok!(Preimage::note_preimage(Origin::signed(0), call.encode())); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::signed(0), call.encode())); run_to_block(5); // #5 empty since postponement is 2 blocks. @@ -619,14 +619,21 @@ fn root_calls_works() { RuntimeCall::Logger(LoggerCall::log { i: 42, weight: Weight::from_ref_time(1000) }) .into(), ); - assert_ok!(Scheduler::schedule_named(Origin::root(), 1u32.encode(), 4, None, 127, call,)); - assert_ok!(Scheduler::schedule(Origin::root(), 4, None, 127, call2)); + assert_ok!(Scheduler::schedule_named( + RuntimeOrigin::root(), + 1u32.encode(), + 4, + None, + 127, + call, + )); + assert_ok!(Scheduler::schedule(RuntimeOrigin::root(), 4, None, 127, call2)); run_to_block(3); // Scheduled calls are in the agenda. assert_eq!(Agenda::::get(4).len(), 2); assert!(logger::log().is_empty()); - assert_ok!(Scheduler::cancel_named(Origin::root(), 1u32.encode())); - assert_ok!(Scheduler::cancel(Origin::root(), 4, 1)); + assert_ok!(Scheduler::cancel_named(RuntimeOrigin::root(), 1u32.encode())); + assert_ok!(Scheduler::cancel(RuntimeOrigin::root(), 4, 1)); // Scheduled calls are made NONE, so should not effect state run_to_block(100); assert!(logger::log().is_empty()); @@ -651,17 +658,17 @@ fn fails_to_schedule_task_in_the_past() { .into(), ); assert_err!( - Scheduler::schedule_named(Origin::root(), 1u32.encode(), 2, None, 127, call1), + Scheduler::schedule_named(RuntimeOrigin::root(), 1u32.encode(), 2, None, 127, call1), Error::::TargetBlockNumberInPast, ); assert_err!( - Scheduler::schedule(Origin::root(), 2, None, 127, call2), + Scheduler::schedule(RuntimeOrigin::root(), 2, None, 127, call2), Error::::TargetBlockNumberInPast, ); assert_err!( - Scheduler::schedule(Origin::root(), 3, None, 127, call3), + Scheduler::schedule(RuntimeOrigin::root(), 3, None, 127, call3), Error::::TargetBlockNumberInPast, ); }); diff --git a/frame/scored-pool/README.md b/frame/scored-pool/README.md index 56c6af916ecd0..455bae24e7951 100644 --- a/frame/scored-pool/README.md +++ b/frame/scored-pool/README.md @@ -58,7 +58,7 @@ pub mod pallet { let who = ensure_signed(origin)?; let _ = >::submit_candidacy( - T::Origin::from(Some(who.clone()).into()) + T::RuntimeOrigin::from(Some(who.clone()).into()) ); Ok(()) } diff --git a/frame/scored-pool/src/lib.rs b/frame/scored-pool/src/lib.rs index c9ba30df80b8b..a015c1c568153 100644 --- a/frame/scored-pool/src/lib.rs +++ b/frame/scored-pool/src/lib.rs @@ -75,7 +75,7 @@ //! let who = ensure_signed(origin)?; //! //! let _ = >::submit_candidacy( -//! T::Origin::from(Some(who.clone()).into()) +//! T::RuntimeOrigin::from(Some(who.clone()).into()) //! ); //! Ok(()) //! } @@ -183,13 +183,13 @@ pub mod pallet { type MembershipChanged: ChangeMembers; /// Allows a configurable origin type to set a score to a candidate in the pool. - type ScoreOrigin: EnsureOrigin; + type ScoreOrigin: EnsureOrigin; /// Required origin for removing a member (though can always be Root). /// Configurable origin which enables removing an entity. If the entity /// is part of the `Members` it is immediately replaced by the next /// highest scoring candidate, if available. - type KickOrigin: EnsureOrigin; + type KickOrigin: EnsureOrigin; } #[pallet::event] diff --git a/frame/scored-pool/src/mock.rs b/frame/scored-pool/src/mock.rs index 20fa47baf639f..d6f653b32ad2d 100644 --- a/frame/scored-pool/src/mock.rs +++ b/frame/scored-pool/src/mock.rs @@ -61,7 +61,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = H256; diff --git a/frame/scored-pool/src/tests.rs b/frame/scored-pool/src/tests.rs index 1a68891be0f50..8f4daff47cc44 100644 --- a/frame/scored-pool/src/tests.rs +++ b/frame/scored-pool/src/tests.rs @@ -41,11 +41,11 @@ fn query_membership_works() { fn submit_candidacy_must_not_work() { new_test_ext().execute_with(|| { assert_noop!( - ScoredPool::submit_candidacy(Origin::signed(99)), + ScoredPool::submit_candidacy(RuntimeOrigin::signed(99)), pallet_balances::Error::::InsufficientBalance, ); assert_noop!( - ScoredPool::submit_candidacy(Origin::signed(40)), + ScoredPool::submit_candidacy(RuntimeOrigin::signed(40)), Error::::AlreadyInPool ); }); @@ -58,7 +58,7 @@ fn submit_candidacy_works() { let who = 15; // when - assert_ok!(ScoredPool::submit_candidacy(Origin::signed(who))); + assert_ok!(ScoredPool::submit_candidacy(RuntimeOrigin::signed(who))); assert_eq!(fetch_from_pool(15), Some((who, None))); // then @@ -72,11 +72,11 @@ fn scoring_works() { // given let who = 15; let score = 99; - assert_ok!(ScoredPool::submit_candidacy(Origin::signed(who))); + assert_ok!(ScoredPool::submit_candidacy(RuntimeOrigin::signed(who))); // when let index = find_in_pool(who).expect("entity must be in pool") as u32; - assert_ok!(ScoredPool::score(Origin::signed(ScoreOrigin::get()), who, index, score)); + assert_ok!(ScoredPool::score(RuntimeOrigin::signed(ScoreOrigin::get()), who, index, score)); // then assert_eq!(fetch_from_pool(who), Some((who, Some(score)))); @@ -93,7 +93,7 @@ fn scoring_same_element_with_same_score_works() { let score = 2; // when - assert_ok!(ScoredPool::score(Origin::signed(ScoreOrigin::get()), who, index, score)); + assert_ok!(ScoredPool::score(RuntimeOrigin::signed(ScoreOrigin::get()), who, index, score)); // then assert_eq!(fetch_from_pool(who), Some((who, Some(score)))); @@ -109,7 +109,7 @@ fn kicking_works_only_for_authorized() { new_test_ext().execute_with(|| { let who = 40; let index = find_in_pool(who).expect("entity must be in pool") as u32; - assert_noop!(ScoredPool::kick(Origin::signed(99), who, index), BadOrigin); + assert_noop!(ScoredPool::kick(RuntimeOrigin::signed(99), who, index), BadOrigin); }); } @@ -123,7 +123,7 @@ fn kicking_works() { // when let index = find_in_pool(who).expect("entity must be in pool") as u32; - assert_ok!(ScoredPool::kick(Origin::signed(KickOrigin::get()), who, index)); + assert_ok!(ScoredPool::kick(RuntimeOrigin::signed(KickOrigin::get()), who, index)); // then assert_eq!(find_in_pool(who), None); @@ -138,14 +138,14 @@ fn unscored_entities_must_not_be_used_for_filling_members() { new_test_ext().execute_with(|| { // given // we submit a candidacy, score will be `None` - assert_ok!(ScoredPool::submit_candidacy(Origin::signed(15))); + assert_ok!(ScoredPool::submit_candidacy(RuntimeOrigin::signed(15))); // when // we remove every scored member ScoredPool::pool().into_iter().for_each(|(who, score)| { if let Some(_) = score { let index = find_in_pool(who).expect("entity must be in pool") as u32; - assert_ok!(ScoredPool::kick(Origin::signed(KickOrigin::get()), who, index)); + assert_ok!(ScoredPool::kick(RuntimeOrigin::signed(KickOrigin::get()), who, index)); } }); @@ -161,9 +161,9 @@ fn refreshing_works() { new_test_ext().execute_with(|| { // given let who = 15; - assert_ok!(ScoredPool::submit_candidacy(Origin::signed(who))); + assert_ok!(ScoredPool::submit_candidacy(RuntimeOrigin::signed(who))); let index = find_in_pool(who).expect("entity must be in pool") as u32; - assert_ok!(ScoredPool::score(Origin::signed(ScoreOrigin::get()), who, index, 99)); + assert_ok!(ScoredPool::score(RuntimeOrigin::signed(ScoreOrigin::get()), who, index, 99)); // when ScoredPool::refresh_members(ScoredPool::pool(), ChangeReceiver::MembershipChanged); @@ -179,9 +179,9 @@ fn refreshing_happens_every_period() { new_test_ext().execute_with(|| { // given System::set_block_number(1); - assert_ok!(ScoredPool::submit_candidacy(Origin::signed(15))); + assert_ok!(ScoredPool::submit_candidacy(RuntimeOrigin::signed(15))); let index = find_in_pool(15).expect("entity must be in pool") as u32; - assert_ok!(ScoredPool::score(Origin::signed(ScoreOrigin::get()), 15, index, 99)); + assert_ok!(ScoredPool::score(RuntimeOrigin::signed(ScoreOrigin::get()), 15, index, 99)); assert_eq!(ScoredPool::members(), vec![20, 40]); // when @@ -200,7 +200,7 @@ fn withdraw_candidacy_must_only_work_for_members() { let who = 77; let index = 0; assert_noop!( - ScoredPool::withdraw_candidacy(Origin::signed(who), index), + ScoredPool::withdraw_candidacy(RuntimeOrigin::signed(who), index), Error::::WrongAccountIndex ); }); @@ -212,15 +212,15 @@ fn oob_index_should_abort() { let who = 40; let oob_index = ScoredPool::pool().len() as u32; assert_noop!( - ScoredPool::withdraw_candidacy(Origin::signed(who), oob_index), + ScoredPool::withdraw_candidacy(RuntimeOrigin::signed(who), oob_index), Error::::InvalidIndex ); assert_noop!( - ScoredPool::score(Origin::signed(ScoreOrigin::get()), who, oob_index, 99), + ScoredPool::score(RuntimeOrigin::signed(ScoreOrigin::get()), who, oob_index, 99), Error::::InvalidIndex ); assert_noop!( - ScoredPool::kick(Origin::signed(KickOrigin::get()), who, oob_index), + ScoredPool::kick(RuntimeOrigin::signed(KickOrigin::get()), who, oob_index), Error::::InvalidIndex ); }); @@ -232,15 +232,15 @@ fn index_mismatches_should_abort() { let who = 40; let index = 3; assert_noop!( - ScoredPool::withdraw_candidacy(Origin::signed(who), index), + ScoredPool::withdraw_candidacy(RuntimeOrigin::signed(who), index), Error::::WrongAccountIndex ); assert_noop!( - ScoredPool::score(Origin::signed(ScoreOrigin::get()), who, index, 99), + ScoredPool::score(RuntimeOrigin::signed(ScoreOrigin::get()), who, index, 99), Error::::WrongAccountIndex ); assert_noop!( - ScoredPool::kick(Origin::signed(KickOrigin::get()), who, index), + ScoredPool::kick(RuntimeOrigin::signed(KickOrigin::get()), who, index), Error::::WrongAccountIndex ); }); @@ -254,7 +254,7 @@ fn withdraw_unscored_candidacy_must_work() { // when let index = find_in_pool(who).expect("entity must be in pool") as u32; - assert_ok!(ScoredPool::withdraw_candidacy(Origin::signed(who), index)); + assert_ok!(ScoredPool::withdraw_candidacy(RuntimeOrigin::signed(who), index)); // then assert_eq!(fetch_from_pool(5), None); @@ -270,7 +270,7 @@ fn withdraw_scored_candidacy_must_work() { // when let index = find_in_pool(who).expect("entity must be in pool") as u32; - assert_ok!(ScoredPool::withdraw_candidacy(Origin::signed(who), index)); + assert_ok!(ScoredPool::withdraw_candidacy(RuntimeOrigin::signed(who), index)); // then assert_eq!(fetch_from_pool(who), None); @@ -286,12 +286,12 @@ fn candidacy_resubmitting_works() { let who = 15; // when - assert_ok!(ScoredPool::submit_candidacy(Origin::signed(who))); + assert_ok!(ScoredPool::submit_candidacy(RuntimeOrigin::signed(who))); assert_eq!(ScoredPool::candidate_exists(who), true); let index = find_in_pool(who).expect("entity must be in pool") as u32; - assert_ok!(ScoredPool::withdraw_candidacy(Origin::signed(who), index)); + assert_ok!(ScoredPool::withdraw_candidacy(RuntimeOrigin::signed(who), index)); assert_eq!(ScoredPool::candidate_exists(who), false); - assert_ok!(ScoredPool::submit_candidacy(Origin::signed(who))); + assert_ok!(ScoredPool::submit_candidacy(RuntimeOrigin::signed(who))); // then assert_eq!(ScoredPool::candidate_exists(who), true); @@ -303,13 +303,18 @@ fn pool_candidates_exceeded() { new_test_ext().execute_with(|| { for i in [1, 2, 3, 4, 6] { let who = i as u64; - assert_ok!(ScoredPool::submit_candidacy(Origin::signed(who))); + assert_ok!(ScoredPool::submit_candidacy(RuntimeOrigin::signed(who))); let index = find_in_pool(who).expect("entity must be in pool") as u32; - assert_ok!(ScoredPool::score(Origin::signed(ScoreOrigin::get()), who, index, 99)); + assert_ok!(ScoredPool::score( + RuntimeOrigin::signed(ScoreOrigin::get()), + who, + index, + 99 + )); } assert_noop!( - ScoredPool::submit_candidacy(Origin::signed(8)), + ScoredPool::submit_candidacy(RuntimeOrigin::signed(8)), Error::::TooManyMembers ); }); diff --git a/frame/session/benchmarking/src/mock.rs b/frame/session/benchmarking/src/mock.rs index de2f4ae23f423..f86ddfeedc08b 100644 --- a/frame/session/benchmarking/src/mock.rs +++ b/frame/session/benchmarking/src/mock.rs @@ -52,7 +52,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; @@ -174,6 +174,7 @@ impl pallet_staking::Config for Test { type ElectionProvider = onchain::UnboundedExecution; type GenesisElectionProvider = Self::ElectionProvider; type MaxUnlockingChunks = ConstU32<32>; + type HistoryDepth = ConstU32<84>; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; type OnStakerSlash = (); diff --git a/frame/session/src/mock.rs b/frame/session/src/mock.rs index f6d9e65c1e0b0..aa13eacba9564 100644 --- a/frame/session/src/mock.rs +++ b/frame/session/src/mock.rs @@ -248,7 +248,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; diff --git a/frame/session/src/tests.rs b/frame/session/src/tests.rs index 7947a8a670b5a..43809cc3a9de0 100644 --- a/frame/session/src/tests.rs +++ b/frame/session/src/tests.rs @@ -21,8 +21,8 @@ use super::*; use crate::mock::{ authorities, before_session_end_called, force_new_session, new_test_ext, reset_before_session_end_called, session_changed, set_next_validators, set_session_length, - Origin, PreUpgradeMockSessionKeys, Session, SessionChanged, System, Test, TestSessionChanged, - TestValidatorIdOf, + PreUpgradeMockSessionKeys, RuntimeOrigin, Session, SessionChanged, System, Test, + TestSessionChanged, TestValidatorIdOf, }; use codec::Decode; @@ -67,7 +67,7 @@ fn keys_cleared_on_kill() { assert_eq!(Session::key_owner(id, UintAuthorityId(1).get_raw(id)), Some(1)); assert!(System::is_provider_required(&1)); - assert_ok!(Session::purge_keys(Origin::signed(1))); + assert_ok!(Session::purge_keys(RuntimeOrigin::signed(1))); assert!(!System::is_provider_required(&1)); assert_eq!(Session::load_keys(&1), None); @@ -87,8 +87,8 @@ fn purge_keys_works_for_stash_id() { let id = DUMMY; assert_eq!(Session::key_owner(id, UintAuthorityId(1).get_raw(id)), Some(1)); - assert_ok!(Session::purge_keys(Origin::signed(10))); - assert_ok!(Session::purge_keys(Origin::signed(2))); + assert_ok!(Session::purge_keys(RuntimeOrigin::signed(10))); + assert_ok!(Session::purge_keys(RuntimeOrigin::signed(2))); assert_eq!(Session::load_keys(&10), None); assert_eq!(Session::load_keys(&20), None); @@ -128,7 +128,7 @@ fn authorities_should_track_validators() { reset_before_session_end_called(); set_next_validators(vec![1, 2, 4]); - assert_ok!(Session::set_keys(Origin::signed(4), UintAuthorityId(4).into(), vec![])); + assert_ok!(Session::set_keys(RuntimeOrigin::signed(4), UintAuthorityId(4).into(), vec![])); force_new_session(); initialize_block(3); assert_eq!( @@ -194,7 +194,7 @@ fn session_change_should_work() { // Block 3: Set new key for validator 2; no visible change. initialize_block(3); - assert_ok!(Session::set_keys(Origin::signed(2), UintAuthorityId(5).into(), vec![])); + assert_ok!(Session::set_keys(RuntimeOrigin::signed(2), UintAuthorityId(5).into(), vec![])); assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]); // Block 4: Session rollover; no visible change. @@ -219,13 +219,13 @@ fn duplicates_are_not_allowed() { System::set_block_number(1); Session::on_initialize(1); assert_noop!( - Session::set_keys(Origin::signed(4), UintAuthorityId(1).into(), vec![]), + Session::set_keys(RuntimeOrigin::signed(4), UintAuthorityId(1).into(), vec![]), Error::::DuplicatedKey, ); - assert_ok!(Session::set_keys(Origin::signed(1), UintAuthorityId(10).into(), vec![])); + assert_ok!(Session::set_keys(RuntimeOrigin::signed(1), UintAuthorityId(10).into(), vec![])); // is fine now that 1 has migrated off. - assert_ok!(Session::set_keys(Origin::signed(4), UintAuthorityId(1).into(), vec![])); + assert_ok!(Session::set_keys(RuntimeOrigin::signed(4), UintAuthorityId(1).into(), vec![])); }); } @@ -268,7 +268,7 @@ fn session_changed_flag_works() { assert!(before_session_end_called()); reset_before_session_end_called(); - assert_ok!(Session::set_keys(Origin::signed(2), UintAuthorityId(5).into(), vec![])); + assert_ok!(Session::set_keys(RuntimeOrigin::signed(2), UintAuthorityId(5).into(), vec![])); force_new_session(); initialize_block(6); assert!(!session_changed()); @@ -276,7 +276,11 @@ fn session_changed_flag_works() { reset_before_session_end_called(); // changing the keys of a validator leads to change. - assert_ok!(Session::set_keys(Origin::signed(69), UintAuthorityId(69).into(), vec![])); + assert_ok!(Session::set_keys( + RuntimeOrigin::signed(69), + UintAuthorityId(69).into(), + vec![] + )); force_new_session(); initialize_block(7); assert!(session_changed()); @@ -355,7 +359,7 @@ fn session_keys_generate_output_works_as_set_keys_input() { new_test_ext().execute_with(|| { let new_keys = mock::MockSessionKeys::generate(None); assert_ok!(Session::set_keys( - Origin::signed(2), + RuntimeOrigin::signed(2), ::Keys::decode(&mut &new_keys[..]).expect("Decode keys"), vec![], )); diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index 122dedabbcf0d..73a09490ea579 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -421,10 +421,10 @@ pub mod pallet { type MaxLockDuration: Get; /// The origin that is allowed to call `found`. - type FounderSetOrigin: EnsureOrigin; + type FounderSetOrigin: EnsureOrigin; /// The origin that is allowed to make suspension judgements. - type SuspensionJudgementOrigin: EnsureOrigin; + type SuspensionJudgementOrigin: EnsureOrigin; /// The number of blocks between membership challenges. #[pallet::constant] @@ -1268,19 +1268,19 @@ pub mod pallet { /// Simple ensure origin struct to filter for the founder account. pub struct EnsureFounder(sp_std::marker::PhantomData); -impl EnsureOrigin for EnsureFounder { +impl EnsureOrigin for EnsureFounder { type Success = T::AccountId; - fn try_origin(o: T::Origin) -> Result { + fn try_origin(o: T::RuntimeOrigin) -> Result { o.into().and_then(|o| match (o, Founder::::get()) { (frame_system::RawOrigin::Signed(ref who), Some(ref f)) if who == f => Ok(who.clone()), - (r, _) => Err(T::Origin::from(r)), + (r, _) => Err(T::RuntimeOrigin::from(r)), }) } #[cfg(feature = "runtime-benchmarks")] - fn try_successful_origin() -> Result { + fn try_successful_origin() -> Result { let founder = Founder::::get().ok_or(())?; - Ok(T::Origin::from(frame_system::RawOrigin::Signed(founder))) + Ok(T::RuntimeOrigin::from(frame_system::RawOrigin::Signed(founder))) } } diff --git a/frame/society/src/mock.rs b/frame/society/src/mock.rs index 1d9eebdda65ce..0b1b93aeae761 100644 --- a/frame/society/src/mock.rs +++ b/frame/society/src/mock.rs @@ -63,7 +63,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = H256; diff --git a/frame/society/src/tests.rs b/frame/society/src/tests.rs index d394ddc9011b0..864735aa10cca 100644 --- a/frame/society/src/tests.rs +++ b/frame/society/src/tests.rs @@ -33,9 +33,9 @@ fn founding_works() { assert_eq!(Society::pot(), 0); // Account 1 is set as the founder origin // Account 5 cannot start a society - assert_noop!(Society::found(Origin::signed(5), 20, 100, vec![]), BadOrigin); + assert_noop!(Society::found(RuntimeOrigin::signed(5), 20, 100, vec![]), BadOrigin); // Account 1 can start a society, where 10 is the founding member - assert_ok!(Society::found(Origin::signed(1), 10, 100, b"be cool".to_vec())); + assert_ok!(Society::found(RuntimeOrigin::signed(1), 10, 100, b"be cool".to_vec())); // Society members only include 10 assert_eq!(Society::members(), vec![10]); // 10 is the head of the society @@ -51,7 +51,7 @@ fn founding_works() { assert_eq!(Society::pot(), 1000); // Cannot start another society assert_noop!( - Society::found(Origin::signed(1), 20, 100, vec![]), + Society::found(RuntimeOrigin::signed(1), 20, 100, vec![]), Error::::AlreadyFounded ); }); @@ -61,22 +61,22 @@ fn founding_works() { fn unfounding_works() { EnvBuilder::new().with_max_members(0).with_members(vec![]).execute(|| { // Account 1 sets the founder... - assert_ok!(Society::found(Origin::signed(1), 10, 100, vec![])); + assert_ok!(Society::found(RuntimeOrigin::signed(1), 10, 100, vec![])); // Account 2 cannot unfound it as it's not the founder. - assert_noop!(Society::unfound(Origin::signed(2)), Error::::NotFounder); + assert_noop!(Society::unfound(RuntimeOrigin::signed(2)), Error::::NotFounder); // Account 10 can, though. - assert_ok!(Society::unfound(Origin::signed(10))); + assert_ok!(Society::unfound(RuntimeOrigin::signed(10))); // 1 sets the founder to 20 this time - assert_ok!(Society::found(Origin::signed(1), 20, 100, vec![])); + assert_ok!(Society::found(RuntimeOrigin::signed(1), 20, 100, vec![])); // Bring in a new member... - assert_ok!(Society::bid(Origin::signed(10), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(10), 0)); run_to_block(4); - assert_ok!(Society::vote(Origin::signed(20), 10, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(20), 10, true)); run_to_block(8); // Unfounding won't work now, even though it's from 20. - assert_noop!(Society::unfound(Origin::signed(20)), Error::::NotHead); + assert_noop!(Society::unfound(RuntimeOrigin::signed(20)), Error::::NotHead); }); } @@ -85,7 +85,7 @@ fn basic_new_member_works() { EnvBuilder::new().execute(|| { assert_eq!(Balances::free_balance(20), 50); // Bid causes Candidate Deposit to be reserved. - assert_ok!(Society::bid(Origin::signed(20), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(20), 0)); assert_eq!(Balances::free_balance(20), 25); assert_eq!(Balances::reserved_balance(20), 25); // Rotate period every 4 blocks @@ -93,7 +93,7 @@ fn basic_new_member_works() { // 20 is now a candidate assert_eq!(Society::candidates(), vec![create_bid(0, 20, BidKind::Deposit(25))]); // 10 (a member) can vote for the candidate - assert_ok!(Society::vote(Origin::signed(10), 20, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 20, true)); // Rotate period every 4 blocks run_to_block(8); // 20 is now a member of the society @@ -108,10 +108,10 @@ fn basic_new_member_works() { fn bidding_works() { EnvBuilder::new().execute(|| { // Users make bids of various amounts - assert_ok!(Society::bid(Origin::signed(60), 1900)); - assert_ok!(Society::bid(Origin::signed(50), 500)); - assert_ok!(Society::bid(Origin::signed(40), 400)); - assert_ok!(Society::bid(Origin::signed(30), 300)); + assert_ok!(Society::bid(RuntimeOrigin::signed(60), 1900)); + assert_ok!(Society::bid(RuntimeOrigin::signed(50), 500)); + assert_ok!(Society::bid(RuntimeOrigin::signed(40), 400)); + assert_ok!(Society::bid(RuntimeOrigin::signed(30), 300)); // Rotate period run_to_block(4); // Pot is 1000 after "PeriodSpend" @@ -126,8 +126,8 @@ fn bidding_works() { ] ); // A member votes for these candidates to join the society - assert_ok!(Society::vote(Origin::signed(10), 30, true)); - assert_ok!(Society::vote(Origin::signed(10), 40, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 30, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 40, true)); run_to_block(8); // Candidates become members after a period rotation assert_eq!(Society::members(), vec![10, 30, 40]); @@ -137,7 +137,7 @@ fn bidding_works() { // Left over from the original bids is 50 who satisfies the condition of bid less than pot. assert_eq!(Society::candidates(), vec![create_bid(500, 50, BidKind::Deposit(25))]); // 40, now a member, can vote for 50 - assert_ok!(Society::vote(Origin::signed(40), 50, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(40), 50, true)); run_to_block(12); // 50 is now a member assert_eq!(Society::members(), vec![10, 30, 40, 50]); @@ -146,8 +146,8 @@ fn bidding_works() { assert_eq!(Balances::free_balance(Society::account_id()), 8_800); // No more candidates satisfy the requirements assert_eq!(Society::candidates(), vec![]); - assert_ok!(Society::defender_vote(Origin::signed(10), true)); // Keep defender around - // Next period + assert_ok!(Society::defender_vote(RuntimeOrigin::signed(10), true)); // Keep defender around + // Next period run_to_block(16); // Same members assert_eq!(Society::members(), vec![10, 30, 40, 50]); @@ -158,7 +158,7 @@ fn bidding_works() { // Candidate 60 now qualifies based on the increased pot size. assert_eq!(Society::candidates(), vec![create_bid(1900, 60, BidKind::Deposit(25))]); // Candidate 60 is voted in. - assert_ok!(Society::vote(Origin::signed(50), 60, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(50), 60, true)); run_to_block(20); // 60 joins as a member assert_eq!(Society::members(), vec![10, 30, 40, 50, 60]); @@ -172,15 +172,15 @@ fn bidding_works() { fn unbidding_works() { EnvBuilder::new().execute(|| { // 20 and 30 make bids - assert_ok!(Society::bid(Origin::signed(20), 1000)); - assert_ok!(Society::bid(Origin::signed(30), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(20), 1000)); + assert_ok!(Society::bid(RuntimeOrigin::signed(30), 0)); // Balances are reserved assert_eq!(Balances::free_balance(30), 25); assert_eq!(Balances::reserved_balance(30), 25); // Must know right position to unbid + cannot unbid someone else - assert_noop!(Society::unbid(Origin::signed(30), 1), Error::::BadPosition); + assert_noop!(Society::unbid(RuntimeOrigin::signed(30), 1), Error::::BadPosition); // Can unbid themselves with the right position - assert_ok!(Society::unbid(Origin::signed(30), 0)); + assert_ok!(Society::unbid(RuntimeOrigin::signed(30), 0)); // Balance is returned assert_eq!(Balances::free_balance(30), 50); assert_eq!(Balances::reserved_balance(30), 0); @@ -195,15 +195,15 @@ fn payout_works() { EnvBuilder::new().execute(|| { // Original balance of 50 assert_eq!(Balances::free_balance(20), 50); - assert_ok!(Society::bid(Origin::signed(20), 1000)); + assert_ok!(Society::bid(RuntimeOrigin::signed(20), 1000)); run_to_block(4); - assert_ok!(Society::vote(Origin::signed(10), 20, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 20, true)); run_to_block(8); // payout not ready - assert_noop!(Society::payout(Origin::signed(20)), Error::::NoPayout); + assert_noop!(Society::payout(RuntimeOrigin::signed(20)), Error::::NoPayout); run_to_block(9); // payout should be here - assert_ok!(Society::payout(Origin::signed(20))); + assert_ok!(Society::payout(RuntimeOrigin::signed(20))); assert_eq!(Balances::free_balance(20), 1050); }); } @@ -212,7 +212,7 @@ fn payout_works() { fn basic_new_member_skeptic_works() { EnvBuilder::new().execute(|| { assert_eq!(Strikes::::get(10), 0); - assert_ok!(Society::bid(Origin::signed(20), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(20), 0)); run_to_block(4); assert_eq!(Society::candidates(), vec![create_bid(0, 20, BidKind::Deposit(25))]); run_to_block(8); @@ -227,14 +227,14 @@ fn basic_new_member_reject_works() { // Starting Balance assert_eq!(Balances::free_balance(20), 50); // 20 makes a bid - assert_ok!(Society::bid(Origin::signed(20), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(20), 0)); assert_eq!(Balances::free_balance(20), 25); assert_eq!(Balances::reserved_balance(20), 25); // Rotation Period run_to_block(4); assert_eq!(Society::candidates(), vec![create_bid(0, 20, BidKind::Deposit(25))]); // We say no - assert_ok!(Society::vote(Origin::signed(10), 20, false)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 20, false)); run_to_block(8); // User is not added as member assert_eq!(Society::members(), vec![10]); @@ -248,19 +248,19 @@ fn basic_new_member_reject_works() { fn slash_payout_works() { EnvBuilder::new().execute(|| { assert_eq!(Balances::free_balance(20), 50); - assert_ok!(Society::bid(Origin::signed(20), 1000)); + assert_ok!(Society::bid(RuntimeOrigin::signed(20), 1000)); run_to_block(4); - assert_ok!(Society::vote(Origin::signed(10), 20, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 20, true)); run_to_block(8); // payout in queue assert_eq!(Payouts::::get(20), vec![(9, 1000)]); - assert_noop!(Society::payout(Origin::signed(20)), Error::::NoPayout); + assert_noop!(Society::payout(RuntimeOrigin::signed(20)), Error::::NoPayout); // slash payout assert_eq!(Society::slash_payout(&20, 500), 500); assert_eq!(Payouts::::get(20), vec![(9, 500)]); run_to_block(9); // payout should be here, but 500 less - assert_ok!(Society::payout(Origin::signed(20))); + assert_ok!(Society::payout(RuntimeOrigin::signed(20))); assert_eq!(Balances::free_balance(20), 550); }); } @@ -295,10 +295,10 @@ fn suspended_member_life_cycle_works() { assert_eq!(>::get(20), false); // Let's suspend account 20 by giving them 2 strikes by not voting - assert_ok!(Society::bid(Origin::signed(30), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(30), 0)); run_to_block(8); assert_eq!(Strikes::::get(20), 1); - assert_ok!(Society::bid(Origin::signed(40), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(40), 0)); run_to_block(16); // Strike 2 is accumulated, and 20 is suspended :( @@ -307,14 +307,17 @@ fn suspended_member_life_cycle_works() { // Suspended members cannot get payout Society::bump_payout(&20, 10, 100); - assert_noop!(Society::payout(Origin::signed(20)), Error::::NotMember); + assert_noop!(Society::payout(RuntimeOrigin::signed(20)), Error::::NotMember); // Normal people cannot make judgement - assert_noop!(Society::judge_suspended_member(Origin::signed(20), 20, true), BadOrigin); + assert_noop!( + Society::judge_suspended_member(RuntimeOrigin::signed(20), 20, true), + BadOrigin + ); // Suspension judgment origin can judge thee // Suspension judgement origin forgives the suspended member - assert_ok!(Society::judge_suspended_member(Origin::signed(2), 20, true)); + assert_ok!(Society::judge_suspended_member(RuntimeOrigin::signed(2), 20, true)); assert_eq!(>::get(20), false); assert_eq!(>::get(), vec![10, 20]); @@ -322,7 +325,7 @@ fn suspended_member_life_cycle_works() { Society::suspend_member(&20); assert_eq!(>::get(20), true); // Suspension judgement origin does not forgive the suspended member - assert_ok!(Society::judge_suspended_member(Origin::signed(2), 20, false)); + assert_ok!(Society::judge_suspended_member(RuntimeOrigin::signed(2), 20, false)); // Cleaned up assert_eq!(>::get(20), false); assert_eq!(>::get(), vec![10]); @@ -337,14 +340,14 @@ fn suspended_candidate_rejected_works() { assert_eq!(Balances::free_balance(20), 50); assert_eq!(Balances::free_balance(Society::account_id()), 10000); // 20 makes a bid - assert_ok!(Society::bid(Origin::signed(20), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(20), 0)); assert_eq!(Balances::free_balance(20), 25); assert_eq!(Balances::reserved_balance(20), 25); // Rotation Period run_to_block(4); assert_eq!(Society::candidates(), vec![create_bid(0, 20, BidKind::Deposit(25))]); // We say no - assert_ok!(Society::vote(Origin::signed(10), 20, false)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 20, false)); run_to_block(8); // User is not added as member assert_eq!(Society::members(), vec![10]); @@ -354,18 +357,22 @@ fn suspended_candidate_rejected_works() { // Normal user cannot make judgement on suspended candidate assert_noop!( - Society::judge_suspended_candidate(Origin::signed(20), 20, Judgement::Approve), + Society::judge_suspended_candidate(RuntimeOrigin::signed(20), 20, Judgement::Approve), BadOrigin ); // Suspension judgement origin makes no direct judgement - assert_ok!(Society::judge_suspended_candidate(Origin::signed(2), 20, Judgement::Rebid)); + assert_ok!(Society::judge_suspended_candidate( + RuntimeOrigin::signed(2), + 20, + Judgement::Rebid + )); // They are placed back in bid pool, repeat suspension process // Rotation Period run_to_block(12); assert_eq!(Society::candidates(), vec![create_bid(0, 20, BidKind::Deposit(25))]); // We say no - assert_ok!(Society::vote(Origin::signed(10), 20, false)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 20, false)); run_to_block(16); // User is not added as member assert_eq!(Society::members(), vec![10]); @@ -374,7 +381,11 @@ fn suspended_candidate_rejected_works() { assert_eq!(Society::suspended_candidate(20).is_some(), true); // Suspension judgement origin rejects the candidate - assert_ok!(Society::judge_suspended_candidate(Origin::signed(2), 20, Judgement::Reject)); + assert_ok!(Society::judge_suspended_candidate( + RuntimeOrigin::signed(2), + 20, + Judgement::Reject + )); // User is slashed assert_eq!(Balances::free_balance(20), 25); assert_eq!(Balances::reserved_balance(20), 0); @@ -392,13 +403,16 @@ fn vouch_works() { // 10 is the only member assert_eq!(Society::members(), vec![10]); // A non-member cannot vouch - assert_noop!(Society::vouch(Origin::signed(1), 20, 1000, 100), Error::::NotMember); + assert_noop!( + Society::vouch(RuntimeOrigin::signed(1), 20, 1000, 100), + Error::::NotMember + ); // A member can though - assert_ok!(Society::vouch(Origin::signed(10), 20, 1000, 100)); + assert_ok!(Society::vouch(RuntimeOrigin::signed(10), 20, 1000, 100)); assert_eq!(>::get(10), Some(VouchingStatus::Vouching)); // A member cannot vouch twice at the same time assert_noop!( - Society::vouch(Origin::signed(10), 30, 100, 0), + Society::vouch(RuntimeOrigin::signed(10), 30, 100, 0), Error::::AlreadyVouching ); // Vouching creates the right kind of bid @@ -407,7 +421,7 @@ fn vouch_works() { run_to_block(4); assert_eq!(Society::candidates(), vec![create_bid(1000, 20, BidKind::Vouch(10, 100))]); // Vote yes - assert_ok!(Society::vote(Origin::signed(10), 20, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 20, true)); // Vouched user can win run_to_block(8); assert_eq!(Society::members(), vec![10, 20]); @@ -426,14 +440,14 @@ fn voucher_cannot_win_more_than_bid() { // 10 is the only member assert_eq!(Society::members(), vec![10]); // 10 vouches, but asks for more than the bid - assert_ok!(Society::vouch(Origin::signed(10), 20, 100, 1000)); + assert_ok!(Society::vouch(RuntimeOrigin::signed(10), 20, 100, 1000)); // Vouching creates the right kind of bid assert_eq!(>::get(), vec![create_bid(100, 20, BidKind::Vouch(10, 1000))]); // Vouched user can become candidate run_to_block(4); assert_eq!(Society::candidates(), vec![create_bid(100, 20, BidKind::Vouch(10, 1000))]); // Vote yes - assert_ok!(Society::vote(Origin::signed(10), 20, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 20, true)); // Vouched user can win run_to_block(8); assert_eq!(Society::members(), vec![10, 20]); @@ -450,25 +464,25 @@ fn unvouch_works() { // 10 is the only member assert_eq!(Society::members(), vec![10]); // 10 vouches for 20 - assert_ok!(Society::vouch(Origin::signed(10), 20, 100, 0)); + assert_ok!(Society::vouch(RuntimeOrigin::signed(10), 20, 100, 0)); // 20 has a bid assert_eq!(>::get(), vec![create_bid(100, 20, BidKind::Vouch(10, 0))]); // 10 is vouched assert_eq!(>::get(10), Some(VouchingStatus::Vouching)); // To unvouch, you must know the right bid position - assert_noop!(Society::unvouch(Origin::signed(10), 2), Error::::BadPosition); + assert_noop!(Society::unvouch(RuntimeOrigin::signed(10), 2), Error::::BadPosition); // 10 can unvouch with the right position - assert_ok!(Society::unvouch(Origin::signed(10), 0)); + assert_ok!(Society::unvouch(RuntimeOrigin::signed(10), 0)); // 20 no longer has a bid assert_eq!(>::get(), vec![]); // 10 is no longer vouching assert_eq!(>::get(10), None); // Cannot unvouch after they become candidate - assert_ok!(Society::vouch(Origin::signed(10), 20, 100, 0)); + assert_ok!(Society::vouch(RuntimeOrigin::signed(10), 20, 100, 0)); run_to_block(4); assert_eq!(Society::candidates(), vec![create_bid(100, 20, BidKind::Vouch(10, 0))]); - assert_noop!(Society::unvouch(Origin::signed(10), 0), Error::::BadPosition); + assert_noop!(Society::unvouch(RuntimeOrigin::signed(10), 0), Error::::BadPosition); // 10 is still vouching until candidate is approved or rejected assert_eq!(>::get(10), Some(VouchingStatus::Vouching)); run_to_block(8); @@ -478,18 +492,22 @@ fn unvouch_works() { // User is stuck vouching until judgement origin resolves suspended candidate assert_eq!(>::get(10), Some(VouchingStatus::Vouching)); // Judge denies candidate - assert_ok!(Society::judge_suspended_candidate(Origin::signed(2), 20, Judgement::Reject)); + assert_ok!(Society::judge_suspended_candidate( + RuntimeOrigin::signed(2), + 20, + Judgement::Reject + )); // 10 is banned from vouching assert_eq!(>::get(10), Some(VouchingStatus::Banned)); assert_eq!(Society::members(), vec![10]); // 10 cannot vouch again assert_noop!( - Society::vouch(Origin::signed(10), 30, 100, 0), + Society::vouch(RuntimeOrigin::signed(10), 30, 100, 0), Error::::AlreadyVouching ); // 10 cannot unvouch either, so they are banned forever. - assert_noop!(Society::unvouch(Origin::signed(10), 0), Error::::NotVouching); + assert_noop!(Society::unvouch(RuntimeOrigin::signed(10), 0), Error::::NotVouching); }); } @@ -499,13 +517,13 @@ fn unbid_vouch_works() { // 10 is the only member assert_eq!(Society::members(), vec![10]); // 10 vouches for 20 - assert_ok!(Society::vouch(Origin::signed(10), 20, 100, 0)); + assert_ok!(Society::vouch(RuntimeOrigin::signed(10), 20, 100, 0)); // 20 has a bid assert_eq!(>::get(), vec![create_bid(100, 20, BidKind::Vouch(10, 0))]); // 10 is vouched assert_eq!(>::get(10), Some(VouchingStatus::Vouching)); // 20 doesn't want to be a member and can unbid themselves. - assert_ok!(Society::unbid(Origin::signed(20), 0)); + assert_ok!(Society::unbid(RuntimeOrigin::signed(20), 0)); // Everything is cleaned up assert_eq!(>::get(10), None); assert_eq!(>::get(), vec![]); @@ -520,22 +538,22 @@ fn founder_and_head_cannot_be_removed() { assert_eq!(Society::founder(), Some(10)); assert_eq!(Society::head(), Some(10)); // 10 can still accumulate strikes - assert_ok!(Society::bid(Origin::signed(20), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(20), 0)); run_to_block(8); assert_eq!(Strikes::::get(10), 1); - assert_ok!(Society::bid(Origin::signed(30), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(30), 0)); run_to_block(16); assert_eq!(Strikes::::get(10), 2); // Awkwardly they can obtain more than MAX_STRIKES... - assert_ok!(Society::bid(Origin::signed(40), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(40), 0)); run_to_block(24); assert_eq!(Strikes::::get(10), 3); // Replace the head - assert_ok!(Society::bid(Origin::signed(50), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(50), 0)); run_to_block(28); - assert_ok!(Society::vote(Origin::signed(10), 50, true)); - assert_ok!(Society::defender_vote(Origin::signed(10), true)); // Keep defender around + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 50, true)); + assert_ok!(Society::defender_vote(RuntimeOrigin::signed(10), true)); // Keep defender around run_to_block(32); assert_eq!(Society::members(), vec![10, 50]); assert_eq!(Society::head(), Some(50)); @@ -543,29 +561,29 @@ fn founder_and_head_cannot_be_removed() { assert_eq!(Society::founder(), Some(10)); // 50 can still accumulate strikes - assert_ok!(Society::bid(Origin::signed(60), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(60), 0)); run_to_block(40); assert_eq!(Strikes::::get(50), 1); - assert_ok!(Society::bid(Origin::signed(70), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(70), 0)); run_to_block(48); assert_eq!(Strikes::::get(50), 2); // Replace the head - assert_ok!(Society::bid(Origin::signed(80), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(80), 0)); run_to_block(52); - assert_ok!(Society::vote(Origin::signed(10), 80, true)); - assert_ok!(Society::vote(Origin::signed(50), 80, true)); - assert_ok!(Society::defender_vote(Origin::signed(10), true)); // Keep defender around + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 80, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(50), 80, true)); + assert_ok!(Society::defender_vote(RuntimeOrigin::signed(10), true)); // Keep defender around run_to_block(56); assert_eq!(Society::members(), vec![10, 50, 80]); assert_eq!(Society::head(), Some(80)); assert_eq!(Society::founder(), Some(10)); // 50 can now be suspended for strikes - assert_ok!(Society::bid(Origin::signed(90), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(90), 0)); run_to_block(60); // The candidate is rejected, so voting approve will give a strike - assert_ok!(Society::vote(Origin::signed(50), 90, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(50), 90, true)); run_to_block(64); assert_eq!(Strikes::::get(50), 0); assert_eq!(>::get(50), true); @@ -592,19 +610,22 @@ fn challenges_work() { run_to_block(8); assert_eq!(Society::defender(), Some(30)); // They can always free vote for themselves - assert_ok!(Society::defender_vote(Origin::signed(30), true)); + assert_ok!(Society::defender_vote(RuntimeOrigin::signed(30), true)); // If no one else votes, nothing happens run_to_block(16); assert_eq!(Society::members(), vec![10, 20, 30, 40]); // New challenge period assert_eq!(Society::defender(), Some(30)); // Non-member cannot challenge - assert_noop!(Society::defender_vote(Origin::signed(1), true), Error::::NotMember); + assert_noop!( + Society::defender_vote(RuntimeOrigin::signed(1), true), + Error::::NotMember + ); // 3 people say accept, 1 reject - assert_ok!(Society::defender_vote(Origin::signed(10), true)); - assert_ok!(Society::defender_vote(Origin::signed(20), true)); - assert_ok!(Society::defender_vote(Origin::signed(30), true)); - assert_ok!(Society::defender_vote(Origin::signed(40), false)); + assert_ok!(Society::defender_vote(RuntimeOrigin::signed(10), true)); + assert_ok!(Society::defender_vote(RuntimeOrigin::signed(20), true)); + assert_ok!(Society::defender_vote(RuntimeOrigin::signed(30), true)); + assert_ok!(Society::defender_vote(RuntimeOrigin::signed(40), false)); run_to_block(24); // 20 survives assert_eq!(Society::members(), vec![10, 20, 30, 40]); @@ -616,10 +637,10 @@ fn challenges_work() { // One more time assert_eq!(Society::defender(), Some(30)); // 2 people say accept, 2 reject - assert_ok!(Society::defender_vote(Origin::signed(10), true)); - assert_ok!(Society::defender_vote(Origin::signed(20), true)); - assert_ok!(Society::defender_vote(Origin::signed(30), false)); - assert_ok!(Society::defender_vote(Origin::signed(40), false)); + assert_ok!(Society::defender_vote(RuntimeOrigin::signed(10), true)); + assert_ok!(Society::defender_vote(RuntimeOrigin::signed(20), true)); + assert_ok!(Society::defender_vote(RuntimeOrigin::signed(30), false)); + assert_ok!(Society::defender_vote(RuntimeOrigin::signed(40), false)); run_to_block(32); // 20 is suspended assert_eq!(Society::members(), vec![10, 20, 40]); @@ -653,12 +674,12 @@ fn bad_vote_slash_works() { assert_eq!(>::get(30), vec![(5, 100)]); assert_eq!(>::get(40), vec![(5, 100)]); // Create a new bid - assert_ok!(Society::bid(Origin::signed(50), 1000)); + assert_ok!(Society::bid(RuntimeOrigin::signed(50), 1000)); run_to_block(4); - assert_ok!(Society::vote(Origin::signed(10), 50, false)); - assert_ok!(Society::vote(Origin::signed(20), 50, true)); - assert_ok!(Society::vote(Origin::signed(30), 50, false)); - assert_ok!(Society::vote(Origin::signed(40), 50, false)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 50, false)); + assert_ok!(Society::vote(RuntimeOrigin::signed(20), 50, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(30), 50, false)); + assert_ok!(Society::vote(RuntimeOrigin::signed(40), 50, false)); run_to_block(8); // Wrong voter gained a strike assert_eq!(>::get(10), 0); @@ -677,15 +698,15 @@ fn bad_vote_slash_works() { fn user_cannot_bid_twice() { EnvBuilder::new().execute(|| { // Cannot bid twice - assert_ok!(Society::bid(Origin::signed(20), 100)); - assert_noop!(Society::bid(Origin::signed(20), 100), Error::::AlreadyBid); + assert_ok!(Society::bid(RuntimeOrigin::signed(20), 100)); + assert_noop!(Society::bid(RuntimeOrigin::signed(20), 100), Error::::AlreadyBid); // Cannot bid when vouched - assert_ok!(Society::vouch(Origin::signed(10), 30, 100, 100)); - assert_noop!(Society::bid(Origin::signed(30), 100), Error::::AlreadyBid); + assert_ok!(Society::vouch(RuntimeOrigin::signed(10), 30, 100, 100)); + assert_noop!(Society::bid(RuntimeOrigin::signed(30), 100), Error::::AlreadyBid); // Cannot vouch when already bid assert_ok!(Society::add_member(&50)); assert_noop!( - Society::vouch(Origin::signed(50), 20, 100, 100), + Society::vouch(RuntimeOrigin::signed(50), 20, 100, 100), Error::::AlreadyBid ); }); @@ -697,7 +718,7 @@ fn vouching_handles_removed_member_with_bid() { // Add a member assert_ok!(Society::add_member(&20)); // Have that member vouch for a user - assert_ok!(Society::vouch(Origin::signed(20), 30, 1000, 100)); + assert_ok!(Society::vouch(RuntimeOrigin::signed(20), 30, 1000, 100)); // That user is now a bid and the member is vouching assert_eq!(>::get(), vec![create_bid(1000, 30, BidKind::Vouch(20, 100))]); assert_eq!(>::get(20), Some(VouchingStatus::Vouching)); @@ -708,7 +729,7 @@ fn vouching_handles_removed_member_with_bid() { assert_eq!(>::get(), vec![create_bid(1000, 30, BidKind::Vouch(20, 100))]); assert_eq!(>::get(20), Some(VouchingStatus::Vouching)); // Remove member - assert_ok!(Society::judge_suspended_member(Origin::signed(2), 20, false)); + assert_ok!(Society::judge_suspended_member(RuntimeOrigin::signed(2), 20, false)); // Bid is removed, vouching status is removed assert_eq!(>::get(), vec![]); assert_eq!(>::get(20), None); @@ -721,7 +742,7 @@ fn vouching_handles_removed_member_with_candidate() { // Add a member assert_ok!(Society::add_member(&20)); // Have that member vouch for a user - assert_ok!(Society::vouch(Origin::signed(20), 30, 1000, 100)); + assert_ok!(Society::vouch(RuntimeOrigin::signed(20), 30, 1000, 100)); // That user is now a bid and the member is vouching assert_eq!(>::get(), vec![create_bid(1000, 30, BidKind::Vouch(20, 100))]); assert_eq!(>::get(20), Some(VouchingStatus::Vouching)); @@ -735,12 +756,12 @@ fn vouching_handles_removed_member_with_candidate() { assert_eq!(Society::candidates(), vec![create_bid(1000, 30, BidKind::Vouch(20, 100))]); assert_eq!(>::get(20), Some(VouchingStatus::Vouching)); // Remove member - assert_ok!(Society::judge_suspended_member(Origin::signed(2), 20, false)); + assert_ok!(Society::judge_suspended_member(RuntimeOrigin::signed(2), 20, false)); // Vouching status is removed, but candidate is still in the queue assert_eq!(>::get(20), None); assert_eq!(Society::candidates(), vec![create_bid(1000, 30, BidKind::Vouch(20, 100))]); // Candidate wins - assert_ok!(Society::vote(Origin::signed(10), 30, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 30, true)); run_to_block(8); assert_eq!(Society::members(), vec![10, 30]); // Payout does not go to removed member @@ -753,16 +774,19 @@ fn vouching_handles_removed_member_with_candidate() { fn votes_are_working() { EnvBuilder::new().execute(|| { // Users make bids of various amounts - assert_ok!(Society::bid(Origin::signed(50), 500)); - assert_ok!(Society::bid(Origin::signed(40), 400)); - assert_ok!(Society::bid(Origin::signed(30), 300)); + assert_ok!(Society::bid(RuntimeOrigin::signed(50), 500)); + assert_ok!(Society::bid(RuntimeOrigin::signed(40), 400)); + assert_ok!(Society::bid(RuntimeOrigin::signed(30), 300)); // Rotate period run_to_block(4); // A member votes for these candidates to join the society - assert_ok!(Society::vote(Origin::signed(10), 30, true)); - assert_ok!(Society::vote(Origin::signed(10), 40, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 30, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 40, true)); // You cannot vote for a non-candidate - assert_noop!(Society::vote(Origin::signed(10), 50, true), Error::::NotCandidate); + assert_noop!( + Society::vote(RuntimeOrigin::signed(10), 50, true), + Error::::NotCandidate + ); // Votes are stored assert_eq!(>::get(30, 10), Some(Vote::Approve)); assert_eq!(>::get(40, 10), Some(Vote::Approve)); @@ -784,7 +808,7 @@ fn max_limits_work() { for i in (100..1110).rev() { // Give them some funds let _ = Balances::make_free_balance_be(&(i as u128), 1000); - assert_ok!(Society::bid(Origin::signed(i as u128), i)); + assert_ok!(Society::bid(RuntimeOrigin::signed(i as u128), i)); } let bids = >::get(); // Length is 1000 @@ -810,7 +834,7 @@ fn max_limits_work() { // Fill up members with suspended candidates from the first rotation for i in 100..104 { assert_ok!(Society::judge_suspended_candidate( - Origin::signed(2), + RuntimeOrigin::signed(2), i, Judgement::Approve )); @@ -821,9 +845,9 @@ fn max_limits_work() { // However, a fringe scenario allows for in-progress candidates to increase the membership // pool, but it has no real after-effects. for i in Society::members().iter() { - assert_ok!(Society::vote(Origin::signed(*i), 110, true)); - assert_ok!(Society::vote(Origin::signed(*i), 111, true)); - assert_ok!(Society::vote(Origin::signed(*i), 112, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(*i), 110, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(*i), 111, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(*i), 112, true)); } // Rotate period run_to_block(12); @@ -832,7 +856,7 @@ fn max_limits_work() { // No candidates because full assert_eq!(Society::candidates().len(), 0); // Increase member limit - assert_ok!(Society::set_max_members(Origin::root(), 200)); + assert_ok!(Society::set_max_members(RuntimeOrigin::root(), 200)); // Rotate period run_to_block(16); // Candidates are back! @@ -847,11 +871,11 @@ fn zero_bid_works() { // * That zero bid is placed as head when accepted. EnvBuilder::new().execute(|| { // Users make bids of various amounts - assert_ok!(Society::bid(Origin::signed(60), 400)); - assert_ok!(Society::bid(Origin::signed(50), 300)); - assert_ok!(Society::bid(Origin::signed(30), 0)); - assert_ok!(Society::bid(Origin::signed(20), 0)); - assert_ok!(Society::bid(Origin::signed(40), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(60), 400)); + assert_ok!(Society::bid(RuntimeOrigin::signed(50), 300)); + assert_ok!(Society::bid(RuntimeOrigin::signed(30), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(20), 0)); + assert_ok!(Society::bid(RuntimeOrigin::signed(40), 0)); // Rotate period run_to_block(4); @@ -872,9 +896,9 @@ fn zero_bid_works() { vec![create_bid(0, 20, BidKind::Deposit(25)), create_bid(0, 40, BidKind::Deposit(25)),] ); // A member votes for these candidates to join the society - assert_ok!(Society::vote(Origin::signed(10), 30, true)); - assert_ok!(Society::vote(Origin::signed(10), 50, true)); - assert_ok!(Society::vote(Origin::signed(10), 60, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 30, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 50, true)); + assert_ok!(Society::vote(RuntimeOrigin::signed(10), 60, true)); run_to_block(8); // Candidates become members after a period rotation assert_eq!(Society::members(), vec![10, 30, 50, 60]); @@ -892,7 +916,7 @@ fn bids_ordered_correctly() { for j in 0..5 { // Give them some funds let _ = Balances::make_free_balance_be(&(100 + (i * 5 + j) as u128), 1000); - assert_ok!(Society::bid(Origin::signed(100 + (i * 5 + j) as u128), j)); + assert_ok!(Society::bid(RuntimeOrigin::signed(100 + (i * 5 + j) as u128), j)); } } diff --git a/frame/staking/src/benchmarking.rs b/frame/staking/src/benchmarking.rs index a79eac3c4dc46..1ea05bba3b579 100644 --- a/frame/staking/src/benchmarking.rs +++ b/frame/staking/src/benchmarking.rs @@ -660,25 +660,6 @@ benchmarks! { assert!(original_bonded < new_bonded); } - set_history_depth { - let e in 1 .. 100; - HistoryDepth::::put(e); - CurrentEra::::put(e); - let dummy = || -> T::AccountId { codec::Decode::decode(&mut TrailingZeroInput::zeroes()).unwrap() }; - for i in 0 .. e { - >::insert(i, dummy(), Exposure::>::default()); - >::insert(i, dummy(), Exposure::>::default()); - >::insert(i, dummy(), ValidatorPrefs::default()); - >::insert(i, BalanceOf::::one()); - >::insert(i, EraRewardPoints::::default()); - >::insert(i, BalanceOf::::one()); - ErasStartSessionIndex::::insert(i, i); - } - }: _(RawOrigin::Root, EraIndex::zero(), u32::MAX) - verify { - assert_eq!(HistoryDepth::::get(), 0); - } - reap_stash { let s in 1 .. MAX_SPANS; // clean up any existing state. @@ -698,7 +679,7 @@ benchmarks! { active: T::Currency::minimum_balance() - One::one(), total: T::Currency::minimum_balance() - One::one(), unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: Default::default(), }; Ledger::::insert(&controller, l); @@ -953,7 +934,7 @@ benchmarks! { #[cfg(test)] mod tests { use super::*; - use crate::mock::{Balances, ExtBuilder, Origin, Staking, Test}; + use crate::mock::{Balances, ExtBuilder, RuntimeOrigin, Staking, Test}; use frame_support::assert_ok; #[test] @@ -1000,7 +981,11 @@ mod tests { let current_era = CurrentEra::::get().unwrap(); let original_free_balance = Balances::free_balance(&validator_stash); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), validator_stash, current_era)); + assert_ok!(Staking::payout_stakers( + RuntimeOrigin::signed(1337), + validator_stash, + current_era + )); let new_free_balance = Balances::free_balance(&validator_stash); assert!(original_free_balance < new_free_balance); diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index 4ff9e99306727..df568d6b596ba 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -299,12 +299,12 @@ pub mod weights; mod pallet; -use codec::{Decode, Encode, HasCompact}; +use codec::{Decode, Encode, HasCompact, MaxEncodedLen}; use frame_support::{ parameter_types, traits::{Currency, Defensive, Get}, weights::Weight, - BoundedVec, EqNoBound, PartialEqNoBound, RuntimeDebugNoBound, + BoundedVec, CloneNoBound, EqNoBound, PartialEqNoBound, RuntimeDebugNoBound, }; use scale_info::TypeInfo; use sp_runtime::{ @@ -354,7 +354,7 @@ parameter_types! { } /// Information regarding the active era (era in used in session). -#[derive(Encode, Decode, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub struct ActiveEraInfo { /// Index of era. pub index: EraIndex, @@ -395,7 +395,7 @@ pub enum StakerStatus { } /// A destination account for payment. -#[derive(PartialEq, Eq, Copy, Clone, Encode, Decode, RuntimeDebug, TypeInfo)] +#[derive(PartialEq, Eq, Copy, Clone, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub enum RewardDestination { /// Pay into the stash account, increasing the amount at stake accordingly. Staked, @@ -416,7 +416,7 @@ impl Default for RewardDestination { } /// Preference of what happens regarding validation. -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo, Default)] +#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo, Default, MaxEncodedLen)] pub struct ValidatorPrefs { /// Reward that validator takes up-front; only the rest is split between themselves and /// nominators. @@ -429,8 +429,8 @@ pub struct ValidatorPrefs { } /// Just a Balance/BlockNumber tuple to encode when a chunk of funds will be unlocked. -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct UnlockChunk { +#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub struct UnlockChunk { /// Amount of funds to be unlocked. #[codec(compact)] value: Balance, @@ -440,7 +440,16 @@ pub struct UnlockChunk { } /// The ledger of a (bonded) stash. -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebugNoBound, TypeInfo)] +#[derive( + PartialEqNoBound, + EqNoBound, + CloneNoBound, + Encode, + Decode, + RuntimeDebugNoBound, + TypeInfo, + MaxEncodedLen, +)] #[scale_info(skip_type_params(T))] pub struct StakingLedger { /// The stash account whose balance is actually locked and at stake. @@ -459,7 +468,7 @@ pub struct StakingLedger { pub unlocking: BoundedVec>, MaxUnlockingChunks>, /// List of eras for which the stakers behind a validator have claimed rewards. Only updated /// for validators. - pub claimed_rewards: Vec, + pub claimed_rewards: BoundedVec, } impl StakingLedger { @@ -470,7 +479,7 @@ impl StakingLedger { total: Zero::zero(), active: Zero::zero(), unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: Default::default(), } } @@ -554,7 +563,7 @@ impl StakingLedger { /// /// This calls `Config::OnStakerSlash::on_slash` with information as to how the slash was /// applied. - fn slash( + pub fn slash( &mut self, slash_amount: BalanceOf, minimum_balance: BalanceOf, @@ -676,7 +685,9 @@ impl StakingLedger { } /// A record of the nominations made by a specific account. -#[derive(PartialEqNoBound, EqNoBound, Clone, Encode, Decode, RuntimeDebugNoBound, TypeInfo)] +#[derive( + PartialEqNoBound, EqNoBound, Clone, Encode, Decode, RuntimeDebugNoBound, TypeInfo, MaxEncodedLen, +)] #[codec(mel_bound())] #[scale_info(skip_type_params(T))] pub struct Nominations { @@ -850,7 +861,7 @@ impl VoterBagsList + V12_0_0, // remove `HistoryDepth`. } impl Default for Releases { diff --git a/frame/staking/src/migrations.rs b/frame/staking/src/migrations.rs index 427570e5cf14f..f47545af694cf 100644 --- a/frame/staking/src/migrations.rs +++ b/frame/staking/src/migrations.rs @@ -20,6 +20,53 @@ use super::*; use frame_election_provider_support::SortedListProvider; use frame_support::traits::OnRuntimeUpgrade; +pub mod v12 { + use super::*; + use frame_support::{pallet_prelude::ValueQuery, storage_alias}; + + #[storage_alias] + type HistoryDepth = StorageValue, u32, ValueQuery>; + + /// Clean up `HistoryDepth` from storage. + /// + /// We will be depending on the configurable value of `HistoryDepth` post + /// this release. + pub struct MigrateToV12(sp_std::marker::PhantomData); + impl OnRuntimeUpgrade for MigrateToV12 { + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, &'static str> { + frame_support::ensure!( + T::HistoryDepth::get() == HistoryDepth::::get(), + "Provided value of HistoryDepth should be same as the existing storage value" + ); + + Ok(Default::default()) + } + + fn on_runtime_upgrade() -> frame_support::weights::Weight { + if StorageVersion::::get() == Releases::V11_0_0 { + HistoryDepth::::kill(); + StorageVersion::::put(Releases::V12_0_0); + + log!(info, "v12 applied successfully"); + T::DbWeight::get().reads_writes(1, 2) + } else { + log!(warn, "Skipping v12, should be removed"); + T::DbWeight::get().reads(1) + } + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(_state: Vec) -> Result<(), &'static str> { + frame_support::ensure!( + StorageVersion::::get() == crate::Releases::V12_0_0, + "v12 not applied" + ); + Ok(()) + } + } +} + pub mod v11 { use super::*; use frame_support::{ @@ -82,11 +129,6 @@ pub mod v11 { #[cfg(feature = "try-runtime")] fn post_upgrade(_state: Vec) -> Result<(), &'static str> { - frame_support::ensure!( - StorageVersion::::get() == crate::Releases::V11_0_0, - "wrong version after the upgrade" - ); - let old_pallet_name = N::get(); let new_pallet_name =

::name(); diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index 5980e6b40d15d..385087f9bec41 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -131,7 +131,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = RocksDbWeight; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; @@ -236,6 +236,7 @@ const THRESHOLDS: [sp_npos_elections::VoteWeight; 9] = parameter_types! { pub static BagThresholds: &'static [sp_npos_elections::VoteWeight] = &THRESHOLDS; pub static MaxNominations: u32 = 16; + pub static HistoryDepth: u32 = 80; pub static RewardOnUnbalanceWasCalled: bool = false; pub static LedgerSlashPerEra: (BalanceOf, BTreeMap>) = (Zero::zero(), BTreeMap::new()); } @@ -301,6 +302,7 @@ impl crate::pallet::pallet::Config for Test { type VoterList = VoterBagsList; type TargetList = UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; + type HistoryDepth = HistoryDepth; type OnStakerSlash = OnStakerSlashMock; type BenchmarkingConfig = TestBenchmarkingConfig; type WeightInfo = (); @@ -660,13 +662,22 @@ pub(crate) fn current_era() -> EraIndex { pub(crate) fn bond(stash: AccountId, ctrl: AccountId, val: Balance) { let _ = Balances::make_free_balance_be(&stash, val); let _ = Balances::make_free_balance_be(&ctrl, val); - assert_ok!(Staking::bond(Origin::signed(stash), ctrl, val, RewardDestination::Controller)); + assert_ok!(Staking::bond( + RuntimeOrigin::signed(stash), + ctrl, + val, + RewardDestination::Controller + )); } pub(crate) fn bond_validator(stash: AccountId, ctrl: AccountId, val: Balance) { bond(stash, ctrl, val); - assert_ok!(Staking::validate(Origin::signed(ctrl), ValidatorPrefs::default())); - assert_ok!(Session::set_keys(Origin::signed(ctrl), SessionKeys { other: ctrl.into() }, vec![])); + assert_ok!(Staking::validate(RuntimeOrigin::signed(ctrl), ValidatorPrefs::default())); + assert_ok!(Session::set_keys( + RuntimeOrigin::signed(ctrl), + SessionKeys { other: ctrl.into() }, + vec![] + )); } pub(crate) fn bond_nominator( @@ -676,7 +687,7 @@ pub(crate) fn bond_nominator( target: Vec, ) { bond(stash, ctrl, val); - assert_ok!(Staking::nominate(Origin::signed(ctrl), target)); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(ctrl), target)); } /// Progress to the given block, triggering session and era changes as we progress. @@ -846,7 +857,7 @@ pub(crate) fn make_all_reward_payment(era: EraIndex) { // reward validators for validator_controller in validators_with_reward.iter().filter_map(Staking::bonded) { let ledger = >::get(&validator_controller).unwrap(); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), ledger.stash, era)); + assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), ledger.stash, era)); } } diff --git a/frame/staking/src/pallet/impls.rs b/frame/staking/src/pallet/impls.rs index 62faaaf68ef62..399f50aaed865 100644 --- a/frame/staking/src/pallet/impls.rs +++ b/frame/staking/src/pallet/impls.rs @@ -25,8 +25,8 @@ use frame_support::{ dispatch::WithPostDispatchInfo, pallet_prelude::*, traits::{ - Currency, CurrencyToVote, Defensive, EstimateNextNewSession, Get, Imbalance, - LockableCurrency, OnUnbalanced, UnixTime, WithdrawReasons, + Currency, CurrencyToVote, Defensive, DefensiveResult, EstimateNextNewSession, Get, + Imbalance, LockableCurrency, OnUnbalanced, UnixTime, WithdrawReasons, }, weights::Weight, }; @@ -101,7 +101,7 @@ impl Pallet { Error::::InvalidEraToReward .with_weight(T::WeightInfo::payout_stakers_alive_staked(0)) })?; - let history_depth = Self::history_depth(); + let history_depth = T::HistoryDepth::get(); ensure!( era <= current_era && era >= current_era.saturating_sub(history_depth), Error::::InvalidEraToReward @@ -123,11 +123,18 @@ impl Pallet { ledger .claimed_rewards .retain(|&x| x >= current_era.saturating_sub(history_depth)); + match ledger.claimed_rewards.binary_search(&era) { Ok(_) => return Err(Error::::AlreadyClaimed .with_weight(T::WeightInfo::payout_stakers_alive_staked(0))), - Err(pos) => ledger.claimed_rewards.insert(pos, era), + Err(pos) => ledger + .claimed_rewards + .try_insert(pos, era) + // Since we retain era entries in `claimed_rewards` only upto + // `HistoryDepth`, following bound is always expected to be + // satisfied. + .defensive_map_err(|_| Error::::BoundNotMet)?, } let exposure = >::get(&era, &ledger.stash); @@ -417,7 +424,7 @@ impl Pallet { ErasStartSessionIndex::::insert(&new_planned_era, &start_session_index); // Clean old era information. - if let Some(old_era) = new_planned_era.checked_sub(Self::history_depth() + 1) { + if let Some(old_era) = new_planned_era.checked_sub(T::HistoryDepth::get() + 1) { Self::clear_era_information(old_era); } @@ -646,10 +653,10 @@ impl Pallet { #[cfg(feature = "runtime-benchmarks")] pub fn add_era_stakers( current_era: EraIndex, - controller: T::AccountId, + stash: T::AccountId, exposure: Exposure>, ) { - >::insert(¤t_era, &controller, &exposure); + >::insert(¤t_era, &stash, &exposure); } #[cfg(feature = "runtime-benchmarks")] @@ -966,7 +973,7 @@ impl ElectionDataProvider for Pallet { active: stake, total: stake, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: Default::default(), }, ); @@ -984,7 +991,7 @@ impl ElectionDataProvider for Pallet { active: stake, total: stake, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: Default::default(), }, ); Self::do_add_validator( @@ -1025,7 +1032,7 @@ impl ElectionDataProvider for Pallet { active: stake, total: stake, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: Default::default(), }, ); Self::do_add_validator( @@ -1046,7 +1053,7 @@ impl ElectionDataProvider for Pallet { active: stake, total: stake, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: Default::default(), }, ); Self::do_add_nominator( diff --git a/frame/staking/src/pallet/mod.rs b/frame/staking/src/pallet/mod.rs index b8a457beb5eae..4db3870c62d8b 100644 --- a/frame/staking/src/pallet/mod.rs +++ b/frame/staking/src/pallet/mod.rs @@ -22,10 +22,12 @@ use frame_support::{ dispatch::Codec, pallet_prelude::*, traits::{ - Currency, CurrencyToVote, Defensive, DefensiveSaturating, EnsureOrigin, - EstimateNextNewSession, Get, LockIdentifier, LockableCurrency, OnUnbalanced, UnixTime, + Currency, CurrencyToVote, Defensive, DefensiveResult, DefensiveSaturating, EnsureOrigin, + EstimateNextNewSession, Get, LockIdentifier, LockableCurrency, OnUnbalanced, TryCollect, + UnixTime, }, weights::Weight, + BoundedVec, }; use frame_system::{ensure_root, ensure_signed, pallet_prelude::*}; use sp_runtime::{ @@ -58,7 +60,6 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(crate) trait Store)] - #[pallet::without_storage_info] pub struct Pallet(_); /// Possible operations on the configuration values of this pallet. @@ -124,6 +125,28 @@ pub mod pallet { #[pallet::constant] type MaxNominations: Get; + /// Number of eras to keep in history. + /// + /// Following information is kept for eras in `[current_era - + /// HistoryDepth, current_era]`: `ErasStakers`, `ErasStakersClipped`, + /// `ErasValidatorPrefs`, `ErasValidatorReward`, `ErasRewardPoints`, + /// `ErasTotalStake`, `ErasStartSessionIndex`, + /// `StakingLedger.claimed_rewards`. + /// + /// Must be more than the number of eras delayed by session. + /// I.e. active era must always be in history. I.e. `active_era > + /// current_era - history_depth` must be guaranteed. + /// + /// If migrating an existing pallet from storage value to config value, + /// this should be set to same value or greater as in storage. + /// + /// Note: `HistoryDepth` is used as the upper bound for the `BoundedVec` + /// item `StakingLedger.claimed_rewards`. Setting this value lower than + /// the existing value can lead to inconsistencies and will need to be + /// handled properly in a migration. + #[pallet::constant] + type HistoryDepth: Get; + /// Tokens have been minted and are unused for validator-reward. /// See [Era payout](./index.html#era-payout). type RewardRemainder: OnUnbalanced>; @@ -155,7 +178,7 @@ pub mod pallet { type SlashDeferDuration: Get; /// The origin which can cancel a deferred slash. Root can always do this. - type SlashCancelOrigin: EnsureOrigin; + type SlashCancelOrigin: EnsureOrigin; /// Interface for interacting with a session pallet. type SessionInterface: SessionInterface; @@ -230,22 +253,6 @@ pub mod pallet { type WeightInfo: WeightInfo; } - #[pallet::type_value] - pub(crate) fn HistoryDepthOnEmpty() -> u32 { - 84u32 - } - - /// Number of eras to keep in history. - /// - /// Information is kept for eras in `[current_era - history_depth; current_era]`. - /// - /// Must be more than the number of eras delayed by session otherwise. I.e. active era must - /// always be in history. I.e. `active_era > current_era - history_depth` must be - /// guaranteed. - #[pallet::storage] - #[pallet::getter(fn history_depth)] - pub(crate) type HistoryDepth = StorageValue<_, u32, ValueQuery, HistoryDepthOnEmpty>; - /// The ideal number of staking participants. #[pallet::storage] #[pallet::getter(fn validator_count)] @@ -261,6 +268,7 @@ pub mod pallet { /// invulnerables) and restricted to testnets. #[pallet::storage] #[pallet::getter(fn invulnerables)] + #[pallet::unbounded] pub type Invulnerables = StorageValue<_, Vec, ValueQuery>; /// Map from all locked "stash" accounts to the controller account. @@ -364,6 +372,7 @@ pub mod pallet { /// If stakers hasn't been set or has been removed then empty exposure is returned. #[pallet::storage] #[pallet::getter(fn eras_stakers)] + #[pallet::unbounded] pub type ErasStakers = StorageDoubleMap< _, Twox64Concat, @@ -386,6 +395,7 @@ pub mod pallet { /// Is it removed after `HISTORY_DEPTH` eras. /// If stakers hasn't been set or has been removed then empty exposure is returned. #[pallet::storage] + #[pallet::unbounded] #[pallet::getter(fn eras_stakers_clipped)] pub type ErasStakersClipped = StorageDoubleMap< _, @@ -425,6 +435,7 @@ pub mod pallet { /// Rewards for the last `HISTORY_DEPTH` eras. /// If reward hasn't been set or has been removed then 0 reward is returned. #[pallet::storage] + #[pallet::unbounded] #[pallet::getter(fn eras_reward_points)] pub type ErasRewardPoints = StorageMap<_, Twox64Concat, EraIndex, EraRewardPoints, ValueQuery>; @@ -456,6 +467,7 @@ pub mod pallet { /// All unapplied slashes that are queued for later. #[pallet::storage] + #[pallet::unbounded] pub type UnappliedSlashes = StorageMap< _, Twox64Concat, @@ -469,6 +481,7 @@ pub mod pallet { /// Must contains information for eras for the range: /// `[active_era - bounding_duration; active_era]` #[pallet::storage] + #[pallet::unbounded] pub(crate) type BondedEras = StorageValue<_, Vec<(EraIndex, SessionIndex)>, ValueQuery>; @@ -491,6 +504,8 @@ pub mod pallet { /// Slashing spans for stash accounts. #[pallet::storage] + #[pallet::getter(fn slashing_spans)] + #[pallet::unbounded] pub(crate) type SlashingSpans = StorageMap<_, Twox64Concat, T::AccountId, slashing::SlashingSpans>; @@ -522,6 +537,7 @@ pub mod pallet { /// whether a given validator has previously offended using binary search. It gets cleared when /// the era ends. #[pallet::storage] + #[pallet::unbounded] #[pallet::getter(fn offending_validators)] pub type OffendingValidators = StorageValue<_, Vec<(u32, bool)>, ValueQuery>; @@ -540,7 +556,6 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig { - pub history_depth: u32, pub validator_count: u32, pub minimum_validator_count: u32, pub invulnerables: Vec, @@ -559,7 +574,6 @@ pub mod pallet { impl Default for GenesisConfig { fn default() -> Self { GenesisConfig { - history_depth: 84u32, validator_count: Default::default(), minimum_validator_count: Default::default(), invulnerables: Default::default(), @@ -578,7 +592,6 @@ pub mod pallet { #[pallet::genesis_build] impl GenesisBuild for GenesisConfig { fn build(&self) { - HistoryDepth::::put(self.history_depth); ValidatorCount::::put(self.validator_count); MinimumValidatorCount::::put(self.minimum_validator_count); Invulnerables::::put(&self.invulnerables); @@ -608,18 +621,18 @@ pub mod pallet { "Stash does not have enough balance to bond." ); frame_support::assert_ok!(>::bond( - T::Origin::from(Some(stash.clone()).into()), + T::RuntimeOrigin::from(Some(stash.clone()).into()), T::Lookup::unlookup(controller.clone()), balance, RewardDestination::Staked, )); frame_support::assert_ok!(match status { crate::StakerStatus::Validator => >::validate( - T::Origin::from(Some(controller.clone()).into()), + T::RuntimeOrigin::from(Some(controller.clone()).into()), Default::default(), ), crate::StakerStatus::Nominator(votes) => >::nominate( - T::Origin::from(Some(controller.clone()).into()), + T::RuntimeOrigin::from(Some(controller.clone()).into()), votes.iter().map(|l| T::Lookup::unlookup(l.clone())).collect(), ), _ => Ok(()), @@ -644,8 +657,8 @@ pub mod pallet { EraPaid(EraIndex, BalanceOf, BalanceOf), /// The nominator has been rewarded by this amount. \[stash, amount\] Rewarded(T::AccountId, BalanceOf), - /// One validator (and its nominators) has been slashed by the given amount. - /// \[validator, amount\] + /// One staker (and potentially its nominators) has been slashed by the given amount. + /// \[staker, amount\] Slashed(T::AccountId, BalanceOf), /// An old slashing report from a prior era was discarded because it could /// not be processed. \[session_index\] @@ -729,6 +742,8 @@ pub mod pallet { TooManyValidators, /// Commission is too low. Must be at least `MinCommission`. CommissionTooLow, + /// Some bound is not met. + BoundNotMet, } #[pallet::hooks] @@ -830,7 +845,7 @@ pub mod pallet { >::insert(&stash, payee); let current_era = CurrentEra::::get().unwrap_or(0); - let history_depth = Self::history_depth(); + let history_depth = T::HistoryDepth::get(); let last_reward_era = current_era.saturating_sub(history_depth); let stash_balance = T::Currency::free_balance(&stash); @@ -841,7 +856,12 @@ pub mod pallet { total: value, active: value, unlocking: Default::default(), - claimed_rewards: (last_reward_era..current_era).collect(), + claimed_rewards: (last_reward_era..current_era) + .try_collect() + // Since last_reward_era is calculated as `current_era - + // HistoryDepth`, following bound is always expected to be + // satisfied. + .defensive_map_err(|_| Error::::BoundNotMet)?, }; Self::update_ledger(&controller, &item); Ok(()) @@ -1466,48 +1486,6 @@ pub mod pallet { Ok(Some(T::WeightInfo::rebond(removed_chunks)).into()) } - /// Set `HistoryDepth` value. This function will delete any history information - /// when `HistoryDepth` is reduced. - /// - /// Parameters: - /// - `new_history_depth`: The new history depth you would like to set. - /// - `era_items_deleted`: The number of items that will be deleted by this dispatch. This - /// should report all the storage items that will be deleted by clearing old era history. - /// Needed to report an accurate weight for the dispatch. Trusted by `Root` to report an - /// accurate number. - /// - /// Origin must be root. - /// - /// # - /// - E: Number of history depths removed, i.e. 10 -> 7 = 3 - /// - Weight: O(E) - /// - DB Weight: - /// - Reads: Current Era, History Depth - /// - Writes: History Depth - /// - Clear Prefix Each: Era Stakers, EraStakersClipped, ErasValidatorPrefs - /// - Writes Each: ErasValidatorReward, ErasRewardPoints, ErasTotalStake, - /// ErasStartSessionIndex - /// # - #[pallet::weight(T::WeightInfo::set_history_depth(*_era_items_deleted))] - pub fn set_history_depth( - origin: OriginFor, - #[pallet::compact] new_history_depth: EraIndex, - #[pallet::compact] _era_items_deleted: u32, - ) -> DispatchResult { - ensure_root(origin)?; - if let Some(current_era) = Self::current_era() { - HistoryDepth::::mutate(|history_depth| { - let last_kept = current_era.saturating_sub(*history_depth); - let new_last_kept = current_era.saturating_sub(new_history_depth); - for era_index in last_kept..new_last_kept { - Self::clear_era_information(era_index); - } - *history_depth = new_history_depth - }) - } - Ok(()) - } - /// Remove all data structures concerning a staker/stash once it is at a state where it can /// be considered `dust` in the staking system. The requirements are: /// @@ -1593,7 +1571,7 @@ pub mod pallet { /// * `min_commission`: The minimum amount of commission that each validators must maintain. /// This is checked only upon calling `validate`. Existing validators are not affected. /// - /// Origin must be Root to call this function. + /// RuntimeOrigin must be Root to call this function. /// /// NOTE: Existing nominators and validators will not be affected by this update. /// to kick people under the new limits, `chill_other` should be called. diff --git a/frame/staking/src/slashing.rs b/frame/staking/src/slashing.rs index 7372c4390f816..f3272a25fab5c 100644 --- a/frame/staking/src/slashing.rs +++ b/frame/staking/src/slashing.rs @@ -53,7 +53,7 @@ use crate::{ BalanceOf, Config, Error, Exposure, NegativeImbalanceOf, Pallet, Perbill, SessionInterface, Store, UnappliedSlash, }; -use codec::{Decode, Encode}; +use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ ensure, traits::{Currency, Defensive, Get, Imbalance, OnUnbalanced}, @@ -182,7 +182,7 @@ impl SlashingSpans { } /// A slashing-span record for a particular stash. -#[derive(Encode, Decode, Default, TypeInfo)] +#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)] pub(crate) struct SpanRecord { slashed: Balance, paid_out: Balance, diff --git a/frame/staking/src/tests.rs b/frame/staking/src/tests.rs index 85badfac769af..6798a78030f9e 100644 --- a/frame/staking/src/tests.rs +++ b/frame/staking/src/tests.rs @@ -44,7 +44,7 @@ fn set_staking_configs_works() { ExtBuilder::default().build_and_execute(|| { // setting works assert_ok!(Staking::set_staking_configs( - Origin::root(), + RuntimeOrigin::root(), ConfigOp::Set(1_500), ConfigOp::Set(2_000), ConfigOp::Set(10), @@ -61,7 +61,7 @@ fn set_staking_configs_works() { // noop does nothing assert_storage_noop!(assert_ok!(Staking::set_staking_configs( - Origin::root(), + RuntimeOrigin::root(), ConfigOp::Noop, ConfigOp::Noop, ConfigOp::Noop, @@ -72,7 +72,7 @@ fn set_staking_configs_works() { // removing works assert_ok!(Staking::set_staking_configs( - Origin::root(), + RuntimeOrigin::root(), ConfigOp::Remove, ConfigOp::Remove, ConfigOp::Remove, @@ -98,22 +98,22 @@ fn force_unstake_works() { add_slash(&11); // Cant transfer assert_noop!( - Balances::transfer(Origin::signed(11), 1, 10), + Balances::transfer(RuntimeOrigin::signed(11), 1, 10), BalancesError::::LiquidityRestrictions ); // Force unstake requires root. - assert_noop!(Staking::force_unstake(Origin::signed(11), 11, 2), BadOrigin); + assert_noop!(Staking::force_unstake(RuntimeOrigin::signed(11), 11, 2), BadOrigin); // Force unstake needs correct number of slashing spans (for weight calculation) assert_noop!( - Staking::force_unstake(Origin::root(), 11, 0), + Staking::force_unstake(RuntimeOrigin::root(), 11, 0), Error::::IncorrectSlashingSpans ); // We now force them to unstake - assert_ok!(Staking::force_unstake(Origin::root(), 11, 2)); + assert_ok!(Staking::force_unstake(RuntimeOrigin::root(), 11, 2)); // No longer bonded. assert_eq!(Staking::bonded(&11), None); // Transfer works. - assert_ok!(Balances::transfer(Origin::signed(11), 1, 10)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(11), 1, 10)); }); } @@ -148,14 +148,14 @@ fn basic_setup_works() { // Account 10 controls the stash from account 11, which is 100 * balance_factor units assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { + Staking::ledger(&10).unwrap(), + StakingLedger { stash: 11, total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: vec![] - }) + claimed_rewards: bounded_vec![], + } ); // Account 20 controls the stash from account 21, which is 200 * balance_factor units assert_eq!( @@ -165,7 +165,7 @@ fn basic_setup_works() { total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: vec![] + claimed_rewards: bounded_vec![], }) ); // Account 1 does not control any stash @@ -188,7 +188,7 @@ fn basic_setup_works() { total: 500, active: 500, unlocking: Default::default(), - claimed_rewards: vec![] + claimed_rewards: bounded_vec![], }) ); assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); @@ -235,19 +235,19 @@ fn change_controller_works() { assert_eq!(Staking::bonded(&11), Some(10)); // 10 can control 11 who is initially a validator. - assert_ok!(Staking::chill(Origin::signed(10))); + assert_ok!(Staking::chill(RuntimeOrigin::signed(10))); // change controller - assert_ok!(Staking::set_controller(Origin::signed(11), 5)); + assert_ok!(Staking::set_controller(RuntimeOrigin::signed(11), 5)); assert_eq!(Staking::bonded(&11), Some(5)); mock::start_active_era(1); // 10 is no longer in control. assert_noop!( - Staking::validate(Origin::signed(10), ValidatorPrefs::default()), + Staking::validate(RuntimeOrigin::signed(10), ValidatorPrefs::default()), Error::::NotController, ); - assert_ok!(Staking::validate(Origin::signed(5), ValidatorPrefs::default())); + assert_ok!(Staking::validate(RuntimeOrigin::signed(5), ValidatorPrefs::default())); }) } @@ -382,9 +382,13 @@ fn staking_should_work() { // --- Block 2: start_session(2); // add a new candidate for being a validator. account 3 controlled by 4. - assert_ok!(Staking::bond(Origin::signed(3), 4, 1500, RewardDestination::Controller)); - assert_ok!(Staking::validate(Origin::signed(4), ValidatorPrefs::default())); - assert_ok!(Session::set_keys(Origin::signed(4), SessionKeys { other: 4.into() }, vec![])); + assert_ok!(Staking::bond(RuntimeOrigin::signed(3), 4, 1500, RewardDestination::Controller)); + assert_ok!(Staking::validate(RuntimeOrigin::signed(4), ValidatorPrefs::default())); + assert_ok!(Session::set_keys( + RuntimeOrigin::signed(4), + SessionKeys { other: 4.into() }, + vec![] + )); // No effects will be seen so far. assert_eq_uvec!(validator_controllers(), vec![20, 10]); @@ -408,7 +412,7 @@ fn staking_should_work() { assert_eq_uvec!(validator_controllers(), vec![20, 4]); // --- Block 6: Unstake 4 as a validator, freeing up the balance stashed in 3 // 4 will chill - Staking::chill(Origin::signed(4)).unwrap(); + Staking::chill(RuntimeOrigin::signed(4)).unwrap(); // --- Block 7: nothing. 4 is still there. start_session(7); @@ -429,7 +433,7 @@ fn staking_should_work() { total: 1500, active: 1500, unlocking: Default::default(), - claimed_rewards: vec![0], + claimed_rewards: bounded_vec![0], }) ); // e.g. it cannot reserve more than 500 that it has free from the total 2000 @@ -447,20 +451,20 @@ fn blocking_and_kicking_works() { .build_and_execute(|| { // block validator 10/11 assert_ok!(Staking::validate( - Origin::signed(10), + RuntimeOrigin::signed(10), ValidatorPrefs { blocked: true, ..Default::default() } )); // attempt to nominate from 100/101... - assert_ok!(Staking::nominate(Origin::signed(100), vec![11])); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(100), vec![11])); // should have worked since we're already nominated them assert_eq!(Nominators::::get(&101).unwrap().targets, vec![11]); // kick the nominator - assert_ok!(Staking::kick(Origin::signed(10), vec![101])); + assert_ok!(Staking::kick(RuntimeOrigin::signed(10), vec![101])); // should have been kicked now assert!(Nominators::::get(&101).unwrap().targets.is_empty()); // attempt to nominate from 100/101... assert_noop!( - Staking::nominate(Origin::signed(100), vec![11]), + Staking::nominate(RuntimeOrigin::signed(100), vec![11]), Error::::BadTarget ); }); @@ -506,7 +510,7 @@ fn no_candidate_emergency_condition() { ::MinimumValidatorCount::put(10); // try to chill - let res = Staking::chill(Origin::signed(10)); + let res = Staking::chill(RuntimeOrigin::signed(10)); assert_ok!(res); let current_era = CurrentEra::::get(); @@ -542,14 +546,26 @@ fn nominating_and_rewards_should_work() { assert_eq_uvec!(validator_controllers(), vec![40, 20]); // re-validate with 11 and 31. - assert_ok!(Staking::validate(Origin::signed(10), Default::default())); - assert_ok!(Staking::validate(Origin::signed(30), Default::default())); + assert_ok!(Staking::validate(RuntimeOrigin::signed(10), Default::default())); + assert_ok!(Staking::validate(RuntimeOrigin::signed(30), Default::default())); // Set payee to controller. - assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); - assert_ok!(Staking::set_payee(Origin::signed(20), RewardDestination::Controller)); - assert_ok!(Staking::set_payee(Origin::signed(30), RewardDestination::Controller)); - assert_ok!(Staking::set_payee(Origin::signed(40), RewardDestination::Controller)); + assert_ok!(Staking::set_payee( + RuntimeOrigin::signed(10), + RewardDestination::Controller + )); + assert_ok!(Staking::set_payee( + RuntimeOrigin::signed(20), + RewardDestination::Controller + )); + assert_ok!(Staking::set_payee( + RuntimeOrigin::signed(30), + RewardDestination::Controller + )); + assert_ok!(Staking::set_payee( + RuntimeOrigin::signed(40), + RewardDestination::Controller + )); // give the man some money let initial_balance = 1000; @@ -558,11 +574,21 @@ fn nominating_and_rewards_should_work() { } // bond two account pairs and state interest in nomination. - assert_ok!(Staking::bond(Origin::signed(1), 2, 1000, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(2), vec![11, 21, 31])); + assert_ok!(Staking::bond( + RuntimeOrigin::signed(1), + 2, + 1000, + RewardDestination::Controller + )); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(2), vec![11, 21, 31])); - assert_ok!(Staking::bond(Origin::signed(3), 4, 1000, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(4), vec![11, 21, 41])); + assert_ok!(Staking::bond( + RuntimeOrigin::signed(3), + 4, + 1000, + RewardDestination::Controller + )); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(4), vec![11, 21, 41])); // the total reward for era 0 let total_payout_0 = current_total_payout_for_duration(reward_time_per_era()); @@ -714,20 +740,28 @@ fn double_staking_should_fail() { let arbitrary_value = 5; // 2 = controller, 1 stashed => ok assert_ok!(Staking::bond( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, arbitrary_value, RewardDestination::default() )); // 4 = not used so far, 1 stashed => not allowed. assert_noop!( - Staking::bond(Origin::signed(1), 4, arbitrary_value, RewardDestination::default()), + Staking::bond( + RuntimeOrigin::signed(1), + 4, + arbitrary_value, + RewardDestination::default() + ), Error::::AlreadyBonded, ); // 1 = stashed => attempting to nominate should fail. - assert_noop!(Staking::nominate(Origin::signed(1), vec![1]), Error::::NotController); + assert_noop!( + Staking::nominate(RuntimeOrigin::signed(1), vec![1]), + Error::::NotController + ); // 2 = controller => nominating should work. - assert_ok!(Staking::nominate(Origin::signed(2), vec![1])); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(2), vec![1])); }); } @@ -740,14 +774,19 @@ fn double_controlling_should_fail() { let arbitrary_value = 5; // 2 = controller, 1 stashed => ok assert_ok!(Staking::bond( - Origin::signed(1), + RuntimeOrigin::signed(1), 2, arbitrary_value, RewardDestination::default(), )); // 2 = controller, 3 stashed (Note that 2 is reused.) => no-op assert_noop!( - Staking::bond(Origin::signed(3), 2, arbitrary_value, RewardDestination::default()), + Staking::bond( + RuntimeOrigin::signed(3), + 2, + arbitrary_value, + RewardDestination::default() + ), Error::::AlreadyPaired, ); }); @@ -913,14 +952,14 @@ fn cannot_transfer_staked_balance() { assert_eq!(Staking::eras_stakers(active_era(), 11).total, 1000); // Confirm account 11 cannot transfer as a result assert_noop!( - Balances::transfer(Origin::signed(11), 20, 1), + Balances::transfer(RuntimeOrigin::signed(11), 20, 1), BalancesError::::LiquidityRestrictions ); // Give account 11 extra free balance let _ = Balances::make_free_balance_be(&11, 10000); // Confirm that account 11 can now transfer some balance - assert_ok!(Balances::transfer(Origin::signed(11), 20, 1)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(11), 20, 1)); }); } @@ -938,10 +977,10 @@ fn cannot_transfer_staked_balance_2() { assert_eq!(Staking::eras_stakers(active_era(), 21).total, 1000); // Confirm account 21 can transfer at most 1000 assert_noop!( - Balances::transfer(Origin::signed(21), 20, 1001), + Balances::transfer(RuntimeOrigin::signed(21), 20, 1001), BalancesError::::LiquidityRestrictions ); - assert_ok!(Balances::transfer(Origin::signed(21), 20, 1000)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(21), 20, 1000)); }); } @@ -983,7 +1022,7 @@ fn reward_destination_works() { total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); @@ -1006,7 +1045,7 @@ fn reward_destination_works() { total: 1000 + total_payout_0, active: 1000 + total_payout_0, unlocking: Default::default(), - claimed_rewards: vec![0], + claimed_rewards: bounded_vec![0], }) ); @@ -1034,7 +1073,7 @@ fn reward_destination_works() { total: 1000 + total_payout_0, active: 1000 + total_payout_0, unlocking: Default::default(), - claimed_rewards: vec![0, 1], + claimed_rewards: bounded_vec![0, 1], }) ); @@ -1063,7 +1102,7 @@ fn reward_destination_works() { total: 1000 + total_payout_0, active: 1000 + total_payout_0, unlocking: Default::default(), - claimed_rewards: vec![0, 1, 2], + claimed_rewards: bounded_vec![0, 1, 2], }) ); // Check that amount in staked account is NOT increased. @@ -1125,7 +1164,7 @@ fn bond_extra_works() { total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); @@ -1133,7 +1172,7 @@ fn bond_extra_works() { let _ = Balances::make_free_balance_be(&11, 1000000); // Call the bond_extra function from controller, add only 100 - assert_ok!(Staking::bond_extra(Origin::signed(11), 100)); + assert_ok!(Staking::bond_extra(RuntimeOrigin::signed(11), 100)); // There should be 100 more `total` and `active` in the ledger assert_eq!( Staking::ledger(&10), @@ -1142,12 +1181,12 @@ fn bond_extra_works() { total: 1000 + 100, active: 1000 + 100, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); // Call the bond_extra function with a large number, should handle it - assert_ok!(Staking::bond_extra(Origin::signed(11), Balance::max_value())); + assert_ok!(Staking::bond_extra(RuntimeOrigin::signed(11), Balance::max_value())); // The full amount of the funds should now be in the total and active assert_eq!( Staking::ledger(&10), @@ -1156,7 +1195,7 @@ fn bond_extra_works() { total: 1000000, active: 1000000, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); }); @@ -1172,7 +1211,7 @@ fn bond_extra_and_withdraw_unbonded_works() { // * Once the unbonding period is done, it can actually take the funds out of the stash. ExtBuilder::default().nominate(false).build_and_execute(|| { // Set payee to controller. avoids confusion - assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); + assert_ok!(Staking::set_payee(RuntimeOrigin::signed(10), RewardDestination::Controller)); // Give account 11 some large free balance greater than total let _ = Balances::make_free_balance_be(&11, 1000000); @@ -1194,7 +1233,7 @@ fn bond_extra_and_withdraw_unbonded_works() { total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); assert_eq!( @@ -1203,7 +1242,7 @@ fn bond_extra_and_withdraw_unbonded_works() { ); // deposit the extra 100 units - Staking::bond_extra(Origin::signed(11), 100).unwrap(); + Staking::bond_extra(RuntimeOrigin::signed(11), 100).unwrap(); assert_eq!( Staking::ledger(&10), @@ -1212,7 +1251,7 @@ fn bond_extra_and_withdraw_unbonded_works() { total: 1000 + 100, active: 1000 + 100, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); // Exposure is a snapshot! only updated after the next era update. @@ -1233,7 +1272,7 @@ fn bond_extra_and_withdraw_unbonded_works() { total: 1000 + 100, active: 1000 + 100, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); // Exposure is now updated. @@ -1243,7 +1282,7 @@ fn bond_extra_and_withdraw_unbonded_works() { ); // Unbond almost all of the funds in stash. - Staking::unbond(Origin::signed(10), 1000).unwrap(); + Staking::unbond(RuntimeOrigin::signed(10), 1000).unwrap(); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1251,12 +1290,12 @@ fn bond_extra_and_withdraw_unbonded_works() { total: 1000 + 100, active: 100, unlocking: bounded_vec![UnlockChunk { value: 1000, era: 2 + 3 }], - claimed_rewards: vec![] + claimed_rewards: bounded_vec![], }), ); // Attempting to free the balances now will fail. 2 eras need to pass. - assert_ok!(Staking::withdraw_unbonded(Origin::signed(10), 0)); + assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(10), 0)); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1264,7 +1303,7 @@ fn bond_extra_and_withdraw_unbonded_works() { total: 1000 + 100, active: 100, unlocking: bounded_vec![UnlockChunk { value: 1000, era: 2 + 3 }], - claimed_rewards: vec![] + claimed_rewards: bounded_vec![], }), ); @@ -1272,7 +1311,7 @@ fn bond_extra_and_withdraw_unbonded_works() { mock::start_active_era(3); // nothing yet - assert_ok!(Staking::withdraw_unbonded(Origin::signed(10), 0)); + assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(10), 0)); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1280,14 +1319,14 @@ fn bond_extra_and_withdraw_unbonded_works() { total: 1000 + 100, active: 100, unlocking: bounded_vec![UnlockChunk { value: 1000, era: 2 + 3 }], - claimed_rewards: vec![] + claimed_rewards: bounded_vec![], }), ); // trigger next era. mock::start_active_era(5); - assert_ok!(Staking::withdraw_unbonded(Origin::signed(10), 0)); + assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(10), 0)); // Now the value is free and the staking ledger is updated. assert_eq!( Staking::ledger(&10), @@ -1296,7 +1335,7 @@ fn bond_extra_and_withdraw_unbonded_works() { total: 100, active: 100, unlocking: Default::default(), - claimed_rewards: vec![] + claimed_rewards: bounded_vec![], }), ); }) @@ -1311,7 +1350,7 @@ fn too_many_unbond_calls_should_not_work() { // There is only 1 chunk per era, so we need to be in a new era to create a chunk. current_era = i as u32; mock::start_active_era(current_era); - assert_ok!(Staking::unbond(Origin::signed(10), 1)); + assert_ok!(Staking::unbond(RuntimeOrigin::signed(10), 1)); } current_era += 1; @@ -1319,24 +1358,24 @@ fn too_many_unbond_calls_should_not_work() { // This chunk is locked at `current_era` through `current_era + 2` (because BondingDuration // == 3). - assert_ok!(Staking::unbond(Origin::signed(10), 1)); + assert_ok!(Staking::unbond(RuntimeOrigin::signed(10), 1)); assert_eq!( Staking::ledger(&10).unwrap().unlocking.len(), MaxUnlockingChunks::get() as usize ); // can't do more. - assert_noop!(Staking::unbond(Origin::signed(10), 1), Error::::NoMoreChunks); + assert_noop!(Staking::unbond(RuntimeOrigin::signed(10), 1), Error::::NoMoreChunks); current_era += 2; mock::start_active_era(current_era); - assert_noop!(Staking::unbond(Origin::signed(10), 1), Error::::NoMoreChunks); + assert_noop!(Staking::unbond(RuntimeOrigin::signed(10), 1), Error::::NoMoreChunks); // free up everything except the most recently added chunk. - assert_ok!(Staking::withdraw_unbonded(Origin::signed(10), 0)); + assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(10), 0)); assert_eq!(Staking::ledger(&10).unwrap().unlocking.len(), 1); // Can add again. - assert_ok!(Staking::unbond(Origin::signed(10), 1)); + assert_ok!(Staking::unbond(RuntimeOrigin::signed(10), 1)); assert_eq!(Staking::ledger(&10).unwrap().unlocking.len(), 2); }) } @@ -1350,7 +1389,7 @@ fn rebond_works() { // * it can re-bond a portion of the funds scheduled to unlock. ExtBuilder::default().nominate(false).build_and_execute(|| { // Set payee to controller. avoids confusion - assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); + assert_ok!(Staking::set_payee(RuntimeOrigin::signed(10), RewardDestination::Controller)); // Give account 11 some large free balance greater than total let _ = Balances::make_free_balance_be(&11, 1000000); @@ -1366,7 +1405,7 @@ fn rebond_works() { total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); @@ -1374,10 +1413,10 @@ fn rebond_works() { assert_eq!(active_era(), 2); // Try to rebond some funds. We get an error since no fund is unbonded. - assert_noop!(Staking::rebond(Origin::signed(10), 500), Error::::NoUnlockChunk); + assert_noop!(Staking::rebond(RuntimeOrigin::signed(10), 500), Error::::NoUnlockChunk); // Unbond almost all of the funds in stash. - Staking::unbond(Origin::signed(10), 900).unwrap(); + Staking::unbond(RuntimeOrigin::signed(10), 900).unwrap(); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1385,12 +1424,12 @@ fn rebond_works() { total: 1000, active: 100, unlocking: bounded_vec![UnlockChunk { value: 900, era: 2 + 3 }], - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); // Re-bond all the funds unbonded. - Staking::rebond(Origin::signed(10), 900).unwrap(); + Staking::rebond(RuntimeOrigin::signed(10), 900).unwrap(); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1398,12 +1437,12 @@ fn rebond_works() { total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); // Unbond almost all of the funds in stash. - Staking::unbond(Origin::signed(10), 900).unwrap(); + Staking::unbond(RuntimeOrigin::signed(10), 900).unwrap(); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1411,12 +1450,12 @@ fn rebond_works() { total: 1000, active: 100, unlocking: bounded_vec![UnlockChunk { value: 900, era: 5 }], - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); // Re-bond part of the funds unbonded. - Staking::rebond(Origin::signed(10), 500).unwrap(); + Staking::rebond(RuntimeOrigin::signed(10), 500).unwrap(); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1424,12 +1463,12 @@ fn rebond_works() { total: 1000, active: 600, unlocking: bounded_vec![UnlockChunk { value: 400, era: 5 }], - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); // Re-bond the remainder of the funds unbonded. - Staking::rebond(Origin::signed(10), 500).unwrap(); + Staking::rebond(RuntimeOrigin::signed(10), 500).unwrap(); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1437,14 +1476,14 @@ fn rebond_works() { total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); // Unbond parts of the funds in stash. - Staking::unbond(Origin::signed(10), 300).unwrap(); - Staking::unbond(Origin::signed(10), 300).unwrap(); - Staking::unbond(Origin::signed(10), 300).unwrap(); + Staking::unbond(RuntimeOrigin::signed(10), 300).unwrap(); + Staking::unbond(RuntimeOrigin::signed(10), 300).unwrap(); + Staking::unbond(RuntimeOrigin::signed(10), 300).unwrap(); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1452,12 +1491,12 @@ fn rebond_works() { total: 1000, active: 100, unlocking: bounded_vec![UnlockChunk { value: 900, era: 5 }], - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); // Re-bond part of the funds unbonded. - Staking::rebond(Origin::signed(10), 500).unwrap(); + Staking::rebond(RuntimeOrigin::signed(10), 500).unwrap(); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1465,7 +1504,7 @@ fn rebond_works() { total: 1000, active: 600, unlocking: bounded_vec![UnlockChunk { value: 400, era: 5 }], - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); }) @@ -1476,7 +1515,7 @@ fn rebond_is_fifo() { // Rebond should proceed by reversing the most recent bond operations. ExtBuilder::default().nominate(false).build_and_execute(|| { // Set payee to controller. avoids confusion - assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); + assert_ok!(Staking::set_payee(RuntimeOrigin::signed(10), RewardDestination::Controller)); // Give account 11 some large free balance greater than total let _ = Balances::make_free_balance_be(&11, 1000000); @@ -1492,14 +1531,14 @@ fn rebond_is_fifo() { total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); mock::start_active_era(2); // Unbond some of the funds in stash. - Staking::unbond(Origin::signed(10), 400).unwrap(); + Staking::unbond(RuntimeOrigin::signed(10), 400).unwrap(); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1507,14 +1546,14 @@ fn rebond_is_fifo() { total: 1000, active: 600, unlocking: bounded_vec![UnlockChunk { value: 400, era: 2 + 3 }], - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); mock::start_active_era(3); // Unbond more of the funds in stash. - Staking::unbond(Origin::signed(10), 300).unwrap(); + Staking::unbond(RuntimeOrigin::signed(10), 300).unwrap(); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1525,14 +1564,14 @@ fn rebond_is_fifo() { UnlockChunk { value: 400, era: 2 + 3 }, UnlockChunk { value: 300, era: 3 + 3 }, ], - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); mock::start_active_era(4); // Unbond yet more of the funds in stash. - Staking::unbond(Origin::signed(10), 200).unwrap(); + Staking::unbond(RuntimeOrigin::signed(10), 200).unwrap(); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1544,12 +1583,12 @@ fn rebond_is_fifo() { UnlockChunk { value: 300, era: 3 + 3 }, UnlockChunk { value: 200, era: 4 + 3 }, ], - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); // Re-bond half of the unbonding funds. - Staking::rebond(Origin::signed(10), 400).unwrap(); + Staking::rebond(RuntimeOrigin::signed(10), 400).unwrap(); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1560,7 +1599,7 @@ fn rebond_is_fifo() { UnlockChunk { value: 400, era: 2 + 3 }, UnlockChunk { value: 100, era: 3 + 3 }, ], - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); }) @@ -1572,7 +1611,7 @@ fn rebond_emits_right_value_in_event() { // and the rebond event emits the actual value rebonded. ExtBuilder::default().nominate(false).build_and_execute(|| { // Set payee to controller. avoids confusion - assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); + assert_ok!(Staking::set_payee(RuntimeOrigin::signed(10), RewardDestination::Controller)); // Give account 11 some large free balance greater than total let _ = Balances::make_free_balance_be(&11, 1000000); @@ -1581,7 +1620,7 @@ fn rebond_emits_right_value_in_event() { mock::start_active_era(1); // Unbond almost all of the funds in stash. - Staking::unbond(Origin::signed(10), 900).unwrap(); + Staking::unbond(RuntimeOrigin::signed(10), 900).unwrap(); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1589,12 +1628,12 @@ fn rebond_emits_right_value_in_event() { total: 1000, active: 100, unlocking: bounded_vec![UnlockChunk { value: 900, era: 1 + 3 }], - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); // Re-bond less than the total - Staking::rebond(Origin::signed(10), 100).unwrap(); + Staking::rebond(RuntimeOrigin::signed(10), 100).unwrap(); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1602,14 +1641,14 @@ fn rebond_emits_right_value_in_event() { total: 1000, active: 200, unlocking: bounded_vec![UnlockChunk { value: 800, era: 1 + 3 }], - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); // Event emitted should be correct assert_eq!(*staking_events().last().unwrap(), Event::Bonded(11, 100)); // Re-bond way more than available - Staking::rebond(Origin::signed(10), 100_000).unwrap(); + Staking::rebond(RuntimeOrigin::signed(10), 100_000).unwrap(); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -1617,7 +1656,7 @@ fn rebond_emits_right_value_in_event() { total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); // Event emitted should be correct, only 800 @@ -1653,7 +1692,7 @@ fn reward_to_stake_works() { total: 69, active: 69, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }, ); @@ -1699,11 +1738,14 @@ fn reap_stash_works() { // stash is not reapable assert_noop!( - Staking::reap_stash(Origin::signed(20), 11, 0), + Staking::reap_stash(RuntimeOrigin::signed(20), 11, 0), Error::::FundedTarget ); // controller or any other account is not reapable - assert_noop!(Staking::reap_stash(Origin::signed(20), 10, 0), Error::::NotStash); + assert_noop!( + Staking::reap_stash(RuntimeOrigin::signed(20), 10, 0), + Error::::NotStash + ); // no easy way to cause an account to go below ED, we tweak their staking ledger // instead. @@ -1714,12 +1756,12 @@ fn reap_stash_works() { total: 5, active: 5, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }, ); // reap-able - assert_ok!(Staking::reap_stash(Origin::signed(20), 11, 0)); + assert_ok!(Staking::reap_stash(RuntimeOrigin::signed(20), 11, 0)); // then assert!(!>::contains_key(&10)); @@ -1736,7 +1778,10 @@ fn switching_roles() { ExtBuilder::default().nominate(false).build_and_execute(|| { // Reset reward destination for i in &[10, 20] { - assert_ok!(Staking::set_payee(Origin::signed(*i), RewardDestination::Controller)); + assert_ok!(Staking::set_payee( + RuntimeOrigin::signed(*i), + RewardDestination::Controller + )); } assert_eq_uvec!(validator_controllers(), vec![20, 10]); @@ -1747,16 +1792,20 @@ fn switching_roles() { } // add 2 nominators - assert_ok!(Staking::bond(Origin::signed(1), 2, 2000, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(2), vec![11, 5])); + assert_ok!(Staking::bond(RuntimeOrigin::signed(1), 2, 2000, RewardDestination::Controller)); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(2), vec![11, 5])); - assert_ok!(Staking::bond(Origin::signed(3), 4, 500, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(4), vec![21, 1])); + assert_ok!(Staking::bond(RuntimeOrigin::signed(3), 4, 500, RewardDestination::Controller)); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(4), vec![21, 1])); // add a new validator candidate - assert_ok!(Staking::bond(Origin::signed(5), 6, 1000, RewardDestination::Controller)); - assert_ok!(Staking::validate(Origin::signed(6), ValidatorPrefs::default())); - assert_ok!(Session::set_keys(Origin::signed(6), SessionKeys { other: 6.into() }, vec![])); + assert_ok!(Staking::bond(RuntimeOrigin::signed(5), 6, 1000, RewardDestination::Controller)); + assert_ok!(Staking::validate(RuntimeOrigin::signed(6), ValidatorPrefs::default())); + assert_ok!(Session::set_keys( + RuntimeOrigin::signed(6), + SessionKeys { other: 6.into() }, + vec![] + )); mock::start_active_era(1); @@ -1764,8 +1813,12 @@ fn switching_roles() { assert_eq_uvec!(validator_controllers(), vec![6, 10]); // 2 decides to be a validator. Consequences: - assert_ok!(Staking::validate(Origin::signed(2), ValidatorPrefs::default())); - assert_ok!(Session::set_keys(Origin::signed(2), SessionKeys { other: 2.into() }, vec![])); + assert_ok!(Staking::validate(RuntimeOrigin::signed(2), ValidatorPrefs::default())); + assert_ok!(Session::set_keys( + RuntimeOrigin::signed(2), + SessionKeys { other: 2.into() }, + vec![] + )); // new stakes: // 10: 1000 self vote // 20: 1000 self vote + 250 vote @@ -1817,15 +1870,20 @@ fn bond_with_no_staked_value() { .build_and_execute(|| { // Can't bond with 1 assert_noop!( - Staking::bond(Origin::signed(1), 2, 1, RewardDestination::Controller), + Staking::bond(RuntimeOrigin::signed(1), 2, 1, RewardDestination::Controller), Error::::InsufficientBond, ); // bonded with absolute minimum value possible. - assert_ok!(Staking::bond(Origin::signed(1), 2, 5, RewardDestination::Controller)); + assert_ok!(Staking::bond( + RuntimeOrigin::signed(1), + 2, + 5, + RewardDestination::Controller + )); assert_eq!(Balances::locks(&1)[0].amount, 5); // unbonding even 1 will cause all to be unbonded. - assert_ok!(Staking::unbond(Origin::signed(2), 1)); + assert_ok!(Staking::unbond(RuntimeOrigin::signed(2), 1)); assert_eq!( Staking::ledger(2), Some(StakingLedger { @@ -1833,7 +1891,7 @@ fn bond_with_no_staked_value() { active: 0, total: 5, unlocking: bounded_vec![UnlockChunk { value: 5, era: 3 }], - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); @@ -1841,14 +1899,14 @@ fn bond_with_no_staked_value() { mock::start_active_era(2); // not yet removed. - assert_ok!(Staking::withdraw_unbonded(Origin::signed(2), 0)); + assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(2), 0)); assert!(Staking::ledger(2).is_some()); assert_eq!(Balances::locks(&1)[0].amount, 5); mock::start_active_era(3); // poof. Account 1 is removed from the staking system. - assert_ok!(Staking::withdraw_unbonded(Origin::signed(2), 0)); + assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(2), 0)); assert!(Staking::ledger(2).is_none()); assert_eq!(Balances::locks(&1).len(), 0); }); @@ -1862,16 +1920,24 @@ fn bond_with_little_staked_value_bounded() { .minimum_validator_count(1) .build_and_execute(|| { // setup - assert_ok!(Staking::chill(Origin::signed(30))); - assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); + assert_ok!(Staking::chill(RuntimeOrigin::signed(30))); + assert_ok!(Staking::set_payee( + RuntimeOrigin::signed(10), + RewardDestination::Controller + )); let init_balance_2 = Balances::free_balance(&2); let init_balance_10 = Balances::free_balance(&10); // Stingy validator. - assert_ok!(Staking::bond(Origin::signed(1), 2, 1, RewardDestination::Controller)); - assert_ok!(Staking::validate(Origin::signed(2), ValidatorPrefs::default())); + assert_ok!(Staking::bond( + RuntimeOrigin::signed(1), + 2, + 1, + RewardDestination::Controller + )); + assert_ok!(Staking::validate(RuntimeOrigin::signed(2), ValidatorPrefs::default())); assert_ok!(Session::set_keys( - Origin::signed(2), + RuntimeOrigin::signed(2), SessionKeys { other: 2.into() }, vec![] )); @@ -1944,11 +2010,21 @@ fn bond_with_duplicate_vote_should_be_ignored_by_election_provider() { let _ = Balances::make_free_balance_be(i, initial_balance); } - assert_ok!(Staking::bond(Origin::signed(1), 2, 1000, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(2), vec![11, 11, 11, 21, 31])); + assert_ok!(Staking::bond( + RuntimeOrigin::signed(1), + 2, + 1000, + RewardDestination::Controller + )); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(2), vec![11, 11, 11, 21, 31])); - assert_ok!(Staking::bond(Origin::signed(3), 4, 1000, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(4), vec![21, 31])); + assert_ok!(Staking::bond( + RuntimeOrigin::signed(3), + 4, + 1000, + RewardDestination::Controller + )); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(4), vec![21, 31])); // winners should be 21 and 31. Otherwise this election is taking duplicates into // account. @@ -1989,11 +2065,21 @@ fn bond_with_duplicate_vote_should_be_ignored_by_election_provider_elected() { let _ = Balances::make_free_balance_be(i, initial_balance); } - assert_ok!(Staking::bond(Origin::signed(1), 2, 1000, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(2), vec![11, 11, 11, 21])); + assert_ok!(Staking::bond( + RuntimeOrigin::signed(1), + 2, + 1000, + RewardDestination::Controller + )); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(2), vec![11, 11, 11, 21])); - assert_ok!(Staking::bond(Origin::signed(3), 4, 1000, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(4), vec![21])); + assert_ok!(Staking::bond( + RuntimeOrigin::signed(3), + 4, + 1000, + RewardDestination::Controller + )); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(4), vec![21])); // winners should be 21 and 11. let supports = ::ElectionProvider::elect().unwrap(); @@ -2025,8 +2111,8 @@ fn phragmen_should_not_overflow() { // This is the maximum value that we can have as the outcome of CurrencyToVote. type Votes = u64; - let _ = Staking::chill(Origin::signed(10)); - let _ = Staking::chill(Origin::signed(20)); + let _ = Staking::chill(RuntimeOrigin::signed(10)); + let _ = Staking::chill(RuntimeOrigin::signed(20)); bond_validator(3, 2, Votes::max_value() as Balance); bond_validator(5, 4, Votes::max_value() as Balance); @@ -2067,7 +2153,7 @@ fn reward_validator_slashing_validator_does_not_overflow() { ErasStakers::::insert(0, 11, &exposure); ErasStakersClipped::::insert(0, 11, exposure); ErasValidatorReward::::insert(0, stake); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 0)); + assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 0)); assert_eq!(Balances::total_balance(&11), stake * 2); // Set staker @@ -2075,7 +2161,8 @@ fn reward_validator_slashing_validator_does_not_overflow() { let _ = Balances::make_free_balance_be(&2, stake); // only slashes out of bonded stake are applied. without this line, it is 0. - Staking::bond(Origin::signed(2), 20000, stake - 1, RewardDestination::default()).unwrap(); + Staking::bond(RuntimeOrigin::signed(2), 20000, stake - 1, RewardDestination::default()) + .unwrap(); // Override exposure of 11 ErasStakers::::insert( 0, @@ -2151,7 +2238,7 @@ fn unbonded_balance_is_not_slashable() { // total amount staked is slashable. assert_eq!(Staking::slashable_balance_of(&11), 1000); - assert_ok!(Staking::unbond(Origin::signed(10), 800)); + assert_ok!(Staking::unbond(RuntimeOrigin::signed(10), 800)); // only the active portion. assert_eq!(Staking::slashable_balance_of(&11), 200); @@ -2207,7 +2294,7 @@ fn offence_forces_new_era() { #[test] fn offence_ensures_new_era_without_clobbering() { ExtBuilder::default().build_and_execute(|| { - assert_ok!(Staking::force_new_era_always(Origin::root())); + assert_ok!(Staking::force_new_era_always(RuntimeOrigin::root())); assert_eq!(Staking::force_era(), Forcing::ForceAlways); on_offence_now( @@ -2288,7 +2375,7 @@ fn slash_in_old_span_does_not_deselect() { mock::start_active_era(2); - Staking::validate(Origin::signed(10), Default::default()).unwrap(); + Staking::validate(RuntimeOrigin::signed(10), Default::default()).unwrap(); assert_eq!(Staking::force_era(), Forcing::NotForcing); assert!(>::contains_key(11)); assert!(!Session::validators().contains(&11)); @@ -2547,10 +2634,10 @@ fn garbage_collection_after_slashing() { // reap_stash respects num_slashing_spans so that weight is accurate assert_noop!( - Staking::reap_stash(Origin::signed(20), 11, 0), + Staking::reap_stash(RuntimeOrigin::signed(20), 11, 0), Error::::IncorrectSlashingSpans ); - assert_ok!(Staking::reap_stash(Origin::signed(20), 11, 2)); + assert_ok!(Staking::reap_stash(RuntimeOrigin::signed(20), 11, 2)); assert!(::SlashingSpans::get(&11).is_none()); assert_eq!(::SpanSlash::get(&(11, 0)).amount(), &0); @@ -2713,7 +2800,7 @@ fn slashes_are_summed_across_spans() { assert_eq!(Balances::free_balance(21), 1900); // 21 has been force-chilled. re-signal intent to validate. - Staking::validate(Origin::signed(20), Default::default()).unwrap(); + Staking::validate(RuntimeOrigin::signed(20), Default::default()).unwrap(); mock::start_active_era(4); @@ -2832,8 +2919,8 @@ fn retroactive_deferred_slashes_one_before() { // unbond at slash era. mock::start_active_era(2); - assert_ok!(Staking::chill(Origin::signed(10))); - assert_ok!(Staking::unbond(Origin::signed(10), 100)); + assert_ok!(Staking::chill(RuntimeOrigin::signed(10))); + assert_ok!(Staking::unbond(RuntimeOrigin::signed(10), 100)); mock::start_active_era(3); on_offence_in_era( @@ -2865,7 +2952,7 @@ fn retroactive_deferred_slashes_one_before() { // their ledger has already been slashed. assert_eq!(Staking::ledger(10).unwrap().total, 900); - assert_ok!(Staking::unbond(Origin::signed(10), 1000)); + assert_ok!(Staking::unbond(RuntimeOrigin::signed(10), 1000)); assert_eq!(Staking::ledger(10).unwrap().total, 900); }) } @@ -2891,8 +2978,8 @@ fn staker_cannot_bail_deferred_slash() { ); // now we chill - assert_ok!(Staking::chill(Origin::signed(100))); - assert_ok!(Staking::unbond(Origin::signed(100), 500)); + assert_ok!(Staking::chill(RuntimeOrigin::signed(100))); + assert_ok!(Staking::unbond(RuntimeOrigin::signed(100), 500)); assert_eq!(Staking::current_era().unwrap(), 1); assert_eq!(active_era(), 1); @@ -2903,7 +2990,7 @@ fn staker_cannot_bail_deferred_slash() { active: 0, total: 500, stash: 101, - claimed_rewards: Default::default(), + claimed_rewards: bounded_vec![], unlocking: bounded_vec![UnlockChunk { era: 4u32, value: 500 }], } ); @@ -2927,7 +3014,9 @@ fn staker_cannot_bail_deferred_slash() { assert_eq!(active_era(), 3); // and cannot yet unbond: - assert_storage_noop!(assert!(Staking::withdraw_unbonded(Origin::signed(100), 0).is_ok())); + assert_storage_noop!(assert!( + Staking::withdraw_unbonded(RuntimeOrigin::signed(100), 0).is_ok() + )); assert_eq!( Ledger::::get(100).unwrap().unlocking.into_inner(), vec![UnlockChunk { era: 4u32, value: 500 as Balance }], @@ -2976,12 +3065,12 @@ fn remove_deferred() { // fails if empty assert_noop!( - Staking::cancel_deferred_slash(Origin::root(), 1, vec![]), + Staking::cancel_deferred_slash(RuntimeOrigin::root(), 1, vec![]), Error::::EmptyTargets ); // cancel one of them. - assert_ok!(Staking::cancel_deferred_slash(Origin::root(), 4, vec![0])); + assert_ok!(Staking::cancel_deferred_slash(RuntimeOrigin::root(), 4, vec![0])); assert_eq!(Balances::free_balance(11), 1000); assert_eq!(Balances::free_balance(101), 2000); @@ -3062,21 +3151,21 @@ fn remove_multi_deferred() { // fails if list is not sorted assert_noop!( - Staking::cancel_deferred_slash(Origin::root(), 1, vec![2, 0, 4]), + Staking::cancel_deferred_slash(RuntimeOrigin::root(), 1, vec![2, 0, 4]), Error::::NotSortedAndUnique ); // fails if list is not unique assert_noop!( - Staking::cancel_deferred_slash(Origin::root(), 1, vec![0, 2, 2]), + Staking::cancel_deferred_slash(RuntimeOrigin::root(), 1, vec![0, 2, 2]), Error::::NotSortedAndUnique ); // fails if bad index assert_noop!( - Staking::cancel_deferred_slash(Origin::root(), 1, vec![1, 2, 3, 4, 5]), + Staking::cancel_deferred_slash(RuntimeOrigin::root(), 1, vec![1, 2, 3, 4, 5]), Error::::InvalidSlashIndex ); - assert_ok!(Staking::cancel_deferred_slash(Origin::root(), 4, vec![0, 2, 4])); + assert_ok!(Staking::cancel_deferred_slash(RuntimeOrigin::root(), 4, vec![0, 2, 4])); let slashes = ::UnappliedSlashes::get(&4); assert_eq!(slashes.len(), 2); @@ -3126,7 +3215,7 @@ fn slash_kicks_validators_not_nominators_and_disables_nominator_for_kicked_valid assert!(nominations.submitted_in < last_slash); // actually re-bond the slashed validator - assert_ok!(Staking::validate(Origin::signed(10), Default::default())); + assert_ok!(Staking::validate(RuntimeOrigin::signed(10), Default::default())); mock::start_active_era(2); let exposure_11 = Staking::eras_stakers(active_era(), &11); @@ -3308,7 +3397,7 @@ fn claim_reward_at_the_last_era_and_no_double_claim_and_invalid_claim() { // * double claim of one era fails ExtBuilder::default().nominate(true).build_and_execute(|| { // Consumed weight for all payout_stakers dispatches that fail - let err_weight = weights::SubstrateWeight::::payout_stakers_alive_staked(0); + let err_weight = ::WeightInfo::payout_stakers_alive_staked(0); let init_balance_10 = Balances::total_balance(&10); let init_balance_100 = Balances::total_balance(&100); @@ -3343,7 +3432,7 @@ fn claim_reward_at_the_last_era_and_no_double_claim_and_invalid_claim() { assert!(total_payout_2 != total_payout_0); assert!(total_payout_2 != total_payout_1); - mock::start_active_era(Staking::history_depth() + 1); + mock::start_active_era(HistoryDepth::get() + 1); let active_era = active_era(); @@ -3351,21 +3440,21 @@ fn claim_reward_at_the_last_era_and_no_double_claim_and_invalid_claim() { let current_era = Staking::current_era().unwrap(); // Last kept is 1: - assert!(current_era - Staking::history_depth() == 1); + assert!(current_era - HistoryDepth::get() == 1); assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 11, 0), + Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 0), // Fail: Era out of history Error::::InvalidEraToReward.with_weight(err_weight) ); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 1)); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 2)); + assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 1)); + assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 2)); assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 11, 2), + Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 2), // Fail: Double claim Error::::AlreadyClaimed.with_weight(err_weight) ); assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 11, active_era), + Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, active_era), // Fail: Era not finished yet Error::::InvalidEraToReward.with_weight(err_weight) ); @@ -3486,12 +3575,12 @@ fn test_max_nominator_rewarded_per_validator_and_cant_steal_someone_else_reward( let balance = 10_000 + i as Balance; Balances::make_free_balance_be(&stash, balance); assert_ok!(Staking::bond( - Origin::signed(stash), + RuntimeOrigin::signed(stash), controller, balance, RewardDestination::Stash )); - assert_ok!(Staking::nominate(Origin::signed(controller), vec![11])); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(controller), vec![11])); } mock::start_active_era(1); @@ -3515,25 +3604,6 @@ fn test_max_nominator_rewarded_per_validator_and_cant_steal_someone_else_reward( }); } -#[test] -fn set_history_depth_works() { - ExtBuilder::default().build_and_execute(|| { - mock::start_active_era(10); - Staking::set_history_depth(Origin::root(), 20, 0).unwrap(); - assert!(::ErasTotalStake::contains_key(10 - 4)); - assert!(::ErasTotalStake::contains_key(10 - 5)); - Staking::set_history_depth(Origin::root(), 4, 0).unwrap(); - assert!(::ErasTotalStake::contains_key(10 - 4)); - assert!(!::ErasTotalStake::contains_key(10 - 5)); - Staking::set_history_depth(Origin::root(), 3, 0).unwrap(); - assert!(!::ErasTotalStake::contains_key(10 - 4)); - assert!(!::ErasTotalStake::contains_key(10 - 5)); - Staking::set_history_depth(Origin::root(), 8, 0).unwrap(); - assert!(!::ErasTotalStake::contains_key(10 - 4)); - assert!(!::ErasTotalStake::contains_key(10 - 5)); - }); -} - #[test] fn test_payout_stakers() { // Test that payout_stakers work in general, including that only the top @@ -3570,7 +3640,7 @@ fn test_payout_stakers() { let pre_payout_total_issuance = Balances::total_issuance(); RewardOnUnbalanceWasCalled::set(false); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 1)); + assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 1)); assert_eq_error_rate!( Balances::total_issuance(), pre_payout_total_issuance + actual_paid_out, @@ -3597,7 +3667,7 @@ fn test_payout_stakers() { total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: vec![1] + claimed_rewards: bounded_vec![1] }) ); @@ -3611,7 +3681,7 @@ fn test_payout_stakers() { mock::start_active_era(i); RewardOnUnbalanceWasCalled::set(false); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, i - 1)); + assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, i - 1)); assert_eq_error_rate!( Balances::total_issuance(), pre_payout_total_issuance + actual_paid_out, @@ -3628,11 +3698,15 @@ fn test_payout_stakers() { total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: (1..=14).collect() + claimed_rewards: (1..=14).collect::>().try_into().unwrap() }) ); - for i in 16..100 { + let last_era = 99; + let history_depth = HistoryDepth::get(); + let expected_last_reward_era = last_era - 1; + let expected_start_reward_era = last_era - history_depth; + for i in 16..=last_era { Staking::reward_by_ids(vec![(11, 1)]); // compute and ensure the reward amount is greater than zero. let _ = current_total_payout_for_duration(reward_time_per_era()); @@ -3640,8 +3714,16 @@ fn test_payout_stakers() { } // We clean it up as history passes - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 15)); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 98)); + assert_ok!(Staking::payout_stakers( + RuntimeOrigin::signed(1337), + 11, + expected_start_reward_era + )); + assert_ok!(Staking::payout_stakers( + RuntimeOrigin::signed(1337), + 11, + expected_last_reward_era + )); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -3649,14 +3731,14 @@ fn test_payout_stakers() { total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: vec![15, 98] + claimed_rewards: bounded_vec![expected_start_reward_era, expected_last_reward_era] }) ); // Out of order claims works. - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 69)); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 23)); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 42)); + assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 69)); + assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 23)); + assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 42)); assert_eq!( Staking::ledger(&10), Some(StakingLedger { @@ -3664,7 +3746,13 @@ fn test_payout_stakers() { total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: vec![15, 23, 42, 69, 98] + claimed_rewards: bounded_vec![ + expected_start_reward_era, + 23, + 42, + 69, + expected_last_reward_era + ] }) ); }); @@ -3675,7 +3763,7 @@ fn payout_stakers_handles_basic_errors() { // Here we will test payouts handle all errors. ExtBuilder::default().has_stakers(false).build_and_execute(|| { // Consumed weight for all payout_stakers dispatches that fail - let err_weight = weights::SubstrateWeight::::payout_stakers_alive_staked(0); + let err_weight = ::WeightInfo::payout_stakers_alive_staked(0); // Same setup as the test above let balance = 1000; @@ -3696,41 +3784,56 @@ fn payout_stakers_handles_basic_errors() { // Wrong Era, too big assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 11, 2), + Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 2), Error::::InvalidEraToReward.with_weight(err_weight) ); // Wrong Staker assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 10, 1), + Staking::payout_stakers(RuntimeOrigin::signed(1337), 10, 1), Error::::NotStash.with_weight(err_weight) ); - for i in 3..100 { + let last_era = 99; + for i in 3..=last_era { Staking::reward_by_ids(vec![(11, 1)]); // compute and ensure the reward amount is greater than zero. let _ = current_total_payout_for_duration(reward_time_per_era()); mock::start_active_era(i); } - // We are at era 99, with history depth of 84 - // We should be able to payout era 15 through 98 (84 total eras), but not 14 or 99. + + let history_depth = HistoryDepth::get(); + let expected_last_reward_era = last_era - 1; + let expected_start_reward_era = last_era - history_depth; + + // We are at era last_era=99. Given history_depth=80, we should be able + // to payout era starting from expected_start_reward_era=19 through + // expected_last_reward_era=98 (80 total eras), but not 18 or 99. assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 11, 14), + Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, expected_start_reward_era - 1), Error::::InvalidEraToReward.with_weight(err_weight) ); assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 11, 99), + Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, expected_last_reward_era + 1), Error::::InvalidEraToReward.with_weight(err_weight) ); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 15)); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 98)); + assert_ok!(Staking::payout_stakers( + RuntimeOrigin::signed(1337), + 11, + expected_start_reward_era + )); + assert_ok!(Staking::payout_stakers( + RuntimeOrigin::signed(1337), + 11, + expected_last_reward_era + )); // Can't claim again assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 11, 15), + Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, expected_start_reward_era), Error::::AlreadyClaimed.with_weight(err_weight) ); assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 11, 98), + Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, expected_last_reward_era), Error::::AlreadyClaimed.with_weight(err_weight) ); }); @@ -3780,7 +3883,7 @@ fn payout_stakers_handles_weight_refund() { // Collect payouts when there are no nominators let call = TestCall::Staking(StakingCall::payout_stakers { validator_stash: 11, era: 1 }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(20)); + let result = call.dispatch(RuntimeOrigin::signed(20)); assert_ok!(result); assert_eq!(extract_actual_weight(&result, &info), zero_nom_payouts_weight); @@ -3793,7 +3896,7 @@ fn payout_stakers_handles_weight_refund() { // Collect payouts for an era where the validator did not receive any points. let call = TestCall::Staking(StakingCall::payout_stakers { validator_stash: 11, era: 2 }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(20)); + let result = call.dispatch(RuntimeOrigin::signed(20)); assert_ok!(result); assert_eq!(extract_actual_weight(&result, &info), zero_nom_payouts_weight); @@ -3806,7 +3909,7 @@ fn payout_stakers_handles_weight_refund() { // Collect payouts when the validator has `half_max_nom_rewarded` nominators. let call = TestCall::Staking(StakingCall::payout_stakers { validator_stash: 11, era: 3 }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(20)); + let result = call.dispatch(RuntimeOrigin::signed(20)); assert_ok!(result); assert_eq!(extract_actual_weight(&result, &info), half_max_nom_rewarded_weight); @@ -3829,14 +3932,14 @@ fn payout_stakers_handles_weight_refund() { // Collect payouts when the validator had `half_max_nom_rewarded` nominators. let call = TestCall::Staking(StakingCall::payout_stakers { validator_stash: 11, era: 5 }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(20)); + let result = call.dispatch(RuntimeOrigin::signed(20)); assert_ok!(result); assert_eq!(extract_actual_weight(&result, &info), max_nom_rewarded_weight); // Try and collect payouts for an era that has already been collected. let call = TestCall::Staking(StakingCall::payout_stakers { validator_stash: 11, era: 5 }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(20)); + let result = call.dispatch(RuntimeOrigin::signed(20)); assert!(result.is_err()); // When there is an error the consumed weight == weight when there are 0 nominator payouts. assert_eq!(extract_actual_weight(&result, &info), zero_nom_payouts_weight); @@ -3855,7 +3958,7 @@ fn bond_during_era_correctly_populates_claimed_rewards() { total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }) ); mock::start_active_era(5); @@ -3867,10 +3970,14 @@ fn bond_during_era_correctly_populates_claimed_rewards() { total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: (0..5).collect(), + claimed_rewards: (0..5).collect::>().try_into().unwrap(), }) ); - mock::start_active_era(99); + + // make sure only era upto history depth is stored + let current_era = 99; + let last_reward_era = 99 - HistoryDepth::get(); + mock::start_active_era(current_era); bond_validator(13, 12, 1000); assert_eq!( Staking::ledger(&12), @@ -3879,7 +3986,10 @@ fn bond_during_era_correctly_populates_claimed_rewards() { total: 1000, active: 1000, unlocking: Default::default(), - claimed_rewards: (15..99).collect(), + claimed_rewards: (last_reward_era..current_era) + .collect::>() + .try_into() + .unwrap(), }) ); }); @@ -3965,7 +4075,7 @@ fn payout_creates_controller() { bond_nominator(1234, 1337, 100, vec![11]); // kill controller - assert_ok!(Balances::transfer(Origin::signed(1337), 1234, 100)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(1337), 1234, 100)); assert_eq!(Balances::free_balance(1337), 0); mock::start_active_era(1); @@ -3973,7 +4083,7 @@ fn payout_creates_controller() { // compute and ensure the reward amount is greater than zero. let _ = current_total_payout_for_duration(reward_time_per_era()); mock::start_active_era(2); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 1)); + assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 1)); // Controller is created assert!(Balances::free_balance(1337) > 0); @@ -3991,7 +4101,7 @@ fn payout_to_any_account_works() { bond_nominator(1234, 1337, 100, vec![11]); // Update payout location - assert_ok!(Staking::set_payee(Origin::signed(1337), RewardDestination::Account(42))); + assert_ok!(Staking::set_payee(RuntimeOrigin::signed(1337), RewardDestination::Account(42))); // Reward Destination account doesn't exist assert_eq!(Balances::free_balance(42), 0); @@ -4001,7 +4111,7 @@ fn payout_to_any_account_works() { // compute and ensure the reward amount is greater than zero. let _ = current_total_payout_for_duration(reward_time_per_era()); mock::start_active_era(2); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 1)); + assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 1)); // Payment is successful assert!(Balances::free_balance(42) > 0); @@ -4124,13 +4234,13 @@ fn cannot_rebond_to_lower_than_ed() { total: 10 * 1000, active: 10 * 1000, unlocking: Default::default(), - claimed_rewards: vec![] + claimed_rewards: bounded_vec![], } ); // unbond all of it. must be chilled first. - assert_ok!(Staking::chill(Origin::signed(20))); - assert_ok!(Staking::unbond(Origin::signed(20), 10 * 1000)); + assert_ok!(Staking::chill(RuntimeOrigin::signed(20))); + assert_ok!(Staking::unbond(RuntimeOrigin::signed(20), 10 * 1000)); assert_eq!( Staking::ledger(&20).unwrap(), StakingLedger { @@ -4138,12 +4248,15 @@ fn cannot_rebond_to_lower_than_ed() { total: 10 * 1000, active: 0, unlocking: bounded_vec![UnlockChunk { value: 10 * 1000, era: 3 }], - claimed_rewards: vec![] + claimed_rewards: bounded_vec![], } ); // now bond a wee bit more - assert_noop!(Staking::rebond(Origin::signed(20), 5), Error::::InsufficientBond); + assert_noop!( + Staking::rebond(RuntimeOrigin::signed(20), 5), + Error::::InsufficientBond + ); }) } @@ -4161,13 +4274,13 @@ fn cannot_bond_extra_to_lower_than_ed() { total: 10 * 1000, active: 10 * 1000, unlocking: Default::default(), - claimed_rewards: vec![] + claimed_rewards: bounded_vec![], } ); // unbond all of it. must be chilled first. - assert_ok!(Staking::chill(Origin::signed(20))); - assert_ok!(Staking::unbond(Origin::signed(20), 10 * 1000)); + assert_ok!(Staking::chill(RuntimeOrigin::signed(20))); + assert_ok!(Staking::unbond(RuntimeOrigin::signed(20), 10 * 1000)); assert_eq!( Staking::ledger(&20).unwrap(), StakingLedger { @@ -4175,13 +4288,13 @@ fn cannot_bond_extra_to_lower_than_ed() { total: 10 * 1000, active: 0, unlocking: bounded_vec![UnlockChunk { value: 10 * 1000, era: 3 }], - claimed_rewards: vec![] + claimed_rewards: bounded_vec![], } ); // now bond a wee bit more assert_noop!( - Staking::bond_extra(Origin::signed(21), 5), + Staking::bond_extra(RuntimeOrigin::signed(21), 5), Error::::InsufficientBond, ); }) @@ -4202,14 +4315,14 @@ fn do_not_die_when_active_is_ed() { total: 1000 * ed, active: 1000 * ed, unlocking: Default::default(), - claimed_rewards: vec![] + claimed_rewards: bounded_vec![], } ); // when unbond all of it except ed. - assert_ok!(Staking::unbond(Origin::signed(20), 999 * ed)); + assert_ok!(Staking::unbond(RuntimeOrigin::signed(20), 999 * ed)); start_active_era(3); - assert_ok!(Staking::withdraw_unbonded(Origin::signed(20), 100)); + assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(20), 100)); // then assert_eq!( @@ -4219,7 +4332,7 @@ fn do_not_die_when_active_is_ed() { total: ed, active: ed, unlocking: Default::default(), - claimed_rewards: vec![] + claimed_rewards: bounded_vec![], } ); }) @@ -4312,7 +4425,7 @@ mod election_data_provider { ); // resubmit and it is back - assert_ok!(Staking::nominate(Origin::signed(100), vec![11, 21])); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(100), vec![11, 21])); assert_eq!( ::electing_voters(None) .unwrap() @@ -4470,13 +4583,13 @@ mod election_data_provider { assert_eq!(staking_events().len(), 3); assert_eq!(*staking_events().last().unwrap(), Event::StakersElected); - Staking::force_no_eras(Origin::root()).unwrap(); + Staking::force_no_eras(RuntimeOrigin::root()).unwrap(); assert_eq!(Staking::next_election_prediction(System::block_number()), u64::MAX); - Staking::force_new_era_always(Origin::root()).unwrap(); + Staking::force_new_era_always(RuntimeOrigin::root()).unwrap(); assert_eq!(Staking::next_election_prediction(System::block_number()), 45 + 5); - Staking::force_new_era(Origin::root()).unwrap(); + Staking::force_new_era(RuntimeOrigin::root()).unwrap(); assert_eq!(Staking::next_election_prediction(System::block_number()), 45 + 5); // Do a fail election @@ -4526,40 +4639,51 @@ fn min_bond_checks_work() { .min_validator_bond(1_500) .build_and_execute(|| { // 500 is not enough for any role - assert_ok!(Staking::bond(Origin::signed(3), 4, 500, RewardDestination::Controller)); + assert_ok!(Staking::bond( + RuntimeOrigin::signed(3), + 4, + 500, + RewardDestination::Controller + )); assert_noop!( - Staking::nominate(Origin::signed(4), vec![1]), + Staking::nominate(RuntimeOrigin::signed(4), vec![1]), Error::::InsufficientBond ); assert_noop!( - Staking::validate(Origin::signed(4), ValidatorPrefs::default()), + Staking::validate(RuntimeOrigin::signed(4), ValidatorPrefs::default()), Error::::InsufficientBond, ); // 1000 is enough for nominator - assert_ok!(Staking::bond_extra(Origin::signed(3), 500)); - assert_ok!(Staking::nominate(Origin::signed(4), vec![1])); + assert_ok!(Staking::bond_extra(RuntimeOrigin::signed(3), 500)); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(4), vec![1])); assert_noop!( - Staking::validate(Origin::signed(4), ValidatorPrefs::default()), + Staking::validate(RuntimeOrigin::signed(4), ValidatorPrefs::default()), Error::::InsufficientBond, ); // 1500 is enough for validator - assert_ok!(Staking::bond_extra(Origin::signed(3), 500)); - assert_ok!(Staking::nominate(Origin::signed(4), vec![1])); - assert_ok!(Staking::validate(Origin::signed(4), ValidatorPrefs::default())); + assert_ok!(Staking::bond_extra(RuntimeOrigin::signed(3), 500)); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(4), vec![1])); + assert_ok!(Staking::validate(RuntimeOrigin::signed(4), ValidatorPrefs::default())); // Can't unbond anything as validator - assert_noop!(Staking::unbond(Origin::signed(4), 500), Error::::InsufficientBond); + assert_noop!( + Staking::unbond(RuntimeOrigin::signed(4), 500), + Error::::InsufficientBond + ); // Once they are a nominator, they can unbond 500 - assert_ok!(Staking::nominate(Origin::signed(4), vec![1])); - assert_ok!(Staking::unbond(Origin::signed(4), 500)); - assert_noop!(Staking::unbond(Origin::signed(4), 500), Error::::InsufficientBond); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(4), vec![1])); + assert_ok!(Staking::unbond(RuntimeOrigin::signed(4), 500)); + assert_noop!( + Staking::unbond(RuntimeOrigin::signed(4), 500), + Error::::InsufficientBond + ); // Once they are chilled they can unbond everything - assert_ok!(Staking::chill(Origin::signed(4))); - assert_ok!(Staking::unbond(Origin::signed(4), 1000)); + assert_ok!(Staking::chill(RuntimeOrigin::signed(4))); + assert_ok!(Staking::unbond(RuntimeOrigin::signed(4), 1000)); }) } @@ -4585,21 +4709,21 @@ fn chill_other_works() { // Nominator assert_ok!(Staking::bond( - Origin::signed(a), + RuntimeOrigin::signed(a), b, 1000, RewardDestination::Controller )); - assert_ok!(Staking::nominate(Origin::signed(b), vec![1])); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(b), vec![1])); // Validator assert_ok!(Staking::bond( - Origin::signed(c), + RuntimeOrigin::signed(c), d, 1500, RewardDestination::Controller )); - assert_ok!(Staking::validate(Origin::signed(d), ValidatorPrefs::default())); + assert_ok!(Staking::validate(RuntimeOrigin::signed(d), ValidatorPrefs::default())); } // To chill other users, we need to: @@ -4612,17 +4736,17 @@ fn chill_other_works() { // Can't chill these users assert_noop!( - Staking::chill_other(Origin::signed(1337), 1), + Staking::chill_other(RuntimeOrigin::signed(1337), 1), Error::::CannotChillOther ); assert_noop!( - Staking::chill_other(Origin::signed(1337), 3), + Staking::chill_other(RuntimeOrigin::signed(1337), 3), Error::::CannotChillOther ); // Change the minimum bond... but no limits. assert_ok!(Staking::set_staking_configs( - Origin::root(), + RuntimeOrigin::root(), ConfigOp::Set(1_500), ConfigOp::Set(2_000), ConfigOp::Remove, @@ -4633,17 +4757,17 @@ fn chill_other_works() { // Still can't chill these users assert_noop!( - Staking::chill_other(Origin::signed(1337), 1), + Staking::chill_other(RuntimeOrigin::signed(1337), 1), Error::::CannotChillOther ); assert_noop!( - Staking::chill_other(Origin::signed(1337), 3), + Staking::chill_other(RuntimeOrigin::signed(1337), 3), Error::::CannotChillOther ); // Add limits, but no threshold assert_ok!(Staking::set_staking_configs( - Origin::root(), + RuntimeOrigin::root(), ConfigOp::Noop, ConfigOp::Noop, ConfigOp::Set(10), @@ -4654,17 +4778,17 @@ fn chill_other_works() { // Still can't chill these users assert_noop!( - Staking::chill_other(Origin::signed(1337), 1), + Staking::chill_other(RuntimeOrigin::signed(1337), 1), Error::::CannotChillOther ); assert_noop!( - Staking::chill_other(Origin::signed(1337), 3), + Staking::chill_other(RuntimeOrigin::signed(1337), 3), Error::::CannotChillOther ); // Add threshold, but no limits assert_ok!(Staking::set_staking_configs( - Origin::root(), + RuntimeOrigin::root(), ConfigOp::Noop, ConfigOp::Noop, ConfigOp::Remove, @@ -4675,17 +4799,17 @@ fn chill_other_works() { // Still can't chill these users assert_noop!( - Staking::chill_other(Origin::signed(1337), 1), + Staking::chill_other(RuntimeOrigin::signed(1337), 1), Error::::CannotChillOther ); assert_noop!( - Staking::chill_other(Origin::signed(1337), 3), + Staking::chill_other(RuntimeOrigin::signed(1337), 3), Error::::CannotChillOther ); // Add threshold and limits assert_ok!(Staking::set_staking_configs( - Origin::root(), + RuntimeOrigin::root(), ConfigOp::Noop, ConfigOp::Noop, ConfigOp::Set(10), @@ -4703,19 +4827,19 @@ fn chill_other_works() { for i in 6..15 { let b = 4 * i + 1; let d = 4 * i + 3; - assert_ok!(Staking::chill_other(Origin::signed(1337), b)); - assert_ok!(Staking::chill_other(Origin::signed(1337), d)); + assert_ok!(Staking::chill_other(RuntimeOrigin::signed(1337), b)); + assert_ok!(Staking::chill_other(RuntimeOrigin::signed(1337), d)); } // chill a nominator. Limit is not reached, not chill-able assert_eq!(Nominators::::count(), 7); assert_noop!( - Staking::chill_other(Origin::signed(1337), 1), + Staking::chill_other(RuntimeOrigin::signed(1337), 1), Error::::CannotChillOther ); // chill a validator. Limit is reached, chill-able. assert_eq!(Validators::::count(), 9); - assert_ok!(Staking::chill_other(Origin::signed(1337), 3)); + assert_ok!(Staking::chill_other(RuntimeOrigin::signed(1337), 3)); }) } @@ -4730,7 +4854,7 @@ fn capped_stakers_works() { // Change the maximums let max = 10; assert_ok!(Staking::set_staking_configs( - Origin::root(), + RuntimeOrigin::root(), ConfigOp::Set(10), ConfigOp::Set(10), ConfigOp::Set(max), @@ -4748,7 +4872,10 @@ fn capped_stakers_works() { RewardDestination::Controller, ) .unwrap(); - assert_ok!(Staking::validate(Origin::signed(controller), ValidatorPrefs::default())); + assert_ok!(Staking::validate( + RuntimeOrigin::signed(controller), + ValidatorPrefs::default() + )); some_existing_validator = controller; } @@ -4761,7 +4888,7 @@ fn capped_stakers_works() { .unwrap(); assert_noop!( - Staking::validate(Origin::signed(last_validator), ValidatorPrefs::default()), + Staking::validate(RuntimeOrigin::signed(last_validator), ValidatorPrefs::default()), Error::::TooManyValidators, ); @@ -4774,7 +4901,7 @@ fn capped_stakers_works() { RewardDestination::Controller, ) .unwrap(); - assert_ok!(Staking::nominate(Origin::signed(controller), vec![1])); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(controller), vec![1])); some_existing_nominator = controller; } @@ -4786,21 +4913,21 @@ fn capped_stakers_works() { ) .unwrap(); assert_noop!( - Staking::nominate(Origin::signed(last_nominator), vec![1]), + Staking::nominate(RuntimeOrigin::signed(last_nominator), vec![1]), Error::::TooManyNominators ); // Re-nominate works fine - assert_ok!(Staking::nominate(Origin::signed(some_existing_nominator), vec![1])); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(some_existing_nominator), vec![1])); // Re-validate works fine assert_ok!(Staking::validate( - Origin::signed(some_existing_validator), + RuntimeOrigin::signed(some_existing_validator), ValidatorPrefs::default() )); // No problem when we set to `None` again assert_ok!(Staking::set_staking_configs( - Origin::root(), + RuntimeOrigin::root(), ConfigOp::Noop, ConfigOp::Noop, ConfigOp::Remove, @@ -4808,8 +4935,11 @@ fn capped_stakers_works() { ConfigOp::Noop, ConfigOp::Noop, )); - assert_ok!(Staking::nominate(Origin::signed(last_nominator), vec![1])); - assert_ok!(Staking::validate(Origin::signed(last_validator), ValidatorPrefs::default())); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(last_nominator), vec![1])); + assert_ok!(Staking::validate( + RuntimeOrigin::signed(last_validator), + ValidatorPrefs::default() + )); }) } @@ -4818,7 +4948,7 @@ fn min_commission_works() { ExtBuilder::default().build_and_execute(|| { // account 10 controls the stash from account 11 assert_ok!(Staking::validate( - Origin::signed(10), + RuntimeOrigin::signed(10), ValidatorPrefs { commission: Perbill::from_percent(5), blocked: false } )); @@ -4832,7 +4962,7 @@ fn min_commission_works() { ); assert_ok!(Staking::set_staking_configs( - Origin::root(), + RuntimeOrigin::root(), ConfigOp::Remove, ConfigOp::Remove, ConfigOp::Remove, @@ -4844,7 +4974,7 @@ fn min_commission_works() { // can't make it less than 10 now assert_noop!( Staking::validate( - Origin::signed(10), + RuntimeOrigin::signed(10), ValidatorPrefs { commission: Perbill::from_percent(5), blocked: false } ), Error::::CommissionTooLow @@ -4852,12 +4982,12 @@ fn min_commission_works() { // can only change to higher. assert_ok!(Staking::validate( - Origin::signed(10), + RuntimeOrigin::signed(10), ValidatorPrefs { commission: Perbill::from_percent(10), blocked: false } )); assert_ok!(Staking::validate( - Origin::signed(10), + RuntimeOrigin::signed(10), ValidatorPrefs { commission: Perbill::from_percent(15), blocked: false } )); }) @@ -4940,7 +5070,7 @@ fn change_of_max_nominations() { assert_eq!(Staking::electing_voters(None).unwrap().len(), 3 + 1); // now one of them can revive themselves by re-nominating to a proper value. - assert_ok!(Staking::nominate(Origin::signed(71), vec![1])); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(71), vec![1])); assert_eq!( Nominators::::iter() .map(|(k, n)| (k, n.targets.len())) @@ -4951,7 +5081,7 @@ fn change_of_max_nominations() { // or they can be chilled by any account. assert!(Nominators::::contains_key(101)); assert!(Nominators::::get(101).is_none()); - assert_ok!(Staking::chill_other(Origin::signed(70), 100)); + assert_ok!(Staking::chill_other(RuntimeOrigin::signed(70), 100)); assert!(!Nominators::::contains_key(101)); assert!(Nominators::::get(101).is_none()); }) @@ -4975,7 +5105,7 @@ mod sorted_list_provider { ); // when account 101 renominates - assert_ok!(Staking::nominate(Origin::signed(100), vec![41])); + assert_ok!(Staking::nominate(RuntimeOrigin::signed(100), vec![41])); // then counts don't change assert_eq!(::VoterList::count(), pre_insert_voter_count); @@ -4998,7 +5128,7 @@ mod sorted_list_provider { assert_eq!(::VoterList::iter().collect::>(), vec![11, 21, 31]); // when account 11 re-validates - assert_ok!(Staking::validate(Origin::signed(10), Default::default())); + assert_ok!(Staking::validate(RuntimeOrigin::signed(10), Default::default())); // then counts don't change assert_eq!(::VoterList::count(), pre_insert_voter_count); @@ -5013,31 +5143,31 @@ fn force_apply_min_commission_works() { let prefs = |c| ValidatorPrefs { commission: Perbill::from_percent(c), blocked: false }; let validators = || Validators::::iter().collect::>(); ExtBuilder::default().build_and_execute(|| { - assert_ok!(Staking::validate(Origin::signed(30), prefs(10))); - assert_ok!(Staking::validate(Origin::signed(20), prefs(5))); + assert_ok!(Staking::validate(RuntimeOrigin::signed(30), prefs(10))); + assert_ok!(Staking::validate(RuntimeOrigin::signed(20), prefs(5))); // Given assert_eq!(validators(), vec![(31, prefs(10)), (21, prefs(5)), (11, prefs(0))]); MinCommission::::set(Perbill::from_percent(5)); // When applying to a commission greater than min - assert_ok!(Staking::force_apply_min_commission(Origin::signed(1), 31)); + assert_ok!(Staking::force_apply_min_commission(RuntimeOrigin::signed(1), 31)); // Then the commission is not changed assert_eq!(validators(), vec![(31, prefs(10)), (21, prefs(5)), (11, prefs(0))]); // When applying to a commission that is equal to min - assert_ok!(Staking::force_apply_min_commission(Origin::signed(1), 21)); + assert_ok!(Staking::force_apply_min_commission(RuntimeOrigin::signed(1), 21)); // Then the commission is not changed assert_eq!(validators(), vec![(31, prefs(10)), (21, prefs(5)), (11, prefs(0))]); // When applying to a commission that is less than the min - assert_ok!(Staking::force_apply_min_commission(Origin::signed(1), 11)); + assert_ok!(Staking::force_apply_min_commission(RuntimeOrigin::signed(1), 11)); // Then the commission is bumped to the min assert_eq!(validators(), vec![(31, prefs(10)), (21, prefs(5)), (11, prefs(5))]); // When applying commission to a validator that doesn't exist then storage is not altered assert_noop!( - Staking::force_apply_min_commission(Origin::signed(1), 420), + Staking::force_apply_min_commission(RuntimeOrigin::signed(1), 420), Error::::NotStash ); }); @@ -5053,7 +5183,7 @@ fn proportional_slash_stop_slashing_if_remaining_zero() { active: 20, // we have some chunks, but they are not affected. unlocking: bounded_vec![c(1, 10), c(2, 10)], - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }; assert_eq!(BondingDuration::get(), 3); @@ -5071,7 +5201,7 @@ fn proportional_ledger_slash_works() { total: 10, active: 10, unlocking: bounded_vec![], - claimed_rewards: vec![], + claimed_rewards: bounded_vec![], }; assert_eq!(BondingDuration::get(), 3); @@ -5287,3 +5417,146 @@ fn proportional_ledger_slash_works() { BTreeMap::from([(4, 0), (5, value_slashed), (6, 0), (7, 0)]) ); } + +#[test] +fn pre_bonding_era_cannot_be_claimed() { + // Verifies initial conditions of mock + ExtBuilder::default().nominate(false).build_and_execute(|| { + let history_depth = HistoryDepth::get(); + // jump to some era above history_depth + let mut current_era = history_depth + 10; + let last_reward_era = current_era - 1; + let start_reward_era = current_era - history_depth; + + // put some money in stash=3 and controller=4. + for i in 3..5 { + let _ = Balances::make_free_balance_be(&i, 2000); + } + + mock::start_active_era(current_era); + + // add a new candidate for being a validator. account 3 controlled by 4. + assert_ok!(Staking::bond(RuntimeOrigin::signed(3), 4, 1500, RewardDestination::Controller)); + + let claimed_rewards: BoundedVec<_, _> = + (start_reward_era..=last_reward_era).collect::>().try_into().unwrap(); + assert_eq!( + Staking::ledger(&4).unwrap(), + StakingLedger { + stash: 3, + total: 1500, + active: 1500, + unlocking: Default::default(), + claimed_rewards, + } + ); + + // start next era + current_era = current_era + 1; + mock::start_active_era(current_era); + + // claiming reward for last era in which validator was active works + assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(4), 3, current_era - 1)); + + // consumed weight for all payout_stakers dispatches that fail + let err_weight = ::WeightInfo::payout_stakers_alive_staked(0); + // cannot claim rewards for an era before bonding occured as it is + // already marked as claimed. + assert_noop!( + Staking::payout_stakers(RuntimeOrigin::signed(4), 3, current_era - 2), + Error::::AlreadyClaimed.with_weight(err_weight) + ); + + // decoding will fail now since Staking Ledger is in corrupt state + HistoryDepth::set(history_depth - 1); + assert_eq!(Staking::ledger(&4), None); + + // make sure stakers still cannot claim rewards that they are not meant to + assert_noop!( + Staking::payout_stakers(RuntimeOrigin::signed(4), 3, current_era - 2), + Error::::NotController + ); + + // fix the corrupted state for post conditions check + HistoryDepth::set(history_depth); + }); +} + +#[test] +fn reducing_history_depth_without_migration() { + // Verifies initial conditions of mock + ExtBuilder::default().nominate(false).build_and_execute(|| { + let original_history_depth = HistoryDepth::get(); + let mut current_era = original_history_depth + 10; + let last_reward_era = current_era - 1; + let start_reward_era = current_era - original_history_depth; + + // put some money in (stash, controller)=(3,4),(5,6). + for i in 3..7 { + let _ = Balances::make_free_balance_be(&i, 2000); + } + + // start current era + mock::start_active_era(current_era); + + // add a new candidate for being a staker. account 3 controlled by 4. + assert_ok!(Staking::bond(RuntimeOrigin::signed(3), 4, 1500, RewardDestination::Controller)); + + // all previous era before the bonding action should be marked as + // claimed. + let claimed_rewards: BoundedVec<_, _> = + (start_reward_era..=last_reward_era).collect::>().try_into().unwrap(); + assert_eq!( + Staking::ledger(&4).unwrap(), + StakingLedger { + stash: 3, + total: 1500, + active: 1500, + unlocking: Default::default(), + claimed_rewards, + } + ); + + // next era + current_era = current_era + 1; + mock::start_active_era(current_era); + + // claiming reward for last era in which validator was active works + assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(4), 3, current_era - 1)); + + // next era + current_era = current_era + 1; + mock::start_active_era(current_era); + + // history_depth reduced without migration + let history_depth = original_history_depth - 1; + HistoryDepth::set(history_depth); + // claiming reward does not work anymore + assert_noop!( + Staking::payout_stakers(RuntimeOrigin::signed(4), 3, current_era - 1), + Error::::NotController + ); + + // new stakers can still bond + assert_ok!(Staking::bond(RuntimeOrigin::signed(5), 6, 1200, RewardDestination::Controller)); + + // new staking ledgers created will be bounded by the current history depth + let last_reward_era = current_era - 1; + let start_reward_era = current_era - history_depth; + let claimed_rewards: BoundedVec<_, _> = + (start_reward_era..=last_reward_era).collect::>().try_into().unwrap(); + assert_eq!( + Staking::ledger(&6).unwrap(), + StakingLedger { + stash: 5, + total: 1200, + active: 1200, + unlocking: Default::default(), + claimed_rewards, + } + ); + + // fix the corrupted state for post conditions check + HistoryDepth::set(original_history_depth); + }); +} diff --git a/frame/staking/src/weights.rs b/frame/staking/src/weights.rs index 09c2d8b5de113..5070232365d3e 100644 --- a/frame/staking/src/weights.rs +++ b/frame/staking/src/weights.rs @@ -18,22 +18,24 @@ //! Autogenerated weights for pallet_staking //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2022-05-24, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2022-09-19, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `bm3`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// ./target/production/substrate +// /home/benchbot/cargo_target_dir/production/substrate // benchmark // pallet -// --chain=dev // --steps=50 // --repeat=20 -// --pallet=pallet_staking // --extrinsic=* // --execution=wasm // --wasm-execution=compiled -// --template=./.maintain/frame-weight-template.hbs +// --heap-pages=4096 +// --pallet=pallet_staking +// --chain=dev // --output=./frame/staking/src/weights.rs +// --template=./.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -65,7 +67,6 @@ pub trait WeightInfo { fn payout_stakers_dead_controller(n: u32, ) -> Weight; fn payout_stakers_alive_staked(n: u32, ) -> Weight; fn rebond(l: u32, ) -> Weight; - fn set_history_depth(e: u32, ) -> Weight; fn reap_stash(s: u32, ) -> Weight; fn new_era(v: u32, n: u32, ) -> Weight; fn get_npos_voters(v: u32, n: u32, s: u32, ) -> Weight; @@ -82,21 +83,20 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking Bonded (r:1 w:1) // Storage: Staking Ledger (r:1 w:1) // Storage: Staking CurrentEra (r:1 w:0) - // Storage: Staking HistoryDepth (r:1 w:0) // Storage: Balances Locks (r:1 w:1) // Storage: Staking Payee (r:0 w:1) fn bond() -> Weight { - Weight::from_ref_time(43_992_000 as u64) - .saturating_add(T::DbWeight::get().reads(5 as u64)) + Weight::from_ref_time(52_281_000 as u64) + .saturating_add(T::DbWeight::get().reads(4 as u64)) .saturating_add(T::DbWeight::get().writes(4 as u64)) } // Storage: Staking Bonded (r:1 w:0) // Storage: Staking Ledger (r:1 w:1) // Storage: Balances Locks (r:1 w:1) - // Storage: BagsList ListNodes (r:3 w:3) - // Storage: BagsList ListBags (r:2 w:2) + // Storage: VoterBagsList ListNodes (r:3 w:3) + // Storage: VoterBagsList ListBags (r:2 w:2) fn bond_extra() -> Weight { - Weight::from_ref_time(75_827_000 as u64) + Weight::from_ref_time(89_748_000 as u64) .saturating_add(T::DbWeight::get().reads(8 as u64)) .saturating_add(T::DbWeight::get().writes(7 as u64)) } @@ -106,11 +106,11 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking CurrentEra (r:1 w:0) // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) - // Storage: BagsList ListNodes (r:3 w:3) + // Storage: VoterBagsList ListNodes (r:3 w:3) // Storage: Staking Bonded (r:1 w:0) - // Storage: BagsList ListBags (r:2 w:2) + // Storage: VoterBagsList ListBags (r:2 w:2) fn unbond() -> Weight { - Weight::from_ref_time(81_075_000 as u64) + Weight::from_ref_time(94_782_000 as u64) .saturating_add(T::DbWeight::get().reads(12 as u64)) .saturating_add(T::DbWeight::get().writes(8 as u64)) } @@ -118,10 +118,11 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking CurrentEra (r:1 w:0) // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) + /// The range of component `s` is `[0, 100]`. fn withdraw_unbonded_update(s: u32, ) -> Weight { - Weight::from_ref_time(35_763_000 as u64) - // Standard Error: 0 - .saturating_add(Weight::from_ref_time(57_000 as u64).saturating_mul(s as u64)) + Weight::from_ref_time(44_499_000 as u64) + // Standard Error: 387 + .saturating_add(Weight::from_ref_time(72_726 as u64).saturating_mul(s as u64)) .saturating_add(T::DbWeight::get().reads(4 as u64)) .saturating_add(T::DbWeight::get().writes(3 as u64)) } @@ -132,14 +133,17 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking Validators (r:1 w:0) // Storage: Staking Nominators (r:1 w:1) // Storage: Staking CounterForNominators (r:1 w:1) - // Storage: BagsList ListNodes (r:2 w:2) - // Storage: BagsList ListBags (r:1 w:1) - // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: VoterBagsList ListNodes (r:2 w:2) + // Storage: VoterBagsList ListBags (r:1 w:1) + // Storage: VoterBagsList CounterForListNodes (r:1 w:1) // Storage: System Account (r:1 w:1) // Storage: Balances Locks (r:1 w:1) // Storage: Staking Payee (r:0 w:1) - fn withdraw_unbonded_kill(_s: u32, ) -> Weight { - Weight::from_ref_time(66_938_000 as u64) + /// The range of component `s` is `[0, 100]`. + fn withdraw_unbonded_kill(s: u32, ) -> Weight { + Weight::from_ref_time(83_230_000 as u64) + // Standard Error: 612 + .saturating_add(Weight::from_ref_time(10_289 as u64).saturating_mul(s as u64)) .saturating_add(T::DbWeight::get().reads(13 as u64)) .saturating_add(T::DbWeight::get().writes(11 as u64)) } @@ -150,23 +154,25 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking MaxValidatorsCount (r:1 w:0) // Storage: Staking Nominators (r:1 w:0) // Storage: Staking Bonded (r:1 w:0) - // Storage: BagsList ListNodes (r:1 w:1) - // Storage: BagsList ListBags (r:1 w:1) - // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: VoterBagsList ListNodes (r:1 w:1) + // Storage: VoterBagsList ListBags (r:1 w:1) + // Storage: VoterBagsList CounterForListNodes (r:1 w:1) // Storage: Staking CounterForValidators (r:1 w:1) fn validate() -> Weight { - Weight::from_ref_time(52_943_000 as u64) + Weight::from_ref_time(64_430_000 as u64) .saturating_add(T::DbWeight::get().reads(11 as u64)) .saturating_add(T::DbWeight::get().writes(5 as u64)) } // Storage: Staking Ledger (r:1 w:0) // Storage: Staking Nominators (r:1 w:1) + /// The range of component `k` is `[1, 128]`. fn kick(k: u32, ) -> Weight { - Weight::from_ref_time(23_264_000 as u64) - // Standard Error: 11_000 - .saturating_add(Weight::from_ref_time(8_006_000 as u64).saturating_mul(k as u64)) - .saturating_add(T::DbWeight::get().reads(1 as u64)) + Weight::from_ref_time(42_030_000 as u64) + // Standard Error: 5_873 + .saturating_add(Weight::from_ref_time(6_747_156 as u64).saturating_mul(k as u64)) + .saturating_add(T::DbWeight::get().reads(2 as u64)) .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(k as u64))) + .saturating_add(T::DbWeight::get().writes(1 as u64)) .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(k as u64))) } // Storage: Staking Ledger (r:1 w:0) @@ -176,15 +182,16 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking Validators (r:2 w:0) // Storage: Staking CurrentEra (r:1 w:0) // Storage: Staking Bonded (r:1 w:0) - // Storage: BagsList ListNodes (r:2 w:2) - // Storage: BagsList ListBags (r:1 w:1) - // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: VoterBagsList ListNodes (r:2 w:2) + // Storage: VoterBagsList ListBags (r:1 w:1) + // Storage: VoterBagsList CounterForListNodes (r:1 w:1) // Storage: Staking CounterForNominators (r:1 w:1) + /// The range of component `n` is `[1, 16]`. fn nominate(n: u32, ) -> Weight { - Weight::from_ref_time(56_596_000 as u64) - // Standard Error: 14_000 - .saturating_add(Weight::from_ref_time(3_644_000 as u64).saturating_mul(n as u64)) - .saturating_add(T::DbWeight::get().reads(12 as u64)) + Weight::from_ref_time(70_834_000 as u64) + // Standard Error: 4_405 + .saturating_add(Weight::from_ref_time(2_583_120 as u64).saturating_mul(n as u64)) + .saturating_add(T::DbWeight::get().reads(13 as u64)) .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(n as u64))) .saturating_add(T::DbWeight::get().writes(6 as u64)) } @@ -192,53 +199,54 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking Validators (r:1 w:0) // Storage: Staking Nominators (r:1 w:1) // Storage: Staking CounterForNominators (r:1 w:1) - // Storage: BagsList ListNodes (r:2 w:2) - // Storage: BagsList ListBags (r:1 w:1) - // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: VoterBagsList ListNodes (r:2 w:2) + // Storage: VoterBagsList ListBags (r:1 w:1) + // Storage: VoterBagsList CounterForListNodes (r:1 w:1) fn chill() -> Weight { - Weight::from_ref_time(51_117_000 as u64) + Weight::from_ref_time(63_328_000 as u64) .saturating_add(T::DbWeight::get().reads(8 as u64)) .saturating_add(T::DbWeight::get().writes(6 as u64)) } // Storage: Staking Ledger (r:1 w:0) // Storage: Staking Payee (r:0 w:1) fn set_payee() -> Weight { - Weight::from_ref_time(11_223_000 as u64) + Weight::from_ref_time(17_763_000 as u64) .saturating_add(T::DbWeight::get().reads(1 as u64)) .saturating_add(T::DbWeight::get().writes(1 as u64)) } // Storage: Staking Bonded (r:1 w:1) // Storage: Staking Ledger (r:2 w:2) fn set_controller() -> Weight { - Weight::from_ref_time(19_826_000 as u64) + Weight::from_ref_time(26_163_000 as u64) .saturating_add(T::DbWeight::get().reads(3 as u64)) .saturating_add(T::DbWeight::get().writes(3 as u64)) } // Storage: Staking ValidatorCount (r:0 w:1) fn set_validator_count() -> Weight { - Weight::from_ref_time(3_789_000 as u64) + Weight::from_ref_time(4_842_000 as u64) .saturating_add(T::DbWeight::get().writes(1 as u64)) } // Storage: Staking ForceEra (r:0 w:1) fn force_no_eras() -> Weight { - Weight::from_ref_time(3_793_000 as u64) + Weight::from_ref_time(4_974_000 as u64) .saturating_add(T::DbWeight::get().writes(1 as u64)) } // Storage: Staking ForceEra (r:0 w:1) fn force_new_era() -> Weight { - Weight::from_ref_time(3_802_000 as u64) + Weight::from_ref_time(5_039_000 as u64) .saturating_add(T::DbWeight::get().writes(1 as u64)) } // Storage: Staking ForceEra (r:0 w:1) fn force_new_era_always() -> Weight { - Weight::from_ref_time(3_762_000 as u64) + Weight::from_ref_time(4_950_000 as u64) .saturating_add(T::DbWeight::get().writes(1 as u64)) } // Storage: Staking Invulnerables (r:0 w:1) + /// The range of component `v` is `[0, 1000]`. fn set_invulnerables(v: u32, ) -> Weight { - Weight::from_ref_time(4_318_000 as u64) - // Standard Error: 0 - .saturating_add(Weight::from_ref_time(10_000 as u64).saturating_mul(v as u64)) + Weight::from_ref_time(5_150_000 as u64) + // Standard Error: 30 + .saturating_add(Weight::from_ref_time(10_540 as u64).saturating_mul(v as u64)) .saturating_add(T::DbWeight::get().writes(1 as u64)) } // Storage: Staking Bonded (r:1 w:1) @@ -246,32 +254,33 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking Validators (r:1 w:0) // Storage: Staking Nominators (r:1 w:1) // Storage: Staking CounterForNominators (r:1 w:1) - // Storage: BagsList ListNodes (r:2 w:2) - // Storage: BagsList ListBags (r:1 w:1) - // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: VoterBagsList ListNodes (r:2 w:2) + // Storage: VoterBagsList ListBags (r:1 w:1) + // Storage: VoterBagsList CounterForListNodes (r:1 w:1) // Storage: System Account (r:1 w:1) // Storage: Balances Locks (r:1 w:1) // Storage: Staking Ledger (r:0 w:1) // Storage: Staking Payee (r:0 w:1) // Storage: Staking SpanSlash (r:0 w:2) + /// The range of component `s` is `[0, 100]`. fn force_unstake(s: u32, ) -> Weight { - Weight::from_ref_time(65_265_000 as u64) - // Standard Error: 1_000 - .saturating_add(Weight::from_ref_time(1_029_000 as u64).saturating_mul(s as u64)) + Weight::from_ref_time(76_282_000 as u64) + // Standard Error: 2_397 + .saturating_add(Weight::from_ref_time(1_137_934 as u64).saturating_mul(s as u64)) .saturating_add(T::DbWeight::get().reads(11 as u64)) - .saturating_add(T::DbWeight::get().writes(12 as u64)) + .saturating_add(T::DbWeight::get().writes(11 as u64)) .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(s as u64))) } // Storage: Staking UnappliedSlashes (r:1 w:1) + /// The range of component `s` is `[1, 1000]`. fn cancel_deferred_slash(s: u32, ) -> Weight { - Weight::from_ref_time(903_312_000 as u64) - // Standard Error: 56_000 - .saturating_add(Weight::from_ref_time(4_968_000 as u64).saturating_mul(s as u64)) + Weight::from_ref_time(93_690_000 as u64) + // Standard Error: 43_203 + .saturating_add(Weight::from_ref_time(6_149_862 as u64).saturating_mul(s as u64)) .saturating_add(T::DbWeight::get().reads(1 as u64)) .saturating_add(T::DbWeight::get().writes(1 as u64)) } // Storage: Staking CurrentEra (r:1 w:0) - // Storage: Staking HistoryDepth (r:1 w:0) // Storage: Staking ErasValidatorReward (r:1 w:0) // Storage: Staking Bonded (r:2 w:0) // Storage: Staking Ledger (r:1 w:1) @@ -280,17 +289,17 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking ErasValidatorPrefs (r:1 w:0) // Storage: Staking Payee (r:2 w:0) // Storage: System Account (r:2 w:2) + /// The range of component `n` is `[1, 256]`. fn payout_stakers_dead_controller(n: u32, ) -> Weight { - Weight::from_ref_time(87_569_000 as u64) - // Standard Error: 14_000 - .saturating_add(Weight::from_ref_time(24_232_000 as u64).saturating_mul(n as u64)) - .saturating_add(T::DbWeight::get().reads(10 as u64)) + Weight::from_ref_time(151_647_000 as u64) + // Standard Error: 8_237 + .saturating_add(Weight::from_ref_time(21_296_415 as u64).saturating_mul(n as u64)) + .saturating_add(T::DbWeight::get().reads(12 as u64)) .saturating_add(T::DbWeight::get().reads((3 as u64).saturating_mul(n as u64))) - .saturating_add(T::DbWeight::get().writes(2 as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64)) .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(n as u64))) } // Storage: Staking CurrentEra (r:1 w:0) - // Storage: Staking HistoryDepth (r:1 w:0) // Storage: Staking ErasValidatorReward (r:1 w:0) // Storage: Staking Bonded (r:2 w:0) // Storage: Staking Ledger (r:2 w:2) @@ -300,45 +309,30 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking Payee (r:2 w:0) // Storage: System Account (r:2 w:2) // Storage: Balances Locks (r:2 w:2) + /// The range of component `n` is `[1, 256]`. fn payout_stakers_alive_staked(n: u32, ) -> Weight { - Weight::from_ref_time(98_839_000 as u64) - // Standard Error: 21_000 - .saturating_add(Weight::from_ref_time(34_480_000 as u64).saturating_mul(n as u64)) - .saturating_add(T::DbWeight::get().reads(11 as u64)) + Weight::from_ref_time(197_310_000 as u64) + // Standard Error: 13_818 + .saturating_add(Weight::from_ref_time(30_053_043 as u64).saturating_mul(n as u64)) + .saturating_add(T::DbWeight::get().reads(15 as u64)) .saturating_add(T::DbWeight::get().reads((5 as u64).saturating_mul(n as u64))) - .saturating_add(T::DbWeight::get().writes(3 as u64)) + .saturating_add(T::DbWeight::get().writes(6 as u64)) .saturating_add(T::DbWeight::get().writes((3 as u64).saturating_mul(n as u64))) } // Storage: Staking Ledger (r:1 w:1) // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) - // Storage: BagsList ListNodes (r:3 w:3) + // Storage: VoterBagsList ListNodes (r:3 w:3) // Storage: Staking Bonded (r:1 w:0) - // Storage: BagsList ListBags (r:2 w:2) + // Storage: VoterBagsList ListBags (r:2 w:2) + /// The range of component `l` is `[1, 32]`. fn rebond(l: u32, ) -> Weight { - Weight::from_ref_time(74_865_000 as u64) - // Standard Error: 3_000 - .saturating_add(Weight::from_ref_time(64_000 as u64).saturating_mul(l as u64)) + Weight::from_ref_time(89_469_000 as u64) + // Standard Error: 1_197 + .saturating_add(Weight::from_ref_time(74_212 as u64).saturating_mul(l as u64)) .saturating_add(T::DbWeight::get().reads(9 as u64)) .saturating_add(T::DbWeight::get().writes(8 as u64)) } - // Storage: Staking CurrentEra (r:1 w:0) - // Storage: Staking HistoryDepth (r:1 w:1) - // Storage: Staking ErasStakersClipped (r:0 w:2) - // Storage: Staking ErasValidatorPrefs (r:0 w:2) - // Storage: Staking ErasValidatorReward (r:0 w:1) - // Storage: Staking ErasRewardPoints (r:0 w:1) - // Storage: Staking ErasStakers (r:0 w:2) - // Storage: Staking ErasTotalStake (r:0 w:1) - // Storage: Staking ErasStartSessionIndex (r:0 w:1) - fn set_history_depth(e: u32, ) -> Weight { - Weight::from_ref_time(0 as u64) - // Standard Error: 62_000 - .saturating_add(Weight::from_ref_time(22_829_000 as u64).saturating_mul(e as u64)) - .saturating_add(T::DbWeight::get().reads(2 as u64)) - .saturating_add(T::DbWeight::get().writes(4 as u64)) - .saturating_add(T::DbWeight::get().writes((7 as u64).saturating_mul(e as u64))) - } // Storage: System Account (r:1 w:1) // Storage: Staking Bonded (r:1 w:1) // Storage: Staking Ledger (r:1 w:1) @@ -346,24 +340,25 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking Validators (r:1 w:0) // Storage: Staking Nominators (r:1 w:1) // Storage: Staking CounterForNominators (r:1 w:1) - // Storage: BagsList ListNodes (r:2 w:2) - // Storage: BagsList ListBags (r:1 w:1) - // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: VoterBagsList ListNodes (r:2 w:2) + // Storage: VoterBagsList ListBags (r:1 w:1) + // Storage: VoterBagsList CounterForListNodes (r:1 w:1) // Storage: Balances Locks (r:1 w:1) // Storage: Staking Payee (r:0 w:1) // Storage: Staking SpanSlash (r:0 w:1) + /// The range of component `s` is `[1, 100]`. fn reap_stash(s: u32, ) -> Weight { - Weight::from_ref_time(70_933_000 as u64) - // Standard Error: 1_000 - .saturating_add(Weight::from_ref_time(1_021_000 as u64).saturating_mul(s as u64)) + Weight::from_ref_time(88_333_000 as u64) + // Standard Error: 1_567 + .saturating_add(Weight::from_ref_time(1_101_099 as u64).saturating_mul(s as u64)) .saturating_add(T::DbWeight::get().reads(12 as u64)) - .saturating_add(T::DbWeight::get().writes(12 as u64)) + .saturating_add(T::DbWeight::get().writes(13 as u64)) .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(s as u64))) } - // Storage: BagsList CounterForListNodes (r:1 w:0) + // Storage: VoterBagsList CounterForListNodes (r:1 w:0) // Storage: Staking SlashingSpans (r:1 w:0) - // Storage: BagsList ListBags (r:200 w:0) - // Storage: BagsList ListNodes (r:101 w:0) + // Storage: VoterBagsList ListBags (r:200 w:0) + // Storage: VoterBagsList ListNodes (r:101 w:0) // Storage: Staking Nominators (r:101 w:0) // Storage: Staking Validators (r:2 w:0) // Storage: Staking Bonded (r:101 w:0) @@ -372,52 +367,54 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking ValidatorCount (r:1 w:0) // Storage: Staking MinimumValidatorCount (r:1 w:0) // Storage: Staking CurrentEra (r:1 w:1) - // Storage: Staking HistoryDepth (r:1 w:0) // Storage: Staking ErasStakersClipped (r:0 w:1) // Storage: Staking ErasValidatorPrefs (r:0 w:1) // Storage: Staking ErasStakers (r:0 w:1) // Storage: Staking ErasTotalStake (r:0 w:1) // Storage: Staking ErasStartSessionIndex (r:0 w:1) + /// The range of component `v` is `[1, 10]`. + /// The range of component `n` is `[1, 100]`. fn new_era(v: u32, n: u32, ) -> Weight { - Weight::from_ref_time(0 as u64) - // Standard Error: 897_000 - .saturating_add(Weight::from_ref_time(213_100_000 as u64).saturating_mul(v as u64)) - // Standard Error: 45_000 - .saturating_add(Weight::from_ref_time(31_123_000 as u64).saturating_mul(n as u64)) - .saturating_add(T::DbWeight::get().reads(208 as u64)) - .saturating_add(T::DbWeight::get().reads((5 as u64).saturating_mul(v as u64))) + Weight::from_ref_time(572_530_000 as u64) + // Standard Error: 3_166_542 + .saturating_add(Weight::from_ref_time(101_354_358 as u64).saturating_mul(v as u64)) + // Standard Error: 315_238 + .saturating_add(Weight::from_ref_time(15_565_319 as u64).saturating_mul(n as u64)) + .saturating_add(T::DbWeight::get().reads(261 as u64)) + .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(v as u64))) .saturating_add(T::DbWeight::get().reads((4 as u64).saturating_mul(n as u64))) - .saturating_add(T::DbWeight::get().writes(3 as u64)) + .saturating_add(T::DbWeight::get().writes(6 as u64)) .saturating_add(T::DbWeight::get().writes((3 as u64).saturating_mul(v as u64))) } - // Storage: BagsList CounterForListNodes (r:1 w:0) + // Storage: VoterBagsList CounterForListNodes (r:1 w:0) // Storage: Staking SlashingSpans (r:21 w:0) - // Storage: BagsList ListBags (r:200 w:0) - // Storage: BagsList ListNodes (r:1500 w:0) + // Storage: VoterBagsList ListBags (r:200 w:0) + // Storage: VoterBagsList ListNodes (r:1500 w:0) // Storage: Staking Nominators (r:1500 w:0) // Storage: Staking Validators (r:500 w:0) // Storage: Staking Bonded (r:1500 w:0) // Storage: Staking Ledger (r:1500 w:0) - fn get_npos_voters(v: u32, n: u32, s: u32, ) -> Weight { - Weight::from_ref_time(0 as u64) - // Standard Error: 116_000 - .saturating_add(Weight::from_ref_time(23_745_000 as u64).saturating_mul(v as u64)) - // Standard Error: 116_000 - .saturating_add(Weight::from_ref_time(22_497_000 as u64).saturating_mul(n as u64)) - // Standard Error: 3_968_000 - .saturating_add(Weight::from_ref_time(20_676_000 as u64).saturating_mul(s as u64)) - .saturating_add(T::DbWeight::get().reads(202 as u64)) - .saturating_add(T::DbWeight::get().reads((5 as u64).saturating_mul(v as u64))) - .saturating_add(T::DbWeight::get().reads((4 as u64).saturating_mul(n as u64))) - .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(s as u64))) + /// The range of component `v` is `[500, 1000]`. + /// The range of component `n` is `[500, 1000]`. + /// The range of component `s` is `[1, 20]`. + fn get_npos_voters(v: u32, n: u32, _s: u32, ) -> Weight { + Weight::from_ref_time(24_930_788_000 as u64) + // Standard Error: 266_386 + .saturating_add(Weight::from_ref_time(6_687_552 as u64).saturating_mul(v as u64)) + // Standard Error: 266_386 + .saturating_add(Weight::from_ref_time(6_839_134 as u64).saturating_mul(n as u64)) + .saturating_add(T::DbWeight::get().reads(6722 as u64)) + .saturating_add(T::DbWeight::get().reads((2 as u64).saturating_mul(v as u64))) + .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(n as u64))) } + // Storage: Staking CounterForValidators (r:1 w:0) // Storage: Staking Validators (r:501 w:0) + /// The range of component `v` is `[500, 1000]`. fn get_npos_targets(v: u32, ) -> Weight { - Weight::from_ref_time(0 as u64) - // Standard Error: 36_000 - .saturating_add(Weight::from_ref_time(8_097_000 as u64).saturating_mul(v as u64)) - .saturating_add(T::DbWeight::get().reads(1 as u64)) - .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(v as u64))) + Weight::from_ref_time(4_864_727_000 as u64) + // Standard Error: 54_240 + .saturating_add(Weight::from_ref_time(3_319_738 as u64).saturating_mul(v as u64)) + .saturating_add(T::DbWeight::get().reads(502 as u64)) } // Storage: Staking MinCommission (r:0 w:1) // Storage: Staking MinValidatorBond (r:0 w:1) @@ -426,7 +423,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking MaxNominatorsCount (r:0 w:1) // Storage: Staking MinNominatorBond (r:0 w:1) fn set_staking_configs_all_set() -> Weight { - Weight::from_ref_time(7_041_000 as u64) + Weight::from_ref_time(10_141_000 as u64) .saturating_add(T::DbWeight::get().writes(6 as u64)) } // Storage: Staking MinCommission (r:0 w:1) @@ -436,7 +433,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking MaxNominatorsCount (r:0 w:1) // Storage: Staking MinNominatorBond (r:0 w:1) fn set_staking_configs_all_remove() -> Weight { - Weight::from_ref_time(6_495_000 as u64) + Weight::from_ref_time(8_993_000 as u64) .saturating_add(T::DbWeight::get().writes(6 as u64)) } // Storage: Staking Ledger (r:1 w:0) @@ -446,18 +443,18 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking CounterForNominators (r:1 w:1) // Storage: Staking MinNominatorBond (r:1 w:0) // Storage: Staking Validators (r:1 w:0) - // Storage: BagsList ListNodes (r:2 w:2) - // Storage: BagsList ListBags (r:1 w:1) - // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: VoterBagsList ListNodes (r:2 w:2) + // Storage: VoterBagsList ListBags (r:1 w:1) + // Storage: VoterBagsList CounterForListNodes (r:1 w:1) fn chill_other() -> Weight { - Weight::from_ref_time(62_014_000 as u64) + Weight::from_ref_time(79_082_000 as u64) .saturating_add(T::DbWeight::get().reads(11 as u64)) .saturating_add(T::DbWeight::get().writes(6 as u64)) } // Storage: Staking MinCommission (r:1 w:0) // Storage: Staking Validators (r:1 w:1) fn force_apply_min_commission() -> Weight { - Weight::from_ref_time(12_814_000 as u64) + Weight::from_ref_time(19_265_000 as u64) .saturating_add(T::DbWeight::get().reads(2 as u64)) .saturating_add(T::DbWeight::get().writes(1 as u64)) } @@ -468,21 +465,20 @@ impl WeightInfo for () { // Storage: Staking Bonded (r:1 w:1) // Storage: Staking Ledger (r:1 w:1) // Storage: Staking CurrentEra (r:1 w:0) - // Storage: Staking HistoryDepth (r:1 w:0) // Storage: Balances Locks (r:1 w:1) // Storage: Staking Payee (r:0 w:1) fn bond() -> Weight { - Weight::from_ref_time(43_992_000 as u64) - .saturating_add(RocksDbWeight::get().reads(5 as u64)) + Weight::from_ref_time(52_281_000 as u64) + .saturating_add(RocksDbWeight::get().reads(4 as u64)) .saturating_add(RocksDbWeight::get().writes(4 as u64)) } // Storage: Staking Bonded (r:1 w:0) // Storage: Staking Ledger (r:1 w:1) // Storage: Balances Locks (r:1 w:1) - // Storage: BagsList ListNodes (r:3 w:3) - // Storage: BagsList ListBags (r:2 w:2) + // Storage: VoterBagsList ListNodes (r:3 w:3) + // Storage: VoterBagsList ListBags (r:2 w:2) fn bond_extra() -> Weight { - Weight::from_ref_time(75_827_000 as u64) + Weight::from_ref_time(89_748_000 as u64) .saturating_add(RocksDbWeight::get().reads(8 as u64)) .saturating_add(RocksDbWeight::get().writes(7 as u64)) } @@ -492,11 +488,11 @@ impl WeightInfo for () { // Storage: Staking CurrentEra (r:1 w:0) // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) - // Storage: BagsList ListNodes (r:3 w:3) + // Storage: VoterBagsList ListNodes (r:3 w:3) // Storage: Staking Bonded (r:1 w:0) - // Storage: BagsList ListBags (r:2 w:2) + // Storage: VoterBagsList ListBags (r:2 w:2) fn unbond() -> Weight { - Weight::from_ref_time(81_075_000 as u64) + Weight::from_ref_time(94_782_000 as u64) .saturating_add(RocksDbWeight::get().reads(12 as u64)) .saturating_add(RocksDbWeight::get().writes(8 as u64)) } @@ -504,10 +500,11 @@ impl WeightInfo for () { // Storage: Staking CurrentEra (r:1 w:0) // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) + /// The range of component `s` is `[0, 100]`. fn withdraw_unbonded_update(s: u32, ) -> Weight { - Weight::from_ref_time(35_763_000 as u64) - // Standard Error: 0 - .saturating_add(Weight::from_ref_time(57_000 as u64).saturating_mul(s as u64)) + Weight::from_ref_time(44_499_000 as u64) + // Standard Error: 387 + .saturating_add(Weight::from_ref_time(72_726 as u64).saturating_mul(s as u64)) .saturating_add(RocksDbWeight::get().reads(4 as u64)) .saturating_add(RocksDbWeight::get().writes(3 as u64)) } @@ -518,14 +515,17 @@ impl WeightInfo for () { // Storage: Staking Validators (r:1 w:0) // Storage: Staking Nominators (r:1 w:1) // Storage: Staking CounterForNominators (r:1 w:1) - // Storage: BagsList ListNodes (r:2 w:2) - // Storage: BagsList ListBags (r:1 w:1) - // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: VoterBagsList ListNodes (r:2 w:2) + // Storage: VoterBagsList ListBags (r:1 w:1) + // Storage: VoterBagsList CounterForListNodes (r:1 w:1) // Storage: System Account (r:1 w:1) // Storage: Balances Locks (r:1 w:1) // Storage: Staking Payee (r:0 w:1) - fn withdraw_unbonded_kill(_s: u32, ) -> Weight { - Weight::from_ref_time(66_938_000 as u64) + /// The range of component `s` is `[0, 100]`. + fn withdraw_unbonded_kill(s: u32, ) -> Weight { + Weight::from_ref_time(83_230_000 as u64) + // Standard Error: 612 + .saturating_add(Weight::from_ref_time(10_289 as u64).saturating_mul(s as u64)) .saturating_add(RocksDbWeight::get().reads(13 as u64)) .saturating_add(RocksDbWeight::get().writes(11 as u64)) } @@ -536,23 +536,25 @@ impl WeightInfo for () { // Storage: Staking MaxValidatorsCount (r:1 w:0) // Storage: Staking Nominators (r:1 w:0) // Storage: Staking Bonded (r:1 w:0) - // Storage: BagsList ListNodes (r:1 w:1) - // Storage: BagsList ListBags (r:1 w:1) - // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: VoterBagsList ListNodes (r:1 w:1) + // Storage: VoterBagsList ListBags (r:1 w:1) + // Storage: VoterBagsList CounterForListNodes (r:1 w:1) // Storage: Staking CounterForValidators (r:1 w:1) fn validate() -> Weight { - Weight::from_ref_time(52_943_000 as u64) + Weight::from_ref_time(64_430_000 as u64) .saturating_add(RocksDbWeight::get().reads(11 as u64)) .saturating_add(RocksDbWeight::get().writes(5 as u64)) } // Storage: Staking Ledger (r:1 w:0) // Storage: Staking Nominators (r:1 w:1) + /// The range of component `k` is `[1, 128]`. fn kick(k: u32, ) -> Weight { - Weight::from_ref_time(23_264_000 as u64) - // Standard Error: 11_000 - .saturating_add(Weight::from_ref_time(8_006_000 as u64).saturating_mul(k as u64)) - .saturating_add(RocksDbWeight::get().reads(1 as u64)) + Weight::from_ref_time(42_030_000 as u64) + // Standard Error: 5_873 + .saturating_add(Weight::from_ref_time(6_747_156 as u64).saturating_mul(k as u64)) + .saturating_add(RocksDbWeight::get().reads(2 as u64)) .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(k as u64))) + .saturating_add(RocksDbWeight::get().writes(1 as u64)) .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(k as u64))) } // Storage: Staking Ledger (r:1 w:0) @@ -562,15 +564,16 @@ impl WeightInfo for () { // Storage: Staking Validators (r:2 w:0) // Storage: Staking CurrentEra (r:1 w:0) // Storage: Staking Bonded (r:1 w:0) - // Storage: BagsList ListNodes (r:2 w:2) - // Storage: BagsList ListBags (r:1 w:1) - // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: VoterBagsList ListNodes (r:2 w:2) + // Storage: VoterBagsList ListBags (r:1 w:1) + // Storage: VoterBagsList CounterForListNodes (r:1 w:1) // Storage: Staking CounterForNominators (r:1 w:1) + /// The range of component `n` is `[1, 16]`. fn nominate(n: u32, ) -> Weight { - Weight::from_ref_time(56_596_000 as u64) - // Standard Error: 14_000 - .saturating_add(Weight::from_ref_time(3_644_000 as u64).saturating_mul(n as u64)) - .saturating_add(RocksDbWeight::get().reads(12 as u64)) + Weight::from_ref_time(70_834_000 as u64) + // Standard Error: 4_405 + .saturating_add(Weight::from_ref_time(2_583_120 as u64).saturating_mul(n as u64)) + .saturating_add(RocksDbWeight::get().reads(13 as u64)) .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(n as u64))) .saturating_add(RocksDbWeight::get().writes(6 as u64)) } @@ -578,53 +581,54 @@ impl WeightInfo for () { // Storage: Staking Validators (r:1 w:0) // Storage: Staking Nominators (r:1 w:1) // Storage: Staking CounterForNominators (r:1 w:1) - // Storage: BagsList ListNodes (r:2 w:2) - // Storage: BagsList ListBags (r:1 w:1) - // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: VoterBagsList ListNodes (r:2 w:2) + // Storage: VoterBagsList ListBags (r:1 w:1) + // Storage: VoterBagsList CounterForListNodes (r:1 w:1) fn chill() -> Weight { - Weight::from_ref_time(51_117_000 as u64) + Weight::from_ref_time(63_328_000 as u64) .saturating_add(RocksDbWeight::get().reads(8 as u64)) .saturating_add(RocksDbWeight::get().writes(6 as u64)) } // Storage: Staking Ledger (r:1 w:0) // Storage: Staking Payee (r:0 w:1) fn set_payee() -> Weight { - Weight::from_ref_time(11_223_000 as u64) + Weight::from_ref_time(17_763_000 as u64) .saturating_add(RocksDbWeight::get().reads(1 as u64)) .saturating_add(RocksDbWeight::get().writes(1 as u64)) } // Storage: Staking Bonded (r:1 w:1) // Storage: Staking Ledger (r:2 w:2) fn set_controller() -> Weight { - Weight::from_ref_time(19_826_000 as u64) + Weight::from_ref_time(26_163_000 as u64) .saturating_add(RocksDbWeight::get().reads(3 as u64)) .saturating_add(RocksDbWeight::get().writes(3 as u64)) } // Storage: Staking ValidatorCount (r:0 w:1) fn set_validator_count() -> Weight { - Weight::from_ref_time(3_789_000 as u64) + Weight::from_ref_time(4_842_000 as u64) .saturating_add(RocksDbWeight::get().writes(1 as u64)) } // Storage: Staking ForceEra (r:0 w:1) fn force_no_eras() -> Weight { - Weight::from_ref_time(3_793_000 as u64) + Weight::from_ref_time(4_974_000 as u64) .saturating_add(RocksDbWeight::get().writes(1 as u64)) } // Storage: Staking ForceEra (r:0 w:1) fn force_new_era() -> Weight { - Weight::from_ref_time(3_802_000 as u64) + Weight::from_ref_time(5_039_000 as u64) .saturating_add(RocksDbWeight::get().writes(1 as u64)) } // Storage: Staking ForceEra (r:0 w:1) fn force_new_era_always() -> Weight { - Weight::from_ref_time(3_762_000 as u64) + Weight::from_ref_time(4_950_000 as u64) .saturating_add(RocksDbWeight::get().writes(1 as u64)) } // Storage: Staking Invulnerables (r:0 w:1) + /// The range of component `v` is `[0, 1000]`. fn set_invulnerables(v: u32, ) -> Weight { - Weight::from_ref_time(4_318_000 as u64) - // Standard Error: 0 - .saturating_add(Weight::from_ref_time(10_000 as u64).saturating_mul(v as u64)) + Weight::from_ref_time(5_150_000 as u64) + // Standard Error: 30 + .saturating_add(Weight::from_ref_time(10_540 as u64).saturating_mul(v as u64)) .saturating_add(RocksDbWeight::get().writes(1 as u64)) } // Storage: Staking Bonded (r:1 w:1) @@ -632,32 +636,33 @@ impl WeightInfo for () { // Storage: Staking Validators (r:1 w:0) // Storage: Staking Nominators (r:1 w:1) // Storage: Staking CounterForNominators (r:1 w:1) - // Storage: BagsList ListNodes (r:2 w:2) - // Storage: BagsList ListBags (r:1 w:1) - // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: VoterBagsList ListNodes (r:2 w:2) + // Storage: VoterBagsList ListBags (r:1 w:1) + // Storage: VoterBagsList CounterForListNodes (r:1 w:1) // Storage: System Account (r:1 w:1) // Storage: Balances Locks (r:1 w:1) // Storage: Staking Ledger (r:0 w:1) // Storage: Staking Payee (r:0 w:1) // Storage: Staking SpanSlash (r:0 w:2) + /// The range of component `s` is `[0, 100]`. fn force_unstake(s: u32, ) -> Weight { - Weight::from_ref_time(65_265_000 as u64) - // Standard Error: 1_000 - .saturating_add(Weight::from_ref_time(1_029_000 as u64).saturating_mul(s as u64)) + Weight::from_ref_time(76_282_000 as u64) + // Standard Error: 2_397 + .saturating_add(Weight::from_ref_time(1_137_934 as u64).saturating_mul(s as u64)) .saturating_add(RocksDbWeight::get().reads(11 as u64)) - .saturating_add(RocksDbWeight::get().writes(12 as u64)) + .saturating_add(RocksDbWeight::get().writes(11 as u64)) .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64))) } // Storage: Staking UnappliedSlashes (r:1 w:1) + /// The range of component `s` is `[1, 1000]`. fn cancel_deferred_slash(s: u32, ) -> Weight { - Weight::from_ref_time(903_312_000 as u64) - // Standard Error: 56_000 - .saturating_add(Weight::from_ref_time(4_968_000 as u64).saturating_mul(s as u64)) + Weight::from_ref_time(93_690_000 as u64) + // Standard Error: 43_203 + .saturating_add(Weight::from_ref_time(6_149_862 as u64).saturating_mul(s as u64)) .saturating_add(RocksDbWeight::get().reads(1 as u64)) .saturating_add(RocksDbWeight::get().writes(1 as u64)) } // Storage: Staking CurrentEra (r:1 w:0) - // Storage: Staking HistoryDepth (r:1 w:0) // Storage: Staking ErasValidatorReward (r:1 w:0) // Storage: Staking Bonded (r:2 w:0) // Storage: Staking Ledger (r:1 w:1) @@ -666,17 +671,17 @@ impl WeightInfo for () { // Storage: Staking ErasValidatorPrefs (r:1 w:0) // Storage: Staking Payee (r:2 w:0) // Storage: System Account (r:2 w:2) + /// The range of component `n` is `[1, 256]`. fn payout_stakers_dead_controller(n: u32, ) -> Weight { - Weight::from_ref_time(87_569_000 as u64) - // Standard Error: 14_000 - .saturating_add(Weight::from_ref_time(24_232_000 as u64).saturating_mul(n as u64)) - .saturating_add(RocksDbWeight::get().reads(10 as u64)) + Weight::from_ref_time(151_647_000 as u64) + // Standard Error: 8_237 + .saturating_add(Weight::from_ref_time(21_296_415 as u64).saturating_mul(n as u64)) + .saturating_add(RocksDbWeight::get().reads(12 as u64)) .saturating_add(RocksDbWeight::get().reads((3 as u64).saturating_mul(n as u64))) - .saturating_add(RocksDbWeight::get().writes(2 as u64)) + .saturating_add(RocksDbWeight::get().writes(3 as u64)) .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(n as u64))) } // Storage: Staking CurrentEra (r:1 w:0) - // Storage: Staking HistoryDepth (r:1 w:0) // Storage: Staking ErasValidatorReward (r:1 w:0) // Storage: Staking Bonded (r:2 w:0) // Storage: Staking Ledger (r:2 w:2) @@ -686,45 +691,30 @@ impl WeightInfo for () { // Storage: Staking Payee (r:2 w:0) // Storage: System Account (r:2 w:2) // Storage: Balances Locks (r:2 w:2) + /// The range of component `n` is `[1, 256]`. fn payout_stakers_alive_staked(n: u32, ) -> Weight { - Weight::from_ref_time(98_839_000 as u64) - // Standard Error: 21_000 - .saturating_add(Weight::from_ref_time(34_480_000 as u64).saturating_mul(n as u64)) - .saturating_add(RocksDbWeight::get().reads(11 as u64)) + Weight::from_ref_time(197_310_000 as u64) + // Standard Error: 13_818 + .saturating_add(Weight::from_ref_time(30_053_043 as u64).saturating_mul(n as u64)) + .saturating_add(RocksDbWeight::get().reads(15 as u64)) .saturating_add(RocksDbWeight::get().reads((5 as u64).saturating_mul(n as u64))) - .saturating_add(RocksDbWeight::get().writes(3 as u64)) + .saturating_add(RocksDbWeight::get().writes(6 as u64)) .saturating_add(RocksDbWeight::get().writes((3 as u64).saturating_mul(n as u64))) } // Storage: Staking Ledger (r:1 w:1) // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) - // Storage: BagsList ListNodes (r:3 w:3) + // Storage: VoterBagsList ListNodes (r:3 w:3) // Storage: Staking Bonded (r:1 w:0) - // Storage: BagsList ListBags (r:2 w:2) + // Storage: VoterBagsList ListBags (r:2 w:2) + /// The range of component `l` is `[1, 32]`. fn rebond(l: u32, ) -> Weight { - Weight::from_ref_time(74_865_000 as u64) - // Standard Error: 3_000 - .saturating_add(Weight::from_ref_time(64_000 as u64).saturating_mul(l as u64)) + Weight::from_ref_time(89_469_000 as u64) + // Standard Error: 1_197 + .saturating_add(Weight::from_ref_time(74_212 as u64).saturating_mul(l as u64)) .saturating_add(RocksDbWeight::get().reads(9 as u64)) .saturating_add(RocksDbWeight::get().writes(8 as u64)) } - // Storage: Staking CurrentEra (r:1 w:0) - // Storage: Staking HistoryDepth (r:1 w:1) - // Storage: Staking ErasStakersClipped (r:0 w:2) - // Storage: Staking ErasValidatorPrefs (r:0 w:2) - // Storage: Staking ErasValidatorReward (r:0 w:1) - // Storage: Staking ErasRewardPoints (r:0 w:1) - // Storage: Staking ErasStakers (r:0 w:2) - // Storage: Staking ErasTotalStake (r:0 w:1) - // Storage: Staking ErasStartSessionIndex (r:0 w:1) - fn set_history_depth(e: u32, ) -> Weight { - Weight::from_ref_time(0 as u64) - // Standard Error: 62_000 - .saturating_add(Weight::from_ref_time(22_829_000 as u64).saturating_mul(e as u64)) - .saturating_add(RocksDbWeight::get().reads(2 as u64)) - .saturating_add(RocksDbWeight::get().writes(4 as u64)) - .saturating_add(RocksDbWeight::get().writes((7 as u64).saturating_mul(e as u64))) - } // Storage: System Account (r:1 w:1) // Storage: Staking Bonded (r:1 w:1) // Storage: Staking Ledger (r:1 w:1) @@ -732,24 +722,25 @@ impl WeightInfo for () { // Storage: Staking Validators (r:1 w:0) // Storage: Staking Nominators (r:1 w:1) // Storage: Staking CounterForNominators (r:1 w:1) - // Storage: BagsList ListNodes (r:2 w:2) - // Storage: BagsList ListBags (r:1 w:1) - // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: VoterBagsList ListNodes (r:2 w:2) + // Storage: VoterBagsList ListBags (r:1 w:1) + // Storage: VoterBagsList CounterForListNodes (r:1 w:1) // Storage: Balances Locks (r:1 w:1) // Storage: Staking Payee (r:0 w:1) // Storage: Staking SpanSlash (r:0 w:1) + /// The range of component `s` is `[1, 100]`. fn reap_stash(s: u32, ) -> Weight { - Weight::from_ref_time(70_933_000 as u64) - // Standard Error: 1_000 - .saturating_add(Weight::from_ref_time(1_021_000 as u64).saturating_mul(s as u64)) + Weight::from_ref_time(88_333_000 as u64) + // Standard Error: 1_567 + .saturating_add(Weight::from_ref_time(1_101_099 as u64).saturating_mul(s as u64)) .saturating_add(RocksDbWeight::get().reads(12 as u64)) - .saturating_add(RocksDbWeight::get().writes(12 as u64)) + .saturating_add(RocksDbWeight::get().writes(13 as u64)) .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64))) } - // Storage: BagsList CounterForListNodes (r:1 w:0) + // Storage: VoterBagsList CounterForListNodes (r:1 w:0) // Storage: Staking SlashingSpans (r:1 w:0) - // Storage: BagsList ListBags (r:200 w:0) - // Storage: BagsList ListNodes (r:101 w:0) + // Storage: VoterBagsList ListBags (r:200 w:0) + // Storage: VoterBagsList ListNodes (r:101 w:0) // Storage: Staking Nominators (r:101 w:0) // Storage: Staking Validators (r:2 w:0) // Storage: Staking Bonded (r:101 w:0) @@ -758,52 +749,54 @@ impl WeightInfo for () { // Storage: Staking ValidatorCount (r:1 w:0) // Storage: Staking MinimumValidatorCount (r:1 w:0) // Storage: Staking CurrentEra (r:1 w:1) - // Storage: Staking HistoryDepth (r:1 w:0) // Storage: Staking ErasStakersClipped (r:0 w:1) // Storage: Staking ErasValidatorPrefs (r:0 w:1) // Storage: Staking ErasStakers (r:0 w:1) // Storage: Staking ErasTotalStake (r:0 w:1) // Storage: Staking ErasStartSessionIndex (r:0 w:1) + /// The range of component `v` is `[1, 10]`. + /// The range of component `n` is `[1, 100]`. fn new_era(v: u32, n: u32, ) -> Weight { - Weight::from_ref_time(0 as u64) - // Standard Error: 897_000 - .saturating_add(Weight::from_ref_time(213_100_000 as u64).saturating_mul(v as u64)) - // Standard Error: 45_000 - .saturating_add(Weight::from_ref_time(31_123_000 as u64).saturating_mul(n as u64)) - .saturating_add(RocksDbWeight::get().reads(208 as u64)) - .saturating_add(RocksDbWeight::get().reads((5 as u64).saturating_mul(v as u64))) + Weight::from_ref_time(572_530_000 as u64) + // Standard Error: 3_166_542 + .saturating_add(Weight::from_ref_time(101_354_358 as u64).saturating_mul(v as u64)) + // Standard Error: 315_238 + .saturating_add(Weight::from_ref_time(15_565_319 as u64).saturating_mul(n as u64)) + .saturating_add(RocksDbWeight::get().reads(261 as u64)) + .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(v as u64))) .saturating_add(RocksDbWeight::get().reads((4 as u64).saturating_mul(n as u64))) - .saturating_add(RocksDbWeight::get().writes(3 as u64)) + .saturating_add(RocksDbWeight::get().writes(6 as u64)) .saturating_add(RocksDbWeight::get().writes((3 as u64).saturating_mul(v as u64))) } - // Storage: BagsList CounterForListNodes (r:1 w:0) + // Storage: VoterBagsList CounterForListNodes (r:1 w:0) // Storage: Staking SlashingSpans (r:21 w:0) - // Storage: BagsList ListBags (r:200 w:0) - // Storage: BagsList ListNodes (r:1500 w:0) + // Storage: VoterBagsList ListBags (r:200 w:0) + // Storage: VoterBagsList ListNodes (r:1500 w:0) // Storage: Staking Nominators (r:1500 w:0) // Storage: Staking Validators (r:500 w:0) // Storage: Staking Bonded (r:1500 w:0) // Storage: Staking Ledger (r:1500 w:0) - fn get_npos_voters(v: u32, n: u32, s: u32, ) -> Weight { - Weight::from_ref_time(0 as u64) - // Standard Error: 116_000 - .saturating_add(Weight::from_ref_time(23_745_000 as u64).saturating_mul(v as u64)) - // Standard Error: 116_000 - .saturating_add(Weight::from_ref_time(22_497_000 as u64).saturating_mul(n as u64)) - // Standard Error: 3_968_000 - .saturating_add(Weight::from_ref_time(20_676_000 as u64).saturating_mul(s as u64)) - .saturating_add(RocksDbWeight::get().reads(202 as u64)) - .saturating_add(RocksDbWeight::get().reads((5 as u64).saturating_mul(v as u64))) - .saturating_add(RocksDbWeight::get().reads((4 as u64).saturating_mul(n as u64))) - .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(s as u64))) + /// The range of component `v` is `[500, 1000]`. + /// The range of component `n` is `[500, 1000]`. + /// The range of component `s` is `[1, 20]`. + fn get_npos_voters(v: u32, n: u32, _s: u32, ) -> Weight { + Weight::from_ref_time(24_930_788_000 as u64) + // Standard Error: 266_386 + .saturating_add(Weight::from_ref_time(6_687_552 as u64).saturating_mul(v as u64)) + // Standard Error: 266_386 + .saturating_add(Weight::from_ref_time(6_839_134 as u64).saturating_mul(n as u64)) + .saturating_add(RocksDbWeight::get().reads(6722 as u64)) + .saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(v as u64))) + .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(n as u64))) } + // Storage: Staking CounterForValidators (r:1 w:0) // Storage: Staking Validators (r:501 w:0) + /// The range of component `v` is `[500, 1000]`. fn get_npos_targets(v: u32, ) -> Weight { - Weight::from_ref_time(0 as u64) - // Standard Error: 36_000 - .saturating_add(Weight::from_ref_time(8_097_000 as u64).saturating_mul(v as u64)) - .saturating_add(RocksDbWeight::get().reads(1 as u64)) - .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(v as u64))) + Weight::from_ref_time(4_864_727_000 as u64) + // Standard Error: 54_240 + .saturating_add(Weight::from_ref_time(3_319_738 as u64).saturating_mul(v as u64)) + .saturating_add(RocksDbWeight::get().reads(502 as u64)) } // Storage: Staking MinCommission (r:0 w:1) // Storage: Staking MinValidatorBond (r:0 w:1) @@ -812,7 +805,7 @@ impl WeightInfo for () { // Storage: Staking MaxNominatorsCount (r:0 w:1) // Storage: Staking MinNominatorBond (r:0 w:1) fn set_staking_configs_all_set() -> Weight { - Weight::from_ref_time(7_041_000 as u64) + Weight::from_ref_time(10_141_000 as u64) .saturating_add(RocksDbWeight::get().writes(6 as u64)) } // Storage: Staking MinCommission (r:0 w:1) @@ -822,7 +815,7 @@ impl WeightInfo for () { // Storage: Staking MaxNominatorsCount (r:0 w:1) // Storage: Staking MinNominatorBond (r:0 w:1) fn set_staking_configs_all_remove() -> Weight { - Weight::from_ref_time(6_495_000 as u64) + Weight::from_ref_time(8_993_000 as u64) .saturating_add(RocksDbWeight::get().writes(6 as u64)) } // Storage: Staking Ledger (r:1 w:0) @@ -832,18 +825,18 @@ impl WeightInfo for () { // Storage: Staking CounterForNominators (r:1 w:1) // Storage: Staking MinNominatorBond (r:1 w:0) // Storage: Staking Validators (r:1 w:0) - // Storage: BagsList ListNodes (r:2 w:2) - // Storage: BagsList ListBags (r:1 w:1) - // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: VoterBagsList ListNodes (r:2 w:2) + // Storage: VoterBagsList ListBags (r:1 w:1) + // Storage: VoterBagsList CounterForListNodes (r:1 w:1) fn chill_other() -> Weight { - Weight::from_ref_time(62_014_000 as u64) + Weight::from_ref_time(79_082_000 as u64) .saturating_add(RocksDbWeight::get().reads(11 as u64)) .saturating_add(RocksDbWeight::get().writes(6 as u64)) } // Storage: Staking MinCommission (r:1 w:0) // Storage: Staking Validators (r:1 w:1) fn force_apply_min_commission() -> Weight { - Weight::from_ref_time(12_814_000 as u64) + Weight::from_ref_time(19_265_000 as u64) .saturating_add(RocksDbWeight::get().reads(2 as u64)) .saturating_add(RocksDbWeight::get().writes(1 as u64)) } diff --git a/frame/state-trie-migration/src/lib.rs b/frame/state-trie-migration/src/lib.rs index 8c73f99be3aea..3f81d3c211a95 100644 --- a/frame/state-trie-migration/src/lib.rs +++ b/frame/state-trie-migration/src/lib.rs @@ -446,10 +446,10 @@ pub mod pallet { #[pallet::config] pub trait Config: frame_system::Config { /// Origin that can control the configurations of this pallet. - type ControlOrigin: frame_support::traits::EnsureOrigin; + type ControlOrigin: frame_support::traits::EnsureOrigin; /// Filter on which origin that trigger the manual migrations. - type SignedFilter: EnsureOrigin; + type SignedFilter: EnsureOrigin; /// The overarching event type. type RuntimeEvent: From> + IsType<::RuntimeEvent>; @@ -1084,7 +1084,7 @@ mod mock { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); type BlockLength = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = u32; @@ -1293,7 +1293,7 @@ mod test { // fails if the top key is too long. frame_support::assert_ok!(StateTrieMigration::continue_migrate( - Origin::signed(1), + RuntimeOrigin::signed(1), MigrationLimits { item: 50, size: 1 << 20 }, Bounded::max_value(), MigrationProcess::::get() @@ -1328,7 +1328,7 @@ mod test { // fails if the top key is too long. frame_support::assert_ok!(StateTrieMigration::continue_migrate( - Origin::signed(1), + RuntimeOrigin::signed(1), MigrationLimits { item: 50, size: 1 << 20 }, Bounded::max_value(), MigrationProcess::::get() @@ -1457,7 +1457,7 @@ mod test { // can't submit if limit is too high. frame_support::assert_err!( StateTrieMigration::continue_migrate( - Origin::signed(1), + RuntimeOrigin::signed(1), MigrationLimits { item: 5, size: sp_runtime::traits::Bounded::max_value() }, Bounded::max_value(), MigrationProcess::::get() @@ -1468,7 +1468,7 @@ mod test { // can't submit if poor. frame_support::assert_err!( StateTrieMigration::continue_migrate( - Origin::signed(2), + RuntimeOrigin::signed(2), MigrationLimits { item: 5, size: 100 }, 100, MigrationProcess::::get() @@ -1479,7 +1479,7 @@ mod test { // can't submit with bad witness. frame_support::assert_err_ignore_postinfo!( StateTrieMigration::continue_migrate( - Origin::signed(1), + RuntimeOrigin::signed(1), MigrationLimits { item: 5, size: 100 }, 100, MigrationTask { @@ -1500,7 +1500,7 @@ mod test { assert!(result.is_ok()); frame_support::assert_ok!(StateTrieMigration::continue_migrate( - Origin::signed(1), + RuntimeOrigin::signed(1), StateTrieMigration::signed_migration_max_limits().unwrap(), task.dyn_size, MigrationProcess::::get() @@ -1523,7 +1523,7 @@ mod test { let correct_witness = 3 + sp_core::storage::TRIE_VALUE_NODE_THRESHOLD * 3 + 1 + 2 + 3; new_test_ext(StateVersion::V0, true, None, None).execute_with(|| { frame_support::assert_ok!(StateTrieMigration::migrate_custom_top( - Origin::signed(1), + RuntimeOrigin::signed(1), vec![b"key1".to_vec(), b"key2".to_vec(), b"key3".to_vec()], correct_witness, )); @@ -1536,7 +1536,7 @@ mod test { new_test_ext(StateVersion::V0, true, None, None).execute_with(|| { // works if the witness is an overestimate frame_support::assert_ok!(StateTrieMigration::migrate_custom_top( - Origin::signed(1), + RuntimeOrigin::signed(1), vec![b"key1".to_vec(), b"key2".to_vec(), b"key3".to_vec()], correct_witness + 99, )); @@ -1551,7 +1551,7 @@ mod test { // note that we don't expect this to be a noop -- we do slash. frame_support::assert_ok!(StateTrieMigration::migrate_custom_top( - Origin::signed(1), + RuntimeOrigin::signed(1), vec![b"key1".to_vec(), b"key2".to_vec(), b"key3".to_vec()], correct_witness - 1, ),); @@ -1569,7 +1569,7 @@ mod test { fn custom_migrate_child_works() { new_test_ext(StateVersion::V0, true, None, None).execute_with(|| { frame_support::assert_ok!(StateTrieMigration::migrate_custom_child( - Origin::signed(1), + RuntimeOrigin::signed(1), StateTrieMigration::childify("chk1"), vec![b"key1".to_vec(), b"key2".to_vec()], 55 + 66, @@ -1585,7 +1585,7 @@ mod test { // note that we don't expect this to be a noop -- we do slash. frame_support::assert_ok!(StateTrieMigration::migrate_custom_child( - Origin::signed(1), + RuntimeOrigin::signed(1), StateTrieMigration::childify("chk1"), vec![b"key1".to_vec(), b"key2".to_vec()], 999999, // wrong witness diff --git a/frame/sudo/src/lib.rs b/frame/sudo/src/lib.rs index 69eac2c1b93c4..75d15d23c680a 100644 --- a/frame/sudo/src/lib.rs +++ b/frame/sudo/src/lib.rs @@ -119,7 +119,7 @@ pub mod pallet { /// A sudo-able call. type RuntimeCall: Parameter - + UnfilteredDispatchable + + UnfilteredDispatchable + GetDispatchInfo; } diff --git a/frame/sudo/src/mock.rs b/frame/sudo/src/mock.rs index 67c221b234de1..db2ad4d563910 100644 --- a/frame/sudo/src/mock.rs +++ b/frame/sudo/src/mock.rs @@ -125,7 +125,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = u64; diff --git a/frame/sudo/src/tests.rs b/frame/sudo/src/tests.rs index fbf4063c992e4..ae8f198736004 100644 --- a/frame/sudo/src/tests.rs +++ b/frame/sudo/src/tests.rs @@ -20,7 +20,7 @@ use super::*; use frame_support::{assert_noop, assert_ok, weights::Weight}; use mock::{ - new_test_ext, Logger, LoggerCall, Origin, RuntimeCall, RuntimeEvent as TestEvent, Sudo, + new_test_ext, Logger, LoggerCall, RuntimeCall, RuntimeEvent as TestEvent, RuntimeOrigin, Sudo, SudoCall, System, Test, }; @@ -43,7 +43,7 @@ fn sudo_basics() { i: 42, weight: Weight::from_ref_time(1_000), })); - assert_ok!(Sudo::sudo(Origin::signed(1), call)); + assert_ok!(Sudo::sudo(RuntimeOrigin::signed(1), call)); assert_eq!(Logger::i32_log(), vec![42i32]); // A privileged function should not work when `sudo` is passed a non-root `key` as `origin`. @@ -51,7 +51,7 @@ fn sudo_basics() { i: 42, weight: Weight::from_ref_time(1_000), })); - assert_noop!(Sudo::sudo(Origin::signed(2), call), Error::::RequireSudo); + assert_noop!(Sudo::sudo(RuntimeOrigin::signed(2), call), Error::::RequireSudo); }); } @@ -66,7 +66,7 @@ fn sudo_emits_events_correctly() { i: 42, weight: Weight::from_ref_time(1), })); - assert_ok!(Sudo::sudo(Origin::signed(1), call)); + assert_ok!(Sudo::sudo(RuntimeOrigin::signed(1), call)); System::assert_has_event(TestEvent::Sudo(Event::Sudid { sudo_result: Ok(()) })); }) } @@ -80,7 +80,7 @@ fn sudo_unchecked_weight_basics() { weight: Weight::from_ref_time(1_000), })); assert_ok!(Sudo::sudo_unchecked_weight( - Origin::signed(1), + RuntimeOrigin::signed(1), call, Weight::from_ref_time(1_000) )); @@ -92,7 +92,11 @@ fn sudo_unchecked_weight_basics() { weight: Weight::from_ref_time(1_000), })); assert_noop!( - Sudo::sudo_unchecked_weight(Origin::signed(2), call, Weight::from_ref_time(1_000)), + Sudo::sudo_unchecked_weight( + RuntimeOrigin::signed(2), + call, + Weight::from_ref_time(1_000) + ), Error::::RequireSudo, ); // `I32Log` is unchanged after unsuccessful call. @@ -122,7 +126,7 @@ fn sudo_unchecked_weight_emits_events_correctly() { weight: Weight::from_ref_time(1), })); assert_ok!(Sudo::sudo_unchecked_weight( - Origin::signed(1), + RuntimeOrigin::signed(1), call, Weight::from_ref_time(1_000) )); @@ -134,14 +138,14 @@ fn sudo_unchecked_weight_emits_events_correctly() { fn set_key_basics() { new_test_ext(1).execute_with(|| { // A root `key` can change the root `key` - assert_ok!(Sudo::set_key(Origin::signed(1), 2)); + assert_ok!(Sudo::set_key(RuntimeOrigin::signed(1), 2)); assert_eq!(Sudo::key(), Some(2u64)); }); new_test_ext(1).execute_with(|| { // A non-root `key` will trigger a `RequireSudo` error and a non-root `key` cannot change // the root `key`. - assert_noop!(Sudo::set_key(Origin::signed(2), 3), Error::::RequireSudo); + assert_noop!(Sudo::set_key(RuntimeOrigin::signed(2), 3), Error::::RequireSudo); }); } @@ -152,10 +156,10 @@ fn set_key_emits_events_correctly() { System::set_block_number(1); // A root `key` can change the root `key`. - assert_ok!(Sudo::set_key(Origin::signed(1), 2)); + assert_ok!(Sudo::set_key(RuntimeOrigin::signed(1), 2)); System::assert_has_event(TestEvent::Sudo(Event::KeyChanged { old_sudoer: Some(1) })); // Double check. - assert_ok!(Sudo::set_key(Origin::signed(2), 4)); + assert_ok!(Sudo::set_key(RuntimeOrigin::signed(2), 4)); System::assert_has_event(TestEvent::Sudo(Event::KeyChanged { old_sudoer: Some(2) })); }); } @@ -168,7 +172,7 @@ fn sudo_as_basics() { i: 42, weight: Weight::from_ref_time(1_000), })); - assert_ok!(Sudo::sudo_as(Origin::signed(1), 2, call)); + assert_ok!(Sudo::sudo_as(RuntimeOrigin::signed(1), 2, call)); assert!(Logger::i32_log().is_empty()); assert!(Logger::account_log().is_empty()); @@ -177,14 +181,14 @@ fn sudo_as_basics() { i: 42, weight: Weight::from_ref_time(1), })); - assert_noop!(Sudo::sudo_as(Origin::signed(3), 2, call), Error::::RequireSudo); + assert_noop!(Sudo::sudo_as(RuntimeOrigin::signed(3), 2, call), Error::::RequireSudo); // A non-privileged function will work when passed to `sudo_as` with the root `key`. let call = Box::new(RuntimeCall::Logger(LoggerCall::non_privileged_log { i: 42, weight: Weight::from_ref_time(1), })); - assert_ok!(Sudo::sudo_as(Origin::signed(1), 2, call)); + assert_ok!(Sudo::sudo_as(RuntimeOrigin::signed(1), 2, call)); assert_eq!(Logger::i32_log(), vec![42i32]); // The correct user makes the call within `sudo_as`. assert_eq!(Logger::account_log(), vec![2]); @@ -202,7 +206,7 @@ fn sudo_as_emits_events_correctly() { i: 42, weight: Weight::from_ref_time(1), })); - assert_ok!(Sudo::sudo_as(Origin::signed(1), 2, call)); + assert_ok!(Sudo::sudo_as(RuntimeOrigin::signed(1), 2, call)); System::assert_has_event(TestEvent::Sudo(Event::SudoAsDone { sudo_result: Ok(()) })); }); } diff --git a/frame/support/procedural/src/construct_runtime/expand/call.rs b/frame/support/procedural/src/construct_runtime/expand/call.rs index 101f0c371382f..8f07448f5785e 100644 --- a/frame/support/procedural/src/construct_runtime/expand/call.rs +++ b/frame/support/procedural/src/construct_runtime/expand/call.rs @@ -162,12 +162,12 @@ pub fn expand_outer_dispatch( } } impl #scrate::dispatch::Dispatchable for RuntimeCall { - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Config = RuntimeCall; type Info = #scrate::dispatch::DispatchInfo; type PostInfo = #scrate::dispatch::PostDispatchInfo; - fn dispatch(self, origin: Origin) -> #scrate::dispatch::DispatchResultWithPostInfo { - if !::filter_call(&origin, &self) { + fn dispatch(self, origin: RuntimeOrigin) -> #scrate::dispatch::DispatchResultWithPostInfo { + if !::filter_call(&origin, &self) { return #scrate::sp_std::result::Result::Err( #system_path::Error::<#runtime>::CallFiltered.into() ); @@ -177,8 +177,8 @@ pub fn expand_outer_dispatch( } } impl #scrate::traits::UnfilteredDispatchable for RuntimeCall { - type Origin = Origin; - fn dispatch_bypass_filter(self, origin: Origin) -> #scrate::dispatch::DispatchResultWithPostInfo { + type RuntimeOrigin = RuntimeOrigin; + fn dispatch_bypass_filter(self, origin: RuntimeOrigin) -> #scrate::dispatch::DispatchResultWithPostInfo { match self { #( #pallet_attrs diff --git a/frame/support/procedural/src/construct_runtime/expand/origin.rs b/frame/support/procedural/src/construct_runtime/expand/origin.rs index d234ca6415115..acbcb65a3e986 100644 --- a/frame/support/procedural/src/construct_runtime/expand/origin.rs +++ b/frame/support/procedural/src/construct_runtime/expand/origin.rs @@ -103,13 +103,13 @@ pub fn expand_outer_origin( /// #[doc = #doc_string] #[derive(Clone)] - pub struct Origin { + pub struct RuntimeOrigin { caller: OriginCaller, filter: #scrate::sp_std::rc::Rc::RuntimeCall) -> bool>>, } #[cfg(not(feature = "std"))] - impl #scrate::sp_std::fmt::Debug for Origin { + impl #scrate::sp_std::fmt::Debug for RuntimeOrigin { fn fmt( &self, fmt: &mut #scrate::sp_std::fmt::Formatter, @@ -119,7 +119,7 @@ pub fn expand_outer_origin( } #[cfg(feature = "std")] - impl #scrate::sp_std::fmt::Debug for Origin { + impl #scrate::sp_std::fmt::Debug for RuntimeOrigin { fn fmt( &self, fmt: &mut #scrate::sp_std::fmt::Formatter, @@ -131,7 +131,7 @@ pub fn expand_outer_origin( } } - impl #scrate::traits::OriginTrait for Origin { + impl #scrate::traits::OriginTrait for RuntimeOrigin { type Call = <#runtime as #system_path::Config>::RuntimeCall; type PalletsOrigin = OriginCaller; type AccountId = <#runtime as #system_path::Config>::AccountId; @@ -214,21 +214,21 @@ pub fn expand_outer_origin( // For backwards compatibility and ease of accessing these functions. #[allow(dead_code)] - impl Origin { + impl RuntimeOrigin { #[doc = #doc_string_none_origin] pub fn none() -> Self { - ::none() + ::none() } #[doc = #doc_string_root_origin] pub fn root() -> Self { - ::root() + ::root() } #[doc = #doc_string_signed_origin] pub fn signed(by: <#runtime as #system_path::Config>::AccountId) -> Self { - ::signed(by) + ::signed(by) } } @@ -251,7 +251,7 @@ pub fn expand_outer_origin( } } - impl From<#system_path::Origin<#runtime>> for Origin { + impl From<#system_path::Origin<#runtime>> for RuntimeOrigin { #[doc = #doc_string_runtime_origin] fn from(x: #system_path::Origin<#runtime>) -> Self { @@ -260,9 +260,9 @@ pub fn expand_outer_origin( } } - impl From for Origin { + impl From for RuntimeOrigin { fn from(x: OriginCaller) -> Self { - let mut o = Origin { + let mut o = RuntimeOrigin { caller: x, filter: #scrate::sp_std::rc::Rc::new(Box::new(|_| true)), }; @@ -273,9 +273,9 @@ pub fn expand_outer_origin( } } - impl From for #scrate::sp_std::result::Result<#system_path::Origin<#runtime>, Origin> { + impl From for #scrate::sp_std::result::Result<#system_path::Origin<#runtime>, RuntimeOrigin> { /// NOTE: converting to pallet origin loses the origin filter information. - fn from(val: Origin) -> Self { + fn from(val: RuntimeOrigin) -> Self { if let OriginCaller::system(l) = val.caller { Ok(l) } else { @@ -283,7 +283,7 @@ pub fn expand_outer_origin( } } } - impl From::AccountId>> for Origin { + impl From::AccountId>> for RuntimeOrigin { #[doc = #doc_string_runtime_origin_with_caller] fn from(x: Option<<#runtime as #system_path::Config>::AccountId>) -> Self { <#system_path::Origin<#runtime>>::from(x).into() @@ -374,7 +374,7 @@ fn expand_origin_pallet_conversions( } #attr - impl From<#pallet_origin> for Origin { + impl From<#pallet_origin> for RuntimeOrigin { #[doc = #doc_string] fn from(x: #pallet_origin) -> Self { let x: OriginCaller = x.into(); @@ -383,9 +383,9 @@ fn expand_origin_pallet_conversions( } #attr - impl From for #scrate::sp_std::result::Result<#pallet_origin, Origin> { + impl From for #scrate::sp_std::result::Result<#pallet_origin, RuntimeOrigin> { /// NOTE: converting to pallet origin loses the origin filter information. - fn from(val: Origin) -> Self { + fn from(val: RuntimeOrigin) -> Self { if let OriginCaller::#variant_name(l) = val.caller { Ok(l) } else { diff --git a/frame/support/procedural/src/pallet/expand/call.rs b/frame/support/procedural/src/pallet/expand/call.rs index d5c84fa37510d..18d5adee63ad6 100644 --- a/frame/support/procedural/src/pallet/expand/call.rs +++ b/frame/support/procedural/src/pallet/expand/call.rs @@ -278,10 +278,10 @@ pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream { for #call_ident<#type_use_gen> #where_clause { - type Origin = #frame_system::pallet_prelude::OriginFor; + type RuntimeOrigin = #frame_system::pallet_prelude::OriginFor; fn dispatch_bypass_filter( self, - origin: Self::Origin + origin: Self::RuntimeOrigin ) -> #frame_support::dispatch::DispatchResultWithPostInfo { match self { #( diff --git a/frame/support/procedural/src/pallet/parse/mod.rs b/frame/support/procedural/src/pallet/parse/mod.rs index f1e520952d872..8b4ab154b306a 100644 --- a/frame/support/procedural/src/pallet/parse/mod.rs +++ b/frame/support/procedural/src/pallet/parse/mod.rs @@ -119,7 +119,7 @@ impl Def { let g = genesis_build::GenesisBuildDef::try_from(span, index, item)?; genesis_build = Some(g); }, - Some(PalletAttr::Origin(_)) if origin.is_none() => + Some(PalletAttr::RuntimeOrigin(_)) if origin.is_none() => origin = Some(origin::OriginDef::try_from(index, item)?), Some(PalletAttr::Inherent(_)) if inherent.is_none() => inherent = Some(inherent::InherentDef::try_from(index, item)?), @@ -394,7 +394,7 @@ enum PalletAttr { RuntimeCall(proc_macro2::Span), Error(proc_macro2::Span), RuntimeEvent(proc_macro2::Span), - Origin(proc_macro2::Span), + RuntimeOrigin(proc_macro2::Span), Inherent(proc_macro2::Span), Storage(proc_macro2::Span), GenesisConfig(proc_macro2::Span), @@ -413,7 +413,7 @@ impl PalletAttr { Self::RuntimeCall(span) => *span, Self::Error(span) => *span, Self::RuntimeEvent(span) => *span, - Self::Origin(span) => *span, + Self::RuntimeOrigin(span) => *span, Self::Inherent(span) => *span, Self::Storage(span) => *span, Self::GenesisConfig(span) => *span, @@ -447,7 +447,7 @@ impl syn::parse::Parse for PalletAttr { } else if lookahead.peek(keyword::event) { Ok(PalletAttr::RuntimeEvent(content.parse::()?.span())) } else if lookahead.peek(keyword::origin) { - Ok(PalletAttr::Origin(content.parse::()?.span())) + Ok(PalletAttr::RuntimeOrigin(content.parse::()?.span())) } else if lookahead.peek(keyword::inherent) { Ok(PalletAttr::Inherent(content.parse::()?.span())) } else if lookahead.peek(keyword::storage) { diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index cacd599fa008c..db2bc90658ee2 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -650,7 +650,7 @@ impl PaysFee for (u64, Pays) { /// # use frame_support::dispatch; /// # use frame_system::{Config, ensure_signed}; /// decl_module! { -/// pub struct Module for enum Call where origin: T::Origin { +/// pub struct Module for enum Call where origin: T::RuntimeOrigin { /// /// // Private functions are dispatchable, but not available to other /// // FRAME pallets. @@ -677,7 +677,7 @@ impl PaysFee for (u64, Pays) { /// * `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::Origin`. +/// * `origin`: Alias of `T::RuntimeOrigin`. /// * `Result`: The expected return type from pallet functions. /// /// The first parameter of dispatchable functions must always be `origin`. @@ -693,7 +693,7 @@ impl PaysFee for (u64, Pays) { /// # use frame_support::dispatch; /// # use frame_system::{Config, ensure_signed}; /// decl_module! { -/// pub struct Module for enum Call where origin: T::Origin { +/// pub struct Module for enum Call where origin: T::RuntimeOrigin { /// #[weight = 0] /// fn my_long_function(origin) -> dispatch::DispatchResult { /// // Your implementation @@ -728,7 +728,7 @@ impl PaysFee for (u64, Pays) { /// # use frame_support::{weights::Weight, dispatch::{DispatchResultWithPostInfo, WithPostDispatchInfo}}; /// # use frame_system::{Config, ensure_signed}; /// decl_module! { -/// pub struct Module for enum Call where origin: T::Origin { +/// 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_ref_time(100_000)))?; @@ -758,7 +758,7 @@ impl PaysFee for (u64, Pays) { /// # use frame_support::transactional; /// # use frame_system::Config; /// decl_module! { -/// pub struct Module for enum Call where origin: T::Origin { +/// pub struct Module for enum Call where origin: T::RuntimeOrigin { /// #[weight = 0] /// #[transactional] /// fn my_short_function(origin) { @@ -779,7 +779,7 @@ impl PaysFee for (u64, Pays) { /// # use frame_support::dispatch; /// # use frame_system::{Config, ensure_signed, ensure_root}; /// decl_module! { -/// pub struct Module for enum Call where origin: T::Origin { +/// pub struct Module for enum Call where origin: T::RuntimeOrigin { /// #[weight = 0] /// fn my_privileged_function(origin) -> dispatch::DispatchResult { /// ensure_root(origin)?; @@ -819,7 +819,7 @@ impl PaysFee for (u64, Pays) { /// pub trait Config: frame_system::Config {} /// /// decl_module! { -/// pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: T::Origin { +/// pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: T::RuntimeOrigin { /// // Your implementation /// } /// } @@ -831,7 +831,7 @@ impl PaysFee for (u64, Pays) { /// /// ## Where clause /// -/// Besides the default `origin: T::Origin`, you can also pass other bounds to the module +/// 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. @@ -844,7 +844,7 @@ impl PaysFee for (u64, Pays) { /// pub trait Config: system::Config where Self::AccountId: From {} /// /// decl_module! { -/// pub struct Module for enum Call where origin: T::Origin, T::AccountId: From { +/// pub struct Module for enum Call where origin: T::RuntimeOrigin, T::AccountId: From { /// // Your implementation /// } /// } @@ -1885,7 +1885,7 @@ macro_rules! decl_module { ) ); }; - // Ignore any ident which is not `origin` with type `T::Origin`. + // Ignore any ident which is not `origin` with type `T::RuntimeOrigin`. (@normalize $(#[$attr:meta])* pub struct $mod_type:ident<$trait_instance:ident: $trait_name:ident$(, I: $instantiable:path $(= $module_default_instance:path)?)?> @@ -1906,7 +1906,7 @@ macro_rules! decl_module { $(#[weight = $weight:expr])? $(#[$fn_attr:meta])* $fn_vis:vis fn $fn_name:ident( - $origin:ident : T::Origin $( , $( #[$codec_attr:ident] )* $param_name:ident : $param:ty )* $(,)? + $origin:ident : T::RuntimeOrigin $( , $( #[$codec_attr:ident] )* $param_name:ident : $param:ty )* $(,)? ) $( -> $result:ty )* { $( $impl:tt )* } $($rest:tt)* ) => { @@ -2906,8 +2906,8 @@ macro_rules! decl_module { impl<$trait_instance: $trait_name $(, $instance: $instantiable)?> $crate::traits::UnfilteredDispatchable for $call_type<$trait_instance $(, $instance)?> where $( $other_where_bounds )* { - type Origin = $origin_type; - fn dispatch_bypass_filter(self, _origin: Self::Origin) -> $crate::dispatch::DispatchResultWithPostInfo { + type RuntimeOrigin = $origin_type; + fn dispatch_bypass_filter(self, _origin: Self::RuntimeOrigin) -> $crate::dispatch::DispatchResultWithPostInfo { match self { $( $call_type::$fn_name { $( $param_name ),* } => { @@ -3200,7 +3200,7 @@ mod tests { type AccountId; type RuntimeCall; type BaseCallFilter; - type Origin: crate::traits::OriginTrait; + type RuntimeOrigin: crate::traits::OriginTrait; type BlockNumber: Into; type PalletInfo: crate::traits::PalletInfo; type DbWeight: Get; @@ -3212,7 +3212,7 @@ mod tests { } decl_module! { - pub struct Module for enum Call where origin: T::Origin, system = system, T::AccountId: From { + pub struct Module for enum Call where origin: T::RuntimeOrigin, system = system, T::AccountId: From { /// Hi, this is a comment. #[weight = 0] fn aux_0(_origin) -> DispatchResult { unreachable!() } @@ -3347,7 +3347,7 @@ mod tests { } impl system::Config for TraitImpl { - type Origin = OuterOrigin; + type RuntimeOrigin = OuterOrigin; type AccountId = u32; type RuntimeCall = (); type BaseCallFilter = frame_support::traits::Everything; @@ -3500,7 +3500,7 @@ mod weight_tests { use sp_weights::RuntimeDbWeight; pub trait Config: 'static { - type Origin; + type RuntimeOrigin; type Balance; type BlockNumber; type DbWeight: Get; @@ -3517,7 +3517,7 @@ mod weight_tests { } impl Config for TraitImpl { - type Origin = u32; + type RuntimeOrigin = u32; type BlockNumber = u32; type Balance = u32; type DbWeight = DbWeight; @@ -3525,7 +3525,7 @@ mod weight_tests { } decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self { + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self { // no arguments, fixed weight #[weight = 1000] fn f00(_origin) { unimplemented!(); } diff --git a/frame/support/src/error.rs b/frame/support/src/error.rs index 0ffe4334e2e30..337bd75895c2c 100644 --- a/frame/support/src/error.rs +++ b/frame/support/src/error.rs @@ -51,7 +51,7 @@ pub use sp_runtime::traits::{BadOrigin, LookupError}; /// // exported in the metadata. /// /// decl_module! { -/// pub struct Module for enum Call where origin: T::Origin { +/// pub struct Module for enum Call where origin: T::RuntimeOrigin { /// type Error = MyError; /// /// #[weight = 0] diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 31b95de5f413d..51aa05261dac3 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -361,9 +361,9 @@ macro_rules! parameter_types { } }; (IMPL_STORAGE $name:ident, $type:ty, $value:expr $(, $ty_params:ident)*) => { + #[allow(unused)] impl< $($ty_params),* > $name< $($ty_params),* > { /// Returns the key for this parameter type. - #[allow(unused)] pub fn key() -> [u8; 16] { $crate::sp_core_hashing_proc_macro::twox_128!(b":", $name, b":") } @@ -372,7 +372,6 @@ macro_rules! parameter_types { /// /// This needs to be executed in an externalities provided /// environment. - #[allow(unused)] pub fn set(value: &$type) { $crate::storage::unhashed::put(&Self::key(), value); } @@ -448,6 +447,7 @@ macro_rules! parameter_types_impl_thread_local { } /// Mutate the internal value in place. + #[allow(unused)] pub fn mutate R>(mutate: F) -> R{ let mut current = Self::get(); let result = mutate(&mut current); @@ -456,6 +456,7 @@ macro_rules! parameter_types_impl_thread_local { } /// Get current value and replace with initial value of the parameter type. + #[allow(unused)] pub fn take() -> $type { let current = Self::get(); Self::set($value); @@ -845,7 +846,7 @@ pub mod tests { pub trait Config: 'static { type BlockNumber: Codec + EncodeLike + Default + TypeInfo; - type Origin; + type RuntimeOrigin; type PalletInfo: crate::traits::PalletInfo; type DbWeight: crate::traits::Get; } @@ -856,7 +857,7 @@ pub mod tests { use super::Config; decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self {} + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self {} } } @@ -888,7 +889,7 @@ pub mod tests { impl Config for Test { type BlockNumber = u32; - type Origin = u32; + type RuntimeOrigin = u32; type PalletInfo = PanicPalletInfo; type DbWeight = (); } diff --git a/frame/support/src/storage/generator/double_map.rs b/frame/support/src/storage/generator/double_map.rs index 4ffe32651a9cc..c95dcee9d7e5c 100644 --- a/frame/support/src/storage/generator/double_map.rs +++ b/frame/support/src/storage/generator/double_map.rs @@ -512,14 +512,14 @@ mod test_iterators { use codec::{Decode, Encode}; pub trait Config: 'static { - type Origin; + type RuntimeOrigin; type BlockNumber; type PalletInfo: crate::traits::PalletInfo; type DbWeight: crate::traits::Get; } crate::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self {} + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self {} } #[derive(PartialEq, Eq, Clone, Encode, Decode)] diff --git a/frame/support/src/storage/generator/map.rs b/frame/support/src/storage/generator/map.rs index d190145ea4c00..f6c8eaa270bb3 100644 --- a/frame/support/src/storage/generator/map.rs +++ b/frame/support/src/storage/generator/map.rs @@ -354,14 +354,14 @@ mod test_iterators { use codec::{Decode, Encode}; pub trait Config: 'static { - type Origin; + type RuntimeOrigin; type BlockNumber; type PalletInfo: crate::traits::PalletInfo; type DbWeight: crate::traits::Get; } crate::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self {} + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self {} } #[derive(PartialEq, Eq, Clone, Encode, Decode)] diff --git a/frame/support/src/storage/generator/mod.rs b/frame/support/src/storage/generator/mod.rs index ca893f44b3cb0..334e9b9e24e86 100644 --- a/frame/support/src/storage/generator/mod.rs +++ b/frame/support/src/storage/generator/mod.rs @@ -47,21 +47,21 @@ mod tests { struct Runtime; pub trait Config: 'static { - type Origin; + type RuntimeOrigin; type BlockNumber; type PalletInfo: crate::traits::PalletInfo; type DbWeight: crate::traits::Get; } impl Config for Runtime { - type Origin = u32; + type RuntimeOrigin = u32; type BlockNumber = u32; type PalletInfo = crate::tests::PanicPalletInfo; type DbWeight = (); } decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self {} + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self {} } crate::decl_storage! { diff --git a/frame/support/src/storage/generator/nmap.rs b/frame/support/src/storage/generator/nmap.rs index f1d0f9a5f0801..79f3d72044e28 100755 --- a/frame/support/src/storage/generator/nmap.rs +++ b/frame/support/src/storage/generator/nmap.rs @@ -460,14 +460,14 @@ mod test_iterators { use codec::{Decode, Encode}; pub trait Config: 'static { - type Origin; + type RuntimeOrigin; type BlockNumber; type PalletInfo: crate::traits::PalletInfo; type DbWeight: crate::traits::Get; } crate::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self {} + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self {} } #[derive(PartialEq, Eq, Clone, Encode, Decode)] diff --git a/frame/support/src/traits/dispatch.rs b/frame/support/src/traits/dispatch.rs index afc819aa454e5..c0e7e32a5529e 100644 --- a/frame/support/src/traits/dispatch.rs +++ b/frame/support/src/traits/dispatch.rs @@ -229,14 +229,14 @@ impl< /// Implemented for pallet dispatchable type by `decl_module` and for runtime dispatchable by /// `construct_runtime`. pub trait UnfilteredDispatchable { - /// The origin type of the runtime, (i.e. `frame_system::Config::Origin`). - type Origin; + /// The origin type of the runtime, (i.e. `frame_system::Config::RuntimeOrigin`). + type RuntimeOrigin; /// Dispatch this call but do not check the filter in origin. - fn dispatch_bypass_filter(self, origin: Self::Origin) -> DispatchResultWithPostInfo; + fn dispatch_bypass_filter(self, origin: Self::RuntimeOrigin) -> DispatchResultWithPostInfo; } -/// Methods available on `frame_system::Config::Origin`. +/// Methods available on `frame_system::Config::RuntimeOrigin`. pub trait OriginTrait: Sized { /// Runtime call type, as in `frame_system::Config::Call` type Call; diff --git a/frame/support/src/traits/hooks.rs b/frame/support/src/traits/hooks.rs index eb1106e4c383f..3415682c0b382 100644 --- a/frame/support/src/traits/hooks.rs +++ b/frame/support/src/traits/hooks.rs @@ -22,7 +22,7 @@ use impl_trait_for_tuples::impl_for_tuples; use sp_runtime::traits::AtLeast32BitUnsigned; use sp_std::prelude::*; -#[cfg(feature = "try-runtime")] +#[cfg(all(feature = "try-runtime", test))] use codec::{Decode, Encode}; /// The block initialization trait. @@ -165,6 +165,7 @@ pub trait OnRuntimeUpgrade { #[cfg_attr(all(feature = "tuples-96", not(feature = "tuples-128")), impl_for_tuples(96))] #[cfg_attr(feature = "tuples-128", impl_for_tuples(128))] impl OnRuntimeUpgrade for Tuple { + #[cfg(not(feature = "try-runtime"))] fn on_runtime_upgrade() -> Weight { let mut weight = Weight::zero(); for_tuples!( #( weight = weight.saturating_add(Tuple::on_runtime_upgrade()); )* ); @@ -172,20 +173,42 @@ impl OnRuntimeUpgrade for Tuple { } #[cfg(feature = "try-runtime")] + /// 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. + fn on_runtime_upgrade() -> Weight { + use scale_info::prelude::format; + + let mut weight = Weight::zero(); + // migration index in the tuple, start with 1 for better readability + let mut i = 1; + for_tuples!( #( + let _guard = frame_support::StorageNoopGuard::default(); + // we want to panic if any checks fail right here right now. + let state = Tuple::pre_upgrade().expect(&format!("PreUpgrade failed for migration #{}", i)); + drop(_guard); + + weight = weight.saturating_add(Tuple::on_runtime_upgrade()); + + let _guard = frame_support::StorageNoopGuard::default(); + // we want to panic if any checks fail right here right now. + Tuple::post_upgrade(state).expect(&format!("PostUpgrade failed for migration #{}", i)); + drop(_guard); + + i += 1; + )* ); + weight + } + + #[cfg(feature = "try-runtime")] + /// noop fn pre_upgrade() -> Result, &'static str> { - let mut state: Vec> = Vec::default(); - for_tuples!( #( state.push(Tuple::pre_upgrade()?); )* ); - Ok(state.encode()) + Ok(Vec::new()) } #[cfg(feature = "try-runtime")] - fn post_upgrade(state: Vec) -> Result<(), &'static str> { - let state: Vec> = Decode::decode(&mut state.as_slice()) - .expect("the state parameter should be the same as pre_upgrade generated"); - let mut state_iter = state.into_iter(); - for_tuples!( #( Tuple::post_upgrade( - state_iter.next().expect("the state parameter should be the same as pre_upgrade generated") - )?; )* ); + /// noop + fn post_upgrade(_state: Vec) -> Result<(), &'static str> { Ok(()) } } @@ -342,7 +365,9 @@ mod tests { #[test] fn on_initialize_and_on_runtime_upgrade_weight_merge_works() { + use sp_io::TestExternalities; struct Test; + impl OnInitialize for Test { fn on_initialize(_n: u8) -> Weight { Weight::from_ref_time(10) @@ -354,8 +379,10 @@ mod tests { } } - assert_eq!(<(Test, Test)>::on_initialize(0), Weight::from_ref_time(20)); - assert_eq!(<(Test, Test)>::on_runtime_upgrade(), Weight::from_ref_time(40)); + TestExternalities::default().execute_with(|| { + assert_eq!(<(Test, Test)>::on_initialize(0), Weight::from_ref_time(20)); + assert_eq!(<(Test, Test)>::on_runtime_upgrade(), Weight::from_ref_time(40)); + }); } #[test] @@ -416,91 +443,107 @@ mod tests { #[cfg(feature = "try-runtime")] #[test] + #[allow(dead_code)] fn on_runtime_upgrade_tuple() { + use frame_support::parameter_types; + use sp_io::TestExternalities; + struct Test1; struct Test2; struct Test3; + parameter_types! { + static Test1Assertions: u8 = 0; + static Test2Assertions: u8 = 0; + static Test3Assertions: u8 = 0; + static EnableSequentialTest: bool = false; + static SequentialAssertions: u8 = 0; + } + impl OnRuntimeUpgrade for Test1 { fn pre_upgrade() -> Result, &'static str> { Ok("Test1".encode()) } fn post_upgrade(state: Vec) -> Result<(), &'static str> { let s: String = Decode::decode(&mut state.as_slice()).unwrap(); + Test1Assertions::mutate(|val| *val += 1); + if EnableSequentialTest::get() { + SequentialAssertions::mutate(|val| *val += 1); + } assert_eq!(s, "Test1"); Ok(()) } } + impl OnRuntimeUpgrade for Test2 { fn pre_upgrade() -> Result, &'static str> { Ok(100u32.encode()) } fn post_upgrade(state: Vec) -> Result<(), &'static str> { let s: u32 = Decode::decode(&mut state.as_slice()).unwrap(); + Test2Assertions::mutate(|val| *val += 1); + if EnableSequentialTest::get() { + assert_eq!(SequentialAssertions::get(), 1); + SequentialAssertions::mutate(|val| *val += 1); + } assert_eq!(s, 100); Ok(()) } } + impl OnRuntimeUpgrade for Test3 { fn pre_upgrade() -> Result, &'static str> { Ok(true.encode()) } fn post_upgrade(state: Vec) -> Result<(), &'static str> { let s: bool = Decode::decode(&mut state.as_slice()).unwrap(); + Test3Assertions::mutate(|val| *val += 1); + if EnableSequentialTest::get() { + assert_eq!(SequentialAssertions::get(), 2); + SequentialAssertions::mutate(|val| *val += 1); + } assert_eq!(s, true); Ok(()) } } - type TestEmpty = (); - let origin_state = ::pre_upgrade().unwrap(); - let states: Vec> = Decode::decode(&mut origin_state.as_slice()).unwrap(); - assert!(states.is_empty()); - ::post_upgrade(origin_state).unwrap(); - - type Test1Tuple = (Test1,); - let origin_state = ::pre_upgrade().unwrap(); - let states: Vec> = Decode::decode(&mut origin_state.as_slice()).unwrap(); - assert_eq!(states.len(), 1); - assert_eq!( - ::decode(&mut states[0].as_slice()).unwrap(), - "Test1".to_owned() - ); - ::post_upgrade(origin_state).unwrap(); - - type Test123 = (Test1, Test2, Test3); - let origin_state = ::pre_upgrade().unwrap(); - let states: Vec> = Decode::decode(&mut origin_state.as_slice()).unwrap(); - assert_eq!( - ::decode(&mut states[0].as_slice()).unwrap(), - "Test1".to_owned() - ); - assert_eq!(::decode(&mut states[1].as_slice()).unwrap(), 100u32); - assert_eq!(::decode(&mut states[2].as_slice()).unwrap(), true); - ::post_upgrade(origin_state).unwrap(); - - type Test321 = (Test3, Test2, Test1); - let origin_state = ::pre_upgrade().unwrap(); - let states: Vec> = Decode::decode(&mut origin_state.as_slice()).unwrap(); - assert_eq!(::decode(&mut states[0].as_slice()).unwrap(), true); - assert_eq!(::decode(&mut states[1].as_slice()).unwrap(), 100u32); - assert_eq!( - ::decode(&mut states[2].as_slice()).unwrap(), - "Test1".to_owned() - ); - ::post_upgrade(origin_state).unwrap(); - - type TestNested123 = (Test1, (Test2, Test3)); - let origin_state = ::pre_upgrade().unwrap(); - let states: Vec> = Decode::decode(&mut origin_state.as_slice()).unwrap(); - assert_eq!( - ::decode(&mut states[0].as_slice()).unwrap(), - "Test1".to_owned() - ); - // nested state for (Test2, Test3) - let nested_states: Vec> = Decode::decode(&mut states[1].as_slice()).unwrap(); - assert_eq!(::decode(&mut nested_states[0].as_slice()).unwrap(), 100u32); - assert_eq!(::decode(&mut nested_states[1].as_slice()).unwrap(), true); - ::post_upgrade(origin_state).unwrap(); + TestExternalities::default().execute_with(|| { + type TestEmpty = (); + let origin_state = ::pre_upgrade().unwrap(); + assert!(origin_state.is_empty()); + ::post_upgrade(origin_state).unwrap(); + + type Test1Tuple = (Test1,); + let origin_state = ::pre_upgrade().unwrap(); + assert!(origin_state.is_empty()); + ::post_upgrade(origin_state).unwrap(); + assert_eq!(Test1Assertions::get(), 0); + ::on_runtime_upgrade(); + assert_eq!(Test1Assertions::take(), 1); + + type Test321 = (Test3, Test2, Test1); + ::on_runtime_upgrade(); + assert_eq!(Test1Assertions::take(), 1); + assert_eq!(Test2Assertions::take(), 1); + assert_eq!(Test3Assertions::take(), 1); + + // enable sequential tests + EnableSequentialTest::mutate(|val| *val = true); + + type Test123 = (Test1, Test2, Test3); + ::on_runtime_upgrade(); + assert_eq!(Test1Assertions::take(), 1); + assert_eq!(Test2Assertions::take(), 1); + assert_eq!(Test3Assertions::take(), 1); + + // reset assertions + SequentialAssertions::take(); + + type TestNested123 = (Test1, (Test2, Test3)); + ::on_runtime_upgrade(); + assert_eq!(Test1Assertions::take(), 1); + assert_eq!(Test2Assertions::take(), 1); + assert_eq!(Test3Assertions::take(), 1); + }); } } diff --git a/frame/support/src/traits/schedule.rs b/frame/support/src/traits/schedule.rs index 39ebbb78321d6..0dbbbd9e2a553 100644 --- a/frame/support/src/traits/schedule.rs +++ b/frame/support/src/traits/schedule.rs @@ -132,7 +132,7 @@ pub mod v1 { use super::*; /// A type that can be used as a scheduler. - pub trait Anon { + pub trait Anon { /// An address which can be used for removing a scheduled task. type Address: Codec + Clone + Eq + EncodeLike + Debug + TypeInfo + MaxEncodedLen; @@ -143,7 +143,7 @@ pub mod v1 { when: DispatchTime, maybe_periodic: Option>, priority: Priority, - origin: Origin, + origin: RuntimeOrigin, call: Call, ) -> Result; @@ -177,7 +177,7 @@ pub mod v1 { } /// A type that can be used as a scheduler. - pub trait Named { + pub trait Named { /// An address which can be used for removing a scheduled task. type Address: Codec + Clone + Eq + EncodeLike + sp_std::fmt::Debug + MaxEncodedLen; @@ -189,7 +189,7 @@ pub mod v1 { when: DispatchTime, maybe_periodic: Option>, priority: Priority, - origin: Origin, + origin: RuntimeOrigin, call: Call, ) -> Result; @@ -215,9 +215,9 @@ pub mod v1 { fn next_dispatch_time(id: Vec) -> Result; } - impl Anon for T + impl Anon for T where - T: v2::Anon, + T: v2::Anon, { type Address = T::Address; @@ -225,7 +225,7 @@ pub mod v1 { when: DispatchTime, maybe_periodic: Option>, priority: Priority, - origin: Origin, + origin: RuntimeOrigin, call: Call, ) -> Result { let c = MaybeHashed::::Value(call); @@ -248,9 +248,9 @@ pub mod v1 { } } - impl Named for T + impl Named for T where - T: v2::Named, + T: v2::Named, { type Address = T::Address; @@ -259,7 +259,7 @@ pub mod v1 { when: DispatchTime, maybe_periodic: Option>, priority: Priority, - origin: Origin, + origin: RuntimeOrigin, call: Call, ) -> Result { let c = MaybeHashed::::Value(call); @@ -287,7 +287,7 @@ pub mod v2 { use super::*; /// A type that can be used as a scheduler. - pub trait Anon { + pub trait Anon { /// An address which can be used for removing a scheduled task. type Address: Codec + Clone + Eq + EncodeLike + Debug + TypeInfo + MaxEncodedLen; /// A means of expressing a call by the hash of its encoded data. @@ -300,7 +300,7 @@ pub mod v2 { when: DispatchTime, maybe_periodic: Option>, priority: Priority, - origin: Origin, + origin: RuntimeOrigin, call: MaybeHashed, ) -> Result; @@ -334,7 +334,7 @@ pub mod v2 { } /// A type that can be used as a scheduler. - pub trait Named { + pub trait Named { /// An address which can be used for removing a scheduled task. type Address: Codec + Clone + Eq + EncodeLike + sp_std::fmt::Debug + MaxEncodedLen; /// A means of expressing a call by the hash of its encoded data. @@ -348,7 +348,7 @@ pub mod v2 { when: DispatchTime, maybe_periodic: Option>, priority: Priority, - origin: Origin, + origin: RuntimeOrigin, call: MaybeHashed, ) -> Result; diff --git a/frame/support/src/traits/tokens/currency.rs b/frame/support/src/traits/tokens/currency.rs index 9a1634fd89313..d0beb66d34923 100644 --- a/frame/support/src/traits/tokens/currency.rs +++ b/frame/support/src/traits/tokens/currency.rs @@ -26,7 +26,7 @@ use crate::{ traits::Get, }; use codec::MaxEncodedLen; -use sp_runtime::traits::MaybeSerializeDeserialize; +use sp_runtime::{traits::MaybeSerializeDeserialize, FixedPointOperand}; use sp_std::fmt::Debug; mod reservable; @@ -37,7 +37,7 @@ pub use lockable::{LockIdentifier, LockableCurrency, VestingSchedule}; /// Abstraction over a fungible assets system. pub trait Currency { /// The balance of an account. - type Balance: Balance + MaybeSerializeDeserialize + Debug + MaxEncodedLen; + type Balance: Balance + MaybeSerializeDeserialize + Debug + MaxEncodedLen + FixedPointOperand; /// The opaque token type for an imbalance. This is returned by unbalanced operations /// and must be dealt with. It may be dropped but cannot be cloned. diff --git a/frame/support/test/compile_pass/src/lib.rs b/frame/support/test/compile_pass/src/lib.rs index 6e4d2363b2f7c..b46f6c48a6d99 100644 --- a/frame/support/test/compile_pass/src/lib.rs +++ b/frame/support/test/compile_pass/src/lib.rs @@ -65,7 +65,7 @@ impl frame_system::Config for Runtime { type BlockHashCount = ConstU64<2400>; type Version = Version; type AccountData = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type BlockNumber = BlockNumber; type AccountId = AccountId; type RuntimeEvent = RuntimeEvent; diff --git a/frame/support/test/src/lib.rs b/frame/support/test/src/lib.rs index dd3fbd1f3020d..0ceeed42ff982 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -25,7 +25,7 @@ /// The configuration trait pub trait Config: 'static { /// The runtime origin type. - type Origin: codec::Codec + codec::EncodeLike + Default + scale_info::TypeInfo; + type RuntimeOrigin: codec::Codec + codec::EncodeLike + Default + scale_info::TypeInfo; /// The block number type. type BlockNumber: codec::Codec + codec::EncodeLike + Default + scale_info::TypeInfo; /// The information about the pallet setup in the runtime. @@ -36,7 +36,7 @@ pub trait Config: 'static { frame_support::decl_module! { /// Some test module - pub struct Module for enum Call where origin: T::Origin, system=self {} + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self {} } /// A PalletInfo implementation which just panics. diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index 4306314b4c005..b1ace12936241 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -49,7 +49,7 @@ mod module1 { frame_support::decl_module! { pub struct Module, I: Instance = DefaultInstance> for enum Call - where origin: ::Origin, system=system + where origin: ::RuntimeOrigin, system=system { #[weight = 0] pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { @@ -89,7 +89,7 @@ mod module2 { frame_support::decl_module! { pub struct Module for enum Call - where origin: ::Origin, system=system + where origin: ::RuntimeOrigin, system=system { #[weight = 0] pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { @@ -134,7 +134,7 @@ mod nested { frame_support::decl_module! { pub struct Module for enum Call - where origin: ::Origin, system=system + where origin: ::RuntimeOrigin, system=system { #[weight = 0] pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { @@ -180,7 +180,7 @@ pub mod module3 { frame_support::decl_module! { pub struct Module for enum Call - where origin: ::Origin, system=system + where origin: ::RuntimeOrigin, system=system { #[weight = 0] pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { @@ -247,7 +247,7 @@ fn test_pub() -> AccountId { impl system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type Hash = H256; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type BlockNumber = BlockNumber; type AccountId = AccountId; type RuntimeEvent = RuntimeEvent; diff --git a/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.rs b/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.rs index fd6b51db07672..2ca9676406579 100644 --- a/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.rs +++ b/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.rs @@ -12,7 +12,7 @@ impl test_pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u32; type RuntimeCall = RuntimeCall; diff --git a/frame/support/test/tests/construct_runtime_ui/old_unsupported_pallet_decl.rs b/frame/support/test/tests/construct_runtime_ui/old_unsupported_pallet_decl.rs index 706d444f23590..5691549c20f34 100644 --- a/frame/support/test/tests/construct_runtime_ui/old_unsupported_pallet_decl.rs +++ b/frame/support/test/tests/construct_runtime_ui/old_unsupported_pallet_decl.rs @@ -8,7 +8,7 @@ mod pallet_old { } decl_module! { - pub struct Module for enum Call where origin: T::Origin {} + pub struct Module for enum Call where origin: T::RuntimeOrigin {} } } 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 f73c611d29686..b7ccadb5e3e58 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 @@ -46,7 +46,7 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u32; type RuntimeCall = RuntimeCall; 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 f90af88d23a9b..abe5c4cfeb343 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 @@ -21,7 +21,7 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u32; type RuntimeCall = RuntimeCall; 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 60d4b166c41fd..9a6ac5c6251fb 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 @@ -21,7 +21,7 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u32; type RuntimeCall = RuntimeCall; 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 5f7beed686339..4facf85e280c0 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 @@ -21,7 +21,7 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u32; type RuntimeCall = RuntimeCall; 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 fb866c161ccb8..322fa2c297285 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 @@ -21,7 +21,7 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u32; type RuntimeCall = RuntimeCall; 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 26ca5d6eb4cb0..55cd5b545d6ba 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 @@ -21,7 +21,7 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u32; type RuntimeCall = RuntimeCall; 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 c692cd61bae8b..b93a2a92911ea 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 @@ -46,39 +46,6 @@ help: if you import `Origin`, refer to it directly 58 - } | -error[E0412]: cannot find type `Origin` in module `pallet` - --> tests/construct_runtime_ui/undefined_origin_part.rs:49:1 - | -49 | / construct_runtime! { -50 | | pub enum Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } - | |_^ not found in `pallet` - | - = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing one of these items - | -1 | use crate::Origin; - | -1 | use frame_system::Origin; - | -help: if you import `Origin`, refer to it directly - | -49 - construct_runtime! { -50 - pub enum Runtime where -51 - Block = Block, -52 - NodeBlock = Block, -53 - UncheckedExtrinsic = UncheckedExtrinsic -54 - { -55 - System: frame_system::{Pallet, Call, Storage, Config, Event}, -56 - Pallet: pallet::{Pallet, Origin}, -57 - } -58 - } - | - error[E0282]: type annotations needed --> tests/construct_runtime_ui/undefined_origin_part.rs:49:1 | 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 81c040c660451..0cf305a7dc055 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 @@ -21,7 +21,7 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u32; type RuntimeCall = RuntimeCall; diff --git a/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.rs b/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.rs index cc7c1ff219d8b..0f662b96e2b13 100644 --- a/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.rs +++ b/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.rs @@ -1,5 +1,5 @@ frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self { + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self { fn integrity_test() {} fn integrity_test() {} diff --git a/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.stderr b/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.stderr index 880695d9b77e2..47ff1c8af8cd2 100644 --- a/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.stderr +++ b/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.stderr @@ -2,7 +2,7 @@ error: `integrity_test` can only be passed once as input. --> tests/decl_module_ui/reserved_keyword_two_times_integrity_test.rs:1:1 | 1 | / frame_support::decl_module! { -2 | | pub struct Module for enum Call where origin: T::Origin, system=self { +2 | | pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self { 3 | | fn integrity_test() {} 4 | | 5 | | fn integrity_test() {} diff --git a/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_on_initialize.rs b/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_on_initialize.rs index 18aaec12c5f39..ea0746b1c501c 100644 --- a/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_on_initialize.rs +++ b/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_on_initialize.rs @@ -1,5 +1,5 @@ frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self { + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self { fn on_initialize() -> Weight { 0 } diff --git a/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_on_initialize.stderr b/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_on_initialize.stderr index 369be77b8d249..bfefadee99403 100644 --- a/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_on_initialize.stderr +++ b/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_on_initialize.stderr @@ -2,7 +2,7 @@ error: `on_initialize` can only be passed once as input. --> $DIR/reserved_keyword_two_times_on_initialize.rs:1:1 | 1 | / frame_support::decl_module! { -2 | | pub struct Module for enum Call where origin: T::Origin, system=self { +2 | | pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self { 3 | | fn on_initialize() -> Weight { 4 | | 0 ... | diff --git a/frame/support/test/tests/decl_storage.rs b/frame/support/test/tests/decl_storage.rs index 7ce43cd5d44d1..a4e420eb454b6 100644 --- a/frame/support/test/tests/decl_storage.rs +++ b/frame/support/test/tests/decl_storage.rs @@ -23,7 +23,7 @@ mod tests { use sp_io::TestExternalities; frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} } pub trait Config: frame_support_test::Config { @@ -94,7 +94,7 @@ mod tests { struct TraitImpl {} impl frame_support_test::Config for TraitImpl { - type Origin = u32; + type RuntimeOrigin = u32; type BlockNumber = u32; type PalletInfo = frame_support_test::PanicPalletInfo; type DbWeight = (); @@ -617,7 +617,7 @@ mod test2 { pub trait Config: frame_support_test::Config {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} } type PairOf = (T, T); @@ -639,7 +639,7 @@ mod test2 { struct TraitImpl {} impl frame_support_test::Config for TraitImpl { - type Origin = u32; + type RuntimeOrigin = u32; type BlockNumber = u32; type PalletInfo = frame_support_test::PanicPalletInfo; type DbWeight = (); @@ -695,7 +695,7 @@ mod test3 { pub trait Config: frame_support_test::Config {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} } frame_support::decl_storage! { trait Store for Module as Test { @@ -708,7 +708,7 @@ mod test3 { struct TraitImpl {} impl frame_support_test::Config for TraitImpl { - type Origin = u32; + type RuntimeOrigin = u32; type BlockNumber = u32; type PalletInfo = frame_support_test::PanicPalletInfo; type DbWeight = (); @@ -726,7 +726,7 @@ mod test_append_and_len { pub trait Config: frame_support_test::Config {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} } #[derive(PartialEq, Eq, Clone, Encode, Decode, scale_info::TypeInfo)] @@ -753,7 +753,7 @@ mod test_append_and_len { struct Test {} impl frame_support_test::Config for Test { - type Origin = u32; + type RuntimeOrigin = u32; type BlockNumber = u32; type PalletInfo = frame_support_test::PanicPalletInfo; type DbWeight = (); diff --git a/frame/support/test/tests/decl_storage_ui/config_duplicate.rs b/frame/support/test/tests/decl_storage_ui/config_duplicate.rs index db2cdbdc65492..af74823f64ca6 100644 --- a/frame/support/test/tests/decl_storage_ui/config_duplicate.rs +++ b/frame/support/test/tests/decl_storage_ui/config_duplicate.rs @@ -18,7 +18,7 @@ pub trait Config: frame_support_test::Config {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} } frame_support::decl_storage!{ diff --git a/frame/support/test/tests/decl_storage_ui/config_get_duplicate.rs b/frame/support/test/tests/decl_storage_ui/config_get_duplicate.rs index b804bf8980383..8805effd9e725 100644 --- a/frame/support/test/tests/decl_storage_ui/config_get_duplicate.rs +++ b/frame/support/test/tests/decl_storage_ui/config_get_duplicate.rs @@ -18,7 +18,7 @@ pub trait Config: frame_support_test::Config {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} } frame_support::decl_storage!{ diff --git a/frame/support/test/tests/decl_storage_ui/get_duplicate.rs b/frame/support/test/tests/decl_storage_ui/get_duplicate.rs index bc03ff6b4a4f9..5e05887110537 100644 --- a/frame/support/test/tests/decl_storage_ui/get_duplicate.rs +++ b/frame/support/test/tests/decl_storage_ui/get_duplicate.rs @@ -18,7 +18,7 @@ pub trait Config: frame_support_test::Config {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} } frame_support::decl_storage!{ diff --git a/frame/support/test/tests/final_keys.rs b/frame/support/test/tests/final_keys.rs index c1723c6ad7a1b..a7ad88c801001 100644 --- a/frame/support/test/tests/final_keys.rs +++ b/frame/support/test/tests/final_keys.rs @@ -28,7 +28,7 @@ mod no_instance { pub trait Config: frame_support_test::Config {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} } frame_support::decl_storage! { @@ -53,7 +53,7 @@ mod instance { frame_support::decl_module! { pub struct Module, I: Instance = DefaultInstance> - for enum Call where origin: T::Origin, system=frame_support_test {} + for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} } frame_support::decl_storage! { diff --git a/frame/support/test/tests/genesisconfig.rs b/frame/support/test/tests/genesisconfig.rs index 367c7236d0158..f0094b3188ae1 100644 --- a/frame/support/test/tests/genesisconfig.rs +++ b/frame/support/test/tests/genesisconfig.rs @@ -18,7 +18,7 @@ pub trait Config: frame_support_test::Config {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} } frame_support::decl_storage! { @@ -31,7 +31,7 @@ struct Test; impl frame_support_test::Config for Test { type BlockNumber = u32; - type Origin = (); + type RuntimeOrigin = (); type PalletInfo = frame_support_test::PanicPalletInfo; type DbWeight = (); } diff --git a/frame/support/test/tests/instance.rs b/frame/support/test/tests/instance.rs index c9eebdaff6bc4..043959b67ee6e 100644 --- a/frame/support/test/tests/instance.rs +++ b/frame/support/test/tests/instance.rs @@ -51,14 +51,14 @@ mod module1 { ::BlockNumber: From, { type RuntimeEvent: From> + Into<::RuntimeEvent>; - type Origin: From>; + type RuntimeOrigin: From>; type SomeParameter: Get; type GenericType: Default + Clone + Codec + EncodeLike + TypeInfo; } frame_support::decl_module! { pub struct Module, I: Instance> for enum Call where - origin: ::Origin, + origin: ::RuntimeOrigin, system = system, T::BlockNumber: From { @@ -155,14 +155,14 @@ mod module2 { pub trait Config: system::Config { type Amount: Parameter + Default; type RuntimeEvent: From> + Into<::RuntimeEvent>; - type Origin: From>; + type RuntimeOrigin: From>; } impl, I: Instance> Currency for Module {} frame_support::decl_module! { pub struct Module, I: Instance=DefaultInstance> for enum Call where - origin: ::Origin, + origin: ::RuntimeOrigin, system = system { fn deposit_event() = default; @@ -228,41 +228,41 @@ mod module3 { } frame_support::decl_module! { - pub struct Module for enum Call where origin: ::Origin, system=system {} + pub struct Module for enum Call where origin: ::RuntimeOrigin, system=system {} } } impl module1::Config for Runtime { type RuntimeEvent = RuntimeEvent; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type SomeParameter = ConstU32<100>; type GenericType = u32; } impl module1::Config for Runtime { type RuntimeEvent = RuntimeEvent; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type SomeParameter = ConstU32<100>; type GenericType = u32; } impl module2::Config for Runtime { type Amount = u16; type RuntimeEvent = RuntimeEvent; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; } impl module2::Config for Runtime { type Amount = u32; type RuntimeEvent = RuntimeEvent; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; } impl module2::Config for Runtime { type Amount = u32; type RuntimeEvent = RuntimeEvent; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; } impl module2::Config for Runtime { type Amount = u64; type RuntimeEvent = RuntimeEvent; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; } impl module3::Config for Runtime { type Currency = Module2_2; @@ -277,7 +277,7 @@ pub type Index = u64; impl system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type Hash = H256; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type BlockNumber = BlockNumber; type AccountId = AccountId; type RuntimeEvent = RuntimeEvent; diff --git a/frame/support/test/tests/issue2219.rs b/frame/support/test/tests/issue2219.rs index 0b24a6aa89828..5d24d54165c1f 100644 --- a/frame/support/test/tests/issue2219.rs +++ b/frame/support/test/tests/issue2219.rs @@ -86,7 +86,7 @@ mod module { pub trait Config: system::Config + TypeInfo {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=system {} + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=system {} } #[derive(Encode, Decode, Copy, Clone, Serialize, Deserialize)] @@ -160,7 +160,7 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic for enum Call - where origin: ::Origin, system=system + where origin: ::RuntimeOrigin, system=system { #[weight = 0] pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { @@ -80,7 +80,7 @@ pub mod module { frame_support::decl_module! { pub struct Module for enum Call - where origin: ::Origin, system=system + where origin: ::RuntimeOrigin, system=system { #[weight = 0] pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { @@ -146,7 +146,7 @@ impl Contains for BaseCallFilter { impl system::Config for RuntimeOriginTest { type BaseCallFilter = BaseCallFilter; type Hash = H256; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type BlockNumber = BlockNumber; type AccountId = u32; type RuntimeEvent = RuntimeEvent; @@ -178,40 +178,40 @@ fn origin_default_filter() { let accepted_call = nested::module::Call::fail {}.into(); let rejected_call = module::Call::fail {}.into(); - assert_eq!(Origin::root().filter_call(&accepted_call), true); - assert_eq!(Origin::root().filter_call(&rejected_call), true); - assert_eq!(Origin::none().filter_call(&accepted_call), true); - assert_eq!(Origin::none().filter_call(&rejected_call), false); - assert_eq!(Origin::signed(0).filter_call(&accepted_call), true); - assert_eq!(Origin::signed(0).filter_call(&rejected_call), false); - assert_eq!(Origin::from(Some(0)).filter_call(&accepted_call), true); - assert_eq!(Origin::from(Some(0)).filter_call(&rejected_call), false); - assert_eq!(Origin::from(None).filter_call(&accepted_call), true); - assert_eq!(Origin::from(None).filter_call(&rejected_call), false); - assert_eq!(Origin::from(nested::module::Origin).filter_call(&accepted_call), true); - assert_eq!(Origin::from(nested::module::Origin).filter_call(&rejected_call), false); - - let mut origin = Origin::from(Some(0)); + assert_eq!(RuntimeOrigin::root().filter_call(&accepted_call), true); + assert_eq!(RuntimeOrigin::root().filter_call(&rejected_call), true); + assert_eq!(RuntimeOrigin::none().filter_call(&accepted_call), true); + assert_eq!(RuntimeOrigin::none().filter_call(&rejected_call), false); + assert_eq!(RuntimeOrigin::signed(0).filter_call(&accepted_call), true); + assert_eq!(RuntimeOrigin::signed(0).filter_call(&rejected_call), false); + assert_eq!(RuntimeOrigin::from(Some(0)).filter_call(&accepted_call), true); + assert_eq!(RuntimeOrigin::from(Some(0)).filter_call(&rejected_call), false); + assert_eq!(RuntimeOrigin::from(None).filter_call(&accepted_call), true); + assert_eq!(RuntimeOrigin::from(None).filter_call(&rejected_call), false); + assert_eq!(RuntimeOrigin::from(nested::module::Origin).filter_call(&accepted_call), true); + assert_eq!(RuntimeOrigin::from(nested::module::Origin).filter_call(&rejected_call), false); + + let mut origin = RuntimeOrigin::from(Some(0)); origin.add_filter(|c| matches!(c, RuntimeCall::Module(_))); assert_eq!(origin.filter_call(&accepted_call), false); assert_eq!(origin.filter_call(&rejected_call), false); // Now test for root origin and filters: - let mut origin = Origin::from(Some(0)); - origin.set_caller_from(Origin::root()); + let mut origin = RuntimeOrigin::from(Some(0)); + origin.set_caller_from(RuntimeOrigin::root()); assert!(matches!(origin.caller, OriginCaller::system(system::RawOrigin::Root))); // Root origin bypass all filter. assert_eq!(origin.filter_call(&accepted_call), true); assert_eq!(origin.filter_call(&rejected_call), true); - origin.set_caller_from(Origin::from(Some(0))); + origin.set_caller_from(RuntimeOrigin::from(Some(0))); // Back to another signed origin, the filtered are now effective again assert_eq!(origin.filter_call(&accepted_call), true); assert_eq!(origin.filter_call(&rejected_call), false); - origin.set_caller_from(Origin::root()); + origin.set_caller_from(RuntimeOrigin::root()); origin.reset_filter(); // Root origin bypass all filter, even when they are reset. diff --git a/frame/support/test/tests/pallet.rs b/frame/support/test/tests/pallet.rs index 4304aa1533a8b..05c1f14601862 100644 --- a/frame/support/test/tests/pallet.rs +++ b/frame/support/test/tests/pallet.rs @@ -552,8 +552,10 @@ pub mod pallet2 { #[frame_support::pallet] pub mod pallet3 { #[pallet::config] - pub trait Config: frame_system::Config::Origin> { - type Origin; + pub trait Config: + frame_system::Config::RuntimeOrigin> + { + type RuntimeOrigin; } #[pallet::pallet] @@ -578,7 +580,7 @@ frame_support::parameter_types!( impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u32; type RuntimeCall = RuntimeCall; @@ -618,7 +620,7 @@ impl pallet4::Config for Runtime {} #[cfg(feature = "frame-feature-testing")] impl pallet3::Config for Runtime { - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; } pub type Header = sp_runtime::generic::Header; diff --git a/frame/support/test/tests/pallet_compatibility.rs b/frame/support/test/tests/pallet_compatibility.rs index 2342f25fb98b9..398137d644ee4 100644 --- a/frame/support/test/tests/pallet_compatibility.rs +++ b/frame/support/test/tests/pallet_compatibility.rs @@ -70,7 +70,7 @@ mod pallet_old { ); decl_module! { - pub struct Module for enum Call where origin: T::Origin { + pub struct Module for enum Call where origin: T::RuntimeOrigin { type Error = Error; fn deposit_event() = default; const SomeConst: T::Balance = T::SomeConst::get(); @@ -226,7 +226,7 @@ pub mod pallet { impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u32; type RuntimeCall = RuntimeCall; diff --git a/frame/support/test/tests/pallet_compatibility_instance.rs b/frame/support/test/tests/pallet_compatibility_instance.rs index b89ab410621e5..e8b5fe9fa33d4 100644 --- a/frame/support/test/tests/pallet_compatibility_instance.rs +++ b/frame/support/test/tests/pallet_compatibility_instance.rs @@ -56,7 +56,7 @@ mod pallet_old { decl_module! { pub struct Module, I: Instance = DefaultInstance> for enum Call - where origin: T::Origin + where origin: T::RuntimeOrigin { type Error = Error; fn deposit_event() = default; @@ -210,7 +210,7 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u32; type RuntimeCall = RuntimeCall; diff --git a/frame/support/test/tests/pallet_instance.rs b/frame/support/test/tests/pallet_instance.rs index 3bbbc559ff9b8..7e05e2ecf783b 100644 --- a/frame/support/test/tests/pallet_instance.rs +++ b/frame/support/test/tests/pallet_instance.rs @@ -286,7 +286,7 @@ pub mod pallet2 { impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u32; type RuntimeCall = RuntimeCall; diff --git a/frame/support/test/tests/pallet_with_name_trait_is_valid.rs b/frame/support/test/tests/pallet_with_name_trait_is_valid.rs index 788e852ba58e9..0066420566fe8 100644 --- a/frame/support/test/tests/pallet_with_name_trait_is_valid.rs +++ b/frame/support/test/tests/pallet_with_name_trait_is_valid.rs @@ -43,7 +43,7 @@ frame_support::decl_error!( ); frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin { + pub struct Module for enum Call where origin: T::RuntimeOrigin { fn deposit_event() = default; type Error = Error; const Foo: u32 = u32::MAX; @@ -126,7 +126,7 @@ mod tests { impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = sp_core::H256; diff --git a/frame/support/test/tests/storage_layers.rs b/frame/support/test/tests/storage_layers.rs index a3e512302fe4f..6fbbb8ac67bd7 100644 --- a/frame/support/test/tests/storage_layers.rs +++ b/frame/support/test/tests/storage_layers.rs @@ -59,7 +59,7 @@ pub mod decl_pallet { pub trait Config: frame_system::Config {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin { + pub struct Module for enum Call where origin: T::RuntimeOrigin { #[weight = 0] pub fn set_value(_origin, value: u32) { DeclValue::put(value); @@ -86,7 +86,7 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u32; type RuntimeCall = RuntimeCall; @@ -256,11 +256,11 @@ fn storage_layer_in_pallet_call() { TestExternalities::default().execute_with(|| { use sp_runtime::traits::Dispatchable; let call1 = RuntimeCall::MyPallet(pallet::Call::set_value { value: 2 }); - assert_ok!(call1.dispatch(Origin::signed(0))); + assert_ok!(call1.dispatch(RuntimeOrigin::signed(0))); assert_eq!(Value::::get(), 2); let call2 = RuntimeCall::MyPallet(pallet::Call::set_value { value: 1 }); - assert_noop!(call2.dispatch(Origin::signed(0)), Error::::Revert); + assert_noop!(call2.dispatch(RuntimeOrigin::signed(0)), Error::::Revert); }); } @@ -271,12 +271,15 @@ fn storage_layer_in_decl_pallet_call() { use sp_runtime::traits::Dispatchable; let call1 = RuntimeCall::DeclPallet(decl_pallet::Call::set_value { value: 2 }); - assert_ok!(call1.dispatch(Origin::signed(0))); + assert_ok!(call1.dispatch(RuntimeOrigin::signed(0))); assert_eq!(decl_pallet::DeclValue::get(), 2); let call2 = RuntimeCall::DeclPallet(decl_pallet::Call::set_value { value: 1 }); - assert_noop!(call2.dispatch(Origin::signed(0)), "Revert!"); + assert_noop!(call2.dispatch(RuntimeOrigin::signed(0)), "Revert!"); // Calling the function directly also works with storage layers. - assert_noop!(decl_pallet::Module::::set_value(Origin::signed(1), 1), "Revert!"); + assert_noop!( + decl_pallet::Module::::set_value(RuntimeOrigin::signed(1), 1), + "Revert!" + ); }); } diff --git a/frame/support/test/tests/storage_transaction.rs b/frame/support/test/tests/storage_transaction.rs index 9e597969d6c89..6fedd75019e37 100644 --- a/frame/support/test/tests/storage_transaction.rs +++ b/frame/support/test/tests/storage_transaction.rs @@ -31,7 +31,7 @@ use sp_std::result; pub trait Config: frame_support_test::Config {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=frame_support_test { + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test { #[weight = 0] #[transactional] fn value_commits(_origin, v: u32) { @@ -57,7 +57,7 @@ frame_support::decl_storage! { struct Runtime; impl frame_support_test::Config for Runtime { - type Origin = u32; + type RuntimeOrigin = u32; type BlockNumber = u32; type PalletInfo = frame_support_test::PanicPalletInfo; type DbWeight = (); diff --git a/frame/support/test/tests/system.rs b/frame/support/test/tests/system.rs index 9736c74dc236d..eff41242917a0 100644 --- a/frame/support/test/tests/system.rs +++ b/frame/support/test/tests/system.rs @@ -22,7 +22,7 @@ use frame_support::{ }; pub trait Config: 'static + Eq + Clone { - type Origin: Into, Self::Origin>> + type RuntimeOrigin: Into, Self::RuntimeOrigin>> + From>; type BaseCallFilter: frame_support::traits::Contains; @@ -36,7 +36,7 @@ pub trait Config: 'static + Eq + Clone { } frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self { + pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self { #[weight = 0] fn noop(_origin) {} } diff --git a/frame/system/benches/bench.rs b/frame/system/benches/bench.rs index 03d3a65812d56..0881b81eaca7d 100644 --- a/frame/system/benches/bench.rs +++ b/frame/system/benches/bench.rs @@ -76,7 +76,7 @@ impl frame_system::Config for Runtime { type BlockWeights = (); type BlockLength = BlockLength; type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; diff --git a/frame/system/benchmarking/src/mock.rs b/frame/system/benchmarking/src/mock.rs index 1c0a7efa03735..a7f28ca30fe87 100644 --- a/frame/system/benchmarking/src/mock.rs +++ b/frame/system/benchmarking/src/mock.rs @@ -43,7 +43,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = AccountIndex; type BlockNumber = BlockNumber; type RuntimeCall = RuntimeCall; diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index f60e3e7349d6b..36360f8fae2c2 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -215,8 +215,8 @@ pub mod pallet { #[pallet::constant] type BlockLength: Get; - /// The `Origin` type used by dispatchable calls. - type Origin: Into, Self::Origin>> + /// The `RuntimeOrigin` type used by dispatchable calls. + type RuntimeOrigin: Into, Self::RuntimeOrigin>> + From> + Clone + OriginTrait; @@ -1701,7 +1701,7 @@ pub mod pallet_prelude { pub use crate::{ensure_none, ensure_root, ensure_signed, ensure_signed_or_root}; /// Type alias for the `Origin` associated type of system config. - pub type OriginFor = ::Origin; + pub type OriginFor = ::RuntimeOrigin; /// Type alias for the `BlockNumber` associated type of system config. pub type BlockNumberFor = ::BlockNumber; diff --git a/frame/system/src/mock.rs b/frame/system/src/mock.rs index fdaaceaf8abe0..1c0511787eb76 100644 --- a/frame/system/src/mock.rs +++ b/frame/system/src/mock.rs @@ -93,7 +93,7 @@ impl Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = RuntimeBlockWeights; type BlockLength = RuntimeBlockLength; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = u64; diff --git a/frame/system/src/tests.rs b/frame/system/src/tests.rs index b6fdda8d9cbe2..92563f4ad1747 100644 --- a/frame/system/src/tests.rs +++ b/frame/system/src/tests.rs @@ -20,7 +20,7 @@ use frame_support::{ assert_noop, assert_ok, dispatch::{Pays, PostDispatchInfo, WithPostDispatchInfo}, }; -use mock::{Origin, *}; +use mock::{RuntimeOrigin, *}; use sp_core::H256; use sp_runtime::{ traits::{BlakeTwo256, Header}, @@ -29,8 +29,8 @@ use sp_runtime::{ #[test] fn origin_works() { - let o = Origin::from(RawOrigin::::Signed(1u64)); - let x: Result, Origin> = o.into(); + let o = RuntimeOrigin::from(RawOrigin::::Signed(1u64)); + let x: Result, RuntimeOrigin> = o.into(); assert_eq!(x.unwrap(), RawOrigin::::Signed(1u64)); } @@ -638,16 +638,16 @@ fn ensure_signed_stuff_works() { } } - let signed_origin = Origin::signed(0u64); + let signed_origin = RuntimeOrigin::signed(0u64); assert_ok!(EnsureSigned::try_origin(signed_origin.clone())); assert_ok!(EnsureSignedBy::::try_origin(signed_origin)); #[cfg(feature = "runtime-benchmarks")] { - let successful_origin: Origin = EnsureSigned::successful_origin(); + let successful_origin: RuntimeOrigin = EnsureSigned::successful_origin(); assert_ok!(EnsureSigned::try_origin(successful_origin)); - let successful_origin: Origin = EnsureSignedBy::::successful_origin(); + let successful_origin: RuntimeOrigin = EnsureSignedBy::::successful_origin(); assert_ok!(EnsureSignedBy::::try_origin(successful_origin)); } } diff --git a/frame/timestamp/src/mock.rs b/frame/timestamp/src/mock.rs index 7d3da0e8a0b83..2208510f24fe5 100644 --- a/frame/timestamp/src/mock.rs +++ b/frame/timestamp/src/mock.rs @@ -55,7 +55,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; diff --git a/frame/timestamp/src/tests.rs b/frame/timestamp/src/tests.rs index ef9fd6e39d4b5..6a76fbc4820e6 100644 --- a/frame/timestamp/src/tests.rs +++ b/frame/timestamp/src/tests.rs @@ -24,7 +24,7 @@ use frame_support::assert_ok; fn timestamp_works() { new_test_ext().execute_with(|| { crate::Now::::put(46); - assert_ok!(Timestamp::set(Origin::none(), 69)); + assert_ok!(Timestamp::set(RuntimeOrigin::none(), 69)); assert_eq!(Timestamp::now(), 69); assert_eq!(Some(69), get_captured_moment()); }); @@ -35,7 +35,7 @@ fn timestamp_works() { fn double_timestamp_should_fail() { new_test_ext().execute_with(|| { Timestamp::set_timestamp(42); - assert_ok!(Timestamp::set(Origin::none(), 69)); + assert_ok!(Timestamp::set(RuntimeOrigin::none(), 69)); }); } @@ -46,6 +46,6 @@ fn double_timestamp_should_fail() { fn block_period_minimum_enforced() { new_test_ext().execute_with(|| { crate::Now::::put(44); - let _ = Timestamp::set(Origin::none(), 46); + let _ = Timestamp::set(RuntimeOrigin::none(), 46); }); } diff --git a/frame/tips/src/benchmarking.rs b/frame/tips/src/benchmarking.rs index 4956e2a095688..312424e5799ec 100644 --- a/frame/tips/src/benchmarking.rs +++ b/frame/tips/src/benchmarking.rs @@ -197,7 +197,7 @@ benchmarks_instance_pallet! { let hash = T::Hashing::hash_of(&(&reason_hash, &beneficiary)); ensure!(Tips::::contains_key(hash), "tip does not exist"); let reject_origin = T::RejectOrigin::successful_origin(); - }: _(reject_origin, hash) + }: _(reject_origin, hash) impl_benchmark_test_suite!(TipsMod, crate::tests::new_test_ext(), crate::tests::Test); } diff --git a/frame/tips/src/tests.rs b/frame/tips/src/tests.rs index 9b721bd77a8bc..cb0b4458c7fba 100644 --- a/frame/tips/src/tests.rs +++ b/frame/tips/src/tests.rs @@ -65,7 +65,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; @@ -230,9 +230,9 @@ fn tip_hash() -> H256 { fn tip_new_cannot_be_used_twice() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Tips::tip_new(Origin::signed(10), b"awesome.dot".to_vec(), 3, 10)); + assert_ok!(Tips::tip_new(RuntimeOrigin::signed(10), b"awesome.dot".to_vec(), 3, 10)); assert_noop!( - Tips::tip_new(Origin::signed(11), b"awesome.dot".to_vec(), 3, 10), + Tips::tip_new(RuntimeOrigin::signed(11), b"awesome.dot".to_vec(), 3, 10), Error::::AlreadyKnown ); }); @@ -242,23 +242,23 @@ fn tip_new_cannot_be_used_twice() { fn report_awesome_and_tip_works() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Tips::report_awesome(Origin::signed(0), b"awesome.dot".to_vec(), 3)); + assert_ok!(Tips::report_awesome(RuntimeOrigin::signed(0), b"awesome.dot".to_vec(), 3)); assert_eq!(Balances::reserved_balance(0), 12); assert_eq!(Balances::free_balance(0), 88); // other reports don't count. assert_noop!( - Tips::report_awesome(Origin::signed(1), b"awesome.dot".to_vec(), 3), + Tips::report_awesome(RuntimeOrigin::signed(1), b"awesome.dot".to_vec(), 3), Error::::AlreadyKnown ); let h = tip_hash(); - assert_ok!(Tips::tip(Origin::signed(10), h, 10)); - assert_ok!(Tips::tip(Origin::signed(11), h, 10)); - assert_ok!(Tips::tip(Origin::signed(12), h, 10)); - assert_noop!(Tips::tip(Origin::signed(9), h, 10), BadOrigin); + assert_ok!(Tips::tip(RuntimeOrigin::signed(10), h, 10)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(11), h, 10)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(12), h, 10)); + assert_noop!(Tips::tip(RuntimeOrigin::signed(9), h, 10), BadOrigin); System::set_block_number(2); - assert_ok!(Tips::close_tip(Origin::signed(100), h.into())); + assert_ok!(Tips::close_tip(RuntimeOrigin::signed(100), h.into())); assert_eq!(Balances::reserved_balance(0), 0); assert_eq!(Balances::free_balance(0), 102); assert_eq!(Balances::free_balance(3), 8); @@ -269,15 +269,15 @@ fn report_awesome_and_tip_works() { fn report_awesome_from_beneficiary_and_tip_works() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Tips::report_awesome(Origin::signed(0), b"awesome.dot".to_vec(), 0)); + assert_ok!(Tips::report_awesome(RuntimeOrigin::signed(0), b"awesome.dot".to_vec(), 0)); assert_eq!(Balances::reserved_balance(0), 12); assert_eq!(Balances::free_balance(0), 88); let h = BlakeTwo256::hash_of(&(BlakeTwo256::hash(b"awesome.dot"), 0u128)); - assert_ok!(Tips::tip(Origin::signed(10), h, 10)); - assert_ok!(Tips::tip(Origin::signed(11), h, 10)); - assert_ok!(Tips::tip(Origin::signed(12), h, 10)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(10), h, 10)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(11), h, 10)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(12), h, 10)); System::set_block_number(2); - assert_ok!(Tips::close_tip(Origin::signed(100), h.into())); + assert_ok!(Tips::close_tip(RuntimeOrigin::signed(100), h.into())); assert_eq!(Balances::reserved_balance(0), 0); assert_eq!(Balances::free_balance(0), 110); }); @@ -291,30 +291,33 @@ fn close_tip_works() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); - assert_ok!(Tips::tip_new(Origin::signed(10), b"awesome.dot".to_vec(), 3, 10)); + assert_ok!(Tips::tip_new(RuntimeOrigin::signed(10), b"awesome.dot".to_vec(), 3, 10)); let h = tip_hash(); assert_eq!(last_event(), TipEvent::NewTip { tip_hash: h }); - assert_ok!(Tips::tip(Origin::signed(11), h, 10)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(11), h, 10)); - assert_noop!(Tips::close_tip(Origin::signed(0), h.into()), Error::::StillOpen); + assert_noop!(Tips::close_tip(RuntimeOrigin::signed(0), h.into()), Error::::StillOpen); - assert_ok!(Tips::tip(Origin::signed(12), h, 10)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(12), h, 10)); assert_eq!(last_event(), TipEvent::TipClosing { tip_hash: h }); - assert_noop!(Tips::close_tip(Origin::signed(0), h.into()), Error::::Premature); + assert_noop!(Tips::close_tip(RuntimeOrigin::signed(0), h.into()), Error::::Premature); System::set_block_number(2); - assert_noop!(Tips::close_tip(Origin::none(), h.into()), BadOrigin); - assert_ok!(Tips::close_tip(Origin::signed(0), h.into())); + assert_noop!(Tips::close_tip(RuntimeOrigin::none(), h.into()), BadOrigin); + assert_ok!(Tips::close_tip(RuntimeOrigin::signed(0), h.into())); assert_eq!(Balances::free_balance(3), 10); assert_eq!(last_event(), TipEvent::TipClosed { tip_hash: h, who: 3, payout: 10 }); - assert_noop!(Tips::close_tip(Origin::signed(100), h.into()), Error::::UnknownTip); + assert_noop!( + Tips::close_tip(RuntimeOrigin::signed(100), h.into()), + Error::::UnknownTip + ); }); } @@ -328,7 +331,7 @@ fn slash_tip_works() { assert_eq!(Balances::reserved_balance(0), 0); assert_eq!(Balances::free_balance(0), 100); - assert_ok!(Tips::report_awesome(Origin::signed(0), b"awesome.dot".to_vec(), 3)); + assert_ok!(Tips::report_awesome(RuntimeOrigin::signed(0), b"awesome.dot".to_vec(), 3)); assert_eq!(Balances::reserved_balance(0), 12); assert_eq!(Balances::free_balance(0), 88); @@ -337,10 +340,10 @@ fn slash_tip_works() { assert_eq!(last_event(), TipEvent::NewTip { tip_hash: h }); // can't remove from any origin - assert_noop!(Tips::slash_tip(Origin::signed(0), h), BadOrigin); + assert_noop!(Tips::slash_tip(RuntimeOrigin::signed(0), h), BadOrigin); // can remove from root. - assert_ok!(Tips::slash_tip(Origin::root(), h)); + assert_ok!(Tips::slash_tip(RuntimeOrigin::root(), h)); assert_eq!(last_event(), TipEvent::TipSlashed { tip_hash: h, finder: 0, deposit: 12 }); // tipper slashed @@ -354,26 +357,32 @@ fn retract_tip_works() { new_test_ext().execute_with(|| { // with report awesome Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Tips::report_awesome(Origin::signed(0), b"awesome.dot".to_vec(), 3)); + assert_ok!(Tips::report_awesome(RuntimeOrigin::signed(0), b"awesome.dot".to_vec(), 3)); let h = tip_hash(); - assert_ok!(Tips::tip(Origin::signed(10), h, 10)); - assert_ok!(Tips::tip(Origin::signed(11), h, 10)); - assert_ok!(Tips::tip(Origin::signed(12), h, 10)); - assert_noop!(Tips::retract_tip(Origin::signed(10), h), Error::::NotFinder); - assert_ok!(Tips::retract_tip(Origin::signed(0), h)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(10), h, 10)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(11), h, 10)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(12), h, 10)); + assert_noop!(Tips::retract_tip(RuntimeOrigin::signed(10), h), Error::::NotFinder); + assert_ok!(Tips::retract_tip(RuntimeOrigin::signed(0), h)); System::set_block_number(2); - assert_noop!(Tips::close_tip(Origin::signed(0), h.into()), Error::::UnknownTip); + assert_noop!( + Tips::close_tip(RuntimeOrigin::signed(0), h.into()), + Error::::UnknownTip + ); // with tip new Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Tips::tip_new(Origin::signed(10), b"awesome.dot".to_vec(), 3, 10)); + assert_ok!(Tips::tip_new(RuntimeOrigin::signed(10), b"awesome.dot".to_vec(), 3, 10)); let h = tip_hash(); - assert_ok!(Tips::tip(Origin::signed(11), h, 10)); - assert_ok!(Tips::tip(Origin::signed(12), h, 10)); - assert_noop!(Tips::retract_tip(Origin::signed(0), h), Error::::NotFinder); - assert_ok!(Tips::retract_tip(Origin::signed(10), h)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(11), h, 10)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(12), h, 10)); + assert_noop!(Tips::retract_tip(RuntimeOrigin::signed(0), h), Error::::NotFinder); + assert_ok!(Tips::retract_tip(RuntimeOrigin::signed(10), h)); System::set_block_number(2); - assert_noop!(Tips::close_tip(Origin::signed(10), h.into()), Error::::UnknownTip); + assert_noop!( + Tips::close_tip(RuntimeOrigin::signed(10), h.into()), + Error::::UnknownTip + ); }); } @@ -381,12 +390,12 @@ fn retract_tip_works() { fn tip_median_calculation_works() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Tips::tip_new(Origin::signed(10), b"awesome.dot".to_vec(), 3, 0)); + assert_ok!(Tips::tip_new(RuntimeOrigin::signed(10), b"awesome.dot".to_vec(), 3, 0)); let h = tip_hash(); - assert_ok!(Tips::tip(Origin::signed(11), h, 10)); - assert_ok!(Tips::tip(Origin::signed(12), h, 1000000)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(11), h, 10)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(12), h, 1000000)); System::set_block_number(2); - assert_ok!(Tips::close_tip(Origin::signed(0), h.into())); + assert_ok!(Tips::close_tip(RuntimeOrigin::signed(0), h.into())); assert_eq!(Balances::free_balance(3), 10); }); } @@ -395,17 +404,17 @@ fn tip_median_calculation_works() { fn tip_changing_works() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Tips::tip_new(Origin::signed(10), b"awesome.dot".to_vec(), 3, 10000)); + assert_ok!(Tips::tip_new(RuntimeOrigin::signed(10), b"awesome.dot".to_vec(), 3, 10000)); let h = tip_hash(); - assert_ok!(Tips::tip(Origin::signed(11), h, 10000)); - assert_ok!(Tips::tip(Origin::signed(12), h, 10000)); - assert_ok!(Tips::tip(Origin::signed(13), h, 0)); - assert_ok!(Tips::tip(Origin::signed(14), h, 0)); - assert_ok!(Tips::tip(Origin::signed(12), h, 1000)); - assert_ok!(Tips::tip(Origin::signed(11), h, 100)); - assert_ok!(Tips::tip(Origin::signed(10), h, 10)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(11), h, 10000)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(12), h, 10000)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(13), h, 0)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(14), h, 0)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(12), h, 1000)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(11), h, 100)); + assert_ok!(Tips::tip(RuntimeOrigin::signed(10), h, 10)); System::set_block_number(2); - assert_ok!(Tips::close_tip(Origin::signed(0), h.into())); + assert_ok!(Tips::close_tip(RuntimeOrigin::signed(0), h.into())); assert_eq!(Balances::free_balance(3), 10); }); } @@ -582,24 +591,24 @@ fn report_awesome_and_tip_works_second_instance() { assert_eq!(Balances::free_balance(&Treasury::account_id()), 101); assert_eq!(Balances::free_balance(&Treasury1::account_id()), 201); - assert_ok!(Tips1::report_awesome(Origin::signed(0), b"awesome.dot".to_vec(), 3)); + assert_ok!(Tips1::report_awesome(RuntimeOrigin::signed(0), b"awesome.dot".to_vec(), 3)); // duplicate report in tips1 reports don't count. assert_noop!( - Tips1::report_awesome(Origin::signed(1), b"awesome.dot".to_vec(), 3), + Tips1::report_awesome(RuntimeOrigin::signed(1), b"awesome.dot".to_vec(), 3), Error::::AlreadyKnown ); // but tips is separate - assert_ok!(Tips::report_awesome(Origin::signed(0), b"awesome.dot".to_vec(), 3)); + assert_ok!(Tips::report_awesome(RuntimeOrigin::signed(0), b"awesome.dot".to_vec(), 3)); let h = tip_hash(); - assert_ok!(Tips1::tip(Origin::signed(10), h, 10)); - assert_ok!(Tips1::tip(Origin::signed(11), h, 10)); - assert_ok!(Tips1::tip(Origin::signed(12), h, 10)); - assert_noop!(Tips1::tip(Origin::signed(9), h, 10), BadOrigin); + assert_ok!(Tips1::tip(RuntimeOrigin::signed(10), h, 10)); + assert_ok!(Tips1::tip(RuntimeOrigin::signed(11), h, 10)); + assert_ok!(Tips1::tip(RuntimeOrigin::signed(12), h, 10)); + assert_noop!(Tips1::tip(RuntimeOrigin::signed(9), h, 10), BadOrigin); System::set_block_number(2); - assert_ok!(Tips1::close_tip(Origin::signed(100), h.into())); + assert_ok!(Tips1::close_tip(RuntimeOrigin::signed(100), h.into())); // Treasury 1 unchanged assert_eq!(Balances::free_balance(&Treasury::account_id()), 101); // Treasury 2 gave the funds diff --git a/frame/transaction-payment/asset-tx-payment/src/tests.rs b/frame/transaction-payment/asset-tx-payment/src/tests.rs index 1f6113aabdddd..cdf7d17898145 100644 --- a/frame/transaction-payment/asset-tx-payment/src/tests.rs +++ b/frame/transaction-payment/asset-tx-payment/src/tests.rs @@ -87,7 +87,7 @@ impl frame_system::Config for Runtime { type BlockWeights = BlockWeights; type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; @@ -338,7 +338,7 @@ fn transaction_payment_in_asset_possible() { let asset_id = 1; let min_balance = 2; assert_ok!(Assets::force_create( - Origin::root(), + RuntimeOrigin::root(), asset_id, 42, /* owner */ true, /* is_sufficient */ @@ -391,7 +391,7 @@ fn transaction_payment_without_fee() { let asset_id = 1; let min_balance = 2; assert_ok!(Assets::force_create( - Origin::root(), + RuntimeOrigin::root(), asset_id, 42, /* owner */ true, /* is_sufficient */ @@ -444,7 +444,7 @@ fn asset_transaction_payment_with_tip_and_refund() { let asset_id = 1; let min_balance = 2; assert_ok!(Assets::force_create( - Origin::root(), + RuntimeOrigin::root(), asset_id, 42, /* owner */ true, /* is_sufficient */ @@ -496,7 +496,7 @@ fn payment_from_account_with_only_assets() { let asset_id = 1; let min_balance = 2; assert_ok!(Assets::force_create( - Origin::root(), + RuntimeOrigin::root(), asset_id, 42, /* owner */ true, /* is_sufficient */ @@ -555,7 +555,7 @@ fn payment_only_with_existing_sufficient_asset() { // create the non-sufficient asset let min_balance = 2; assert_ok!(Assets::force_create( - Origin::root(), + RuntimeOrigin::root(), asset_id, 42, /* owner */ false, /* is_sufficient */ @@ -580,7 +580,7 @@ fn converted_fee_is_never_zero_if_input_fee_is_not() { let asset_id = 1; let min_balance = 1; assert_ok!(Assets::force_create( - Origin::root(), + RuntimeOrigin::root(), asset_id, 42, /* owner */ true, /* is_sufficient */ @@ -645,7 +645,7 @@ fn post_dispatch_fee_is_zero_if_pre_dispatch_fee_is_zero() { let asset_id = 1; let min_balance = 100; assert_ok!(Assets::force_create( - Origin::root(), + RuntimeOrigin::root(), asset_id, 42, /* owner */ true, /* is_sufficient */ @@ -702,7 +702,7 @@ fn post_dispatch_fee_is_zero_if_unsigned_pre_dispatch_fee_is_zero() { let asset_id = 1; let min_balance = 100; assert_ok!(Assets::force_create( - Origin::root(), + RuntimeOrigin::root(), asset_id, 42, /* owner */ true, /* is_sufficient */ diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index 0447ea6bfd99d..1ad6a2b3b3b6f 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -906,7 +906,7 @@ mod tests { type BlockWeights = BlockWeights; type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; diff --git a/frame/transaction-storage/Cargo.toml b/frame/transaction-storage/Cargo.toml index 61b71b000a616..a6e177af1853d 100644 --- a/frame/transaction-storage/Cargo.toml +++ b/frame/transaction-storage/Cargo.toml @@ -13,8 +13,8 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] +array-bytes = { version = "4.1", optional = true } codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } -hex-literal = { version = "0.3.4", optional = true } scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } serde = { version = "1.0.136", optional = true } frame-benchmarking = { version = "4.0.0-dev", default-features = false, optional = true, path = "../benchmarking" } @@ -34,7 +34,7 @@ sp-transaction-storage-proof = { version = "4.0.0-dev", default-features = true, [features] default = ["std"] -runtime-benchmarks = ["frame-benchmarking/runtime-benchmarks", "hex-literal"] +runtime-benchmarks = ["array-bytes", "frame-benchmarking/runtime-benchmarks"] std = [ "log/std", "frame-benchmarking?/std", diff --git a/frame/transaction-storage/src/benchmarking.rs b/frame/transaction-storage/src/benchmarking.rs index cab4c92317bb5..c7fbd00fb565d 100644 --- a/frame/transaction-storage/src/benchmarking.rs +++ b/frame/transaction-storage/src/benchmarking.rs @@ -40,67 +40,68 @@ use crate::Pallet as TransactionStorage; // build_proof(hash.as_slice(), transactions).unwrap().encode() // ``` // while hardforcing target chunk key in `build_proof` to [22, 21, 1, 0]. -const PROOF: &[u8] = &hex_literal::hex!( - " - 0104000000000000000000000000000000000000000000000000000000000000000000000000 - 0000000000000000000000000000000000000000000000000000000000000000000000000000 - 0000000000000000000000000000000000000000000000000000000000000000000000000000 - 0000000000000000000000000000000000000000000000000000000000000000000000000000 - 0000000000000000000000000000000000000000000000000000000000000000000000000000 - 0000000000000000000000000000000000000000000000000000000000000000000000000000 - 00000000000000000000000000000000000000000000000000000000000014cd0780ffff8030 - 2eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba0080302eb0a6d2 - f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15 - f1e729d1c1004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1 - 004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e304 - 8cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697 - eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a - 30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba80302e - b0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b - 834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e7 - 29d1c1004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c10046 - 57e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf2 - 06d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb1 - 53f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba - bd058077778010fd81bc1359802f0b871aeb95e4410a8ec92b93af10ea767a2027cf4734e8de - 808da338e6b722f7bf2051901bd5bccee5e71d5cf6b1faff338ad7120b0256c28380221ce17f - 19117affa96e077905fe48a99723a065969c638593b7d9ab57b538438010fd81bc1359802f0b - 871aeb95e4410a8ec92b93af10ea767a2027cf4734e8de808da338e6b722f7bf2051901bd5bc - cee5e71d5cf6b1faff338ad7120b0256c283008010fd81bc1359802f0b871aeb95e4410a8ec9 - 2b93af10ea767a2027cf4734e8de808da338e6b722f7bf2051901bd5bccee5e71d5cf6b1faff - 338ad7120b0256c28380221ce17f19117affa96e077905fe48a99723a065969c638593b7d9ab - 57b538438010fd81bc1359802f0b871aeb95e4410a8ec92b93af10ea767a2027cf4734e8de80 - 8da338e6b722f7bf2051901bd5bccee5e71d5cf6b1faff338ad7120b0256c28380221ce17f19 - 117affa96e077905fe48a99723a065969c638593b7d9ab57b53843cd0780ffff804509f59593 - fd47b1a97189127ba65a5649cfb0346637f9836e155eaf891a939c00804509f59593fd47b1a9 - 7189127ba65a5649cfb0346637f9836e155eaf891a939c804509f59593fd47b1a97189127ba6 - 5a5649cfb0346637f9836e155eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb0 - 346637f9836e155eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb0346637f983 - 6e155eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb0346637f9836e155eaf89 - 1a939c804509f59593fd47b1a97189127ba65a5649cfb0346637f9836e155eaf891a939c8045 - 09f59593fd47b1a97189127ba65a5649cfb0346637f9836e155eaf891a939c804509f59593fd - 47b1a97189127ba65a5649cfb0346637f9836e155eaf891a939c804509f59593fd47b1a97189 - 127ba65a5649cfb0346637f9836e155eaf891a939c804509f59593fd47b1a97189127ba65a56 - 49cfb0346637f9836e155eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb03466 - 37f9836e155eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb0346637f9836e15 - 5eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb0346637f9836e155eaf891a93 - 9c804509f59593fd47b1a97189127ba65a5649cfb0346637f9836e155eaf891a939ccd0780ff - ff8078916e776c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e - 776c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea - 05e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea05e958559f - 015c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea05e958559f015c082d9d - 06feafa3610fc44a5b2ef543cb81008078916e776c64ccea05e958559f015c082d9d06feafa3 - 610fc44a5b2ef543cb818078916e776c64ccea05e958559f015c082d9d06feafa3610fc44a5b - 2ef543cb818078916e776c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef543cb81 - 8078916e776c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e77 - 6c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea05 - e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea05e958559f01 - 5c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea05e958559f015c082d9d06 - feafa3610fc44a5b2ef543cb818078916e776c64ccea05e958559f015c082d9d06feafa3610f - c44a5b2ef543cb818078916e776c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef5 - 43cb811044010000 - " -); +const PROOF: &str = "\ + 0104000000000000000000000000000000000000000000000000000000000000000000000000\ + 0000000000000000000000000000000000000000000000000000000000000000000000000000\ + 0000000000000000000000000000000000000000000000000000000000000000000000000000\ + 0000000000000000000000000000000000000000000000000000000000000000000000000000\ + 0000000000000000000000000000000000000000000000000000000000000000000000000000\ + 0000000000000000000000000000000000000000000000000000000000000000000000000000\ + 00000000000000000000000000000000000000000000000000000000000014cd0780ffff8030\ + 2eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba0080302eb0a6d2\ + f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15\ + f1e729d1c1004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1\ + 004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e304\ + 8cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697\ + eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a\ + 30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba80302e\ + b0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b\ + 834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e7\ + 29d1c1004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c10046\ + 57e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf2\ + 06d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb1\ + 53f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba\ + bd058077778010fd81bc1359802f0b871aeb95e4410a8ec92b93af10ea767a2027cf4734e8de\ + 808da338e6b722f7bf2051901bd5bccee5e71d5cf6b1faff338ad7120b0256c28380221ce17f\ + 19117affa96e077905fe48a99723a065969c638593b7d9ab57b538438010fd81bc1359802f0b\ + 871aeb95e4410a8ec92b93af10ea767a2027cf4734e8de808da338e6b722f7bf2051901bd5bc\ + cee5e71d5cf6b1faff338ad7120b0256c283008010fd81bc1359802f0b871aeb95e4410a8ec9\ + 2b93af10ea767a2027cf4734e8de808da338e6b722f7bf2051901bd5bccee5e71d5cf6b1faff\ + 338ad7120b0256c28380221ce17f19117affa96e077905fe48a99723a065969c638593b7d9ab\ + 57b538438010fd81bc1359802f0b871aeb95e4410a8ec92b93af10ea767a2027cf4734e8de80\ + 8da338e6b722f7bf2051901bd5bccee5e71d5cf6b1faff338ad7120b0256c28380221ce17f19\ + 117affa96e077905fe48a99723a065969c638593b7d9ab57b53843cd0780ffff804509f59593\ + fd47b1a97189127ba65a5649cfb0346637f9836e155eaf891a939c00804509f59593fd47b1a9\ + 7189127ba65a5649cfb0346637f9836e155eaf891a939c804509f59593fd47b1a97189127ba6\ + 5a5649cfb0346637f9836e155eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb0\ + 346637f9836e155eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb0346637f983\ + 6e155eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb0346637f9836e155eaf89\ + 1a939c804509f59593fd47b1a97189127ba65a5649cfb0346637f9836e155eaf891a939c8045\ + 09f59593fd47b1a97189127ba65a5649cfb0346637f9836e155eaf891a939c804509f59593fd\ + 47b1a97189127ba65a5649cfb0346637f9836e155eaf891a939c804509f59593fd47b1a97189\ + 127ba65a5649cfb0346637f9836e155eaf891a939c804509f59593fd47b1a97189127ba65a56\ + 49cfb0346637f9836e155eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb03466\ + 37f9836e155eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb0346637f9836e15\ + 5eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb0346637f9836e155eaf891a93\ + 9c804509f59593fd47b1a97189127ba65a5649cfb0346637f9836e155eaf891a939ccd0780ff\ + ff8078916e776c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e\ + 776c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea\ + 05e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea05e958559f\ + 015c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea05e958559f015c082d9d\ + 06feafa3610fc44a5b2ef543cb81008078916e776c64ccea05e958559f015c082d9d06feafa3\ + 610fc44a5b2ef543cb818078916e776c64ccea05e958559f015c082d9d06feafa3610fc44a5b\ + 2ef543cb818078916e776c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef543cb81\ + 8078916e776c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e77\ + 6c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea05\ + e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea05e958559f01\ + 5c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea05e958559f015c082d9d06\ + feafa3610fc44a5b2ef543cb818078916e776c64ccea05e958559f015c082d9d06feafa3610f\ + c44a5b2ef543cb818078916e776c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef5\ + 43cb811044010000\ +"; +fn proof() -> Vec { + array_bytes::hex2bytes_unchecked(PROOF) +} type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; @@ -159,8 +160,8 @@ benchmarks! { )?; } run_to_block::(StoragePeriod::::get() + T::BlockNumber::one()); - let mut encoded_proof = PROOF; - let proof = TransactionStorageProof::decode(&mut encoded_proof).unwrap(); + let encoded_proof = proof(); + let proof = TransactionStorageProof::decode(&mut &*encoded_proof).unwrap(); }: check_proof(RawOrigin::None, proof) verify { assert_last_event::(Event::ProofChecked.into()); diff --git a/frame/transaction-storage/src/lib.rs b/frame/transaction-storage/src/lib.rs index e623079ac863b..07144c5617113 100644 --- a/frame/transaction-storage/src/lib.rs +++ b/frame/transaction-storage/src/lib.rs @@ -95,7 +95,7 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// A dispatchable call. type RuntimeCall: Parameter - + Dispatchable + + Dispatchable + GetDispatchInfo + From>; /// The currency trait. diff --git a/frame/transaction-storage/src/mock.rs b/frame/transaction-storage/src/mock.rs index 1cb725e63e83b..8764b16c31d8d 100644 --- a/frame/transaction-storage/src/mock.rs +++ b/frame/transaction-storage/src/mock.rs @@ -51,7 +51,7 @@ impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); type BlockLength = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = u64; @@ -116,7 +116,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { pub fn run_to_block(n: u64, f: impl Fn() -> Option) { while System::block_number() < n { if let Some(proof) = f() { - TransactionStorage::check_proof(Origin::none(), proof).unwrap(); + TransactionStorage::check_proof(RuntimeOrigin::none(), proof).unwrap(); } TransactionStorage::on_finalize(System::block_number()); System::on_finalize(System::block_number()); diff --git a/frame/transaction-storage/src/tests.rs b/frame/transaction-storage/src/tests.rs index 4f5ce1c4b654d..01b71a7851ac3 100644 --- a/frame/transaction-storage/src/tests.rs +++ b/frame/transaction-storage/src/tests.rs @@ -95,7 +95,7 @@ fn checks_proof() { let proof = build_proof(parent_hash.as_ref(), vec![vec![0u8; MAX_DATA_SIZE as usize]]).unwrap(); assert_noop!( - TransactionStorage::::check_proof(Origin::none(), proof,), + TransactionStorage::::check_proof(RuntimeOrigin::none(), proof,), Error::::UnexpectedProof, ); run_to_block(11, || None); @@ -103,13 +103,13 @@ fn checks_proof() { let invalid_proof = build_proof(parent_hash.as_ref(), vec![vec![0u8; 1000]]).unwrap(); assert_noop!( - TransactionStorage::::check_proof(Origin::none(), invalid_proof,), + TransactionStorage::::check_proof(RuntimeOrigin::none(), invalid_proof,), Error::::InvalidProof, ); let proof = build_proof(parent_hash.as_ref(), vec![vec![0u8; MAX_DATA_SIZE as usize]]).unwrap(); - assert_ok!(TransactionStorage::::check_proof(Origin::none(), proof)); + assert_ok!(TransactionStorage::::check_proof(RuntimeOrigin::none(), proof)); }); } diff --git a/frame/treasury/src/benchmarking.rs b/frame/treasury/src/benchmarking.rs index b3787e2063c45..d718a5fb89521 100644 --- a/frame/treasury/src/benchmarking.rs +++ b/frame/treasury/src/benchmarking.rs @@ -100,7 +100,7 @@ benchmarks_instance_pallet! { )?; let proposal_id = Treasury::::proposal_count() - 1; let reject_origin = T::RejectOrigin::successful_origin(); - }: _(reject_origin, proposal_id) + }: _(reject_origin, proposal_id) approve_proposal { let p in 0 .. T::MaxApprovals::get() - 1; @@ -113,7 +113,7 @@ benchmarks_instance_pallet! { )?; let proposal_id = Treasury::::proposal_count() - 1; let approve_origin = T::ApproveOrigin::successful_origin(); - }: _(approve_origin, proposal_id) + }: _(approve_origin, proposal_id) remove_approval { let (caller, value, beneficiary_lookup) = setup_proposal::(SEED); @@ -125,7 +125,7 @@ benchmarks_instance_pallet! { let proposal_id = Treasury::::proposal_count() - 1; Treasury::::approve_proposal(RawOrigin::Root.into(), proposal_id)?; let reject_origin = T::RejectOrigin::successful_origin(); - }: _(reject_origin, proposal_id) + }: _(reject_origin, proposal_id) on_initialize_proposals { let p in 0 .. T::MaxApprovals::get(); diff --git a/frame/treasury/src/lib.rs b/frame/treasury/src/lib.rs index bebbcda2effb6..21b4d2b769c8b 100644 --- a/frame/treasury/src/lib.rs +++ b/frame/treasury/src/lib.rs @@ -149,10 +149,10 @@ pub mod pallet { type Currency: Currency + ReservableCurrency; /// Origin from which approvals must come. - type ApproveOrigin: EnsureOrigin; + type ApproveOrigin: EnsureOrigin; /// Origin from which rejections must come. - type RejectOrigin: EnsureOrigin; + type RejectOrigin: EnsureOrigin; /// The overarching event type. type RuntimeEvent: From> @@ -204,7 +204,7 @@ pub mod pallet { /// The origin required for approving spends from the treasury outside of the proposal /// process. The `Success` value is the maximum amount that this origin is allowed to /// spend at a time. - type SpendOrigin: EnsureOrigin>; + type SpendOrigin: EnsureOrigin>; } /// Number of proposals that have been made. diff --git a/frame/treasury/src/tests.rs b/frame/treasury/src/tests.rs index af77b419d67d2..9cfe147ec4ce4 100644 --- a/frame/treasury/src/tests.rs +++ b/frame/treasury/src/tests.rs @@ -60,7 +60,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type RuntimeCall = RuntimeCall; @@ -98,21 +98,21 @@ parameter_types! { pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); } pub struct TestSpendOrigin; -impl frame_support::traits::EnsureOrigin for TestSpendOrigin { +impl frame_support::traits::EnsureOrigin for TestSpendOrigin { type Success = u64; - fn try_origin(o: Origin) -> Result { - Result::, Origin>::from(o).and_then(|o| match o { + fn try_origin(o: RuntimeOrigin) -> Result { + Result::, RuntimeOrigin>::from(o).and_then(|o| match o { frame_system::RawOrigin::Root => Ok(u64::max_value()), frame_system::RawOrigin::Signed(10) => Ok(5), frame_system::RawOrigin::Signed(11) => Ok(10), frame_system::RawOrigin::Signed(12) => Ok(20), frame_system::RawOrigin::Signed(13) => Ok(50), - r => Err(Origin::from(r)), + r => Err(RuntimeOrigin::from(r)), }) } #[cfg(feature = "runtime-benchmarks")] - fn try_successful_origin() -> Result { - Ok(Origin::root()) + fn try_successful_origin() -> Result { + Ok(RuntimeOrigin::root()) } } @@ -158,21 +158,21 @@ fn genesis_config_works() { #[test] fn spend_origin_permissioning_works() { new_test_ext().execute_with(|| { - assert_noop!(Treasury::spend(Origin::signed(1), 1, 1), BadOrigin); + assert_noop!(Treasury::spend(RuntimeOrigin::signed(1), 1, 1), BadOrigin); assert_noop!( - Treasury::spend(Origin::signed(10), 6, 1), + Treasury::spend(RuntimeOrigin::signed(10), 6, 1), Error::::InsufficientPermission ); assert_noop!( - Treasury::spend(Origin::signed(11), 11, 1), + Treasury::spend(RuntimeOrigin::signed(11), 11, 1), Error::::InsufficientPermission ); assert_noop!( - Treasury::spend(Origin::signed(12), 21, 1), + Treasury::spend(RuntimeOrigin::signed(12), 21, 1), Error::::InsufficientPermission ); assert_noop!( - Treasury::spend(Origin::signed(13), 51, 1), + Treasury::spend(RuntimeOrigin::signed(13), 51, 1), Error::::InsufficientPermission ); }); @@ -183,13 +183,13 @@ fn spend_origin_works() { new_test_ext().execute_with(|| { // Check that accumulate works when we have Some value in Dummy already. Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Treasury::spend(Origin::signed(10), 5, 6)); - assert_ok!(Treasury::spend(Origin::signed(10), 5, 6)); - assert_ok!(Treasury::spend(Origin::signed(10), 5, 6)); - assert_ok!(Treasury::spend(Origin::signed(10), 5, 6)); - assert_ok!(Treasury::spend(Origin::signed(11), 10, 6)); - assert_ok!(Treasury::spend(Origin::signed(12), 20, 6)); - assert_ok!(Treasury::spend(Origin::signed(13), 50, 6)); + assert_ok!(Treasury::spend(RuntimeOrigin::signed(10), 5, 6)); + assert_ok!(Treasury::spend(RuntimeOrigin::signed(10), 5, 6)); + assert_ok!(Treasury::spend(RuntimeOrigin::signed(10), 5, 6)); + assert_ok!(Treasury::spend(RuntimeOrigin::signed(10), 5, 6)); + assert_ok!(Treasury::spend(RuntimeOrigin::signed(11), 10, 6)); + assert_ok!(Treasury::spend(RuntimeOrigin::signed(12), 20, 6)); + assert_ok!(Treasury::spend(RuntimeOrigin::signed(13), 50, 6)); >::on_initialize(1); assert_eq!(Balances::free_balance(6), 0); @@ -212,7 +212,7 @@ fn minting_works() { #[test] fn spend_proposal_takes_min_deposit() { new_test_ext().execute_with(|| { - assert_ok!(Treasury::propose_spend(Origin::signed(0), 1, 3)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 1, 3)); assert_eq!(Balances::free_balance(0), 99); assert_eq!(Balances::reserved_balance(0), 1); }); @@ -221,7 +221,7 @@ fn spend_proposal_takes_min_deposit() { #[test] fn spend_proposal_takes_proportional_deposit() { new_test_ext().execute_with(|| { - assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3)); assert_eq!(Balances::free_balance(0), 95); assert_eq!(Balances::reserved_balance(0), 5); }); @@ -231,7 +231,7 @@ fn spend_proposal_takes_proportional_deposit() { fn spend_proposal_fails_when_proposer_poor() { new_test_ext().execute_with(|| { assert_noop!( - Treasury::propose_spend(Origin::signed(2), 100, 3), + Treasury::propose_spend(RuntimeOrigin::signed(2), 100, 3), Error::::InsufficientProposersBalance, ); }); @@ -242,8 +242,8 @@ fn accepted_spend_proposal_ignored_outside_spend_period() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); - assert_ok!(Treasury::approve_proposal(Origin::root(), 0)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3)); + assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 0)); >::on_initialize(1); assert_eq!(Balances::free_balance(3), 0); @@ -269,8 +269,8 @@ fn rejected_spend_proposal_ignored_on_spend_period() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); - assert_ok!(Treasury::reject_proposal(Origin::root(), 0)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3)); + assert_ok!(Treasury::reject_proposal(RuntimeOrigin::root(), 0)); >::on_initialize(2); assert_eq!(Balances::free_balance(3), 0); @@ -283,23 +283,32 @@ fn reject_already_rejected_spend_proposal_fails() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); - assert_ok!(Treasury::reject_proposal(Origin::root(), 0)); - assert_noop!(Treasury::reject_proposal(Origin::root(), 0), Error::::InvalidIndex); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3)); + assert_ok!(Treasury::reject_proposal(RuntimeOrigin::root(), 0)); + assert_noop!( + Treasury::reject_proposal(RuntimeOrigin::root(), 0), + Error::::InvalidIndex + ); }); } #[test] fn reject_non_existent_spend_proposal_fails() { new_test_ext().execute_with(|| { - assert_noop!(Treasury::reject_proposal(Origin::root(), 0), Error::::InvalidIndex); + assert_noop!( + Treasury::reject_proposal(RuntimeOrigin::root(), 0), + Error::::InvalidIndex + ); }); } #[test] fn accept_non_existent_spend_proposal_fails() { new_test_ext().execute_with(|| { - assert_noop!(Treasury::approve_proposal(Origin::root(), 0), Error::::InvalidIndex); + assert_noop!( + Treasury::approve_proposal(RuntimeOrigin::root(), 0), + Error::::InvalidIndex + ); }); } @@ -308,9 +317,12 @@ fn accept_already_rejected_spend_proposal_fails() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); - assert_ok!(Treasury::reject_proposal(Origin::root(), 0)); - assert_noop!(Treasury::approve_proposal(Origin::root(), 0), Error::::InvalidIndex); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3)); + assert_ok!(Treasury::reject_proposal(RuntimeOrigin::root(), 0)); + assert_noop!( + Treasury::approve_proposal(RuntimeOrigin::root(), 0), + Error::::InvalidIndex + ); }); } @@ -320,8 +332,8 @@ fn accepted_spend_proposal_enacted_on_spend_period() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); - assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); - assert_ok!(Treasury::approve_proposal(Origin::root(), 0)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3)); + assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 0)); >::on_initialize(2); assert_eq!(Balances::free_balance(3), 100); @@ -335,8 +347,8 @@ fn pot_underflow_should_not_diminish() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); - assert_ok!(Treasury::propose_spend(Origin::signed(0), 150, 3)); - assert_ok!(Treasury::approve_proposal(Origin::root(), 0)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 150, 3)); + assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 0)); >::on_initialize(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed @@ -357,14 +369,14 @@ fn treasury_account_doesnt_get_deleted() { assert_eq!(Treasury::pot(), 100); let treasury_balance = Balances::free_balance(&Treasury::account_id()); - assert_ok!(Treasury::propose_spend(Origin::signed(0), treasury_balance, 3)); - assert_ok!(Treasury::approve_proposal(Origin::root(), 0)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), treasury_balance, 3)); + assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 0)); >::on_initialize(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed - assert_ok!(Treasury::propose_spend(Origin::signed(0), Treasury::pot(), 3)); - assert_ok!(Treasury::approve_proposal(Origin::root(), 1)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), Treasury::pot(), 3)); + assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 1)); >::on_initialize(4); assert_eq!(Treasury::pot(), 0); // Pot is emptied @@ -387,10 +399,10 @@ fn inexistent_account_works() { assert_eq!(Balances::free_balance(Treasury::account_id()), 0); // Account does not exist assert_eq!(Treasury::pot(), 0); // Pot is empty - assert_ok!(Treasury::propose_spend(Origin::signed(0), 99, 3)); - assert_ok!(Treasury::approve_proposal(Origin::root(), 0)); - assert_ok!(Treasury::propose_spend(Origin::signed(0), 1, 3)); - assert_ok!(Treasury::approve_proposal(Origin::root(), 1)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 99, 3)); + assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 0)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 1, 3)); + assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 1)); >::on_initialize(2); assert_eq!(Treasury::pot(), 0); // Pot hasn't changed assert_eq!(Balances::free_balance(3), 0); // Balance of `3` hasn't changed @@ -432,14 +444,14 @@ fn max_approvals_limited() { Balances::make_free_balance_be(&0, u64::MAX); for _ in 0..::MaxApprovals::get() { - assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); - assert_ok!(Treasury::approve_proposal(Origin::root(), 0)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3)); + assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 0)); } // One too many will fail - assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3)); assert_noop!( - Treasury::approve_proposal(Origin::root(), 0), + Treasury::approve_proposal(RuntimeOrigin::root(), 0), Error::::TooManyApprovals ); }); @@ -450,14 +462,14 @@ fn remove_already_removed_approval_fails() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); - assert_ok!(Treasury::approve_proposal(Origin::root(), 0)); + assert_ok!(Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3)); + assert_ok!(Treasury::approve_proposal(RuntimeOrigin::root(), 0)); assert_eq!(Treasury::approvals(), vec![0]); - assert_ok!(Treasury::remove_approval(Origin::root(), 0)); + assert_ok!(Treasury::remove_approval(RuntimeOrigin::root(), 0)); assert_eq!(Treasury::approvals(), vec![]); assert_noop!( - Treasury::remove_approval(Origin::root(), 0), + Treasury::remove_approval(RuntimeOrigin::root(), 0), Error::::ProposalNotApproved ); }); diff --git a/frame/uniques/src/lib.rs b/frame/uniques/src/lib.rs index b02a10270dd7d..d519eedd2787f 100644 --- a/frame/uniques/src/lib.rs +++ b/frame/uniques/src/lib.rs @@ -105,12 +105,12 @@ pub mod pallet { /// The origin which may forcibly create or destroy an item or otherwise alter privileged /// attributes. - type ForceOrigin: EnsureOrigin; + type ForceOrigin: EnsureOrigin; /// Standard collection creation is only allowed if the origin attempting it and the /// collection are in this set. type CreateOrigin: EnsureOriginWithArg< - Self::Origin, + Self::RuntimeOrigin, Self::CollectionId, Success = Self::AccountId, >; diff --git a/frame/uniques/src/mock.rs b/frame/uniques/src/mock.rs index 6808c48007a92..d6ed5cc5cc23e 100644 --- a/frame/uniques/src/mock.rs +++ b/frame/uniques/src/mock.rs @@ -49,7 +49,7 @@ impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); type BlockLength = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = u64; type BlockNumber = u64; diff --git a/frame/uniques/src/tests.rs b/frame/uniques/src/tests.rs index 5ac677758316a..7af54ddbb188c 100644 --- a/frame/uniques/src/tests.rs +++ b/frame/uniques/src/tests.rs @@ -92,14 +92,14 @@ fn basic_setup_works() { #[test] fn basic_minting_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, true)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, true)); assert_eq!(collections(), vec![(1, 0)]); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 42, 1)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 42, 1)); assert_eq!(items(), vec![(1, 0, 42)]); - assert_ok!(Uniques::force_create(Origin::root(), 1, 2, true)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 1, 2, true)); assert_eq!(collections(), vec![(1, 0), (2, 1)]); - assert_ok!(Uniques::mint(Origin::signed(2), 1, 69, 1)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(2), 1, 69, 1)); assert_eq!(items(), vec![(1, 0, 42), (1, 1, 69)]); }); } @@ -108,32 +108,37 @@ fn basic_minting_should_work() { fn lifecycle_should_work() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&1, 100); - assert_ok!(Uniques::create(Origin::signed(1), 0, 1)); + assert_ok!(Uniques::create(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(Balances::reserved_balance(&1), 2); assert_eq!(collections(), vec![(1, 0)]); - assert_ok!(Uniques::set_collection_metadata(Origin::signed(1), 0, bvec![0, 0], false)); + assert_ok!(Uniques::set_collection_metadata( + RuntimeOrigin::signed(1), + 0, + bvec![0, 0], + false + )); assert_eq!(Balances::reserved_balance(&1), 5); assert!(CollectionMetadataOf::::contains_key(0)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 42, 10)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 42, 10)); assert_eq!(Balances::reserved_balance(&1), 6); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 69, 20)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 69, 20)); assert_eq!(Balances::reserved_balance(&1), 7); assert_eq!(items(), vec![(10, 0, 42), (20, 0, 69)]); assert_eq!(Collection::::get(0).unwrap().items, 2); assert_eq!(Collection::::get(0).unwrap().item_metadatas, 0); - assert_ok!(Uniques::set_metadata(Origin::signed(1), 0, 42, bvec![42, 42], false)); + assert_ok!(Uniques::set_metadata(RuntimeOrigin::signed(1), 0, 42, bvec![42, 42], false)); assert_eq!(Balances::reserved_balance(&1), 10); assert!(ItemMetadataOf::::contains_key(0, 42)); - assert_ok!(Uniques::set_metadata(Origin::signed(1), 0, 69, bvec![69, 69], false)); + assert_ok!(Uniques::set_metadata(RuntimeOrigin::signed(1), 0, 69, bvec![69, 69], false)); assert_eq!(Balances::reserved_balance(&1), 13); assert!(ItemMetadataOf::::contains_key(0, 69)); let w = Collection::::get(0).unwrap().destroy_witness(); assert_eq!(w.items, 2); assert_eq!(w.item_metadatas, 2); - assert_ok!(Uniques::destroy(Origin::signed(1), 0, w)); + assert_ok!(Uniques::destroy(RuntimeOrigin::signed(1), 0, w)); assert_eq!(Balances::reserved_balance(&1), 0); assert!(!Collection::::contains_key(0)); @@ -151,19 +156,19 @@ fn lifecycle_should_work() { fn destroy_with_bad_witness_should_not_work() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&1, 100); - assert_ok!(Uniques::create(Origin::signed(1), 0, 1)); + assert_ok!(Uniques::create(RuntimeOrigin::signed(1), 0, 1)); let w = Collection::::get(0).unwrap().destroy_witness(); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 42, 1)); - assert_noop!(Uniques::destroy(Origin::signed(1), 0, w), Error::::BadWitness); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 42, 1)); + assert_noop!(Uniques::destroy(RuntimeOrigin::signed(1), 0, w), Error::::BadWitness); }); } #[test] fn mint_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, true)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 42, 1)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, true)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 42, 1)); assert_eq!(Uniques::owner(0, 42).unwrap(), 1); assert_eq!(collections(), vec![(1, 0)]); assert_eq!(items(), vec![(1, 0, 42)]); @@ -173,54 +178,66 @@ fn mint_should_work() { #[test] fn transfer_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, true)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 42, 2)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, true)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 42, 2)); - assert_ok!(Uniques::transfer(Origin::signed(2), 0, 42, 3)); + assert_ok!(Uniques::transfer(RuntimeOrigin::signed(2), 0, 42, 3)); assert_eq!(items(), vec![(3, 0, 42)]); - assert_noop!(Uniques::transfer(Origin::signed(2), 0, 42, 4), Error::::NoPermission); + assert_noop!( + Uniques::transfer(RuntimeOrigin::signed(2), 0, 42, 4), + Error::::NoPermission + ); - assert_ok!(Uniques::approve_transfer(Origin::signed(3), 0, 42, 2)); - assert_ok!(Uniques::transfer(Origin::signed(2), 0, 42, 4)); + assert_ok!(Uniques::approve_transfer(RuntimeOrigin::signed(3), 0, 42, 2)); + assert_ok!(Uniques::transfer(RuntimeOrigin::signed(2), 0, 42, 4)); }); } #[test] fn freezing_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, true)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 42, 1)); - assert_ok!(Uniques::freeze(Origin::signed(1), 0, 42)); - assert_noop!(Uniques::transfer(Origin::signed(1), 0, 42, 2), Error::::Frozen); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, true)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 42, 1)); + assert_ok!(Uniques::freeze(RuntimeOrigin::signed(1), 0, 42)); + assert_noop!(Uniques::transfer(RuntimeOrigin::signed(1), 0, 42, 2), Error::::Frozen); - assert_ok!(Uniques::thaw(Origin::signed(1), 0, 42)); - assert_ok!(Uniques::freeze_collection(Origin::signed(1), 0)); - assert_noop!(Uniques::transfer(Origin::signed(1), 0, 42, 2), Error::::Frozen); + assert_ok!(Uniques::thaw(RuntimeOrigin::signed(1), 0, 42)); + assert_ok!(Uniques::freeze_collection(RuntimeOrigin::signed(1), 0)); + assert_noop!(Uniques::transfer(RuntimeOrigin::signed(1), 0, 42, 2), Error::::Frozen); - assert_ok!(Uniques::thaw_collection(Origin::signed(1), 0)); - assert_ok!(Uniques::transfer(Origin::signed(1), 0, 42, 2)); + assert_ok!(Uniques::thaw_collection(RuntimeOrigin::signed(1), 0)); + assert_ok!(Uniques::transfer(RuntimeOrigin::signed(1), 0, 42, 2)); }); } #[test] fn origin_guards_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, true)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 42, 1)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, true)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 42, 1)); Balances::make_free_balance_be(&2, 100); - assert_ok!(Uniques::set_accept_ownership(Origin::signed(2), Some(0))); + assert_ok!(Uniques::set_accept_ownership(RuntimeOrigin::signed(2), Some(0))); + assert_noop!( + Uniques::transfer_ownership(RuntimeOrigin::signed(2), 0, 2), + Error::::NoPermission + ); + assert_noop!( + Uniques::set_team(RuntimeOrigin::signed(2), 0, 2, 2, 2), + Error::::NoPermission + ); + assert_noop!(Uniques::freeze(RuntimeOrigin::signed(2), 0, 42), Error::::NoPermission); + assert_noop!(Uniques::thaw(RuntimeOrigin::signed(2), 0, 42), Error::::NoPermission); + assert_noop!( + Uniques::mint(RuntimeOrigin::signed(2), 0, 69, 2), + Error::::NoPermission + ); assert_noop!( - Uniques::transfer_ownership(Origin::signed(2), 0, 2), + Uniques::burn(RuntimeOrigin::signed(2), 0, 42, None), Error::::NoPermission ); - assert_noop!(Uniques::set_team(Origin::signed(2), 0, 2, 2, 2), Error::::NoPermission); - assert_noop!(Uniques::freeze(Origin::signed(2), 0, 42), Error::::NoPermission); - assert_noop!(Uniques::thaw(Origin::signed(2), 0, 42), Error::::NoPermission); - assert_noop!(Uniques::mint(Origin::signed(2), 0, 69, 2), Error::::NoPermission); - assert_noop!(Uniques::burn(Origin::signed(2), 0, 42, None), Error::::NoPermission); let w = Collection::::get(0).unwrap().destroy_witness(); - assert_noop!(Uniques::destroy(Origin::signed(2), 0, w), Error::::NoPermission); + assert_noop!(Uniques::destroy(RuntimeOrigin::signed(2), 0, w), Error::::NoPermission); }); } @@ -230,14 +247,14 @@ fn transfer_owner_should_work() { Balances::make_free_balance_be(&1, 100); Balances::make_free_balance_be(&2, 100); Balances::make_free_balance_be(&3, 100); - assert_ok!(Uniques::create(Origin::signed(1), 0, 1)); + assert_ok!(Uniques::create(RuntimeOrigin::signed(1), 0, 1)); assert_eq!(collections(), vec![(1, 0)]); assert_noop!( - Uniques::transfer_ownership(Origin::signed(1), 0, 2), + Uniques::transfer_ownership(RuntimeOrigin::signed(1), 0, 2), Error::::Unaccepted ); - assert_ok!(Uniques::set_accept_ownership(Origin::signed(2), Some(0))); - assert_ok!(Uniques::transfer_ownership(Origin::signed(1), 0, 2)); + assert_ok!(Uniques::set_accept_ownership(RuntimeOrigin::signed(2), Some(0))); + assert_ok!(Uniques::transfer_ownership(RuntimeOrigin::signed(1), 0, 2)); assert_eq!(collections(), vec![(2, 0)]); assert_eq!(Balances::total_balance(&1), 98); @@ -245,18 +262,23 @@ fn transfer_owner_should_work() { assert_eq!(Balances::reserved_balance(&1), 0); assert_eq!(Balances::reserved_balance(&2), 2); - assert_ok!(Uniques::set_accept_ownership(Origin::signed(1), Some(0))); + assert_ok!(Uniques::set_accept_ownership(RuntimeOrigin::signed(1), Some(0))); assert_noop!( - Uniques::transfer_ownership(Origin::signed(1), 0, 1), + Uniques::transfer_ownership(RuntimeOrigin::signed(1), 0, 1), Error::::NoPermission ); // Mint and set metadata now and make sure that deposit gets transferred back. - assert_ok!(Uniques::set_collection_metadata(Origin::signed(2), 0, bvec![0u8; 20], false)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 42, 1)); - assert_ok!(Uniques::set_metadata(Origin::signed(2), 0, 42, bvec![0u8; 20], false)); - assert_ok!(Uniques::set_accept_ownership(Origin::signed(3), Some(0))); - assert_ok!(Uniques::transfer_ownership(Origin::signed(2), 0, 3)); + assert_ok!(Uniques::set_collection_metadata( + RuntimeOrigin::signed(2), + 0, + bvec![0u8; 20], + false + )); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 42, 1)); + assert_ok!(Uniques::set_metadata(RuntimeOrigin::signed(2), 0, 42, bvec![0u8; 20], false)); + assert_ok!(Uniques::set_accept_ownership(RuntimeOrigin::signed(3), Some(0))); + assert_ok!(Uniques::transfer_ownership(RuntimeOrigin::signed(2), 0, 3)); assert_eq!(collections(), vec![(3, 0)]); assert_eq!(Balances::total_balance(&2), 57); assert_eq!(Balances::total_balance(&3), 145); @@ -266,7 +288,7 @@ fn transfer_owner_should_work() { // 2's acceptence from before is reset when it became owner, so it cannot be transfered // without a fresh acceptance. assert_noop!( - Uniques::transfer_ownership(Origin::signed(3), 0, 2), + Uniques::transfer_ownership(RuntimeOrigin::signed(3), 0, 2), Error::::Unaccepted ); }); @@ -275,14 +297,14 @@ fn transfer_owner_should_work() { #[test] fn set_team_should_work() { new_test_ext().execute_with(|| { - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, true)); - assert_ok!(Uniques::set_team(Origin::signed(1), 0, 2, 3, 4)); - - assert_ok!(Uniques::mint(Origin::signed(2), 0, 42, 2)); - assert_ok!(Uniques::freeze(Origin::signed(4), 0, 42)); - assert_ok!(Uniques::thaw(Origin::signed(3), 0, 42)); - assert_ok!(Uniques::transfer(Origin::signed(3), 0, 42, 3)); - assert_ok!(Uniques::burn(Origin::signed(3), 0, 42, None)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, true)); + assert_ok!(Uniques::set_team(RuntimeOrigin::signed(1), 0, 2, 3, 4)); + + assert_ok!(Uniques::mint(RuntimeOrigin::signed(2), 0, 42, 2)); + assert_ok!(Uniques::freeze(RuntimeOrigin::signed(4), 0, 42)); + assert_ok!(Uniques::thaw(RuntimeOrigin::signed(3), 0, 42)); + assert_ok!(Uniques::transfer(RuntimeOrigin::signed(3), 0, 42, 3)); + assert_ok!(Uniques::burn(RuntimeOrigin::signed(3), 0, 42, None)); }); } @@ -291,59 +313,89 @@ fn set_collection_metadata_should_work() { new_test_ext().execute_with(|| { // Cannot add metadata to unknown item assert_noop!( - Uniques::set_collection_metadata(Origin::signed(1), 0, bvec![0u8; 20], false), + Uniques::set_collection_metadata(RuntimeOrigin::signed(1), 0, bvec![0u8; 20], false), Error::::UnknownCollection, ); - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, false)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, false)); // Cannot add metadata to unowned item assert_noop!( - Uniques::set_collection_metadata(Origin::signed(2), 0, bvec![0u8; 20], false), + Uniques::set_collection_metadata(RuntimeOrigin::signed(2), 0, bvec![0u8; 20], false), Error::::NoPermission, ); // Successfully add metadata and take deposit Balances::make_free_balance_be(&1, 30); - assert_ok!(Uniques::set_collection_metadata(Origin::signed(1), 0, bvec![0u8; 20], false)); + assert_ok!(Uniques::set_collection_metadata( + RuntimeOrigin::signed(1), + 0, + bvec![0u8; 20], + false + )); assert_eq!(Balances::free_balance(&1), 9); assert!(CollectionMetadataOf::::contains_key(0)); // Force origin works, too. - assert_ok!(Uniques::set_collection_metadata(Origin::root(), 0, bvec![0u8; 18], false)); + assert_ok!(Uniques::set_collection_metadata( + RuntimeOrigin::root(), + 0, + bvec![0u8; 18], + false + )); // Update deposit - assert_ok!(Uniques::set_collection_metadata(Origin::signed(1), 0, bvec![0u8; 15], false)); + assert_ok!(Uniques::set_collection_metadata( + RuntimeOrigin::signed(1), + 0, + bvec![0u8; 15], + false + )); assert_eq!(Balances::free_balance(&1), 14); - assert_ok!(Uniques::set_collection_metadata(Origin::signed(1), 0, bvec![0u8; 25], false)); + assert_ok!(Uniques::set_collection_metadata( + RuntimeOrigin::signed(1), + 0, + bvec![0u8; 25], + false + )); assert_eq!(Balances::free_balance(&1), 4); // Cannot over-reserve assert_noop!( - Uniques::set_collection_metadata(Origin::signed(1), 0, bvec![0u8; 40], false), + Uniques::set_collection_metadata(RuntimeOrigin::signed(1), 0, bvec![0u8; 40], false), BalancesError::::InsufficientBalance, ); // Can't set or clear metadata once frozen - assert_ok!(Uniques::set_collection_metadata(Origin::signed(1), 0, bvec![0u8; 15], true)); + assert_ok!(Uniques::set_collection_metadata( + RuntimeOrigin::signed(1), + 0, + bvec![0u8; 15], + true + )); assert_noop!( - Uniques::set_collection_metadata(Origin::signed(1), 0, bvec![0u8; 15], false), + Uniques::set_collection_metadata(RuntimeOrigin::signed(1), 0, bvec![0u8; 15], false), Error::::Frozen, ); assert_noop!( - Uniques::clear_collection_metadata(Origin::signed(1), 0), + Uniques::clear_collection_metadata(RuntimeOrigin::signed(1), 0), Error::::Frozen ); // Clear Metadata - assert_ok!(Uniques::set_collection_metadata(Origin::root(), 0, bvec![0u8; 15], false)); + assert_ok!(Uniques::set_collection_metadata( + RuntimeOrigin::root(), + 0, + bvec![0u8; 15], + false + )); assert_noop!( - Uniques::clear_collection_metadata(Origin::signed(2), 0), + Uniques::clear_collection_metadata(RuntimeOrigin::signed(2), 0), Error::::NoPermission ); assert_noop!( - Uniques::clear_collection_metadata(Origin::signed(1), 1), + Uniques::clear_collection_metadata(RuntimeOrigin::signed(1), 1), Error::::UnknownCollection ); - assert_ok!(Uniques::clear_collection_metadata(Origin::signed(1), 0)); + assert_ok!(Uniques::clear_collection_metadata(RuntimeOrigin::signed(1), 0)); assert!(!CollectionMetadataOf::::contains_key(0)); }); } @@ -354,53 +406,56 @@ fn set_item_metadata_should_work() { Balances::make_free_balance_be(&1, 30); // Cannot add metadata to unknown item - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, false)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 42, 1)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, false)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 42, 1)); // Cannot add metadata to unowned item assert_noop!( - Uniques::set_metadata(Origin::signed(2), 0, 42, bvec![0u8; 20], false), + Uniques::set_metadata(RuntimeOrigin::signed(2), 0, 42, bvec![0u8; 20], false), Error::::NoPermission, ); // Successfully add metadata and take deposit - assert_ok!(Uniques::set_metadata(Origin::signed(1), 0, 42, bvec![0u8; 20], false)); + assert_ok!(Uniques::set_metadata(RuntimeOrigin::signed(1), 0, 42, bvec![0u8; 20], false)); assert_eq!(Balances::free_balance(&1), 8); assert!(ItemMetadataOf::::contains_key(0, 42)); // Force origin works, too. - assert_ok!(Uniques::set_metadata(Origin::root(), 0, 42, bvec![0u8; 18], false)); + assert_ok!(Uniques::set_metadata(RuntimeOrigin::root(), 0, 42, bvec![0u8; 18], false)); // Update deposit - assert_ok!(Uniques::set_metadata(Origin::signed(1), 0, 42, bvec![0u8; 15], false)); + assert_ok!(Uniques::set_metadata(RuntimeOrigin::signed(1), 0, 42, bvec![0u8; 15], false)); assert_eq!(Balances::free_balance(&1), 13); - assert_ok!(Uniques::set_metadata(Origin::signed(1), 0, 42, bvec![0u8; 25], false)); + assert_ok!(Uniques::set_metadata(RuntimeOrigin::signed(1), 0, 42, bvec![0u8; 25], false)); assert_eq!(Balances::free_balance(&1), 3); // Cannot over-reserve assert_noop!( - Uniques::set_metadata(Origin::signed(1), 0, 42, bvec![0u8; 40], false), + Uniques::set_metadata(RuntimeOrigin::signed(1), 0, 42, bvec![0u8; 40], false), BalancesError::::InsufficientBalance, ); // Can't set or clear metadata once frozen - assert_ok!(Uniques::set_metadata(Origin::signed(1), 0, 42, bvec![0u8; 15], true)); + assert_ok!(Uniques::set_metadata(RuntimeOrigin::signed(1), 0, 42, bvec![0u8; 15], true)); assert_noop!( - Uniques::set_metadata(Origin::signed(1), 0, 42, bvec![0u8; 15], false), + Uniques::set_metadata(RuntimeOrigin::signed(1), 0, 42, bvec![0u8; 15], false), Error::::Frozen, ); - assert_noop!(Uniques::clear_metadata(Origin::signed(1), 0, 42), Error::::Frozen); + assert_noop!( + Uniques::clear_metadata(RuntimeOrigin::signed(1), 0, 42), + Error::::Frozen + ); // Clear Metadata - assert_ok!(Uniques::set_metadata(Origin::root(), 0, 42, bvec![0u8; 15], false)); + assert_ok!(Uniques::set_metadata(RuntimeOrigin::root(), 0, 42, bvec![0u8; 15], false)); assert_noop!( - Uniques::clear_metadata(Origin::signed(2), 0, 42), + Uniques::clear_metadata(RuntimeOrigin::signed(2), 0, 42), Error::::NoPermission ); assert_noop!( - Uniques::clear_metadata(Origin::signed(1), 1, 42), + Uniques::clear_metadata(RuntimeOrigin::signed(1), 1, 42), Error::::UnknownCollection ); - assert_ok!(Uniques::clear_metadata(Origin::signed(1), 0, 42)); + assert_ok!(Uniques::clear_metadata(RuntimeOrigin::signed(1), 0, 42)); assert!(!ItemMetadataOf::::contains_key(0, 42)); }); } @@ -410,11 +465,23 @@ fn set_attribute_should_work() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&1, 100); - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, false)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, false)); - assert_ok!(Uniques::set_attribute(Origin::signed(1), 0, None, bvec![0], bvec![0])); - assert_ok!(Uniques::set_attribute(Origin::signed(1), 0, Some(0), bvec![0], bvec![0])); - assert_ok!(Uniques::set_attribute(Origin::signed(1), 0, Some(0), bvec![1], bvec![0])); + assert_ok!(Uniques::set_attribute(RuntimeOrigin::signed(1), 0, None, bvec![0], bvec![0])); + assert_ok!(Uniques::set_attribute( + RuntimeOrigin::signed(1), + 0, + Some(0), + bvec![0], + bvec![0] + )); + assert_ok!(Uniques::set_attribute( + RuntimeOrigin::signed(1), + 0, + Some(0), + bvec![1], + bvec![0] + )); assert_eq!( attributes(0), vec![ @@ -425,7 +492,13 @@ fn set_attribute_should_work() { ); assert_eq!(Balances::reserved_balance(1), 9); - assert_ok!(Uniques::set_attribute(Origin::signed(1), 0, None, bvec![0], bvec![0; 10])); + assert_ok!(Uniques::set_attribute( + RuntimeOrigin::signed(1), + 0, + None, + bvec![0], + bvec![0; 10] + )); assert_eq!( attributes(0), vec![ @@ -436,7 +509,7 @@ fn set_attribute_should_work() { ); assert_eq!(Balances::reserved_balance(1), 18); - assert_ok!(Uniques::clear_attribute(Origin::signed(1), 0, Some(0), bvec![1])); + assert_ok!(Uniques::clear_attribute(RuntimeOrigin::signed(1), 0, Some(0), bvec![1])); assert_eq!( attributes(0), vec![(None, bvec![0], bvec![0; 10]), (Some(0), bvec![0], bvec![0]),] @@ -444,7 +517,7 @@ fn set_attribute_should_work() { assert_eq!(Balances::reserved_balance(1), 15); let w = Collection::::get(0).unwrap().destroy_witness(); - assert_ok!(Uniques::destroy(Origin::signed(1), 0, w)); + assert_ok!(Uniques::destroy(RuntimeOrigin::signed(1), 0, w)); assert_eq!(attributes(0), vec![]); assert_eq!(Balances::reserved_balance(1), 0); }); @@ -455,11 +528,23 @@ fn set_attribute_should_respect_freeze() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&1, 100); - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, false)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, false)); - assert_ok!(Uniques::set_attribute(Origin::signed(1), 0, None, bvec![0], bvec![0])); - assert_ok!(Uniques::set_attribute(Origin::signed(1), 0, Some(0), bvec![0], bvec![0])); - assert_ok!(Uniques::set_attribute(Origin::signed(1), 0, Some(1), bvec![0], bvec![0])); + assert_ok!(Uniques::set_attribute(RuntimeOrigin::signed(1), 0, None, bvec![0], bvec![0])); + assert_ok!(Uniques::set_attribute( + RuntimeOrigin::signed(1), + 0, + Some(0), + bvec![0], + bvec![0] + )); + assert_ok!(Uniques::set_attribute( + RuntimeOrigin::signed(1), + 0, + Some(1), + bvec![0], + bvec![0] + )); assert_eq!( attributes(0), vec![ @@ -470,15 +555,33 @@ fn set_attribute_should_respect_freeze() { ); assert_eq!(Balances::reserved_balance(1), 9); - assert_ok!(Uniques::set_collection_metadata(Origin::signed(1), 0, bvec![], true)); + assert_ok!(Uniques::set_collection_metadata(RuntimeOrigin::signed(1), 0, bvec![], true)); let e = Error::::Frozen; - assert_noop!(Uniques::set_attribute(Origin::signed(1), 0, None, bvec![0], bvec![0]), e); - assert_ok!(Uniques::set_attribute(Origin::signed(1), 0, Some(0), bvec![0], bvec![1])); + assert_noop!( + Uniques::set_attribute(RuntimeOrigin::signed(1), 0, None, bvec![0], bvec![0]), + e + ); + assert_ok!(Uniques::set_attribute( + RuntimeOrigin::signed(1), + 0, + Some(0), + bvec![0], + bvec![1] + )); - assert_ok!(Uniques::set_metadata(Origin::signed(1), 0, 0, bvec![], true)); + assert_ok!(Uniques::set_metadata(RuntimeOrigin::signed(1), 0, 0, bvec![], true)); let e = Error::::Frozen; - assert_noop!(Uniques::set_attribute(Origin::signed(1), 0, Some(0), bvec![0], bvec![1]), e); - assert_ok!(Uniques::set_attribute(Origin::signed(1), 0, Some(1), bvec![0], bvec![1])); + assert_noop!( + Uniques::set_attribute(RuntimeOrigin::signed(1), 0, Some(0), bvec![0], bvec![1]), + e + ); + assert_ok!(Uniques::set_attribute( + RuntimeOrigin::signed(1), + 0, + Some(1), + bvec![0], + bvec![1] + )); }); } @@ -487,32 +590,42 @@ fn force_item_status_should_work() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&1, 100); - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, false)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 42, 1)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 69, 2)); - assert_ok!(Uniques::set_collection_metadata(Origin::signed(1), 0, bvec![0; 20], false)); - assert_ok!(Uniques::set_metadata(Origin::signed(1), 0, 42, bvec![0; 20], false)); - assert_ok!(Uniques::set_metadata(Origin::signed(1), 0, 69, bvec![0; 20], false)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, false)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 42, 1)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 69, 2)); + assert_ok!(Uniques::set_collection_metadata( + RuntimeOrigin::signed(1), + 0, + bvec![0; 20], + false + )); + assert_ok!(Uniques::set_metadata(RuntimeOrigin::signed(1), 0, 42, bvec![0; 20], false)); + assert_ok!(Uniques::set_metadata(RuntimeOrigin::signed(1), 0, 69, bvec![0; 20], false)); assert_eq!(Balances::reserved_balance(1), 65); // force item status to be free holding - assert_ok!(Uniques::force_item_status(Origin::root(), 0, 1, 1, 1, 1, true, false)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 142, 1)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 169, 2)); - assert_ok!(Uniques::set_metadata(Origin::signed(1), 0, 142, bvec![0; 20], false)); - assert_ok!(Uniques::set_metadata(Origin::signed(1), 0, 169, bvec![0; 20], false)); + assert_ok!(Uniques::force_item_status(RuntimeOrigin::root(), 0, 1, 1, 1, 1, true, false)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 142, 1)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 169, 2)); + assert_ok!(Uniques::set_metadata(RuntimeOrigin::signed(1), 0, 142, bvec![0; 20], false)); + assert_ok!(Uniques::set_metadata(RuntimeOrigin::signed(1), 0, 169, bvec![0; 20], false)); assert_eq!(Balances::reserved_balance(1), 65); - assert_ok!(Uniques::redeposit(Origin::signed(1), 0, bvec![0, 42, 50, 69, 100])); + assert_ok!(Uniques::redeposit(RuntimeOrigin::signed(1), 0, bvec![0, 42, 50, 69, 100])); assert_eq!(Balances::reserved_balance(1), 63); - assert_ok!(Uniques::set_metadata(Origin::signed(1), 0, 42, bvec![0; 20], false)); + assert_ok!(Uniques::set_metadata(RuntimeOrigin::signed(1), 0, 42, bvec![0; 20], false)); assert_eq!(Balances::reserved_balance(1), 42); - assert_ok!(Uniques::set_metadata(Origin::signed(1), 0, 69, bvec![0; 20], false)); + assert_ok!(Uniques::set_metadata(RuntimeOrigin::signed(1), 0, 69, bvec![0; 20], false)); assert_eq!(Balances::reserved_balance(1), 21); - assert_ok!(Uniques::set_collection_metadata(Origin::signed(1), 0, bvec![0; 20], false)); + assert_ok!(Uniques::set_collection_metadata( + RuntimeOrigin::signed(1), + 0, + bvec![0; 20], + false + )); assert_eq!(Balances::reserved_balance(1), 0); }); } @@ -521,23 +634,29 @@ fn force_item_status_should_work() { fn burn_works() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&1, 100); - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, false)); - assert_ok!(Uniques::set_team(Origin::signed(1), 0, 2, 3, 4)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, false)); + assert_ok!(Uniques::set_team(RuntimeOrigin::signed(1), 0, 2, 3, 4)); assert_noop!( - Uniques::burn(Origin::signed(5), 0, 42, Some(5)), + Uniques::burn(RuntimeOrigin::signed(5), 0, 42, Some(5)), Error::::UnknownCollection ); - assert_ok!(Uniques::mint(Origin::signed(2), 0, 42, 5)); - assert_ok!(Uniques::mint(Origin::signed(2), 0, 69, 5)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(2), 0, 42, 5)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(2), 0, 69, 5)); assert_eq!(Balances::reserved_balance(1), 2); - assert_noop!(Uniques::burn(Origin::signed(0), 0, 42, None), Error::::NoPermission); - assert_noop!(Uniques::burn(Origin::signed(5), 0, 42, Some(6)), Error::::WrongOwner); + assert_noop!( + Uniques::burn(RuntimeOrigin::signed(0), 0, 42, None), + Error::::NoPermission + ); + assert_noop!( + Uniques::burn(RuntimeOrigin::signed(5), 0, 42, Some(6)), + Error::::WrongOwner + ); - assert_ok!(Uniques::burn(Origin::signed(5), 0, 42, Some(5))); - assert_ok!(Uniques::burn(Origin::signed(3), 0, 69, Some(5))); + assert_ok!(Uniques::burn(RuntimeOrigin::signed(5), 0, 42, Some(5))); + assert_ok!(Uniques::burn(RuntimeOrigin::signed(3), 0, 69, Some(5))); assert_eq!(Balances::reserved_balance(1), 0); }); } @@ -545,31 +664,37 @@ fn burn_works() { #[test] fn approval_lifecycle_works() { new_test_ext().execute_with(|| { - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, true)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 42, 2)); - assert_ok!(Uniques::approve_transfer(Origin::signed(2), 0, 42, 3)); - assert_ok!(Uniques::transfer(Origin::signed(3), 0, 42, 4)); - assert_noop!(Uniques::transfer(Origin::signed(3), 0, 42, 3), Error::::NoPermission); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, true)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 42, 2)); + assert_ok!(Uniques::approve_transfer(RuntimeOrigin::signed(2), 0, 42, 3)); + assert_ok!(Uniques::transfer(RuntimeOrigin::signed(3), 0, 42, 4)); + assert_noop!( + Uniques::transfer(RuntimeOrigin::signed(3), 0, 42, 3), + Error::::NoPermission + ); assert!(Item::::get(0, 42).unwrap().approved.is_none()); - assert_ok!(Uniques::approve_transfer(Origin::signed(4), 0, 42, 2)); - assert_ok!(Uniques::transfer(Origin::signed(2), 0, 42, 2)); + assert_ok!(Uniques::approve_transfer(RuntimeOrigin::signed(4), 0, 42, 2)); + assert_ok!(Uniques::transfer(RuntimeOrigin::signed(2), 0, 42, 2)); }); } #[test] fn approved_account_gets_reset_after_transfer() { new_test_ext().execute_with(|| { - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, true)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 42, 2)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, true)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 42, 2)); - assert_ok!(Uniques::approve_transfer(Origin::signed(2), 0, 42, 3)); - assert_ok!(Uniques::transfer(Origin::signed(2), 0, 42, 5)); + assert_ok!(Uniques::approve_transfer(RuntimeOrigin::signed(2), 0, 42, 3)); + assert_ok!(Uniques::transfer(RuntimeOrigin::signed(2), 0, 42, 5)); // this shouldn't work because we have just transfered the item to another account. - assert_noop!(Uniques::transfer(Origin::signed(3), 0, 42, 4), Error::::NoPermission); + assert_noop!( + Uniques::transfer(RuntimeOrigin::signed(3), 0, 42, 4), + Error::::NoPermission + ); // The new owner can transfer fine: - assert_ok!(Uniques::transfer(Origin::signed(5), 0, 42, 6)); + assert_ok!(Uniques::transfer(RuntimeOrigin::signed(5), 0, 42, 6)); }); } @@ -581,47 +706,50 @@ fn approved_account_gets_reset_after_buy_item() { Balances::make_free_balance_be(&2, 100); - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, true)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, item, 1)); - assert_ok!(Uniques::approve_transfer(Origin::signed(1), 0, item, 5)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, true)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, item, 1)); + assert_ok!(Uniques::approve_transfer(RuntimeOrigin::signed(1), 0, item, 5)); - assert_ok!(Uniques::set_price(Origin::signed(1), 0, item, Some(price), None)); + assert_ok!(Uniques::set_price(RuntimeOrigin::signed(1), 0, item, Some(price), None)); - assert_ok!(Uniques::buy_item(Origin::signed(2), 0, item, price)); + assert_ok!(Uniques::buy_item(RuntimeOrigin::signed(2), 0, item, price)); // this shouldn't work because the item has been bough and the approved account should be // reset. - assert_noop!(Uniques::transfer(Origin::signed(5), 0, item, 4), Error::::NoPermission); + assert_noop!( + Uniques::transfer(RuntimeOrigin::signed(5), 0, item, 4), + Error::::NoPermission + ); }); } #[test] fn cancel_approval_works() { new_test_ext().execute_with(|| { - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, true)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 42, 2)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, true)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 42, 2)); - assert_ok!(Uniques::approve_transfer(Origin::signed(2), 0, 42, 3)); + assert_ok!(Uniques::approve_transfer(RuntimeOrigin::signed(2), 0, 42, 3)); assert_noop!( - Uniques::cancel_approval(Origin::signed(2), 1, 42, None), + Uniques::cancel_approval(RuntimeOrigin::signed(2), 1, 42, None), Error::::UnknownCollection ); assert_noop!( - Uniques::cancel_approval(Origin::signed(2), 0, 43, None), + Uniques::cancel_approval(RuntimeOrigin::signed(2), 0, 43, None), Error::::UnknownCollection ); assert_noop!( - Uniques::cancel_approval(Origin::signed(3), 0, 42, None), + Uniques::cancel_approval(RuntimeOrigin::signed(3), 0, 42, None), Error::::NoPermission ); assert_noop!( - Uniques::cancel_approval(Origin::signed(2), 0, 42, Some(4)), + Uniques::cancel_approval(RuntimeOrigin::signed(2), 0, 42, Some(4)), Error::::WrongDelegate ); - assert_ok!(Uniques::cancel_approval(Origin::signed(2), 0, 42, Some(3))); + assert_ok!(Uniques::cancel_approval(RuntimeOrigin::signed(2), 0, 42, Some(3))); assert_noop!( - Uniques::cancel_approval(Origin::signed(2), 0, 42, None), + Uniques::cancel_approval(RuntimeOrigin::signed(2), 0, 42, None), Error::::NoDelegate ); }); @@ -630,26 +758,26 @@ fn cancel_approval_works() { #[test] fn cancel_approval_works_with_admin() { new_test_ext().execute_with(|| { - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, true)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 42, 2)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, true)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 42, 2)); - assert_ok!(Uniques::approve_transfer(Origin::signed(2), 0, 42, 3)); + assert_ok!(Uniques::approve_transfer(RuntimeOrigin::signed(2), 0, 42, 3)); assert_noop!( - Uniques::cancel_approval(Origin::signed(1), 1, 42, None), + Uniques::cancel_approval(RuntimeOrigin::signed(1), 1, 42, None), Error::::UnknownCollection ); assert_noop!( - Uniques::cancel_approval(Origin::signed(1), 0, 43, None), + Uniques::cancel_approval(RuntimeOrigin::signed(1), 0, 43, None), Error::::UnknownCollection ); assert_noop!( - Uniques::cancel_approval(Origin::signed(1), 0, 42, Some(4)), + Uniques::cancel_approval(RuntimeOrigin::signed(1), 0, 42, Some(4)), Error::::WrongDelegate ); - assert_ok!(Uniques::cancel_approval(Origin::signed(1), 0, 42, Some(3))); + assert_ok!(Uniques::cancel_approval(RuntimeOrigin::signed(1), 0, 42, Some(3))); assert_noop!( - Uniques::cancel_approval(Origin::signed(1), 0, 42, None), + Uniques::cancel_approval(RuntimeOrigin::signed(1), 0, 42, None), Error::::NoDelegate ); }); @@ -658,26 +786,26 @@ fn cancel_approval_works_with_admin() { #[test] fn cancel_approval_works_with_force() { new_test_ext().execute_with(|| { - assert_ok!(Uniques::force_create(Origin::root(), 0, 1, true)); - assert_ok!(Uniques::mint(Origin::signed(1), 0, 42, 2)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), 0, 1, true)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(1), 0, 42, 2)); - assert_ok!(Uniques::approve_transfer(Origin::signed(2), 0, 42, 3)); + assert_ok!(Uniques::approve_transfer(RuntimeOrigin::signed(2), 0, 42, 3)); assert_noop!( - Uniques::cancel_approval(Origin::root(), 1, 42, None), + Uniques::cancel_approval(RuntimeOrigin::root(), 1, 42, None), Error::::UnknownCollection ); assert_noop!( - Uniques::cancel_approval(Origin::root(), 0, 43, None), + Uniques::cancel_approval(RuntimeOrigin::root(), 0, 43, None), Error::::UnknownCollection ); assert_noop!( - Uniques::cancel_approval(Origin::root(), 0, 42, Some(4)), + Uniques::cancel_approval(RuntimeOrigin::root(), 0, 42, Some(4)), Error::::WrongDelegate ); - assert_ok!(Uniques::cancel_approval(Origin::root(), 0, 42, Some(3))); + assert_ok!(Uniques::cancel_approval(RuntimeOrigin::root(), 0, 42, Some(3))); assert_noop!( - Uniques::cancel_approval(Origin::root(), 0, 42, None), + Uniques::cancel_approval(RuntimeOrigin::root(), 0, 42, None), Error::::NoDelegate ); }); @@ -691,11 +819,11 @@ fn max_supply_should_work() { let max_supply = 2; // validate set_collection_max_supply - assert_ok!(Uniques::force_create(Origin::root(), collection_id, user_id, true)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), collection_id, user_id, true)); assert!(!CollectionMaxSupply::::contains_key(collection_id)); assert_ok!(Uniques::set_collection_max_supply( - Origin::signed(user_id), + RuntimeOrigin::signed(user_id), collection_id, max_supply )); @@ -708,7 +836,7 @@ fn max_supply_should_work() { assert_noop!( Uniques::set_collection_max_supply( - Origin::signed(user_id), + RuntimeOrigin::signed(user_id), collection_id, max_supply + 1 ), @@ -716,16 +844,16 @@ fn max_supply_should_work() { ); // validate we can't mint more to max supply - assert_ok!(Uniques::mint(Origin::signed(user_id), collection_id, 0, user_id)); - assert_ok!(Uniques::mint(Origin::signed(user_id), collection_id, 1, user_id)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(user_id), collection_id, 0, user_id)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(user_id), collection_id, 1, user_id)); assert_noop!( - Uniques::mint(Origin::signed(user_id), collection_id, 2, user_id), + Uniques::mint(RuntimeOrigin::signed(user_id), collection_id, 2, user_id), Error::::MaxSupplyReached ); // validate we remove the CollectionMaxSupply record when we destroy the collection assert_ok!(Uniques::destroy( - Origin::signed(user_id), + RuntimeOrigin::signed(user_id), collection_id, Collection::::get(collection_id).unwrap().destroy_witness() )); @@ -741,13 +869,13 @@ fn set_price_should_work() { let item_1 = 1; let item_2 = 2; - assert_ok!(Uniques::force_create(Origin::root(), collection_id, user_id, true)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), collection_id, user_id, true)); - assert_ok!(Uniques::mint(Origin::signed(user_id), collection_id, item_1, user_id)); - assert_ok!(Uniques::mint(Origin::signed(user_id), collection_id, item_2, user_id)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(user_id), collection_id, item_1, user_id)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(user_id), collection_id, item_2, user_id)); assert_ok!(Uniques::set_price( - Origin::signed(user_id), + RuntimeOrigin::signed(user_id), collection_id, item_1, Some(1), @@ -755,7 +883,7 @@ fn set_price_should_work() { )); assert_ok!(Uniques::set_price( - Origin::signed(user_id), + RuntimeOrigin::signed(user_id), collection_id, item_2, Some(2), @@ -778,7 +906,13 @@ fn set_price_should_work() { })); // validate we can unset the price - assert_ok!(Uniques::set_price(Origin::signed(user_id), collection_id, item_2, None, None)); + assert_ok!(Uniques::set_price( + RuntimeOrigin::signed(user_id), + collection_id, + item_2, + None, + None + )); assert!(events().contains(&Event::::ItemPriceRemoved { collection: collection_id, item: item_2 @@ -805,14 +939,14 @@ fn buy_item_should_work() { Balances::make_free_balance_be(&user_2, initial_balance); Balances::make_free_balance_be(&user_3, initial_balance); - assert_ok!(Uniques::force_create(Origin::root(), collection_id, user_1, true)); + assert_ok!(Uniques::force_create(RuntimeOrigin::root(), collection_id, user_1, true)); - assert_ok!(Uniques::mint(Origin::signed(user_1), collection_id, item_1, user_1)); - assert_ok!(Uniques::mint(Origin::signed(user_1), collection_id, item_2, user_1)); - assert_ok!(Uniques::mint(Origin::signed(user_1), collection_id, item_3, user_1)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(user_1), collection_id, item_1, user_1)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(user_1), collection_id, item_2, user_1)); + assert_ok!(Uniques::mint(RuntimeOrigin::signed(user_1), collection_id, item_3, user_1)); assert_ok!(Uniques::set_price( - Origin::signed(user_1), + RuntimeOrigin::signed(user_1), collection_id, item_1, Some(price_1), @@ -820,7 +954,7 @@ fn buy_item_should_work() { )); assert_ok!(Uniques::set_price( - Origin::signed(user_1), + RuntimeOrigin::signed(user_1), collection_id, item_2, Some(price_2), @@ -829,12 +963,17 @@ fn buy_item_should_work() { // can't buy for less assert_noop!( - Uniques::buy_item(Origin::signed(user_2), collection_id, item_1, 1), + Uniques::buy_item(RuntimeOrigin::signed(user_2), collection_id, item_1, 1), Error::::BidTooLow ); // pass the higher price to validate it will still deduct correctly - assert_ok!(Uniques::buy_item(Origin::signed(user_2), collection_id, item_1, price_1 + 1,)); + assert_ok!(Uniques::buy_item( + RuntimeOrigin::signed(user_2), + collection_id, + item_1, + price_1 + 1, + )); // validate the new owner & balances let item = Item::::get(collection_id, item_1).unwrap(); @@ -844,18 +983,23 @@ fn buy_item_should_work() { // can't buy from yourself assert_noop!( - Uniques::buy_item(Origin::signed(user_1), collection_id, item_2, price_2), + Uniques::buy_item(RuntimeOrigin::signed(user_1), collection_id, item_2, price_2), Error::::NoPermission ); // can't buy when the item is listed for a specific buyer assert_noop!( - Uniques::buy_item(Origin::signed(user_2), collection_id, item_2, price_2), + Uniques::buy_item(RuntimeOrigin::signed(user_2), collection_id, item_2, price_2), Error::::NoPermission ); // can buy when I'm a whitelisted buyer - assert_ok!(Uniques::buy_item(Origin::signed(user_3), collection_id, item_2, price_2,)); + assert_ok!(Uniques::buy_item( + RuntimeOrigin::signed(user_3), + collection_id, + item_2, + price_2, + )); assert!(events().contains(&Event::::ItemBought { collection: collection_id, @@ -870,14 +1014,14 @@ fn buy_item_should_work() { // can't buy when item is not for sale assert_noop!( - Uniques::buy_item(Origin::signed(user_2), collection_id, item_3, price_2), + Uniques::buy_item(RuntimeOrigin::signed(user_2), collection_id, item_3, price_2), Error::::NotForSale ); // ensure we can't buy an item when the collection or an item is frozen { assert_ok!(Uniques::set_price( - Origin::signed(user_1), + RuntimeOrigin::signed(user_1), collection_id, item_3, Some(price_1), @@ -885,26 +1029,32 @@ fn buy_item_should_work() { )); // freeze collection - assert_ok!(Uniques::freeze_collection(Origin::signed(user_1), collection_id)); + assert_ok!(Uniques::freeze_collection(RuntimeOrigin::signed(user_1), collection_id)); let buy_item_call = mock::RuntimeCall::Uniques(crate::Call::::buy_item { collection: collection_id, item: item_3, bid_price: price_1, }); - assert_noop!(buy_item_call.dispatch(Origin::signed(user_2)), Error::::Frozen); + assert_noop!( + buy_item_call.dispatch(RuntimeOrigin::signed(user_2)), + Error::::Frozen + ); - assert_ok!(Uniques::thaw_collection(Origin::signed(user_1), collection_id)); + assert_ok!(Uniques::thaw_collection(RuntimeOrigin::signed(user_1), collection_id)); // freeze item - assert_ok!(Uniques::freeze(Origin::signed(user_1), collection_id, item_3)); + assert_ok!(Uniques::freeze(RuntimeOrigin::signed(user_1), collection_id, item_3)); let buy_item_call = mock::RuntimeCall::Uniques(crate::Call::::buy_item { collection: collection_id, item: item_3, bid_price: price_1, }); - assert_noop!(buy_item_call.dispatch(Origin::signed(user_2)), Error::::Frozen); + assert_noop!( + buy_item_call.dispatch(RuntimeOrigin::signed(user_2)), + Error::::Frozen + ); } }); } diff --git a/frame/utility/src/benchmarking.rs b/frame/utility/src/benchmarking.rs index c29eded25aa5b..07bc14951cb3b 100644 --- a/frame/utility/src/benchmarking.rs +++ b/frame/utility/src/benchmarking.rs @@ -30,7 +30,7 @@ fn assert_last_event(generic_event: ::RuntimeEvent) { } benchmarks! { - where_clause { where ::PalletsOrigin: Clone } + where_clause { where ::PalletsOrigin: Clone } batch { let c in 0 .. 1000; let mut calls: Vec<::RuntimeCall> = Vec::new(); @@ -68,8 +68,8 @@ benchmarks! { dispatch_as { let caller = account("caller", SEED, SEED); let call = Box::new(frame_system::Call::remark { remark: vec![] }.into()); - let origin: T::Origin = RawOrigin::Signed(caller).into(); - let pallets_origin: ::PalletsOrigin = origin.caller().clone(); + let origin: T::RuntimeOrigin = RawOrigin::Signed(caller).into(); + let pallets_origin: ::PalletsOrigin = origin.caller().clone(); let pallets_origin = Into::::into(pallets_origin); }: _(RawOrigin::Root, Box::new(pallets_origin), call) diff --git a/frame/utility/src/lib.rs b/frame/utility/src/lib.rs index 08fb34ed9e3c1..819314f3d8454 100644 --- a/frame/utility/src/lib.rs +++ b/frame/utility/src/lib.rs @@ -87,17 +87,17 @@ pub mod pallet { /// The overarching call type. type RuntimeCall: Parameter - + Dispatchable + + Dispatchable + GetDispatchInfo + From> - + UnfilteredDispatchable + + UnfilteredDispatchable + IsSubType> + IsType<::RuntimeCall>; /// The caller origin, overarching type of all pallets origins. type PalletsOrigin: Parameter + - Into<::Origin> + - IsType<<::Origin as frame_support::traits::OriginTrait>::PalletsOrigin>; + Into<::RuntimeOrigin> + + IsType<<::RuntimeOrigin as frame_support::traits::OriginTrait>::PalletsOrigin>; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; @@ -203,7 +203,7 @@ pub mod pallet { origin: OriginFor, calls: Vec<::RuntimeCall>, ) -> DispatchResultWithPostInfo { - let is_root = ensure_root(origin.clone()).is_ok(); + let is_root = ensure_signed_or_root(origin.clone())?.is_none(); let calls_len = calls.len(); ensure!(calls_len <= Self::batched_calls_limit() as usize, Error::::TooManyCalls); @@ -319,7 +319,7 @@ pub mod pallet { origin: OriginFor, calls: Vec<::RuntimeCall>, ) -> DispatchResultWithPostInfo { - let is_root = ensure_root(origin.clone()).is_ok(); + let is_root = ensure_signed_or_root(origin.clone())?.is_none(); let calls_len = calls.len(); ensure!(calls_len <= Self::batched_calls_limit() as usize, Error::::TooManyCalls); @@ -426,7 +426,7 @@ pub mod pallet { origin: OriginFor, calls: Vec<::RuntimeCall>, ) -> DispatchResultWithPostInfo { - let is_root = ensure_root(origin.clone()).is_ok(); + let is_root = ensure_signed_or_root(origin.clone())?.is_none(); let calls_len = calls.len(); ensure!(calls_len <= Self::batched_calls_limit() as usize, Error::::TooManyCalls); diff --git a/frame/utility/src/tests.rs b/frame/utility/src/tests.rs index 93b80672f55e2..ebd8dda81adbc 100644 --- a/frame/utility/src/tests.rs +++ b/frame/utility/src/tests.rs @@ -25,6 +25,7 @@ use crate as utility; use frame_support::{ assert_err_ignore_postinfo, assert_noop, assert_ok, dispatch::{DispatchError, DispatchErrorWithPostInfo, Dispatchable, Pays}, + error::BadOrigin, parameter_types, storage, traits::{ConstU32, ConstU64, Contains}, weights::Weight, @@ -106,7 +107,7 @@ impl frame_system::Config for Test { type BlockWeights = BlockWeights; type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = H256; @@ -199,12 +200,16 @@ fn call_foobar(err: bool, start_weight: Weight, end_weight: Option) -> R fn as_derivative_works() { new_test_ext().execute_with(|| { let sub_1_0 = Utility::derivative_account_id(1, 0); - assert_ok!(Balances::transfer(Origin::signed(1), sub_1_0, 5)); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(1), sub_1_0, 5)); assert_err_ignore_postinfo!( - Utility::as_derivative(Origin::signed(1), 1, Box::new(call_transfer(6, 3)),), + Utility::as_derivative(RuntimeOrigin::signed(1), 1, Box::new(call_transfer(6, 3)),), BalancesError::::InsufficientBalance ); - assert_ok!(Utility::as_derivative(Origin::signed(1), 0, Box::new(call_transfer(2, 3)),)); + assert_ok!(Utility::as_derivative( + RuntimeOrigin::signed(1), + 0, + Box::new(call_transfer(2, 3)), + )); assert_eq!(Balances::free_balance(sub_1_0), 2); assert_eq!(Balances::free_balance(2), 13); }); @@ -224,7 +229,7 @@ fn as_derivative_handles_weight_refund() { call: Box::new(inner_call), }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(1)); + let result = call.dispatch(RuntimeOrigin::signed(1)); assert_ok!(result); assert_eq!(extract_actual_weight(&result, &info), info.weight); @@ -235,7 +240,7 @@ fn as_derivative_handles_weight_refund() { call: Box::new(inner_call), }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(1)); + let result = call.dispatch(RuntimeOrigin::signed(1)); assert_ok!(result); // Diff is refunded assert_eq!(extract_actual_weight(&result, &info), info.weight - diff); @@ -247,7 +252,7 @@ fn as_derivative_handles_weight_refund() { call: Box::new(inner_call), }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(1)); + let result = call.dispatch(RuntimeOrigin::signed(1)); assert_noop!( result, DispatchErrorWithPostInfo { @@ -267,7 +272,7 @@ fn as_derivative_handles_weight_refund() { call: Box::new(inner_call), }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(1)); + let result = call.dispatch(RuntimeOrigin::signed(1)); assert_noop!( result, DispatchErrorWithPostInfo { @@ -287,7 +292,7 @@ fn as_derivative_filters() { new_test_ext().execute_with(|| { assert_err_ignore_postinfo!( Utility::as_derivative( - Origin::signed(1), + RuntimeOrigin::signed(1), 1, Box::new(RuntimeCall::Balances(pallet_balances::Call::transfer_keep_alive { dest: 2, @@ -310,7 +315,7 @@ fn batch_with_root_works() { assert_eq!(Balances::free_balance(1), 10); assert_eq!(Balances::free_balance(2), 10); assert_ok!(Utility::batch( - Origin::root(), + RuntimeOrigin::root(), vec![ RuntimeCall::Balances(BalancesCall::force_transfer { source: 1, @@ -337,7 +342,7 @@ fn batch_with_signed_works() { assert_eq!(Balances::free_balance(1), 10); assert_eq!(Balances::free_balance(2), 10); assert_ok!(Utility::batch( - Origin::signed(1), + RuntimeOrigin::signed(1), vec![call_transfer(2, 5), call_transfer(2, 5)] ),); assert_eq!(Balances::free_balance(1), 0); @@ -349,7 +354,7 @@ fn batch_with_signed_works() { fn batch_with_signed_filters() { new_test_ext().execute_with(|| { assert_ok!(Utility::batch( - Origin::signed(1), + RuntimeOrigin::signed(1), vec![RuntimeCall::Balances(pallet_balances::Call::transfer_keep_alive { dest: 2, value: 1 @@ -371,7 +376,7 @@ fn batch_early_exit_works() { assert_eq!(Balances::free_balance(1), 10); assert_eq!(Balances::free_balance(2), 10); assert_ok!(Utility::batch( - Origin::signed(1), + RuntimeOrigin::signed(1), vec![call_transfer(2, 5), call_transfer(2, 10), call_transfer(2, 5),] ),); assert_eq!(Balances::free_balance(1), 5); @@ -409,7 +414,7 @@ fn batch_handles_weight_refund() { let batch_calls = vec![inner_call; batch_len as usize]; let call = RuntimeCall::Utility(UtilityCall::batch { calls: batch_calls }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(1)); + let result = call.dispatch(RuntimeOrigin::signed(1)); assert_ok!(result); assert_eq!(extract_actual_weight(&result, &info), info.weight); @@ -418,7 +423,7 @@ fn batch_handles_weight_refund() { let batch_calls = vec![inner_call; batch_len as usize]; let call = RuntimeCall::Utility(UtilityCall::batch { calls: batch_calls }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(1)); + let result = call.dispatch(RuntimeOrigin::signed(1)); assert_ok!(result); // Diff is refunded assert_eq!(extract_actual_weight(&result, &info), info.weight - diff * batch_len); @@ -429,7 +434,7 @@ fn batch_handles_weight_refund() { let batch_calls = vec![good_call, bad_call]; let call = RuntimeCall::Utility(UtilityCall::batch { calls: batch_calls }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(1)); + let result = call.dispatch(RuntimeOrigin::signed(1)); assert_ok!(result); System::assert_last_event( utility::Event::BatchInterrupted { index: 1, error: DispatchError::Other("") }.into(), @@ -444,7 +449,7 @@ fn batch_handles_weight_refund() { let batch_len = batch_calls.len() as u64; let call = RuntimeCall::Utility(UtilityCall::batch { calls: batch_calls }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(1)); + let result = call.dispatch(RuntimeOrigin::signed(1)); assert_ok!(result); System::assert_last_event( utility::Event::BatchInterrupted { index: 1, error: DispatchError::Other("") }.into(), @@ -457,7 +462,7 @@ fn batch_handles_weight_refund() { let batch_calls = vec![good_call, bad_call.clone(), bad_call]; let call = RuntimeCall::Utility(UtilityCall::batch { calls: batch_calls }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(1)); + let result = call.dispatch(RuntimeOrigin::signed(1)); assert_ok!(result); System::assert_last_event( utility::Event::BatchInterrupted { index: 1, error: DispatchError::Other("") }.into(), @@ -476,7 +481,7 @@ fn batch_all_works() { assert_eq!(Balances::free_balance(1), 10); assert_eq!(Balances::free_balance(2), 10); assert_ok!(Utility::batch_all( - Origin::signed(1), + RuntimeOrigin::signed(1), vec![call_transfer(2, 5), call_transfer(2, 5)] ),); assert_eq!(Balances::free_balance(1), 0); @@ -496,7 +501,7 @@ fn batch_all_revert() { calls: vec![call_transfer(2, 5), call_transfer(2, 10), call_transfer(2, 5)], }); assert_noop!( - batch_all_calls.dispatch(Origin::signed(1)), + batch_all_calls.dispatch(RuntimeOrigin::signed(1)), DispatchErrorWithPostInfo { post_info: PostDispatchInfo { actual_weight: Some( @@ -525,7 +530,7 @@ fn batch_all_handles_weight_refund() { let batch_calls = vec![inner_call; batch_len as usize]; let call = RuntimeCall::Utility(UtilityCall::batch_all { calls: batch_calls }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(1)); + let result = call.dispatch(RuntimeOrigin::signed(1)); assert_ok!(result); assert_eq!(extract_actual_weight(&result, &info), info.weight); @@ -534,7 +539,7 @@ fn batch_all_handles_weight_refund() { let batch_calls = vec![inner_call; batch_len as usize]; let call = RuntimeCall::Utility(UtilityCall::batch_all { calls: batch_calls }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(1)); + let result = call.dispatch(RuntimeOrigin::signed(1)); assert_ok!(result); // Diff is refunded assert_eq!(extract_actual_weight(&result, &info), info.weight - diff * batch_len); @@ -545,7 +550,7 @@ fn batch_all_handles_weight_refund() { let batch_calls = vec![good_call, bad_call]; let call = RuntimeCall::Utility(UtilityCall::batch_all { calls: batch_calls }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(1)); + let result = call.dispatch(RuntimeOrigin::signed(1)); assert_err_ignore_postinfo!(result, "The cake is a lie."); // No weight is refunded assert_eq!(extract_actual_weight(&result, &info), info.weight); @@ -557,7 +562,7 @@ fn batch_all_handles_weight_refund() { let batch_len = batch_calls.len() as u64; let call = RuntimeCall::Utility(UtilityCall::batch_all { calls: batch_calls }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(1)); + let result = call.dispatch(RuntimeOrigin::signed(1)); assert_err_ignore_postinfo!(result, "The cake is a lie."); assert_eq!(extract_actual_weight(&result, &info), info.weight - diff * batch_len); @@ -567,7 +572,7 @@ fn batch_all_handles_weight_refund() { let batch_calls = vec![good_call, bad_call.clone(), bad_call]; let call = RuntimeCall::Utility(UtilityCall::batch_all { calls: batch_calls }); let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(1)); + let result = call.dispatch(RuntimeOrigin::signed(1)); assert_err_ignore_postinfo!(result, "The cake is a lie."); assert_eq!( extract_actual_weight(&result, &info), @@ -590,7 +595,7 @@ fn batch_all_does_not_nest() { assert_eq!(Balances::free_balance(2), 10); // A nested batch_all call will not pass the filter, and fail with `BadOrigin`. assert_noop!( - Utility::batch_all(Origin::signed(1), vec![batch_all.clone()]), + Utility::batch_all(RuntimeOrigin::signed(1), vec![batch_all.clone()]), DispatchErrorWithPostInfo { post_info: PostDispatchInfo { actual_weight: Some(::WeightInfo::batch_all(1) + info.weight), @@ -606,7 +611,7 @@ fn batch_all_does_not_nest() { let batch_nested = RuntimeCall::Utility(UtilityCall::batch { calls: vec![batch_all] }); // Batch will end with `Ok`, but does not actually execute as we can see from the event // and balances. - assert_ok!(Utility::batch_all(Origin::signed(1), vec![batch_nested])); + assert_ok!(Utility::batch_all(RuntimeOrigin::signed(1), vec![batch_nested])); System::assert_has_event( utility::Event::BatchInterrupted { index: 0, @@ -623,8 +628,14 @@ fn batch_all_does_not_nest() { fn batch_limit() { new_test_ext().execute_with(|| { let calls = vec![RuntimeCall::System(SystemCall::remark { remark: vec![] }); 40_000]; - assert_noop!(Utility::batch(Origin::signed(1), calls.clone()), Error::::TooManyCalls); - assert_noop!(Utility::batch_all(Origin::signed(1), calls), Error::::TooManyCalls); + assert_noop!( + Utility::batch(RuntimeOrigin::signed(1), calls.clone()), + Error::::TooManyCalls + ); + assert_noop!( + Utility::batch_all(RuntimeOrigin::signed(1), calls), + Error::::TooManyCalls + ); }); } @@ -634,14 +645,14 @@ fn force_batch_works() { assert_eq!(Balances::free_balance(1), 10); assert_eq!(Balances::free_balance(2), 10); assert_ok!(Utility::force_batch( - Origin::signed(1), + RuntimeOrigin::signed(1), vec![ call_transfer(2, 5), call_foobar(true, Weight::from_ref_time(75), None), call_transfer(2, 10), call_transfer(2, 5), ] - ),); + )); System::assert_last_event(utility::Event::BatchCompletedWithErrors.into()); System::assert_has_event( utility::Event::ItemFailed { error: DispatchError::Other("") }.into(), @@ -650,12 +661,21 @@ fn force_batch_works() { assert_eq!(Balances::free_balance(2), 20); assert_ok!(Utility::force_batch( - Origin::signed(2), + RuntimeOrigin::signed(2), vec![call_transfer(1, 5), call_transfer(1, 5),] - ),); + )); System::assert_last_event(utility::Event::BatchCompleted.into()); - assert_ok!(Utility::force_batch(Origin::signed(1), vec![call_transfer(2, 50),]),); + assert_ok!(Utility::force_batch(RuntimeOrigin::signed(1), vec![call_transfer(2, 50),]),); System::assert_last_event(utility::Event::BatchCompletedWithErrors.into()); }); } + +#[test] +fn none_origin_does_not_work() { + new_test_ext().execute_with(|| { + assert_noop!(Utility::force_batch(RuntimeOrigin::none(), vec![]), BadOrigin); + assert_noop!(Utility::batch(RuntimeOrigin::none(), vec![]), BadOrigin); + assert_noop!(Utility::batch_all(RuntimeOrigin::none(), vec![]), BadOrigin); + }) +} diff --git a/frame/vesting/src/mock.rs b/frame/vesting/src/mock.rs index cc4a3523459d7..c4e520b37c8c8 100644 --- a/frame/vesting/src/mock.rs +++ b/frame/vesting/src/mock.rs @@ -67,7 +67,7 @@ impl frame_system::Config for Test { type OnNewAccount = (); type OnSetCode = (); type MaxConsumers = frame_support::traits::ConstU32<16>; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type PalletInfo = PalletInfo; type SS58Prefix = (); type SystemWeightInfo = (); diff --git a/frame/whitelist/src/benchmarking.rs b/frame/whitelist/src/benchmarking.rs index 9e55d38fd8140..e0a758b2ddfdf 100644 --- a/frame/whitelist/src/benchmarking.rs +++ b/frame/whitelist/src/benchmarking.rs @@ -33,7 +33,7 @@ benchmarks! { whitelist_call { let origin = T::WhitelistOrigin::successful_origin(); let call_hash = Default::default(); - }: _(origin, call_hash) + }: _(origin, call_hash) verify { ensure!( WhitelistedCall::::contains_key(call_hash), @@ -50,7 +50,7 @@ benchmarks! { let call_hash = Default::default(); Pallet::::whitelist_call(origin.clone(), call_hash) .expect("whitelisting call must be successful"); - }: _(origin, call_hash) + }: _(origin, call_hash) verify { ensure!( !WhitelistedCall::::contains_key(call_hash), @@ -82,7 +82,7 @@ benchmarks! { let encoded_call = encoded_call.try_into().expect("encoded_call must be small enough"); T::PreimageProvider::note_preimage(encoded_call); - }: _(origin, call_hash, call_weight) + }: _(origin, call_hash, call_weight) verify { ensure!( !WhitelistedCall::::contains_key(call_hash), @@ -105,7 +105,7 @@ benchmarks! { Pallet::::whitelist_call(origin.clone(), call_hash) .expect("whitelisting call must be successful"); - }: _(origin, Box::new(call)) + }: _(origin, Box::new(call)) verify { ensure!( !WhitelistedCall::::contains_key(call_hash), diff --git a/frame/whitelist/src/lib.rs b/frame/whitelist/src/lib.rs index c5621a239f3a6..55d5c42b8f4bc 100644 --- a/frame/whitelist/src/lib.rs +++ b/frame/whitelist/src/lib.rs @@ -66,7 +66,7 @@ pub mod pallet { /// The overarching call type. type RuntimeCall: IsType<::RuntimeCall> - + Dispatchable + + Dispatchable + GetDispatchInfo + FullCodec + TypeInfo @@ -74,10 +74,10 @@ pub mod pallet { + Parameter; /// Required origin for whitelisting a call. - type WhitelistOrigin: EnsureOrigin; + type WhitelistOrigin: EnsureOrigin; /// Required origin for dispatching whitelisted call with root origin. - type DispatchWhitelistedOrigin: EnsureOrigin; + type DispatchWhitelistedOrigin: EnsureOrigin; /// The handler of pre-images. // NOTE: recipient is only needed for benchmarks. diff --git a/frame/whitelist/src/mock.rs b/frame/whitelist/src/mock.rs index b6eac316bc113..44aea86be6f19 100644 --- a/frame/whitelist/src/mock.rs +++ b/frame/whitelist/src/mock.rs @@ -58,7 +58,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u64; type Hash = H256; diff --git a/frame/whitelist/src/tests.rs b/frame/whitelist/src/tests.rs index ebb111149fd42..fd6558e83f30e 100644 --- a/frame/whitelist/src/tests.rs +++ b/frame/whitelist/src/tests.rs @@ -32,35 +32,35 @@ fn test_whitelist_call_and_remove() { let call_hash = ::Hashing::hash(&encoded_call[..]); assert_noop!( - Whitelist::remove_whitelisted_call(Origin::root(), call_hash), + Whitelist::remove_whitelisted_call(RuntimeOrigin::root(), call_hash), crate::Error::::CallIsNotWhitelisted, ); assert_noop!( - Whitelist::whitelist_call(Origin::signed(1), call_hash), + Whitelist::whitelist_call(RuntimeOrigin::signed(1), call_hash), DispatchError::BadOrigin, ); - assert_ok!(Whitelist::whitelist_call(Origin::root(), call_hash)); + assert_ok!(Whitelist::whitelist_call(RuntimeOrigin::root(), call_hash)); assert!(Preimage::preimage_requested(&call_hash)); assert_noop!( - Whitelist::whitelist_call(Origin::root(), call_hash), + Whitelist::whitelist_call(RuntimeOrigin::root(), call_hash), crate::Error::::CallAlreadyWhitelisted, ); assert_noop!( - Whitelist::remove_whitelisted_call(Origin::signed(1), call_hash), + Whitelist::remove_whitelisted_call(RuntimeOrigin::signed(1), call_hash), DispatchError::BadOrigin, ); - assert_ok!(Whitelist::remove_whitelisted_call(Origin::root(), call_hash)); + assert_ok!(Whitelist::remove_whitelisted_call(RuntimeOrigin::root(), call_hash)); assert!(!Preimage::preimage_requested(&call_hash)); assert_noop!( - Whitelist::remove_whitelisted_call(Origin::root(), call_hash), + Whitelist::remove_whitelisted_call(RuntimeOrigin::root(), call_hash), crate::Error::::CallIsNotWhitelisted, ); }); @@ -75,41 +75,45 @@ fn test_whitelist_call_and_execute() { let call_hash = ::Hashing::hash(&encoded_call[..]); assert_noop!( - Whitelist::dispatch_whitelisted_call(Origin::root(), call_hash, call_weight), + Whitelist::dispatch_whitelisted_call(RuntimeOrigin::root(), call_hash, call_weight), crate::Error::::CallIsNotWhitelisted, ); - assert_ok!(Whitelist::whitelist_call(Origin::root(), call_hash)); + assert_ok!(Whitelist::whitelist_call(RuntimeOrigin::root(), call_hash)); assert_noop!( - Whitelist::dispatch_whitelisted_call(Origin::signed(1), call_hash, call_weight), + Whitelist::dispatch_whitelisted_call(RuntimeOrigin::signed(1), call_hash, call_weight), DispatchError::BadOrigin, ); assert_noop!( - Whitelist::dispatch_whitelisted_call(Origin::root(), call_hash, call_weight), + Whitelist::dispatch_whitelisted_call(RuntimeOrigin::root(), call_hash, call_weight), crate::Error::::UnavailablePreImage, ); - assert_ok!(Preimage::note_preimage(Origin::root(), encoded_call)); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::root(), encoded_call)); assert!(Preimage::preimage_requested(&call_hash)); assert_noop!( Whitelist::dispatch_whitelisted_call( - Origin::root(), + RuntimeOrigin::root(), call_hash, call_weight - Weight::from_ref_time(1) ), crate::Error::::InvalidCallWeightWitness, ); - assert_ok!(Whitelist::dispatch_whitelisted_call(Origin::root(), call_hash, call_weight)); + assert_ok!(Whitelist::dispatch_whitelisted_call( + RuntimeOrigin::root(), + call_hash, + call_weight + )); assert!(!Preimage::preimage_requested(&call_hash)); assert_noop!( - Whitelist::dispatch_whitelisted_call(Origin::root(), call_hash, call_weight), + Whitelist::dispatch_whitelisted_call(RuntimeOrigin::root(), call_hash, call_weight), crate::Error::::CallIsNotWhitelisted, ); }); @@ -126,10 +130,14 @@ fn test_whitelist_call_and_execute_failing_call() { let encoded_call = call.encode(); let call_hash = ::Hashing::hash(&encoded_call[..]); - assert_ok!(Whitelist::whitelist_call(Origin::root(), call_hash)); - assert_ok!(Preimage::note_preimage(Origin::root(), encoded_call)); + assert_ok!(Whitelist::whitelist_call(RuntimeOrigin::root(), call_hash)); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::root(), encoded_call)); assert!(Preimage::preimage_requested(&call_hash)); - assert_ok!(Whitelist::dispatch_whitelisted_call(Origin::root(), call_hash, call_weight)); + assert_ok!(Whitelist::dispatch_whitelisted_call( + RuntimeOrigin::root(), + call_hash, + call_weight + )); assert!(!Preimage::preimage_requested(&call_hash)); }); } @@ -142,18 +150,18 @@ fn test_whitelist_call_and_execute_without_note_preimage() { })); let call_hash = ::Hashing::hash_of(&call); - assert_ok!(Whitelist::whitelist_call(Origin::root(), call_hash)); + assert_ok!(Whitelist::whitelist_call(RuntimeOrigin::root(), call_hash)); assert!(Preimage::preimage_requested(&call_hash)); assert_ok!(Whitelist::dispatch_whitelisted_call_with_preimage( - Origin::root(), + RuntimeOrigin::root(), call.clone() )); assert!(!Preimage::preimage_requested(&call_hash)); assert_noop!( - Whitelist::dispatch_whitelisted_call_with_preimage(Origin::root(), call), + Whitelist::dispatch_whitelisted_call_with_preimage(RuntimeOrigin::root(), call), crate::Error::::CallIsNotWhitelisted, ); }); @@ -171,11 +179,11 @@ fn test_whitelist_call_and_execute_decode_consumes_all() { let call_hash = ::Hashing::hash(&call[..]); - assert_ok!(Preimage::note_preimage(Origin::root(), call)); - assert_ok!(Whitelist::whitelist_call(Origin::root(), call_hash)); + assert_ok!(Preimage::note_preimage(RuntimeOrigin::root(), call)); + assert_ok!(Whitelist::whitelist_call(RuntimeOrigin::root(), call_hash)); assert_noop!( - Whitelist::dispatch_whitelisted_call(Origin::root(), call_hash, call_weight), + Whitelist::dispatch_whitelisted_call(RuntimeOrigin::root(), call_hash, call_weight), crate::Error::::UndecodableCall, ); }); diff --git a/primitives/beefy/Cargo.toml b/primitives/beefy/Cargo.toml index 320a30770ab42..1c1afde36ce5c 100644 --- a/primitives/beefy/Cargo.toml +++ b/primitives/beefy/Cargo.toml @@ -22,8 +22,7 @@ sp-runtime = { version = "6.0.0", default-features = false, path = "../runtime" sp-std = { version = "4.0.0", default-features = false, path = "../std" } [dev-dependencies] -hex = "0.4.3" -hex-literal = "0.3" +array-bytes = "4.1" sp-keystore = { version = "0.12.0", path = "../keystore" } [features] diff --git a/primitives/beefy/src/commitment.rs b/primitives/beefy/src/commitment.rs index ddf58474e77a0..4880d4b69ab01 100644 --- a/primitives/beefy/src/commitment.rs +++ b/primitives/beefy/src/commitment.rs @@ -301,7 +301,6 @@ impl From> for VersionedFinalityProof { #[cfg(test)] mod tests { - use sp_core::{keccak_256, Pair}; use sp_keystore::{testing::KeyStore, SyncCryptoStore, SyncCryptoStorePtr}; @@ -314,6 +313,8 @@ mod tests { type TestSignedCommitment = SignedCommitment; type TestVersionedFinalityProof = VersionedFinalityProof; + const LARGE_RAW_COMMITMENT: &[u8] = include_bytes!("../test-res/large-raw-commitment"); + // The mock signatures are equivalent to the ones produced by the BEEFY keystore fn mock_signatures() -> (crypto::Signature, crypto::Signature) { let store: SyncCryptoStorePtr = KeyStore::new().into(); @@ -351,7 +352,7 @@ mod tests { assert_eq!(decoded, Ok(commitment)); assert_eq!( encoded, - hex_literal::hex!( + array_bytes::hex2bytes_unchecked( "046d68343048656c6c6f20576f726c6421050000000000000000000000000000000000000000000000" ) ); @@ -379,12 +380,14 @@ mod tests { assert_eq!(decoded, Ok(signed)); assert_eq!( encoded, - hex_literal::hex!( - "046d68343048656c6c6f20576f726c6421050000000000000000000000000000000000000000000000 - 04300400000008558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746 - cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba012d6e1f8105c337a86cdd9a - aacdc496577f3db8c55ef9e6fd48f2c5c05a2274707491635d8ba3df64f324575b7b2a34487bca2324b - 6a0046395a71681be3d0c2a00" + array_bytes::hex2bytes_unchecked( + "\ + 046d68343048656c6c6f20576f726c64210500000000000000000000000000000000000000000000000\ + 4300400000008558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746c\ + c321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba012d6e1f8105c337a86cdd9aa\ + acdc496577f3db8c55ef9e6fd48f2c5c05a2274707491635d8ba3df64f324575b7b2a34487bca2324b6\ + a0046395a71681be3d0c2a00\ + " ) ); } @@ -481,56 +484,6 @@ mod tests { // then assert_eq!(decoded, Ok(signed)); - assert_eq!( - encoded, - hex_literal::hex!( - "046d68343048656c6c6f20576f726c6421050000000000000000000000000000000000000000000000 - 05020000000000000000000000000000000000000000000000000000000000000000000000000000000 - 000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff - fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff - fffffffffff0000040000b10a558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed - 4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad812 - 79df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d1 - 0dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2 - ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01 - 558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e9 - 9a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72 - d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bc - b7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc3 - 21f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc9855 - 80e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0 - c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da - 8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279d - f0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd - 3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac8 - 0a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558 - 455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a8 - 30e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d94 - 8d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb78 - 16f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f - 2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e - 4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33 - c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da848 - 0c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df07 - 95cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd - 68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a0 - 9abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455 - ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e - 314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1 - 107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f - 9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f231 - 9a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb - 75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86 - e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c7 - 46cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795c - c985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68c - e3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09ab - ed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad8 - 1279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314 - d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107 - b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba - 01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01" - ) - ); + assert_eq!(encoded, LARGE_RAW_COMMITMENT); } } diff --git a/primitives/beefy/src/witness.rs b/primitives/beefy/src/witness.rs index aae0608150534..cebfc3de85049 100644 --- a/primitives/beefy/src/witness.rs +++ b/primitives/beefy/src/witness.rs @@ -148,12 +148,14 @@ mod tests { assert_eq!(decoded, Ok(witness)); assert_eq!( encoded, - hex_literal::hex!( - "046d683048656c6c6f20576f726c642105000000000000000000000000000000000000000000000010 - 0000010110000001558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c - 746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01012d6e1f8105c337a86 - cdd9aaacdc496577f3db8c55ef9e6fd48f2c5c05a2274707491635d8ba3df64f324575b7b2a34487bc - a2324b6a0046395a71681be3d0c2a00" + array_bytes::hex2bytes_unchecked( + "\ + 046d683048656c6c6f20576f726c642105000000000000000000000000000000000000000000000010\ + 0000010110000001558455ad81279df0795cc985580e4fb75d72d948d1107b2ac80a09abed4da8480c\ + 746cc321f2319a5e99a830e314d10dd3cd68ce3dc0c33c86e99bcb7816f9ba01012d6e1f8105c337a8\ + 6cdd9aaacdc496577f3db8c55ef9e6fd48f2c5c05a2274707491635d8ba3df64f324575b7b2a34487b\ + ca2324b6a0046395a71681be3d0c2a00\ + " ) ); } diff --git a/primitives/beefy/test-res/large-raw-commitment b/primitives/beefy/test-res/large-raw-commitment new file mode 100644 index 0000000000000..d5dbbe402a88e Binary files /dev/null and b/primitives/beefy/test-res/large-raw-commitment differ diff --git a/primitives/core/Cargo.toml b/primitives/core/Cargo.toml index 15504aa3b9906..b7bc6dfdce496 100644 --- a/primitives/core/Cargo.toml +++ b/primitives/core/Cargo.toml @@ -47,13 +47,13 @@ thiserror = { version = "1.0.30", optional = true } bitflags = "1.3" # full crypto +array-bytes = { version = "4.1", optional = true } ed25519-zebra = { version = "3.0.0", default-features = false, optional = true} blake2 = { version = "0.10.4", default-features = false, optional = true } schnorrkel = { version = "0.9.1", features = [ "preaudit_deprecated", "u64_backend", ], default-features = false, optional = true } -hex = { version = "0.4", default-features = false, optional = true } libsecp256k1 = { version = "0.7", default-features = false, features = ["static-context"], optional = true } merlin = { version = "2.0", default-features = false, optional = true } secp256k1 = { version = "0.24.0", default-features = false, features = ["recovery", "alloc"], optional = true } @@ -63,7 +63,6 @@ sp-runtime-interface = { version = "6.0.0", default-features = false, path = ".. [dev-dependencies] sp-serializer = { version = "4.0.0-dev", path = "../serializer" } -hex-literal = "0.3.4" rand = "0.7.2" criterion = "0.3.3" serde_json = "1.0" @@ -99,8 +98,8 @@ std = [ "sp-std/std", "serde", "blake2/std", + "array-bytes", "ed25519-zebra", - "hex/std", "base58", "substrate-bip39", "tiny-bip39", @@ -129,10 +128,10 @@ std = [ # or Intel SGX. # For the regular wasm runtime builds this should not be used. full_crypto = [ + "array-bytes", "ed25519-zebra", "blake2", "schnorrkel", - "hex", "libsecp256k1", "secp256k1", "sp-core-hashing", diff --git a/primitives/core/src/crypto.rs b/primitives/core/src/crypto.rs index 377ae480edd17..db855620a8f0d 100644 --- a/primitives/core/src/crypto.rs +++ b/primitives/core/src/crypto.rs @@ -421,7 +421,7 @@ impl + AsRef<[u8]> + Public + Derive> Ss58Codec for T { let cap = SS58_REGEX.captures(s).ok_or(PublicError::InvalidFormat)?; let s = cap.name("ss58").map(|r| r.as_str()).unwrap_or(DEV_ADDRESS); let addr = if let Some(stripped) = s.strip_prefix("0x") { - let d = hex::decode(stripped).map_err(|_| PublicError::InvalidFormat)?; + let d = array_bytes::hex2bytes(stripped).map_err(|_| PublicError::InvalidFormat)?; Self::from_slice(&d).map_err(|()| PublicError::BadLength)? } else { Self::from_ss58check(s)? @@ -614,10 +614,7 @@ impl sp_std::str::FromStr for AccountId32 { fn from_str(s: &str) -> Result { let hex_or_ss58_without_prefix = s.trim_start_matches("0x"); if hex_or_ss58_without_prefix.len() == 64 { - let mut bytes = [0u8; 32]; - hex::decode_to_slice(hex_or_ss58_without_prefix, &mut bytes) - .map_err(|_| "invalid hex address.") - .map(|_| Self::from(bytes)) + array_bytes::hex_n_into(hex_or_ss58_without_prefix).map_err(|_| "invalid hex address.") } else { Self::from_ss58check(s).map_err(|_| "invalid ss58 address.") } @@ -943,7 +940,7 @@ pub trait Pair: CryptoType + Sized + Clone + Send + Sync + 'static { password_override.or_else(|| password.as_ref().map(|p| p.expose_secret().as_str())); let (root, seed) = if let Some(stripped) = phrase.expose_secret().strip_prefix("0x") { - hex::decode(stripped) + array_bytes::hex2bytes(stripped) .ok() .and_then(|seed_vec| { let mut seed = Self::Seed::default(); @@ -1127,7 +1124,6 @@ pub mod key_types { mod tests { use super::*; use crate::DeriveJunction; - use hex_literal::hex; #[derive(Clone, Eq, PartialEq, Debug)] enum TestPair { @@ -1269,7 +1265,7 @@ mod tests { fn interpret_std_seed_should_work() { assert_eq!( TestPair::from_string("0x0123456789abcdef", None), - Ok(TestPair::Seed(hex!["0123456789abcdef"][..].to_owned())) + Ok(TestPair::Seed(array_bytes::hex2bytes_unchecked("0123456789abcdef"))) ); } diff --git a/primitives/core/src/ecdsa.rs b/primitives/core/src/ecdsa.rs index d56f65fd289e7..ca6b800625bc2 100644 --- a/primitives/core/src/ecdsa.rs +++ b/primitives/core/src/ecdsa.rs @@ -229,7 +229,7 @@ impl Serialize for Signature { where S: Serializer, { - serializer.serialize_str(&hex::encode(self)) + serializer.serialize_str(&array_bytes::bytes2hex("", self.as_ref())) } } @@ -239,7 +239,7 @@ impl<'de> Deserialize<'de> for Signature { where D: Deserializer<'de>, { - let signature_hex = hex::decode(&String::deserialize(deserializer)?) + let signature_hex = array_bytes::hex2bytes(&String::deserialize(deserializer)?) .map_err(|e| de::Error::custom(format!("{:?}", e)))?; Signature::try_from(signature_hex.as_ref()) .map_err(|e| de::Error::custom(format!("{:?}", e))) @@ -597,7 +597,6 @@ mod test { set_default_ss58_version, PublicError, Ss58AddressFormat, Ss58AddressFormatRegistry, DEV_PHRASE, }; - use hex_literal::hex; use serde_json; #[test] @@ -612,31 +611,35 @@ mod test { #[test] fn seed_and_derive_should_work() { - let seed = hex!("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"); + let seed = array_bytes::hex2array_unchecked( + "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", + ); let pair = Pair::from_seed(&seed); assert_eq!(pair.seed(), seed); let path = vec![DeriveJunction::Hard([0u8; 32])]; let derived = pair.derive(path.into_iter(), None).ok().unwrap(); assert_eq!( derived.0.seed(), - hex!("b8eefc4937200a8382d00050e050ced2d4ab72cc2ef1b061477afb51564fdd61") + array_bytes::hex2array_unchecked::<32>( + "b8eefc4937200a8382d00050e050ced2d4ab72cc2ef1b061477afb51564fdd61" + ) ); } #[test] fn test_vector_should_work() { - let pair = Pair::from_seed(&hex!( - "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60" + let pair = Pair::from_seed(&array_bytes::hex2array_unchecked( + "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", )); let public = pair.public(); assert_eq!( public, Public::from_full( - &hex!("8db55b05db86c0b1786ca49f095d76344c9e6056b2f02701a7e7f3c20aabfd913ebbe148dd17c56551a52952371071a6c604b3f3abe8f2c8fa742158ea6dd7d4")[..], + &array_bytes::hex2bytes_unchecked("8db55b05db86c0b1786ca49f095d76344c9e6056b2f02701a7e7f3c20aabfd913ebbe148dd17c56551a52952371071a6c604b3f3abe8f2c8fa742158ea6dd7d4"), ).unwrap(), ); let message = b""; - let signature = hex!("3dde91174bd9359027be59a428b8146513df80a2a3c7eda2194f64de04a69ab97b753169e94db6ffd50921a2668a48b94ca11e3d32c1ff19cfe88890aa7e8f3c00"); + let signature = array_bytes::hex2array_unchecked("3dde91174bd9359027be59a428b8146513df80a2a3c7eda2194f64de04a69ab97b753169e94db6ffd50921a2668a48b94ca11e3d32c1ff19cfe88890aa7e8f3c00"); let signature = Signature::from_raw(signature); assert!(pair.sign(&message[..]) == signature); assert!(Pair::verify(&signature, &message[..], &public)); @@ -653,11 +656,11 @@ mod test { assert_eq!( public, Public::from_full( - &hex!("8db55b05db86c0b1786ca49f095d76344c9e6056b2f02701a7e7f3c20aabfd913ebbe148dd17c56551a52952371071a6c604b3f3abe8f2c8fa742158ea6dd7d4")[..], + &array_bytes::hex2bytes_unchecked("8db55b05db86c0b1786ca49f095d76344c9e6056b2f02701a7e7f3c20aabfd913ebbe148dd17c56551a52952371071a6c604b3f3abe8f2c8fa742158ea6dd7d4"), ).unwrap(), ); let message = b""; - let signature = hex!("3dde91174bd9359027be59a428b8146513df80a2a3c7eda2194f64de04a69ab97b753169e94db6ffd50921a2668a48b94ca11e3d32c1ff19cfe88890aa7e8f3c00"); + let signature = array_bytes::hex2array_unchecked("3dde91174bd9359027be59a428b8146513df80a2a3c7eda2194f64de04a69ab97b753169e94db6ffd50921a2668a48b94ca11e3d32c1ff19cfe88890aa7e8f3c00"); let signature = Signature::from_raw(signature); assert!(pair.sign(&message[..]) == signature); assert!(Pair::verify(&signature, &message[..], &public)); @@ -680,10 +683,10 @@ mod test { assert_eq!( public, Public::from_full( - &hex!("5676109c54b9a16d271abeb4954316a40a32bcce023ac14c8e26e958aa68fba995840f3de562156558efbfdac3f16af0065e5f66795f4dd8262a228ef8c6d813")[..], + &array_bytes::hex2bytes_unchecked("5676109c54b9a16d271abeb4954316a40a32bcce023ac14c8e26e958aa68fba995840f3de562156558efbfdac3f16af0065e5f66795f4dd8262a228ef8c6d813"), ).unwrap(), ); - let message = hex!("2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000000200d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000"); + let message = array_bytes::hex2bytes_unchecked("2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000000200d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000"); let signature = pair.sign(&message[..]); println!("Correct signature: {:?}", signature); assert!(Pair::verify(&signature, &message[..], &public)); diff --git a/primitives/core/src/ed25519.rs b/primitives/core/src/ed25519.rs index 0553cf4843df5..e85eb87c9fd83 100644 --- a/primitives/core/src/ed25519.rs +++ b/primitives/core/src/ed25519.rs @@ -228,7 +228,7 @@ impl Serialize for Signature { where S: Serializer, { - serializer.serialize_str(&hex::encode(self)) + serializer.serialize_str(&array_bytes::bytes2hex("", self.as_ref())) } } @@ -238,7 +238,7 @@ impl<'de> Deserialize<'de> for Signature { where D: Deserializer<'de>, { - let signature_hex = hex::decode(&String::deserialize(deserializer)?) + let signature_hex = array_bytes::hex2bytes(&String::deserialize(deserializer)?) .map_err(|e| de::Error::custom(format!("{:?}", e)))?; Signature::try_from(signature_hex.as_ref()) .map_err(|e| de::Error::custom(format!("{:?}", e))) @@ -551,7 +551,6 @@ impl CryptoType for Pair { mod test { use super::*; use crate::crypto::DEV_PHRASE; - use hex_literal::hex; use serde_json; #[test] @@ -566,31 +565,35 @@ mod test { #[test] fn seed_and_derive_should_work() { - let seed = hex!("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"); + let seed = array_bytes::hex2array_unchecked( + "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", + ); let pair = Pair::from_seed(&seed); assert_eq!(pair.seed(), seed); let path = vec![DeriveJunction::Hard([0u8; 32])]; let derived = pair.derive(path.into_iter(), None).ok().unwrap().0; assert_eq!( derived.seed(), - hex!("ede3354e133f9c8e337ddd6ee5415ed4b4ffe5fc7d21e933f4930a3730e5b21c") + array_bytes::hex2array_unchecked::<32>( + "ede3354e133f9c8e337ddd6ee5415ed4b4ffe5fc7d21e933f4930a3730e5b21c" + ) ); } #[test] fn test_vector_should_work() { - let pair = Pair::from_seed(&hex!( - "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60" + let pair = Pair::from_seed(&array_bytes::hex2array_unchecked( + "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", )); let public = pair.public(); assert_eq!( public, - Public::from_raw(hex!( + Public::from_raw(array_bytes::hex2array_unchecked( "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a" )) ); let message = b""; - let signature = hex!("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"); + let signature = array_bytes::hex2array_unchecked("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"); let signature = Signature::from_raw(signature); assert!(pair.sign(&message[..]) == signature); assert!(Pair::verify(&signature, &message[..], &public)); @@ -606,12 +609,12 @@ mod test { let public = pair.public(); assert_eq!( public, - Public::from_raw(hex!( + Public::from_raw(array_bytes::hex2array_unchecked( "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a" )) ); let message = b""; - let signature = hex!("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"); + let signature = array_bytes::hex2array_unchecked("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"); let signature = Signature::from_raw(signature); assert!(pair.sign(&message[..]) == signature); assert!(Pair::verify(&signature, &message[..], &public)); @@ -633,11 +636,11 @@ mod test { let public = pair.public(); assert_eq!( public, - Public::from_raw(hex!( + Public::from_raw(array_bytes::hex2array_unchecked( "2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee" )) ); - let message = hex!("2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000000200d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000"); + let message = array_bytes::hex2bytes_unchecked("2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000000200d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000"); let signature = pair.sign(&message[..]); println!("Correct signature: {:?}", signature); assert!(Pair::verify(&signature, &message[..], &public)); diff --git a/primitives/core/src/sr25519.rs b/primitives/core/src/sr25519.rs index ef033c2099b5f..9064fb7427393 100644 --- a/primitives/core/src/sr25519.rs +++ b/primitives/core/src/sr25519.rs @@ -233,7 +233,7 @@ impl Serialize for Signature { where S: Serializer, { - serializer.serialize_str(&hex::encode(self)) + serializer.serialize_str(&array_bytes::bytes2hex("", self.as_ref())) } } @@ -243,7 +243,7 @@ impl<'de> Deserialize<'de> for Signature { where D: Deserializer<'de>, { - let signature_hex = hex::decode(&String::deserialize(deserializer)?) + let signature_hex = array_bytes::hex2bytes(&String::deserialize(deserializer)?) .map_err(|e| de::Error::custom(format!("{:?}", e)))?; Signature::try_from(signature_hex.as_ref()) .map_err(|e| de::Error::custom(format!("{:?}", e))) @@ -664,7 +664,6 @@ pub fn verify_batch( mod compatibility_test { use super::*; use crate::crypto::DEV_PHRASE; - use hex_literal::hex; // NOTE: tests to ensure addresses that are created with the `0.1.x` version (pre-audit) are // still functional. @@ -673,7 +672,9 @@ mod compatibility_test { fn derive_soft_known_pair_should_work() { let pair = Pair::from_string(&format!("{}/Alice", DEV_PHRASE), None).unwrap(); // known address of DEV_PHRASE with 1.1 - let known = hex!("d6c71059dbbe9ad2b0ed3f289738b800836eb425544ce694825285b958ca755e"); + let known = array_bytes::hex2bytes_unchecked( + "d6c71059dbbe9ad2b0ed3f289738b800836eb425544ce694825285b958ca755e", + ); assert_eq!(pair.public().to_raw_vec(), known); } @@ -681,17 +682,19 @@ mod compatibility_test { fn derive_hard_known_pair_should_work() { let pair = Pair::from_string(&format!("{}//Alice", DEV_PHRASE), None).unwrap(); // known address of DEV_PHRASE with 1.1 - let known = hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"); + let known = array_bytes::hex2bytes_unchecked( + "d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d", + ); assert_eq!(pair.public().to_raw_vec(), known); } #[test] fn verify_known_old_message_should_work() { - let public = Public::from_raw(hex!( - "b4bfa1f7a5166695eb75299fd1c4c03ea212871c342f2c5dfea0902b2c246918" + let public = Public::from_raw(array_bytes::hex2array_unchecked( + "b4bfa1f7a5166695eb75299fd1c4c03ea212871c342f2c5dfea0902b2c246918", )); // signature generated by the 1.1 version with the same ^^ public key. - let signature = Signature::from_raw(hex!( + let signature = Signature::from_raw(array_bytes::hex2array_unchecked( "5a9755f069939f45d96aaf125cf5ce7ba1db998686f87f2fb3cbdea922078741a73891ba265f70c31436e18a9acd14d189d73c12317ab6c313285cd938453202" )); let message = b"Verifying that I am the owner of 5G9hQLdsKQswNPgB499DeA5PkFBbgkLPJWkkS6FAM6xGQ8xD. Hash: 221455a3\n"; @@ -704,7 +707,6 @@ mod compatibility_test { mod test { use super::*; use crate::crypto::{Ss58Codec, DEV_ADDRESS, DEV_PHRASE}; - use hex_literal::hex; use serde_json; #[test] @@ -745,8 +747,8 @@ mod test { #[test] fn derive_soft_should_work() { - let pair = Pair::from_seed(&hex!( - "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60" + let pair = Pair::from_seed(&array_bytes::hex2array_unchecked( + "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", )); let derive_1 = pair.derive(Some(DeriveJunction::soft(1)).into_iter(), None).unwrap().0; let derive_1b = pair.derive(Some(DeriveJunction::soft(1)).into_iter(), None).unwrap().0; @@ -757,8 +759,8 @@ mod test { #[test] fn derive_hard_should_work() { - let pair = Pair::from_seed(&hex!( - "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60" + let pair = Pair::from_seed(&array_bytes::hex2array_unchecked( + "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", )); let derive_1 = pair.derive(Some(DeriveJunction::hard(1)).into_iter(), None).unwrap().0; let derive_1b = pair.derive(Some(DeriveJunction::hard(1)).into_iter(), None).unwrap().0; @@ -769,8 +771,8 @@ mod test { #[test] fn derive_soft_public_should_work() { - let pair = Pair::from_seed(&hex!( - "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60" + let pair = Pair::from_seed(&array_bytes::hex2array_unchecked( + "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", )); let path = Some(DeriveJunction::soft(1)); let pair_1 = pair.derive(path.into_iter(), None).unwrap().0; @@ -780,8 +782,8 @@ mod test { #[test] fn derive_hard_public_should_fail() { - let pair = Pair::from_seed(&hex!( - "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60" + let pair = Pair::from_seed(&array_bytes::hex2array_unchecked( + "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", )); let path = Some(DeriveJunction::hard(1)); assert!(pair.public().derive(path.into_iter()).is_none()); @@ -789,13 +791,13 @@ mod test { #[test] fn sr_test_vector_should_work() { - let pair = Pair::from_seed(&hex!( - "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60" + let pair = Pair::from_seed(&array_bytes::hex2array_unchecked( + "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", )); let public = pair.public(); assert_eq!( public, - Public::from_raw(hex!( + Public::from_raw(array_bytes::hex2array_unchecked( "44a996beb1eef7bdcab976ab6d2ca26104834164ecf28fb375600576fcc6eb0f" )) ); @@ -840,11 +842,11 @@ mod test { let public = pair.public(); assert_eq!( public, - Public::from_raw(hex!( + Public::from_raw(array_bytes::hex2array_unchecked( "741c08a06f41c596608f6774259bd9043304adfa5d3eea62760bd9be97634d63" )) ); - let message = hex!("2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000000200d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000"); + let message = array_bytes::hex2bytes_unchecked("2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000000200d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000"); let signature = pair.sign(&message[..]); assert!(Pair::verify(&signature, &message[..], &public)); } @@ -865,11 +867,11 @@ mod test { // schnorrkel-js. // // This is to make sure that the wasm library is compatible. - let pk = Pair::from_seed(&hex!( - "0000000000000000000000000000000000000000000000000000000000000000" + let pk = Pair::from_seed(&array_bytes::hex2array_unchecked( + "0000000000000000000000000000000000000000000000000000000000000000", )); let public = pk.public(); - let js_signature = Signature::from_raw(hex!( + let js_signature = Signature::from_raw(array_bytes::hex2array_unchecked( "28a854d54903e056f89581c691c1f7d2ff39f8f896c9e9c22475e60902cc2b3547199e0e91fa32902028f2ca2355e8cdd16cfe19ba5e8b658c94aa80f3b81a00" )); assert!(Pair::verify_deprecated(&js_signature, b"SUBSTRATE", &public)); diff --git a/primitives/merkle-mountain-range/Cargo.toml b/primitives/merkle-mountain-range/Cargo.toml index 2be3f592b2b20..e7e203942e845 100644 --- a/primitives/merkle-mountain-range/Cargo.toml +++ b/primitives/merkle-mountain-range/Cargo.toml @@ -22,7 +22,7 @@ sp-runtime = { version = "6.0.0", default-features = false, path = "../runtime" sp-std = { version = "4.0.0", default-features = false, path = "../std" } [dev-dependencies] -hex-literal = "0.3" +array-bytes = "4.1" [features] default = ["std"] diff --git a/primitives/merkle-mountain-range/src/lib.rs b/primitives/merkle-mountain-range/src/lib.rs index 8a2e901aefddf..29a7e3d1a6fb6 100644 --- a/primitives/merkle-mountain-range/src/lib.rs +++ b/primitives/merkle-mountain-range/src/lib.rs @@ -535,11 +535,16 @@ mod tests { cases.into_iter().map(Result::<_, codec::Error>::Ok).collect::>() ); // check encoding correctness - assert_eq!(&encoded[0], &hex_literal::hex!("00343048656c6c6f20576f726c6421")); + assert_eq!( + &encoded[0], + &array_bytes::hex2bytes_unchecked("00343048656c6c6f20576f726c6421") + ); assert_eq!( encoded[1].as_slice(), - hex_literal::hex!("01c3e7ba6b511162fead58f2c8b5764ce869ed1118011ac37392522ed16720bbcd") - .as_ref() + array_bytes::hex2bytes_unchecked( + "01c3e7ba6b511162fead58f2c8b5764ce869ed1118011ac37392522ed16720bbcd" + ) + .as_slice() ); } diff --git a/primitives/runtime/src/generic/checked_extrinsic.rs b/primitives/runtime/src/generic/checked_extrinsic.rs index 5d6c657a68977..fd7745c6031ff 100644 --- a/primitives/runtime/src/generic/checked_extrinsic.rs +++ b/primitives/runtime/src/generic/checked_extrinsic.rs @@ -39,12 +39,13 @@ pub struct CheckedExtrinsic { pub function: Call, } -impl traits::Applyable for CheckedExtrinsic +impl traits::Applyable + for CheckedExtrinsic where AccountId: Member + MaybeDisplay, - Call: Member + Dispatchable, + Call: Member + Dispatchable, Extra: SignedExtension, - Origin: From>, + RuntimeOrigin: From>, { type Call = Call; @@ -78,7 +79,7 @@ where U::pre_dispatch(&self.function)?; (None, None) }; - let res = self.function.dispatch(Origin::from(maybe_who)); + let res = self.function.dispatch(RuntimeOrigin::from(maybe_who)); let post_info = match res { Ok(info) => info, Err(err) => err.post_info, diff --git a/primitives/runtime/src/testing.rs b/primitives/runtime/src/testing.rs index 003fa62c9e088..d16a37e6a2059 100644 --- a/primitives/runtime/src/testing.rs +++ b/primitives/runtime/src/testing.rs @@ -358,8 +358,15 @@ where impl Applyable for TestXt where - Call: - 'static + Sized + Send + Sync + Clone + Eq + Codec + Debug + Dispatchable, + Call: 'static + + Sized + + Send + + Sync + + Clone + + Eq + + Codec + + Debug + + Dispatchable, Extra: SignedExtension, Origin: From>, { diff --git a/primitives/runtime/src/traits.rs b/primitives/runtime/src/traits.rs index 495dfa66c5462..1c48b1933431d 100644 --- a/primitives/runtime/src/traits.rs +++ b/primitives/runtime/src/traits.rs @@ -1018,7 +1018,7 @@ pub trait Dispatchable { /// Every function call from your runtime has an origin, which specifies where the extrinsic was /// generated from. In the case of a signed extrinsic (transaction), the origin contains an /// identifier for the caller. The origin can be empty in the case of an inherent extrinsic. - type Origin; + type RuntimeOrigin; /// ... type Config; /// An opaque set of information attached to the transaction. This could be constructed anywhere @@ -1029,7 +1029,8 @@ pub trait Dispatchable { /// with information about a `Dispatchable` that is ownly known post dispatch. type PostInfo: Eq + PartialEq + Clone + Copy + Encode + Decode + Printable; /// Actually dispatch this call and return the result of it. - fn dispatch(self, origin: Self::Origin) -> crate::DispatchResultWithInfo; + fn dispatch(self, origin: Self::RuntimeOrigin) + -> crate::DispatchResultWithInfo; } /// Shortcut to reference the `Info` type of a `Dispatchable`. @@ -1038,11 +1039,14 @@ pub type DispatchInfoOf = ::Info; pub type PostDispatchInfoOf = ::PostInfo; impl Dispatchable for () { - type Origin = (); + type RuntimeOrigin = (); type Config = (); type Info = (); type PostInfo = (); - fn dispatch(self, _origin: Self::Origin) -> crate::DispatchResultWithInfo { + fn dispatch( + self, + _origin: Self::RuntimeOrigin, + ) -> crate::DispatchResultWithInfo { panic!("This implementation should not be used for actual dispatch."); } } diff --git a/primitives/state-machine/Cargo.toml b/primitives/state-machine/Cargo.toml index 5de6eb7112eea..860bca2a9de18 100644 --- a/primitives/state-machine/Cargo.toml +++ b/primitives/state-machine/Cargo.toml @@ -31,7 +31,7 @@ sp-std = { version = "4.0.0", default-features = false, path = "../std" } sp-trie = { version = "6.0.0", default-features = false, path = "../trie" } [dev-dependencies] -hex-literal = "0.3.4" +array-bytes = "4.1" pretty_assertions = "1.2.1" rand = "0.7.2" sp-runtime = { version = "6.0.0", path = "../runtime" } diff --git a/primitives/state-machine/src/basic.rs b/primitives/state-machine/src/basic.rs index 236a515a2412d..fdc50e3f8f207 100644 --- a/primitives/state-machine/src/basic.rs +++ b/primitives/state-machine/src/basic.rs @@ -356,7 +356,6 @@ impl sp_externalities::ExtensionStore for BasicExternalities { #[cfg(test)] mod tests { use super::*; - use hex_literal::hex; use sp_core::{ map, storage::{well_known_keys::CODE, Storage, StorageChild}, @@ -368,10 +367,11 @@ 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()); - const ROOT: [u8; 32] = - hex!("39245109cef3758c2eed2ccba8d9b370a917850af3824bc8348d505df2c298fa"); + let root = array_bytes::hex2bytes_unchecked( + "39245109cef3758c2eed2ccba8d9b370a917850af3824bc8348d505df2c298fa", + ); - assert_eq!(&ext.storage_root(StateVersion::default())[..], &ROOT); + assert_eq!(&ext.storage_root(StateVersion::default())[..], &root); } #[test] diff --git a/primitives/state-machine/src/overlayed_changes/mod.rs b/primitives/state-machine/src/overlayed_changes/mod.rs index 001b4b656c34e..ef5c02d2ec1fa 100644 --- a/primitives/state-machine/src/overlayed_changes/mod.rs +++ b/primitives/state-machine/src/overlayed_changes/mod.rs @@ -743,7 +743,6 @@ impl<'a> OverlayedExtensions<'a> { mod tests { use super::*; use crate::{ext::Ext, InMemoryBackend}; - use hex_literal::hex; use sp_core::{traits::Externalities, Blake2Hasher}; use std::collections::BTreeMap; @@ -870,10 +869,11 @@ mod tests { let mut cache = StorageTransactionCache::default(); let mut ext = Ext::new(&mut overlay, &mut cache, &backend, None); - const ROOT: [u8; 32] = - hex!("39245109cef3758c2eed2ccba8d9b370a917850af3824bc8348d505df2c298fa"); + let root = array_bytes::hex2bytes_unchecked( + "39245109cef3758c2eed2ccba8d9b370a917850af3824bc8348d505df2c298fa", + ); - assert_eq!(&ext.storage_root(state_version)[..], &ROOT); + assert_eq!(&ext.storage_root(state_version)[..], &root); } #[test] diff --git a/primitives/state-machine/src/testing.rs b/primitives/state-machine/src/testing.rs index 46b7573d9d1a6..e94d34b5560cd 100644 --- a/primitives/state-machine/src/testing.rs +++ b/primitives/state-machine/src/testing.rs @@ -334,7 +334,6 @@ where #[cfg(test)] mod tests { use super::*; - use hex_literal::hex; use sp_core::{storage::ChildInfo, traits::Externalities, H256}; use sp_runtime::traits::BlakeTwo256; @@ -346,8 +345,9 @@ 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 = - H256::from(hex!("ed4d8c799d996add422395a6abd7545491d40bd838d738afafa1b8a4de625489")); + let root = array_bytes::hex_n_into_unchecked::( + "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 9b2b8a29b8640..2636648f40387 100644 --- a/primitives/trie/Cargo.toml +++ b/primitives/trie/Cargo.toml @@ -36,8 +36,8 @@ sp-core = { version = "6.0.0", default-features = false, path = "../core" } sp-std = { version = "4.0.0", default-features = false, path = "../std" } [dev-dependencies] +array-bytes = "4.1" criterion = "0.3.3" -hex-literal = "0.3.4" trie-bench = "0.32.0" trie-standardmap = "0.15.2" sp-runtime = { version = "6.0.0", path = "../runtime" } diff --git a/primitives/trie/src/lib.rs b/primitives/trie/src/lib.rs index fafa2a2891ce4..c2ab12dbee14c 100644 --- a/primitives/trie/src/lib.rs +++ b/primitives/trie/src/lib.rs @@ -542,7 +542,6 @@ mod tests { use super::*; use codec::{Compact, Decode, Encode}; use hash_db::{HashDB, Hasher}; - use hex_literal::hex; use sp_core::Blake2Hasher; use trie_db::{DBValue, NodeCodec as NodeCodecT, Trie, TrieMut}; use trie_standardmap::{Alphabet, StandardMap, ValueMode}; @@ -845,8 +844,14 @@ mod tests { } fn iterator_works_inner() { let pairs = vec![ - (hex!("0103000000000000000464").to_vec(), hex!("0400000000").to_vec()), - (hex!("0103000000000000000469").to_vec(), hex!("0401000000").to_vec()), + ( + array_bytes::hex2bytes_unchecked("0103000000000000000464"), + array_bytes::hex2bytes_unchecked("0400000000"), + ), + ( + array_bytes::hex2bytes_unchecked("0103000000000000000469"), + array_bytes::hex2bytes_unchecked("0401000000"), + ), ]; let mut mdb = MemoryDB::default(); @@ -859,7 +864,7 @@ mod tests { let mut iter_pairs = Vec::new(); for pair in iter { let (key, value) = pair.unwrap(); - iter_pairs.push((key, value.to_vec())); + iter_pairs.push((key, value)); } assert_eq!(pairs, iter_pairs); @@ -868,15 +873,15 @@ mod tests { #[test] fn proof_non_inclusion_works() { let pairs = vec![ - (hex!("0102").to_vec(), hex!("01").to_vec()), - (hex!("0203").to_vec(), hex!("0405").to_vec()), + (array_bytes::hex2bytes_unchecked("0102"), array_bytes::hex2bytes_unchecked("01")), + (array_bytes::hex2bytes_unchecked("0203"), array_bytes::hex2bytes_unchecked("0405")), ]; let mut memdb = MemoryDB::default(); let mut root = Default::default(); populate_trie::(&mut memdb, &mut root, &pairs); - let non_included_key: Vec = hex!("0909").to_vec(); + let non_included_key: Vec = array_bytes::hex2bytes_unchecked("0909"); let proof = generate_trie_proof::(&memdb, root, &[non_included_key.clone()]) .unwrap(); @@ -893,7 +898,7 @@ mod tests { assert!(verify_trie_proof::>( &root, &proof, - &[(non_included_key, Some(hex!("1010").to_vec()))], + &[(non_included_key, Some(array_bytes::hex2bytes_unchecked("1010")))], ) .is_err()); } @@ -901,8 +906,8 @@ mod tests { #[test] fn proof_inclusion_works() { let pairs = vec![ - (hex!("0102").to_vec(), hex!("01").to_vec()), - (hex!("0203").to_vec(), hex!("0405").to_vec()), + (array_bytes::hex2bytes_unchecked("0102"), array_bytes::hex2bytes_unchecked("01")), + (array_bytes::hex2bytes_unchecked("0203"), array_bytes::hex2bytes_unchecked("0405")), ]; let mut memdb = MemoryDB::default(); @@ -932,7 +937,7 @@ mod tests { assert!(verify_trie_proof::( &root, &proof, - &[(hex!("4242").to_vec(), Some(pairs[0].1.clone()))] + &[(array_bytes::hex2bytes_unchecked("4242"), Some(pairs[0].1.clone()))] ) .is_err()); diff --git a/primitives/wasm-interface/Cargo.toml b/primitives/wasm-interface/Cargo.toml index 05ccad88ec37a..d61c74f20222c 100644 --- a/primitives/wasm-interface/Cargo.toml +++ b/primitives/wasm-interface/Cargo.toml @@ -18,7 +18,7 @@ codec = { package = "parity-scale-codec", version = "3.0.0", default-features = impl-trait-for-tuples = "0.2.2" log = { version = "0.4.17", optional = true } wasmi = { version = "0.13", optional = true } -wasmtime = { version = "0.40.1", default-features = false, optional = true } +wasmtime = { version = "1.0.0", default-features = false, optional = true } sp-std = { version = "4.0.0", default-features = false, path = "../std" } [features] diff --git a/test-utils/client/Cargo.toml b/test-utils/client/Cargo.toml index f8a1f437d45e1..fcac37441ba98 100644 --- a/test-utils/client/Cargo.toml +++ b/test-utils/client/Cargo.toml @@ -12,10 +12,10 @@ publish = false targets = ["x86_64-unknown-linux-gnu"] [dependencies] +array-bytes = "4.1" async-trait = "0.1.57" codec = { package = "parity-scale-codec", version = "3.0.0" } futures = "0.3.21" -hex = "0.4" serde = "1.0.136" serde_json = "1.0.85" sc-client-api = { version = "4.0.0-dev", path = "../../client/api" } diff --git a/test-utils/client/src/lib.rs b/test-utils/client/src/lib.rs index 3115be58425e6..be4549c9957c0 100644 --- a/test-utils/client/src/lib.rs +++ b/test-utils/client/src/lib.rs @@ -346,7 +346,7 @@ impl RpcHandlersExt for RpcHandlers { "params": ["0x{}"], "id": 0 }}"#, - hex::encode(extrinsic.encode()) + array_bytes::bytes2hex("", &extrinsic.encode()) )) .await .expect("valid JSON-RPC request object; qed"); diff --git a/test-utils/runtime/src/genesismap.rs b/test-utils/runtime/src/genesismap.rs index 3ece5165e1757..42706730eb9ac 100644 --- a/test-utils/runtime/src/genesismap.rs +++ b/test-utils/runtime/src/genesismap.rs @@ -17,8 +17,9 @@ //! Tool for creating the genesis block. -use super::{system, wasm_binary_unwrap, AccountId, AuthorityId}; +use super::{system, wasm_binary_unwrap, AccountId, AuthorityId, Runtime}; use codec::{Encode, Joiner, KeyedVec}; +use frame_support::traits::GenesisBuild; use sc_service::client::genesis; use sp_core::{ map, @@ -80,10 +81,11 @@ impl GenesisConfig { // Assimilate the system genesis config. let mut storage = Storage { top: map, children_default: self.extra_storage.children_default.clone() }; - let config = system::GenesisConfig { authorities: self.authorities.clone() }; - config - .assimilate_storage(&mut storage) - .expect("Adding `system::GensisConfig` to the genesis"); + >::assimilate_storage( + &system::GenesisConfig { authorities: self.authorities.clone() }, + &mut storage, + ) + .expect("Adding `system::GensisConfig` to the genesis"); storage } diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index 4ed159fd7e2ed..a64e3f25ef041 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -233,11 +233,14 @@ impl ExtrinsicT for Extrinsic { } impl sp_runtime::traits::Dispatchable for Extrinsic { - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type Config = (); type Info = (); type PostInfo = (); - fn dispatch(self, _origin: Self::Origin) -> sp_runtime::DispatchResultWithInfo { + fn dispatch( + self, + _origin: Self::RuntimeOrigin, + ) -> sp_runtime::DispatchResultWithInfo { panic!("This implementation should not be used for actual dispatch."); } } @@ -441,22 +444,22 @@ impl GetRuntimeBlockType for Runtime { } #[derive(Clone, RuntimeDebug, Encode, Decode, PartialEq, Eq, TypeInfo, MaxEncodedLen)] -pub struct Origin; +pub struct RuntimeOrigin; -impl From> for Origin { +impl From> for RuntimeOrigin { fn from(_o: frame_system::Origin) -> Self { unimplemented!("Not required in tests!") } } -impl From for Result, Origin> { - fn from(_origin: Origin) -> Result, Origin> { +impl From for Result, RuntimeOrigin> { + fn from(_origin: RuntimeOrigin) -> Result, RuntimeOrigin> { unimplemented!("Not required in tests!") } } -impl frame_support::traits::OriginTrait for Origin { +impl frame_support::traits::OriginTrait for RuntimeOrigin { type Call = ::RuntimeCall; - type PalletsOrigin = Origin; + type PalletsOrigin = RuntimeOrigin; type AccountId = ::AccountId; fn add_filter(&mut self, _filter: impl Fn(&Self::Call) -> bool + 'static) { @@ -584,7 +587,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = RuntimeBlockWeights; type BlockLength = RuntimeBlockLength; - type Origin = Origin; + type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = Extrinsic; type Index = u64; type BlockNumber = u64; @@ -607,6 +610,8 @@ impl frame_system::Config for Runtime { type MaxConsumers = ConstU32<16>; } +impl system::Config for Runtime {} + impl pallet_timestamp::Config for Runtime { /// A timestamp: milliseconds since the unix epoch. type Moment = u64; diff --git a/test-utils/runtime/src/system.rs b/test-utils/runtime/src/system.rs index 45a6f66416d8c..6e33d5c25fe6f 100644 --- a/test-utils/runtime/src/system.rs +++ b/test-utils/runtime/src/system.rs @@ -19,11 +19,11 @@ //! and depositing logs. use crate::{ - AccountId, AuthorityId, Block, BlockNumber, Digest, Extrinsic, Header, Transfer, H256 as Hash, + AccountId, AuthorityId, Block, BlockNumber, Digest, Extrinsic, Header, Runtime, Transfer, + H256 as Hash, }; use codec::{Decode, Encode, KeyedVec}; -use frame_support::{decl_module, decl_storage, storage}; -use frame_system::Config; +use frame_support::storage; use sp_core::storage::well_known_keys; use sp_io::{hashing::blake2_256, storage::root as storage_root, trie}; use sp_runtime::{ @@ -39,19 +39,51 @@ use sp_std::prelude::*; const NONCE_OF: &[u8] = b"nonce:"; const BALANCE_OF: &[u8] = b"balance:"; -decl_module! { - pub struct Module for enum Call where origin: T::Origin {} -} +pub use self::pallet::*; + +#[frame_support::pallet] +mod pallet { + use super::*; + use frame_support::pallet_prelude::*; + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + #[pallet::without_storage_info] + pub struct Pallet(PhantomData); + + #[pallet::config] + pub trait Config: frame_system::Config {} + + #[pallet::storage] + pub type ExtrinsicData = StorageMap<_, Blake2_128Concat, u32, Vec, ValueQuery>; + + // The current block number being processed. Set by `execute_block`. + #[pallet::storage] + pub type Number = StorageValue<_, BlockNumber, OptionQuery>; -decl_storage! { - trait Store for Module as TestRuntime { - ExtrinsicData: map hasher(blake2_128_concat) u32 => Vec; - // The current block number being processed. Set by `execute_block`. - Number get(fn number): Option; - ParentHash get(fn parent_hash): Hash; - NewAuthorities get(fn new_authorities): Option>; - StorageDigest get(fn storage_digest): Option; - Authorities get(fn authorities) config(): Vec; + #[pallet::storage] + pub type ParentHash = StorageValue<_, Hash, ValueQuery>; + + #[pallet::storage] + pub type NewAuthorities = StorageValue<_, Vec, OptionQuery>; + + #[pallet::storage] + pub type StorageDigest = StorageValue<_, Digest, OptionQuery>; + + #[pallet::storage] + pub type Authorities = StorageValue<_, Vec, ValueQuery>; + + #[pallet::genesis_config] + #[cfg_attr(feature = "std", derive(Default))] + pub struct GenesisConfig { + pub authorities: Vec, + } + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + >::put(self.authorities.clone()); + } } } @@ -69,9 +101,9 @@ pub fn nonce_of(who: AccountId) -> u64 { pub fn initialize_block(header: &Header) { // populate environment. - ::put(&header.number); - ::put(&header.parent_hash); - ::put(header.digest()); + >::put(&header.number); + >::put(&header.parent_hash); + >::put(header.digest()); storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32); // try to read something that depends on current header digest @@ -82,15 +114,15 @@ pub fn initialize_block(header: &Header) { } pub fn authorities() -> Vec { - Authorities::get() + >::get() } pub fn get_block_number() -> Option { - Number::get() + >::get() } pub fn take_block_number() -> Option { - Number::take() + >::take() } #[derive(Copy, Clone)] @@ -124,8 +156,8 @@ fn execute_block_with_state_root_handler(block: &mut Block, mode: Mode) -> Heade header.state_root = new_header.state_root; } else { info_expect_equal_hash(&new_header.state_root, &header.state_root); - assert!( - new_header.state_root == header.state_root, + assert_eq!( + new_header.state_root, header.state_root, "Storage root must match that calculated.", ); } @@ -134,8 +166,8 @@ fn execute_block_with_state_root_handler(block: &mut Block, mode: Mode) -> Heade header.extrinsics_root = new_header.extrinsics_root; } else { info_expect_equal_hash(&new_header.extrinsics_root, &header.extrinsics_root); - assert!( - new_header.extrinsics_root == header.extrinsics_root, + assert_eq!( + new_header.extrinsics_root, header.extrinsics_root, "Transaction trie root must be valid.", ); } @@ -187,7 +219,7 @@ pub fn execute_transaction(utx: Extrinsic) -> ApplyExtrinsicResult { let extrinsic_index: u32 = storage::unhashed::get(well_known_keys::EXTRINSIC_INDEX).unwrap_or_default(); let result = execute_transaction_backend(&utx, extrinsic_index); - ExtrinsicData::insert(extrinsic_index, utx.encode()); + >::insert(extrinsic_index, utx.encode()); storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &(extrinsic_index + 1)); result } @@ -196,13 +228,14 @@ pub fn execute_transaction(utx: Extrinsic) -> ApplyExtrinsicResult { pub fn finalize_block() -> Header { use sp_core::storage::StateVersion; let extrinsic_index: u32 = storage::unhashed::take(well_known_keys::EXTRINSIC_INDEX).unwrap(); - let txs: Vec<_> = (0..extrinsic_index).map(ExtrinsicData::take).collect(); + let txs: Vec<_> = (0..extrinsic_index).map(>::take).collect(); let extrinsics_root = trie::blake2_256_ordered_root(txs, StateVersion::V0); - let number = ::take().expect("Number is set by `initialize_block`"); - let parent_hash = ::take(); - let mut digest = ::take().expect("StorageDigest is set by `initialize_block`"); + let number = >::take().expect("Number is set by `initialize_block`"); + let parent_hash = >::take(); + let mut digest = + >::take().expect("StorageDigest is set by `initialize_block`"); - let o_new_authorities = ::take(); + let o_new_authorities = >::take(); // This MUST come after all changes to storage are done. Otherwise we will fail the // “Storage root does not match that calculated” assertion. @@ -280,7 +313,7 @@ fn execute_store(data: Vec) -> ApplyExtrinsicResult { } fn execute_new_authorities_backend(new_authorities: &[AuthorityId]) -> ApplyExtrinsicResult { - NewAuthorities::put(new_authorities.to_vec()); + >::put(new_authorities.to_vec()); Ok(Ok(())) } diff --git a/utils/frame/benchmarking-cli/Cargo.toml b/utils/frame/benchmarking-cli/Cargo.toml index 382754a36762a..8eedcb870a3d0 100644 --- a/utils/frame/benchmarking-cli/Cargo.toml +++ b/utils/frame/benchmarking-cli/Cargo.toml @@ -13,13 +13,13 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] +array-bytes = "4.1" chrono = "0.4" clap = { version = "3.1.18", features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.0.0" } comfy-table = { version = "6.0.0", default-features = false } handlebars = "4.2.2" hash-db = "0.15.2" -hex = "0.4.3" Inflector = "0.11.4" itertools = "0.10.3" kvdb = "0.12.0" diff --git a/utils/frame/benchmarking-cli/src/block/bench.rs b/utils/frame/benchmarking-cli/src/block/bench.rs index 36215c8a0586d..32282b314b804 100644 --- a/utils/frame/benchmarking-cli/src/block/bench.rs +++ b/utils/frame/benchmarking-cli/src/block/bench.rs @@ -131,7 +131,9 @@ where fn consumed_weight(&self, block: &BlockId) -> Result { // Hard-coded key for System::BlockWeight. It could also be passed in as argument // for the benchmark, but I think this should work as well. - let hash = hex::decode("26aa394eea5630e07c48ae0c9558cef734abf5cb34d6244378cddbf18e849d96")?; + let hash = array_bytes::hex2bytes( + "26aa394eea5630e07c48ae0c9558cef734abf5cb34d6244378cddbf18e849d96", + )?; let key = StorageKey(hash); let mut raw_weight = &self diff --git a/utils/frame/benchmarking-cli/src/lib.rs b/utils/frame/benchmarking-cli/src/lib.rs index 6e4f092084ef5..a44a208b16ae9 100644 --- a/utils/frame/benchmarking-cli/src/lib.rs +++ b/utils/frame/benchmarking-cli/src/lib.rs @@ -30,6 +30,7 @@ pub use extrinsic::{ExtrinsicBuilder, ExtrinsicCmd, ExtrinsicFactory}; pub use machine::{MachineCmd, Requirements, SUBSTRATE_REFERENCE_HARDWARE}; pub use overhead::OverheadCmd; pub use pallet::PalletCmd; +pub use sc_service::BasePath; pub use storage::StorageCmd; use sc_cli::{CliConfiguration, DatabaseParams, ImportParams, PruningParams, Result, SharedParams}; @@ -87,6 +88,19 @@ impl CliConfiguration for BenchmarkCmd { } } + fn base_path(&self) -> Result> { + let inner = unwrap_cmd! { + self, cmd, cmd.base_path() + }; + + // If the base path was not provided, benchmark command shall use temporary path. Otherwise + // we may end up using shared path, which may be inappropriate for benchmarking. + match inner { + Ok(None) => Some(BasePath::new_temp_dir()).transpose().map_err(|e| e.into()), + e => e, + } + } + fn pruning_params(&self) -> Option<&PruningParams> { unwrap_cmd! { self, cmd, cmd.pruning_params() diff --git a/utils/frame/benchmarking-cli/src/overhead/weights.hbs b/utils/frame/benchmarking-cli/src/overhead/weights.hbs index 86b2c0b0e0cdb..8d1a369372721 100644 --- a/utils/frame/benchmarking-cli/src/overhead/weights.hbs +++ b/utils/frame/benchmarking-cli/src/overhead/weights.hbs @@ -39,7 +39,6 @@ parameter_types! { #[cfg(test)] mod test_weights { - use super::*; use sp_weights::constants; /// Checks that the weight exists and is sane. @@ -51,14 +50,26 @@ mod test_weights { {{#if (eq short_name "block")}} // At least 100 µs. - assert!(w.ref_time() >= 100u64 * constants::WEIGHT_PER_MICROS.ref_time(), "Weight should be at least 100 µs."); + assert!( + w.ref_time() >= 100u64 * constants::WEIGHT_PER_MICROS.ref_time(), + "Weight should be at least 100 µs." + ); // At most 50 ms. - assert!(w.ref_time() <= 50u64 * constants::WEIGHT_PER_MILLIS.ref_time(), "Weight should be at most 50 ms."); + assert!( + w.ref_time() <= 50u64 * constants::WEIGHT_PER_MILLIS.ref_time(), + "Weight should be at most 50 ms." + ); {{else}} // At least 10 µs. - assert!(w.ref_time() >= 10u64 * constants::WEIGHT_PER_MICROS.ref_time(), "Weight should be at least 10 µs."); + assert!( + w.ref_time() >= 10u64 * constants::WEIGHT_PER_MICROS.ref_time(), + "Weight should be at least 10 µs." + ); // At most 1 ms. - assert!(w.ref_time() <= constants::WEIGHT_PER_MILLIS.ref_time(), "Weight should be at most 1 ms."); + assert!( + w.ref_time() <= constants::WEIGHT_PER_MILLIS.ref_time(), + "Weight should be at most 1 ms." + ); {{/if}} } } diff --git a/utils/frame/benchmarking-cli/src/pallet/command.rs b/utils/frame/benchmarking-cli/src/pallet/command.rs index 0fc7cc4d783f7..6870ec386d23d 100644 --- a/utils/frame/benchmarking-cli/src/pallet/command.rs +++ b/utils/frame/benchmarking-cli/src/pallet/command.rs @@ -228,7 +228,7 @@ impl PalletCmd { let mut component_ranges = HashMap::<(Vec, Vec), Vec>::new(); for (pallet, extrinsic, components) in benchmarks_to_run { - log::info!( + println!( "Starting benchmark: {}::{}", String::from_utf8(pallet.clone()).expect("Encoded from String; qed"), String::from_utf8(extrinsic.clone()).expect("Encoded from String; qed"), @@ -376,7 +376,7 @@ impl PalletCmd { if let Ok(elapsed) = timer.elapsed() { if elapsed >= time::Duration::from_secs(5) { timer = time::SystemTime::now(); - log::info!( + println!( "Running Benchmark: {}.{}({} args) {}/{} {}/{}", String::from_utf8(pallet.clone()) .expect("Encoded from String; qed"), @@ -398,16 +398,17 @@ impl PalletCmd { // are together. let batches: Vec = combine_batches(batches, batches_db); - // Create the weights.rs file. - if let Some(output_path) = &self.output { - writer::write_results(&batches, &storage_info, &component_ranges, output_path, self)?; - } - // Jsonify the result and write it to a file or stdout if desired. if !self.jsonify(&batches)? { // Print the summary only if `jsonify` did not write to stdout. self.print_summary(&batches, &storage_info) } + + // Create the weights.rs file. + if let Some(output_path) = &self.output { + writer::write_results(&batches, &storage_info, &component_ranges, output_path, self)?; + } + Ok(()) } diff --git a/utils/frame/benchmarking-cli/src/pallet/mod.rs b/utils/frame/benchmarking-cli/src/pallet/mod.rs index 7beaf321a2927..b8c1f7b905c0c 100644 --- a/utils/frame/benchmarking-cli/src/pallet/mod.rs +++ b/utils/frame/benchmarking-cli/src/pallet/mod.rs @@ -43,7 +43,7 @@ pub struct PalletCmd { pub extrinsic: Option, /// Select how many samples we should take across the variable components. - #[clap(short, long, default_value = "1")] + #[clap(short, long, default_value = "2")] pub steps: u32, /// Indicates lowest values for each of the component ranges. diff --git a/utils/frame/benchmarking-cli/src/pallet/template.hbs b/utils/frame/benchmarking-cli/src/pallet/template.hbs index 6e016c47ef010..fbe435edf8fc3 100644 --- a/utils/frame/benchmarking-cli/src/pallet/template.hbs +++ b/utils/frame/benchmarking-cli/src/pallet/template.hbs @@ -15,7 +15,7 @@ #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::{Weight}}; +use frame_support::{traits::Get, weights::Weight}; use sp_std::marker::PhantomData; /// Weight functions for `{{pallet}}`. diff --git a/utils/frame/benchmarking-cli/src/pallet/writer.rs b/utils/frame/benchmarking-cli/src/pallet/writer.rs index a601c09eb5033..cd52ffc329d1c 100644 --- a/utils/frame/benchmarking-cli/src/pallet/writer.rs +++ b/utils/frame/benchmarking-cli/src/pallet/writer.rs @@ -24,6 +24,7 @@ use std::{ }; use inflector::Inflector; +use itertools::Itertools; use serde::Serialize; use crate::{pallet::command::ComponentRange, shared::UnderscoreHelper, PalletCmd}; @@ -314,18 +315,21 @@ pub(crate) fn write_results( // Organize results by pallet into a JSON map let all_results = map_results(batches, storage_info, component_ranges, &analysis_choice)?; + let mut created_files = Vec::new(); + for ((pallet, instance), results) in all_results.iter() { let mut file_path = path.clone(); // If a user only specified a directory... if file_path.is_dir() { + // Start with "path/to/pallet_name". + let mut file_name = pallet.clone(); // Check if there might be multiple instances benchmarked. if all_results.keys().any(|(p, i)| p == pallet && i != instance) { - // Create new file: "path/to/pallet_name_instance_name.rs". - file_path.push(pallet.clone() + "_" + instance.to_snake_case().as_str()); - } else { - // Create new file: "path/to/pallet_name.rs". - file_path.push(pallet.clone()); + // Append "_instance_name". + file_name = format!("{}_{}", file_name, instance.to_snake_case()); } + // "mod::pallet_name.rs" becomes "mod_pallet_name.rs". + file_path.push(file_name.replace("::", "_")); file_path.set_extension("rs"); } @@ -342,10 +346,18 @@ pub(crate) fn write_results( benchmarks: results.clone(), }; - let mut output_file = fs::File::create(file_path)?; + let mut output_file = fs::File::create(&file_path)?; handlebars .render_template_to_write(&template, &hbs_data, &mut output_file) .map_err(|e| io_error(&e.to_string()))?; + println!("Created file: {:?}", &file_path); + created_files.push(file_path); + } + + for file in created_files.iter().duplicates() { + // This can happen when there are multiple instances of a pallet deployed + // and `--output` forces the output of all instances into the same file. + println!("Multiple benchmarks were written to the same file: {:?}.", file); } Ok(()) } diff --git a/utils/frame/rpc/support/Cargo.toml b/utils/frame/rpc/support/Cargo.toml index 2104774bd2605..38e40a33d9c7f 100644 --- a/utils/frame/rpc/support/Cargo.toml +++ b/utils/frame/rpc/support/Cargo.toml @@ -27,4 +27,6 @@ sp-storage = { version = "6.0.0", path = "../../../../primitives/storage" } scale-info = "2.1.1" jsonrpsee = { version = "0.15.1", features = ["ws-client", "jsonrpsee-types"] } tokio = "1.17.0" +sp-core = { version = "6.0.0", path = "../../../../primitives/core" } +sp-runtime = { version = "6.0.0", path = "../../../../primitives/runtime" } frame-system = { version = "4.0.0-dev", path = "../../../../frame/system" } diff --git a/utils/frame/rpc/support/src/lib.rs b/utils/frame/rpc/support/src/lib.rs index 2ee007c84f0aa..fdf6fe0be8172 100644 --- a/utils/frame/rpc/support/src/lib.rs +++ b/utils/frame/rpc/support/src/lib.rs @@ -34,50 +34,104 @@ use sp_storage::{StorageData, StorageKey}; /// # use jsonrpsee::core::Error as RpcError; /// # use jsonrpsee::ws_client::WsClientBuilder; /// # use codec::Encode; -/// # use frame_support::{decl_storage, decl_module}; +/// # use frame_support::{construct_runtime, traits::ConstU32}; /// # use substrate_frame_rpc_support::StorageQuery; -/// # use frame_system::Config; /// # use sc_rpc_api::state::StateApiClient; +/// # use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::Header}; /// # -/// # // Hash would normally be ::Hash, but we don't have -/// # // frame_system::Config implemented for TestRuntime. Here we just pretend. -/// # type Hash = (); +/// # construct_runtime!( +/// # pub enum TestRuntime where +/// # Block = frame_system::mocking::MockBlock, +/// # NodeBlock = frame_system::mocking::MockBlock, +/// # UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic, +/// # { +/// # System: frame_system::{Pallet, Call, Config, Storage, Event}, +/// # Test: pallet_test::{Pallet, Storage}, +/// # } +/// # ); /// # +/// # type Hash = sp_core::H256; /// # -/// # struct TestRuntime; -/// # -/// # decl_module! { -/// # pub struct Module for enum Call where origin: T::Origin {} +/// # impl frame_system::Config for TestRuntime { +/// # type BaseCallFilter = (); +/// # type BlockWeights = (); +/// # type BlockLength = (); +/// # 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 RuntimeEvent = RuntimeEvent; +/// # type BlockHashCount = (); +/// # type DbWeight = (); +/// # type Version = (); +/// # type PalletInfo = PalletInfo; +/// # type AccountData = (); +/// # type OnNewAccount = (); +/// # type OnKilledAccount = (); +/// # type SystemWeightInfo = (); +/// # type SS58Prefix = (); +/// # type OnSetCode = (); +/// # type MaxConsumers = ConstU32<16>; /// # } /// # +/// # impl pallet_test::Config for TestRuntime {} +/// # +/// /// pub type Loc = (i64, i64, i64); /// pub type Block = u8; /// /// // Note that all fields are marked pub. -/// decl_storage! { -/// trait Store for Module as TestRuntime { -/// pub LastActionId: u64; -/// pub Voxels: map hasher(blake2_128_concat) Loc => Block; -/// pub Actions: map hasher(blake2_128_concat) u64 => Loc; -/// pub Prefab: double_map hasher(blake2_128_concat) u128, hasher(blake2_128_concat) (i8, i8, i8) => Block; -/// } +/// pub use self::pallet_test::*; +/// +/// #[frame_support::pallet] +/// mod pallet_test { +/// use super::*; +/// use frame_support::pallet_prelude::*; +/// +/// #[pallet::pallet] +/// #[pallet::generate_store(pub(super) trait Store)] +/// pub struct Pallet(PhantomData); +/// +/// #[pallet::config] +/// pub trait Config: frame_system::Config {} +/// +/// #[pallet::storage] +/// pub type LastActionId = StorageValue<_, u64, ValueQuery>; +/// +/// #[pallet::storage] +/// pub type Voxels = StorageMap<_, Blake2_128Concat, Loc, Block>; +/// +/// #[pallet::storage] +/// pub type Actions = StorageMap<_, Blake2_128Concat, u64, Loc>; +/// +/// #[pallet::storage] +/// pub type Prefab = StorageDoubleMap< +/// _, +/// Blake2_128Concat, u128, +/// Blake2_128Concat, (i8, i8, i8), Block +/// >; /// } /// /// #[tokio::main] /// async fn main() -> Result<(), RpcError> { /// let cl = WsClientBuilder::default().build("ws://[::1]:9944").await?; /// -/// let q = StorageQuery::value::(); +/// let q = StorageQuery::value::>(); /// let hash = None::; /// let _: Option = q.get(&cl, hash).await?; /// -/// let q = StorageQuery::map::((0, 0, 0)); +/// let q = StorageQuery::map::, _>((0, 0, 0)); /// let _: Option = q.get(&cl, hash).await?; /// -/// let q = StorageQuery::map::(12); +/// let q = StorageQuery::map::, _>(12); /// let _: Option = q.get(&cl, hash).await?; /// -/// let q = StorageQuery::double_map::(3, (0, 0, 0)); +/// let q = StorageQuery::double_map::, _, _>(3, (0, 0, 0)); /// let _: Option = q.get(&cl, hash).await?; /// /// Ok(()) diff --git a/utils/frame/try-runtime/cli/src/commands/execute_block.rs b/utils/frame/try-runtime/cli/src/commands/execute_block.rs index 70ba3615f874a..0c8b968d1b4b1 100644 --- a/utils/frame/try-runtime/cli/src/commands/execute_block.rs +++ b/utils/frame/try-runtime/cli/src/commands/execute_block.rs @@ -195,7 +195,7 @@ where block_ws_uri.clone(), expected_spec_name, expected_spec_version, - shared.no_spec_name_check, + shared.no_spec_check_panic, ) .await; diff --git a/utils/frame/try-runtime/cli/src/commands/follow_chain.rs b/utils/frame/try-runtime/cli/src/commands/follow_chain.rs index f493d5c10cd29..88866b538169b 100644 --- a/utils/frame/try-runtime/cli/src/commands/follow_chain.rs +++ b/utils/frame/try-runtime/cli/src/commands/follow_chain.rs @@ -275,7 +275,7 @@ where command.uri.clone(), expected_spec_name, expected_spec_version, - shared.no_spec_name_check, + shared.no_spec_check_panic, ) .await; diff --git a/utils/frame/try-runtime/cli/src/commands/offchain_worker.rs b/utils/frame/try-runtime/cli/src/commands/offchain_worker.rs index a579692abd9e2..b0404fff18135 100644 --- a/utils/frame/try-runtime/cli/src/commands/offchain_worker.rs +++ b/utils/frame/try-runtime/cli/src/commands/offchain_worker.rs @@ -152,7 +152,7 @@ where header_ws_uri, expected_spec_name, expected_spec_version, - shared.no_spec_name_check, + shared.no_spec_check_panic, ) .await; diff --git a/utils/frame/try-runtime/cli/src/commands/on_runtime_upgrade.rs b/utils/frame/try-runtime/cli/src/commands/on_runtime_upgrade.rs index 9bc6d32d4762a..5055e4fb34581 100644 --- a/utils/frame/try-runtime/cli/src/commands/on_runtime_upgrade.rs +++ b/utils/frame/try-runtime/cli/src/commands/on_runtime_upgrade.rs @@ -64,7 +64,7 @@ where uri, expected_spec_name, expected_spec_version, - shared.no_spec_name_check, + shared.no_spec_check_panic, ) .await; } diff --git a/utils/frame/try-runtime/cli/src/lib.rs b/utils/frame/try-runtime/cli/src/lib.rs index c3382045add16..b8a2779d57e19 100644 --- a/utils/frame/try-runtime/cli/src/lib.rs +++ b/utils/frame/try-runtime/cli/src/lib.rs @@ -421,9 +421,9 @@ pub struct SharedParams { #[clap(long)] pub heap_pages: Option, - /// When enabled, the spec name check will not panic, and instead only show a warning. + /// When enabled, the spec check will not panic, and instead only show a warning. #[clap(long)] - pub no_spec_name_check: bool, + pub no_spec_check_panic: bool, /// State version that is used by the chain. #[clap(long, default_value = "1", parse(try_from_str = parse::state_version))]