diff --git a/Cargo.lock b/Cargo.lock index 9f217ed1..37c63293 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -274,7 +274,7 @@ dependencies = [ "num-bigint", "num-traits", "paste", - "rustc_version", + "rustc_version 0.4.0", "zeroize", ] @@ -480,8 +480,8 @@ dependencies = [ "frame-benchmarking", "frame-executive", "frame-metadata-hash-extension", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "frame-system-benchmarking", "frame-system-rpc-runtime-api", "frame-try-runtime", @@ -520,20 +520,20 @@ dependencies = [ "scale-info", "serde_json", "snowbridge-router-primitives", - "sp-api", + "sp-api 33.0.0", "sp-block-builder", "sp-consensus-aura", "sp-core", - "sp-genesis-builder", - "sp-inherents", - "sp-io", + "sp-genesis-builder 0.14.0", + "sp-inherents 33.0.0", + "sp-io 37.0.0", "sp-offchain", - "sp-runtime", + "sp-runtime 38.0.0", "sp-session", "sp-std", "sp-storage", "sp-transaction-pool", - "sp-version", + "sp-version 36.0.0", "sp-weights", "staging-parachain-info", "staging-xcm", @@ -553,8 +553,8 @@ dependencies = [ "cumulus-pallet-parachain-system", "cumulus-pallet-xcmp-queue", "cumulus-primitives-core", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "pallet-assets", "pallet-balances", "pallet-collator-selection", @@ -565,8 +565,8 @@ dependencies = [ "parachains-common", "parachains-runtimes-test-utils", "parity-scale-codec", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "staging-parachain-info", "staging-xcm", @@ -582,7 +582,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4e2360c96927aa33b3fef7190eabf2aa4129fe3505c11dfa860ada0f27fd1b1" dependencies = [ "cumulus-primitives-core", - "frame-support", + "frame-support 36.0.0", "impl-trait-for-tuples", "log", "pallet-asset-conversion", @@ -590,8 +590,8 @@ dependencies = [ "parachains-common", "parity-scale-codec", "scale-info", - "sp-api", - "sp-runtime", + "sp-api 33.0.0", + "sp-runtime 38.0.0", "sp-std", "staging-xcm", "staging-xcm-builder", @@ -1064,18 +1064,6 @@ dependencies = [ "piper", ] -[[package]] -name = "bounded-collections" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca548b6163b872067dc5eb82fd130c56881435e30367d2073594a3d9744120dd" -dependencies = [ - "log", - "parity-scale-codec", - "scale-info", - "serde", -] - [[package]] name = "bounded-collections" version = "0.2.0" @@ -1103,7 +1091,7 @@ version = "1.0.0" source = "git+https://github.com/polkadot-fellows/runtimes#f42acab60edf4d6ded4d9e99b1a8fbacded85669" dependencies = [ "bp-xcm-bridge-hub-router", - "frame-support", + "frame-support 36.0.0", "parity-scale-codec", "scale-info", "sp-std", @@ -1117,7 +1105,7 @@ version = "1.0.0" source = "git+https://github.com/polkadot-fellows/runtimes#f42acab60edf4d6ded4d9e99b1a8fbacded85669" dependencies = [ "bp-xcm-bridge-hub-router", - "frame-support", + "frame-support 36.0.0", "parity-scale-codec", "scale-info", "sp-std", @@ -1134,10 +1122,10 @@ dependencies = [ "bp-messages", "bp-polkadot-core", "bp-runtime", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "polkadot-primitives", - "sp-api", + "sp-api 33.0.0", "sp-std", ] @@ -1149,11 +1137,11 @@ dependencies = [ "bp-bridge-hub-cumulus", "bp-messages", "bp-runtime", - "frame-support", + "frame-support 36.0.0", "kusama-runtime-constants", "polkadot-runtime-constants", - "sp-api", - "sp-runtime", + "sp-api 33.0.0", + "sp-runtime 38.0.0", "sp-std", "system-parachains-constants", ] @@ -1167,12 +1155,12 @@ dependencies = [ "bp-messages", "bp-polkadot-bulletin", "bp-runtime", - "frame-support", + "frame-support 36.0.0", "kusama-runtime-constants", "polkadot-runtime-constants", "snowbridge-core", - "sp-api", - "sp-runtime", + "sp-api 33.0.0", + "sp-runtime 38.0.0", "sp-std", "staging-xcm", "system-parachains-constants", @@ -1186,13 +1174,13 @@ checksum = "57cac4b71008e46d43e346476ed1be85cf7b505efacee17dad84d687344bf1b1" dependencies = [ "bp-runtime", "finality-grandpa", - "frame-support", + "frame-support 36.0.0", "parity-scale-codec", "scale-info", "serde", "sp-consensus-grandpa", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -1204,7 +1192,7 @@ checksum = "f97eec00a98efeb052ac9fc9676d9fccf5acd19e3b18530f3d72af1a1faf21ec" dependencies = [ "bp-header-chain", "bp-runtime", - "frame-support", + "frame-support 36.0.0", "parity-scale-codec", "scale-info", "serde", @@ -1221,12 +1209,12 @@ dependencies = [ "bp-header-chain", "bp-polkadot-core", "bp-runtime", - "frame-support", + "frame-support 36.0.0", "impl-trait-for-tuples", "parity-scale-codec", "scale-info", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -1240,12 +1228,12 @@ dependencies = [ "bp-messages", "bp-polkadot-core", "bp-runtime", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", - "sp-api", - "sp-runtime", + "sp-api 33.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -1257,14 +1245,14 @@ checksum = "6ef2272823ecfee580c00f6542dfcab3ec7abdb00857af853429736847c3a2d9" dependencies = [ "bp-messages", "bp-runtime", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "parity-util-mem", "scale-info", "serde", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -1276,10 +1264,10 @@ checksum = "5a589f5bb70baa4377a798823be752042aa6c220d51afc559716667e29b0203d" dependencies = [ "bp-messages", "bp-runtime", - "frame-support", + "frame-support 36.0.0", "parity-scale-codec", "scale-info", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -1289,8 +1277,8 @@ version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "904644c23b437dde65741f3148067624ed0b4d8360f68adf9e92273aeb970814" dependencies = [ - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "hash-db", "impl-trait-for-tuples", "log", @@ -1299,11 +1287,11 @@ dependencies = [ "scale-info", "serde", "sp-core", - "sp-io", - "sp-runtime", - "sp-state-machine", + "sp-io 37.0.0", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", "sp-std", - "sp-trie", + "sp-trie 36.0.0", "trie-db", ] @@ -1320,12 +1308,12 @@ dependencies = [ "ed25519-dalek", "finality-grandpa", "parity-scale-codec", - "sp-application-crypto", + "sp-application-crypto 37.0.0", "sp-consensus-grandpa", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", - "sp-trie", + "sp-trie 36.0.0", ] [[package]] @@ -1346,7 +1334,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", ] [[package]] @@ -1363,8 +1351,8 @@ dependencies = [ "bp-runtime", "bp-xcm-bridge-hub", "bp-xcm-bridge-hub-router", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "hash-db", "log", "pallet-bridge-grandpa", @@ -1375,12 +1363,12 @@ dependencies = [ "pallet-utility", "parity-scale-codec", "scale-info", - "sp-api", + "sp-api 33.0.0", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", - "sp-trie", + "sp-trie 36.0.0", "staging-xcm", "staging-xcm-builder", "tuplex", @@ -2125,7 +2113,7 @@ dependencies = [ "sc-service", "sp-blockchain", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "url", ] @@ -2146,10 +2134,10 @@ dependencies = [ "polkadot-overseer", "polkadot-primitives", "sc-client-api", - "sp-api", + "sp-api 33.0.0", "sp-consensus", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "tracing", ] @@ -2181,17 +2169,17 @@ dependencies = [ "sc-consensus-slots", "sc-telemetry", "schnellru", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-block-builder", "sp-blockchain", "sp-consensus", "sp-consensus-aura", "sp-core", - "sp-inherents", + "sp-inherents 33.0.0", "sp-keystore", - "sp-runtime", - "sp-state-machine", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", "sp-timestamp", "substrate-prometheus-endpoint", "tracing", @@ -2220,10 +2208,10 @@ dependencies = [ "sp-consensus", "sp-consensus-slots", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-timestamp", - "sp-trie", - "sp-version", + "sp-trie 36.0.0", + "sp-version 36.0.0", "substrate-prometheus-endpoint", "tracing", ] @@ -2238,9 +2226,9 @@ dependencies = [ "async-trait", "cumulus-primitives-parachain-inherent", "sp-consensus", - "sp-inherents", - "sp-runtime", - "sp-state-machine", + "sp-inherents 33.0.0", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", "thiserror", ] @@ -2261,13 +2249,13 @@ dependencies = [ "polkadot-parachain-primitives", "polkadot-primitives", "sc-client-api", - "sp-api", + "sp-api 33.0.0", "sp-blockchain", "sp-consensus", "sp-core", - "sp-runtime", - "sp-state-machine", - "sp-version", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", + "sp-version 36.0.0", "tracing", ] @@ -2285,14 +2273,14 @@ dependencies = [ "parity-scale-codec", "sc-client-api", "scale-info", - "sp-api", + "sp-api 33.0.0", "sp-crypto-hashing", - "sp-inherents", - "sp-runtime", - "sp-state-machine", + "sp-inherents 33.0.0", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", "sp-std", "sp-storage", - "sp-trie", + "sp-trie 36.0.0", "tracing", ] @@ -2315,11 +2303,11 @@ dependencies = [ "rand", "sc-client-api", "sc-consensus", - "sp-api", + "sp-api 33.0.0", "sp-consensus", "sp-maybe-compressed-blob", - "sp-runtime", - "sp-version", + "sp-runtime 38.0.0", + "sp-version 36.0.0", "tracing", ] @@ -2352,12 +2340,12 @@ dependencies = [ "sc-telemetry", "sc-transaction-pool", "sc-utils", - "sp-api", + "sp-api 33.0.0", "sp-blockchain", "sp-consensus", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-transaction-pool", ] @@ -2368,15 +2356,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c5e8af48090936c45483d489ee681acb54277763586b53fa3dbd17173aa474fc" dependencies = [ "cumulus-pallet-parachain-system", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "pallet-aura", "pallet-timestamp", "parity-scale-codec", "scale-info", - "sp-application-crypto", + "sp-application-crypto 37.0.0", "sp-consensus-aura", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -2393,8 +2381,8 @@ dependencies = [ "cumulus-primitives-proof-size-hostfunction", "environmental", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "impl-trait-for-tuples", "log", "pallet-message-queue", @@ -2405,13 +2393,13 @@ dependencies = [ "scale-info", "sp-core", "sp-externalities", - "sp-inherents", - "sp-io", - "sp-runtime", - "sp-state-machine", + "sp-inherents 33.0.0", + "sp-io 37.0.0", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", "sp-std", - "sp-trie", - "sp-version", + "sp-trie 36.0.0", + "sp-version 36.0.0", "staging-xcm", "staging-xcm-builder", "trie-db", @@ -2436,11 +2424,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "506daacefa861aa2909b64f26e76495ce029227fd8355b97e074cc1d5dc54ab2" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "pallet-session", "parity-scale-codec", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -2451,12 +2439,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d5224285f60e5159bab549f458079d606a7f95ef779def8b89f1a244dc7cf81" dependencies = [ "cumulus-primitives-core", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "staging-xcm", ] @@ -2467,12 +2455,12 @@ version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0adf5409618b21e754fef0ac70f257878d22d61c48fdeefcab666835dcb8e0f0" dependencies = [ - "bounded-collections 0.2.0", + "bounded-collections", "bp-xcm-bridge-hub-router", "cumulus-primitives-core", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-message-queue", "parity-scale-codec", @@ -2480,8 +2468,8 @@ dependencies = [ "polkadot-runtime-parachains", "scale-info", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "staging-xcm", "staging-xcm-builder", @@ -2497,9 +2485,9 @@ dependencies = [ "parity-scale-codec", "polkadot-core-primitives", "polkadot-primitives", - "sp-api", + "sp-api 33.0.0", "sp-consensus-aura", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -2514,10 +2502,10 @@ dependencies = [ "polkadot-parachain-primitives", "polkadot-primitives", "scale-info", - "sp-api", - "sp-runtime", + "sp-api 33.0.0", + "sp-runtime 38.0.0", "sp-std", - "sp-trie", + "sp-trie 36.0.0", "staging-xcm", ] @@ -2532,11 +2520,11 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-inherents", - "sp-runtime", - "sp-state-machine", + "sp-inherents 33.0.0", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", "sp-std", - "sp-trie", + "sp-trie 36.0.0", ] [[package]] @@ -2547,7 +2535,7 @@ checksum = "9f973d2a7262c90e48dcd42062bcb1e0fbf48bbcdac4ea6df3d85212d8d8be5d" dependencies = [ "sp-externalities", "sp-runtime-interface", - "sp-trie", + "sp-trie 36.0.0", ] [[package]] @@ -2559,12 +2547,12 @@ dependencies = [ "cumulus-primitives-core", "cumulus-primitives-proof-size-hostfunction", "docify", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -2575,14 +2563,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05742c520065e3870d419683113ed7f6d35de66f0c80af6828e7878d1bb0ea94" dependencies = [ "cumulus-primitives-core", - "frame-support", + "frame-support 36.0.0", "log", "pallet-asset-conversion", "parity-scale-codec", "polkadot-runtime-common", "polkadot-runtime-parachains", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "staging-xcm", "staging-xcm-builder", @@ -2607,11 +2595,11 @@ dependencies = [ "sc-sysinfo", "sc-telemetry", "sc-tracing", - "sp-api", + "sp-api 33.0.0", "sp-consensus", "sp-core", - "sp-runtime", - "sp-state-machine", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", ] [[package]] @@ -2627,10 +2615,10 @@ dependencies = [ "parity-scale-codec", "polkadot-overseer", "sc-client-api", - "sp-api", + "sp-api 33.0.0", "sp-blockchain", - "sp-state-machine", - "sp-version", + "sp-state-machine 0.42.0", + "sp-version 36.0.0", "thiserror", ] @@ -2667,11 +2655,11 @@ dependencies = [ "sc-service", "sc-tracing", "sc-utils", - "sp-api", + "sp-api 33.0.0", "sp-blockchain", "sp-consensus", "sp-consensus-babe", - "sp-runtime", + "sp-runtime 38.0.0", "substrate-prometheus-endpoint", "tokio", "tracing", @@ -2702,14 +2690,14 @@ dependencies = [ "serde_json", "smoldot", "smoldot-light", - "sp-api", + "sp-api 33.0.0", "sp-authority-discovery", "sp-consensus-babe", "sp-core", - "sp-runtime", - "sp-state-machine", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", "sp-storage", - "sp-version", + "sp-version 36.0.0", "thiserror", "tokio", "tokio-util", @@ -2726,10 +2714,10 @@ dependencies = [ "cumulus-primitives-core", "parity-scale-codec", "polkadot-primitives", - "sp-runtime", - "sp-state-machine", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", "sp-std", - "sp-trie", + "sp-trie 36.0.0", ] [[package]] @@ -2744,7 +2732,7 @@ dependencies = [ "digest 0.10.7", "fiat-crypto", "platforms", - "rustc_version", + "rustc_version 0.4.0", "subtle 2.5.0", "zeroize", ] @@ -2914,17 +2902,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "derive-syn-parse" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e79116f119dd1dba1abf1f3405f03b9b0e79a27a3883864bfebded8a3dc768cd" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "derive-syn-parse" version = "0.2.0" @@ -2945,10 +2922,16 @@ dependencies = [ "convert_case", "proc-macro2", "quote", - "rustc_version", + "rustc_version 0.4.0", "syn 2.0.66", ] +[[package]] +name = "diff" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" + [[package]] name = "difflib" version = "0.4.0" @@ -3054,7 +3037,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a081e51fb188742f5a7a1164ad752121abcb22874b21e2c3b0dd040c515fdad" dependencies = [ "common-path", - "derive-syn-parse 0.2.0", + "derive-syn-parse", "once_cell", "proc-macro2", "quote", @@ -3203,7 +3186,7 @@ dependencies = [ "cumulus-pallet-parachain-system", "cumulus-pallet-xcmp-queue", "cumulus-primitives-core", - "frame-support", + "frame-support 36.0.0", "pallet-assets", "pallet-balances", "pallet-bridge-messages", @@ -3220,7 +3203,7 @@ dependencies = [ "sp-consensus-babe", "sp-consensus-beefy", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "staging-xcm", "xcm-emulator", ] @@ -3660,20 +3643,20 @@ version = "36.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "709b26657ebbba53dc7bb616577375ca462b20fef1b00e8d9b20d2435e87f7bc" dependencies = [ - "frame-support", + "frame-support 36.0.0", "frame-support-procedural", - "frame-system", + "frame-system 36.1.0", "linregress", "log", "parity-scale-codec", "paste", "scale-info", "serde", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-runtime-interface", "sp-std", "sp-storage", @@ -3692,8 +3675,8 @@ dependencies = [ "clap", "comfy-table", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "gethostname", "handlebars", "itertools 0.11.0", @@ -3713,19 +3696,19 @@ dependencies = [ "sc-sysinfo", "serde", "serde_json", - "sp-api", + "sp-api 33.0.0", "sp-blockchain", "sp-core", "sp-database", "sp-externalities", - "sp-genesis-builder", - "sp-inherents", - "sp-io", + "sp-genesis-builder 0.14.0", + "sp-inherents 33.0.0", + "sp-io 37.0.0", "sp-keystore", - "sp-runtime", - "sp-state-machine", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", "sp-storage", - "sp-trie", + "sp-trie 36.0.0", "sp-wasm-interface", "thiserror", "thousands", @@ -3750,14 +3733,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1ec289ebad5e601bb165cf7eb6ec2179ae34280ee310d0710a3111d4f8f8f94" dependencies = [ "frame-election-provider-solution-type", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", "sp-arithmetic", "sp-core", "sp-npos-elections", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -3768,15 +3751,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d878830330eaa9e8b886279c338556b05702d0059989cb51cfb226b70bf3fa4" dependencies = [ "aquamarine", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "frame-try-runtime", "log", "parity-scale-codec", "scale-info", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "sp-tracing", ] @@ -3801,12 +3784,12 @@ checksum = "cf37fc730bf4b51e82a34c6357eebe32c04dbacf6525e0a7b9726f6a17ec9427" dependencies = [ "array-bytes", "docify", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", - "sp-runtime", + "sp-runtime 38.0.0", ] [[package]] @@ -3832,18 +3815,60 @@ dependencies = [ "serde", "serde_json", "smallvec", - "sp-api", + "sp-api 33.0.0", "sp-arithmetic", "sp-core", "sp-crypto-hashing-proc-macro", "sp-debug-derive", - "sp-genesis-builder", - "sp-inherents", - "sp-io", + "sp-genesis-builder 0.14.0", + "sp-inherents 33.0.0", + "sp-io 37.0.0", "sp-metadata-ir", - "sp-runtime", - "sp-staking", - "sp-state-machine", + "sp-runtime 38.0.0", + "sp-staking 33.0.0", + "sp-state-machine 0.42.0", + "sp-std", + "sp-tracing", + "sp-weights", + "static_assertions", + "tt-call", +] + +[[package]] +name = "frame-support" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87cae973c331b7f52ba18435713f9ed02bac20bd4fdedaaad57445d82f05eb9d" +dependencies = [ + "aquamarine", + "array-bytes", + "bitflags 1.3.2", + "docify", + "environmental", + "frame-metadata", + "frame-support-procedural", + "impl-trait-for-tuples", + "k256", + "log", + "macro_magic", + "parity-scale-codec", + "paste", + "scale-info", + "serde", + "serde_json", + "smallvec", + "sp-api 34.0.0", + "sp-arithmetic", + "sp-core", + "sp-crypto-hashing-proc-macro", + "sp-debug-derive", + "sp-genesis-builder 0.15.0", + "sp-inherents 34.0.0", + "sp-io 38.0.0", + "sp-metadata-ir", + "sp-runtime 39.0.0", + "sp-staking 34.0.0", + "sp-state-machine 0.43.0", "sp-std", "sp-tracing", "sp-weights", @@ -3859,7 +3884,7 @@ checksum = "fd94af68373e179c32c360b3c280497a9cf0f45a4f47f0ee6539a6c6c9cf2343" dependencies = [ "Inflector", "cfg-expr", - "derive-syn-parse 0.2.0", + "derive-syn-parse", "expander", "frame-support-procedural-tools", "itertools 0.11.0", @@ -3903,16 +3928,37 @@ checksum = "64d6a0e7bb6503facdcc6f8e19c83cd0bfc8bbbd268522b1a50e107dfc6b972d" dependencies = [ "cfg-if", "docify", - "frame-support", + "frame-support 36.0.0", "log", "parity-scale-codec", "scale-info", "serde", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", - "sp-version", + "sp-version 36.0.0", + "sp-weights", +] + +[[package]] +name = "frame-system" +version = "37.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "043790fff021477061b207fd6b33743793b63fc64a583358956787229d039717" +dependencies = [ + "cfg-if", + "docify", + "frame-support 37.0.0", + "log", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core", + "sp-io 38.0.0", + "sp-runtime 39.0.0", + "sp-std", + "sp-version 37.0.0", "sp-weights", ] @@ -3923,12 +3969,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15afc91c7780e18274dcea58ed1edb700c48d10e086a9785e3f6708099cd3250" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -3939,7 +3985,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c9e9e2b7b85e451e367f4fb85ff3295bd039e17f64de1906154d3976e2638ee8" dependencies = [ "parity-scale-codec", - "sp-api", + "sp-api 33.0.0", ] [[package]] @@ -3948,10 +3994,10 @@ version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae6ba8b36a52775ad39ccfb45ff4ad814c3cb45ec74d0a4271889e00bd791c6c" dependencies = [ - "frame-support", + "frame-support 36.0.0", "parity-scale-codec", - "sp-api", - "sp-runtime", + "sp-api 33.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -4983,7 +5029,7 @@ dependencies = [ "asset-test-utils", "cumulus-primitives-core", "emulated-integration-tests-common", - "frame-support", + "frame-support 36.0.0", "pallet-assets", "pallet-balances", "pallet-message-queue", @@ -5001,7 +5047,7 @@ dependencies = [ "sp-consensus-beefy", "sp-consensus-grandpa", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "staging-xcm", "staging-xcm-executor", "tracing-subscriber 0.3.18", @@ -5297,12 +5343,12 @@ name = "kusama-runtime-constants" version = "1.0.0" source = "git+https://github.com/polkadot-fellows/runtimes#f42acab60edf4d6ded4d9e99b1a8fbacded85669" dependencies = [ - "frame-support", + "frame-support 36.0.0", "polkadot-primitives", "polkadot-runtime-common", "smallvec", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-weights", "staging-xcm-builder", ] @@ -5363,6 +5409,12 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" +[[package]] +name = "leb128" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67" + [[package]] name = "libc" version = "0.2.155" @@ -6107,9 +6159,9 @@ dependencies = [ [[package]] name = "macro_magic" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e03844fc635e92f3a0067e25fa4bf3e3dbf3f2927bf3aa01bb7bc8f1c428949d" +checksum = "cc33f9f0351468d26fbc53d9ce00a096c8522ecb42f19b50f34f2c422f76d21d" dependencies = [ "macro_magic_core", "macro_magic_macros", @@ -6119,12 +6171,12 @@ dependencies = [ [[package]] name = "macro_magic_core" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "468155613a44cfd825f1fb0ffa532b018253920d404e6fca1e8d43155198a46d" +checksum = "1687dc887e42f352865a393acae7cf79d98fab6351cde1f58e9e057da89bf150" dependencies = [ "const-random", - "derive-syn-parse 0.1.5", + "derive-syn-parse", "macro_magic_core_macros", "proc-macro2", "quote", @@ -6133,9 +6185,9 @@ dependencies = [ [[package]] name = "macro_magic_core_macros" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ea73aa640dc01d62a590d48c0c3521ed739d53b27f919b25c3551e233481654" +checksum = "b02abfe41815b5bd98dbd4260173db2c116dda171dc0fe7838cb206333b83308" dependencies = [ "proc-macro2", "quote", @@ -6144,9 +6196,9 @@ dependencies = [ [[package]] name = "macro_magic_macros" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef9d79ae96aaba821963320eb2b6e34d17df1e5a83d8a1985c29cc5be59577b3" +checksum = "73ea28ee64b88876bf45277ed9a5817c1817df061a74f2b988971a12570e5869" dependencies = [ "macro_magic_core", "quote", @@ -6343,13 +6395,13 @@ dependencies = [ "parity-scale-codec", "sc-client-api", "sc-offchain", - "sp-api", + "sp-api 33.0.0", "sp-blockchain", "sp-consensus", "sp-consensus-beefy", "sp-core", "sp-mmr-primitives", - "sp-runtime", + "sp-runtime 38.0.0", ] [[package]] @@ -6361,11 +6413,11 @@ dependencies = [ "jsonrpsee", "parity-scale-codec", "serde", - "sp-api", + "sp-api 33.0.0", "sp-blockchain", "sp-core", "sp-mmr-primitives", - "sp-runtime", + "sp-runtime 38.0.0", ] [[package]] @@ -7026,6 +7078,25 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" +[[package]] +name = "pallet-api" +version = "0.1.0" +dependencies = [ + "frame-benchmarking", + "frame-support 36.0.0", + "frame-system 36.1.0", + "log", + "pallet-assets", + "pallet-balances", + "parity-scale-codec", + "pop-chain-extension", + "scale-info", + "sp-core", + "sp-io 37.0.0", + "sp-runtime 38.0.0", + "sp-std", +] + [[package]] name = "pallet-asset-conversion" version = "18.0.0" @@ -7033,16 +7104,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f726ebb59401c1844a4a8703047bdafcd99a1827cd5d8b2c82abeb8948a7f25b" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", - "sp-api", + "sp-api 33.0.0", "sp-arithmetic", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -7052,13 +7123,13 @@ version = "18.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e0fde03a96382f4dbe37ef95cb4ef7aade7c0be410cb6c888eda911c94af3eaf" dependencies = [ - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "pallet-asset-conversion", "pallet-transaction-payment", "parity-scale-codec", "scale-info", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -7069,12 +7140,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e806842bec955190ec64f8b2179f74f5355137c4cadf04f3269e6196cd19caf9" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -7085,15 +7156,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "100a180dfbf30a1c872100ec2dae8a61c0f5e8b3f2d3a5cbb34093826293e2ab" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "pallet-transaction-payment", "parity-scale-codec", "scale-info", "serde", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -7104,14 +7175,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f79ef6a7763fc08177f014052469ee12aefcdad0d99a747372360c2f648d2cc4" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "impl-trait-for-tuples", "log", "parity-scale-codec", "scale-info", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -7121,15 +7192,15 @@ version = "35.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0861b2a1ad6526948567bb59a3fdc4c7f02ee79b07be8b931a544350ec35ab0c" dependencies = [ - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-timestamp", "parity-scale-codec", "scale-info", - "sp-application-crypto", + "sp-application-crypto 37.0.0", "sp-consensus-aura", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -7139,14 +7210,14 @@ version = "36.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2c3666a476132f5846fe4d5e1961a923a58a0f54d873d84566f24ffaa3684f" dependencies = [ - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "pallet-session", "parity-scale-codec", "scale-info", - "sp-application-crypto", + "sp-application-crypto 37.0.0", "sp-authority-discovery", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -7156,12 +7227,12 @@ version = "36.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38885846dbcf03b025fdbd7edb3649046dbc68fa0b419ffe8837ef853a10d31f" dependencies = [ - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "impl-trait-for-tuples", "parity-scale-codec", "scale-info", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -7172,21 +7243,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b23d2d814e3cb793659fcf84533f66fdf0ed9cccb66cb2225851f482843ed096" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-authorship", "pallet-session", "pallet-timestamp", "parity-scale-codec", "scale-info", - "sp-application-crypto", + "sp-application-crypto 37.0.0", "sp-consensus-babe", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-session", - "sp-staking", + "sp-staking 33.0.0", "sp-std", ] @@ -7200,15 +7271,15 @@ dependencies = [ "docify", "frame-benchmarking", "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-balances", "parity-scale-codec", "scale-info", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "sp-tracing", ] @@ -7221,12 +7292,12 @@ checksum = "6878e240962d3887f0e0654ac343a18845adb95ad493c9d4d5e803c015d4a4c3" dependencies = [ "docify", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -7236,8 +7307,8 @@ version = "36.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "715dfcd1bf3f1f37af6335d4eb3cef921e746ac54721e2258c4fd968b61eb009" dependencies = [ - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-authorship", "pallet-session", @@ -7245,9 +7316,9 @@ dependencies = [ "scale-info", "serde", "sp-consensus-beefy", - "sp-runtime", + "sp-runtime 38.0.0", "sp-session", - "sp-staking", + "sp-staking 33.0.0", "sp-std", ] @@ -7259,8 +7330,8 @@ checksum = "01d70c6f872eb3f2635355ccbea944a4f9ea411c0aa25f6f1a15219e8da11ad2" dependencies = [ "array-bytes", "binary-merkle-tree", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-beefy", "pallet-mmr", @@ -7268,12 +7339,12 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-api", + "sp-api 33.0.0", "sp-consensus-beefy", "sp-core", - "sp-io", - "sp-runtime", - "sp-state-machine", + "sp-io 37.0.0", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", "sp-std", ] @@ -7284,15 +7355,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0566499e74ba4b7ccbd1b667eef0dab76ca28402a8d501e22b73a363717b05a9" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-treasury", "parity-scale-codec", "scale-info", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -7307,15 +7378,15 @@ dependencies = [ "bp-test-utils", "finality-grandpa", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", "sp-consensus-grandpa", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", - "sp-trie", + "sp-trie 36.0.0", ] [[package]] @@ -7327,13 +7398,13 @@ dependencies = [ "bp-messages", "bp-runtime", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "num-traits", "parity-scale-codec", "scale-info", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -7348,15 +7419,15 @@ dependencies = [ "bp-polkadot-core", "bp-runtime", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-bridge-grandpa", "parity-scale-codec", "scale-info", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", - "sp-trie", + "sp-trie 36.0.0", ] [[package]] @@ -7369,14 +7440,14 @@ dependencies = [ "bp-relayers", "bp-runtime", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-bridge-messages", "parity-scale-codec", "scale-info", "sp-arithmetic", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -7388,15 +7459,15 @@ checksum = "cd0d652c399b6ed776ee3322e60f40e323f86b413719d7696eddb8f64c368ac0" dependencies = [ "bitvec", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", - "sp-api", + "sp-api 33.0.0", "sp-arithmetic", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -7407,16 +7478,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38e351f103ebbdd1eb095da8c2379caccc82ebc59a740c2731693d2204286b83" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-bounties", "pallet-treasury", "parity-scale-codec", "scale-info", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -7427,8 +7498,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f660cc09f2f277a3976da2eef856b5c725ab7ad1192902ef7f4e4bafd992f04f" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-authorship", "pallet-balances", @@ -7436,8 +7507,8 @@ dependencies = [ "parity-scale-codec", "rand", "scale-info", - "sp-runtime", - "sp-staking", + "sp-runtime 38.0.0", + "sp-staking 33.0.0", "sp-std", ] @@ -7448,56 +7519,79 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "771bf7f6c76c3ea5e965fee0bf1d8a8c79c8c52d75ead65ed3c4d385f333756f" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] [[package]] name = "pallet-contracts" -version = "35.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e6989ac82690f981959b0d38ac6d6d52fc06bf00a035548d62b9a2e9c220376" +version = "27.0.0" dependencies = [ + "array-bytes", + "assert_matches", "bitflags 1.3.2", "environmental", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "impl-trait-for-tuples", "log", + "pallet-assets", "pallet-balances", + "pallet-contracts-fixtures", "pallet-contracts-proc-macro", "pallet-contracts-uapi", + "pallet-insecure-randomness-collective-flip", + "pallet-message-queue", + "pallet-proxy", + "pallet-timestamp", + "pallet-utility", "parity-scale-codec", "paste", + "pretty_assertions", "rand", "rand_pcg", "scale-info", "serde", "smallvec", - "sp-api", + "sp-api 33.0.0", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-keystore", + "sp-runtime 38.0.0", "sp-std", + "sp-tracing", "staging-xcm", "staging-xcm-builder", "wasm-instrument", "wasmi 0.32.3", + "wat", +] + +[[package]] +name = "pallet-contracts-fixtures" +version = "1.0.0" +dependencies = [ + "anyhow", + "frame-system 36.1.0", + "parity-wasm", + "polkavm-linker", + "sp-runtime 38.0.0", + "tempfile", + "toml 0.8.14", + "twox-hash", ] [[package]] name = "pallet-contracts-proc-macro" -version = "23.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94226cbd48516b7c310eb5dae8d50798c1ce73a7421dc0977c55b7fc2237a283" +version = "18.0.0" dependencies = [ "proc-macro2", "quote", @@ -7506,9 +7600,7 @@ dependencies = [ [[package]] name = "pallet-contracts-uapi" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1330375dcced95509e3cca7ef6b1c3fac648df995b86d39467d082ba981dc46" +version = "5.0.0" dependencies = [ "bitflags 1.3.2", "parity-scale-codec", @@ -7525,13 +7617,13 @@ checksum = "9033f0d23500bbc39298fd50c07b89a2f2d9f07300139b4df8005995ef683875" dependencies = [ "assert_matches", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", "serde", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -7541,12 +7633,12 @@ version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0596ec5ab55e02b1b5637b3ec2b99027d036fe97a1ab4733ae105474dfa727cf" dependencies = [ - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", - "sp-runtime", - "sp-staking", + "sp-runtime 38.0.0", + "sp-staking 33.0.0", "sp-std", ] @@ -7557,15 +7649,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ccd68a2bf5f2dfda2b810cbe1a779492d4c2e99338989fede4389d412ae325b" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", "serde", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -7577,8 +7669,8 @@ checksum = "bd1090fdc6ccdd8ff08c60000c970428baaaf0b33e7a6b01a91ec8b697a650a3" dependencies = [ "frame-benchmarking", "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-election-provider-support-benchmarking", "parity-scale-codec", @@ -7586,9 +7678,9 @@ dependencies = [ "scale-info", "sp-arithmetic", "sp-core", - "sp-io", + "sp-io 37.0.0", "sp-npos-elections", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", "strum 0.26.2", ] @@ -7601,10 +7693,10 @@ checksum = "93475989d2f6900caf8f1c847a55d909295c156525a7510c5f1dde176ec7c714" dependencies = [ "frame-benchmarking", "frame-election-provider-support", - "frame-system", + "frame-system 36.1.0", "parity-scale-codec", "sp-npos-elections", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -7615,16 +7707,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9320d95c95e2d4d3ee24c9292b4ee8562ecb724b985613cfa7f274912bad2c9d" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", "sp-core", - "sp-io", + "sp-io 37.0.0", "sp-npos-elections", - "sp-runtime", - "sp-staking", + "sp-runtime 38.0.0", + "sp-staking 33.0.0", "sp-std", ] @@ -7637,14 +7729,14 @@ dependencies = [ "docify", "frame-benchmarking", "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", - "sp-staking", + "sp-io 37.0.0", + "sp-runtime 38.0.0", + "sp-staking 33.0.0", "sp-std", ] @@ -7655,20 +7747,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8244b686d5cae6a8af1557ed0f49db08f812f0e7942a8d2da554b4da8a69daf0" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-authorship", "pallet-session", "parity-scale-codec", "scale-info", - "sp-application-crypto", + "sp-application-crypto 37.0.0", "sp-consensus-grandpa", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-session", - "sp-staking", + "sp-staking 33.0.0", "sp-std", ] @@ -7680,13 +7772,13 @@ checksum = "4555795a3e0e3aa49ea432b7afecb9c71a7db8793a99c68bd8dd3a52a12571f3" dependencies = [ "enumflags2", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -7697,17 +7789,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa761292e95020304b58b50e5187f8bb82f557c8c2d013e3c96ab41d611873b0" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-authorship", "parity-scale-codec", "scale-info", - "sp-application-crypto", + "sp-application-crypto 37.0.0", "sp-core", - "sp-io", - "sp-runtime", - "sp-staking", + "sp-io 37.0.0", + "sp-runtime 38.0.0", + "sp-staking 33.0.0", "sp-std", ] @@ -7718,17 +7810,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b183880ad5efae06afe6066e76f2bac5acf67f34b3cfab7352ceec46accf4b45" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", "sp-core", - "sp-io", + "sp-io 37.0.0", "sp-keyring", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] +[[package]] +name = "pallet-insecure-randomness-collective-flip" +version = "25.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e0875af2d12eb49d57c00f37cfbfba458033c10cfe87114318746381300a0e" +dependencies = [ + "frame-support 37.0.0", + "frame-system 37.1.0", + "parity-scale-codec", + "safe-mix", + "scale-info", + "sp-runtime 39.0.0", +] + [[package]] name = "pallet-membership" version = "36.0.0" @@ -7736,14 +7842,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34006cf047f47edbef33874cc64895918e2c5d7562795209068d5fb388c53a30" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -7755,15 +7861,15 @@ checksum = "20e65a37881d1998546254a5e50a1f768b3f82deabe774e750f4ea95aba8030c" dependencies = [ "environmental", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", "sp-arithmetic", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "sp-weights", ] @@ -7775,15 +7881,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8ccec82827413f031689fef4c714fdb0213d58c7a6e208d33f5eab80483770" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", "sp-core", - "sp-io", + "sp-io 37.0.0", "sp-mmr-primitives", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -7794,13 +7900,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be58483d827602eb8353ecf36aed65c857f0974db5d27981831e5ebf853040bd" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -7811,14 +7917,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dcaa330221f60feaf3b23d495cccc3bf2a3d6254c596b3c032273c2b46d4078" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-assets", "pallet-nfts", "parity-scale-codec", "scale-info", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -7830,14 +7936,14 @@ checksum = "3e1cd476809de3840e19091a083d5a79178af1f108ad489706e1f9e04c8836a4" dependencies = [ "enumflags2", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -7849,7 +7955,7 @@ checksum = "b0ca7a0446d2d3c27f726a016c6366218df2e0bfef9ed35886b252cfa9757f6c" dependencies = [ "pallet-nfts", "parity-scale-codec", - "sp-api", + "sp-api 33.0.0", "sp-std", ] @@ -7860,13 +7966,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e77cba0e15749c8de2be65efffa51e02bd051b4e6fcf23360d43c3b6a859187c" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", "sp-arithmetic", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -7876,16 +7982,16 @@ version = "33.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "36f8c994eb7298a394b58f98afd520b521b5d46f6f39eade4657eeaac9962471" dependencies = [ - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-balances", "parity-scale-codec", "scale-info", "sp-core", - "sp-io", - "sp-runtime", - "sp-staking", + "sp-io 37.0.0", + "sp-runtime 38.0.0", + "sp-staking 33.0.0", "sp-std", "sp-tracing", ] @@ -7898,17 +8004,17 @@ checksum = "39ee599f2861e55fc6113c01e9b14d6e85fda46bac36a906b5dd5a951fa0455c" dependencies = [ "frame-benchmarking", "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "pallet-bags-list", "pallet-delegated-staking", "pallet-nomination-pools", "pallet-staking", "parity-scale-codec", "scale-info", - "sp-runtime", + "sp-runtime 38.0.0", "sp-runtime-interface", - "sp-staking", + "sp-staking 33.0.0", "sp-std", ] @@ -7920,7 +8026,7 @@ checksum = "2906899d8f029780f0d9da77b90ae86f42bcfda5ac402c931406cd84852012ed" dependencies = [ "pallet-nomination-pools", "parity-scale-codec", - "sp-api", + "sp-api 33.0.0", "sp-std", ] @@ -7930,15 +8036,15 @@ version = "35.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4859e7bb2af46d2e0f137c2f777adf39f0e5d4d188226158d599f1cfcfb76b9e" dependencies = [ - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-balances", "parity-scale-codec", "scale-info", "serde", - "sp-runtime", - "sp-staking", + "sp-runtime 38.0.0", + "sp-staking 33.0.0", "sp-std", ] @@ -7950,8 +8056,8 @@ checksum = "4351b0edafcdf3240f0471c638b39d2c981bde9d17c0172536a0aa3b7c3097ef" dependencies = [ "frame-benchmarking", "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-babe", "pallet-balances", @@ -7962,8 +8068,8 @@ dependencies = [ "pallet-staking", "parity-scale-codec", "scale-info", - "sp-runtime", - "sp-staking", + "sp-runtime 38.0.0", + "sp-staking 33.0.0", "sp-std", ] @@ -7975,14 +8081,14 @@ checksum = "58d9a81a93202105a660e6aa3d3f81638bdd109ca0497f3e528529cd52d034db" dependencies = [ "docify", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "paste", "scale-info", "serde", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -7993,14 +8099,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68ac726abc5b1bcd6c8f783514b8e1a48be32c7d15e0b263e4bc28cc1e4e7763" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -8011,12 +8117,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4e12680e176607815a78a0cd10a52af50790292cb950404f30a885e2a7229e9" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -8027,16 +8133,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "862ea8d386ed5737e859470c43cbfd9652c81398cad29e03ae7846c21aaee4c6" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "impl-trait-for-tuples", "log", "parity-scale-codec", "scale-info", "sp-arithmetic", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -8047,12 +8153,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b24d4131bc79fee0b07550136ca6329faa84c1c3e76ae62a74aef6b1da0b95b4" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -8064,15 +8170,15 @@ checksum = "b2c906a9c4573eb58de4134ec7180bf12c6769df2b9859dae8adcbc5fce78add" dependencies = [ "assert_matches", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", "serde", "sp-arithmetic", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -8082,13 +8188,13 @@ version = "12.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa61642f7bdc1a393798aa1ff67bb8c29f8f184b6fce165e1079010d446a1e29" dependencies = [ - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -8100,13 +8206,13 @@ checksum = "b170d6aa191197d3f50b1193925546972ffc394376ead4d2739eb40909b73c85" dependencies = [ "docify", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "sp-weights", ] @@ -8117,21 +8223,21 @@ version = "36.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c92b24c911c2cfa5351616edc7f2f93427ea6f4f95efdb13f0f5d51997939c3" dependencies = [ - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "impl-trait-for-tuples", "log", "pallet-timestamp", "parity-scale-codec", "scale-info", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-session", - "sp-staking", - "sp-state-machine", + "sp-staking 33.0.0", + "sp-state-machine 0.42.0", "sp-std", - "sp-trie", + "sp-trie 36.0.0", ] [[package]] @@ -8141,13 +8247,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd02aaf5f10734670346677042ece94fae20dcd5436eafeb9b429d8d6d5b6385" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "pallet-session", "pallet-staking", "parity-scale-codec", "rand", - "sp-runtime", + "sp-runtime 38.0.0", "sp-session", "sp-std", ] @@ -8159,15 +8265,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66b60b1d726532317f9965bab4995aa49b73f9b7ca3b9a0f75d158bd84686c5f" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "rand_chacha", "scale-info", "sp-arithmetic", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -8179,8 +8285,8 @@ checksum = "fbebdb060417654f215fc6f03675e5f44cfc83837d9e523e1b8fd9a4a2e1bdc2" dependencies = [ "frame-benchmarking", "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-authorship", "pallet-session", @@ -8188,10 +8294,10 @@ dependencies = [ "rand_chacha", "scale-info", "serde", - "sp-application-crypto", - "sp-io", - "sp-runtime", - "sp-staking", + "sp-application-crypto 37.0.0", + "sp-io 37.0.0", + "sp-runtime 38.0.0", + "sp-staking 33.0.0", "sp-std", ] @@ -8224,8 +8330,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3350ef1795b832f4adc464e88fb6d44827bd3f98701b0b0bbee495267b444a92" dependencies = [ "parity-scale-codec", - "sp-api", - "sp-staking", + "sp-api 33.0.0", + "sp-staking 33.0.0", ] [[package]] @@ -8235,14 +8341,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e07f8626f4ff62ac79d6ad0bd01fab7645897ce35706ddb95fa084e75be9306d" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -8254,12 +8360,12 @@ checksum = "1bd2a8797c1bb3d3897b4f87a7716111da5eeb8561345277b6e6d70349ec8b35" dependencies = [ "docify", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -8271,14 +8377,14 @@ checksum = "ae789d344be857679b0b98b28a67c747119724847f81d704d3fd03ee13fb6841" dependencies = [ "docify", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", - "sp-inherents", - "sp-io", - "sp-runtime", + "sp-inherents 33.0.0", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "sp-storage", "sp-timestamp", @@ -8291,16 +8397,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7dfec7872ee9e071209ae860094569745e8bd47564bacdba739256ee52cf78c" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-treasury", "parity-scale-codec", "scale-info", "serde", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -8310,14 +8416,14 @@ version = "36.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74fb6114223c8d967c3c2f21cbc845e8ea604ff7e21a8e59d119d5a9257ba886" dependencies = [ - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", "serde", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -8330,11 +8436,11 @@ dependencies = [ "jsonrpsee", "pallet-transaction-payment-rpc-runtime-api", "parity-scale-codec", - "sp-api", + "sp-api 33.0.0", "sp-blockchain", "sp-core", "sp-rpc", - "sp-runtime", + "sp-runtime 38.0.0", "sp-weights", ] @@ -8346,8 +8452,8 @@ checksum = "f4bad1700ad7eb5ab254189e1df894d1d16b3626a3c4b9c45259ec4d9efc262c" dependencies = [ "pallet-transaction-payment", "parity-scale-codec", - "sp-api", - "sp-runtime", + "sp-api 33.0.0", + "sp-runtime 38.0.0", "sp-weights", ] @@ -8359,15 +8465,15 @@ checksum = "9c502615bb4fdd02856a131cb2a612ad40c26435ec938f65f11cae4ff230812b" dependencies = [ "docify", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "impl-trait-for-tuples", "pallet-balances", "parity-scale-codec", "scale-info", "serde", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -8378,12 +8484,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a59e8599a8c19908e934645f845b5cb546cef1f08745319db7e5b9c24f9e0e4" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -8394,13 +8500,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3238fe6ad00da6a137be115904c39cab97eb5c7f03da0bb1a20de1bef03f0c71" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -8411,12 +8517,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78f7f0f4fe5e1d851e85d81e5e73b6f929f0c35af786ce8be9c9e3363717c136" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -8427,12 +8533,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e4f27640279229eb73fde0cb06e98b799305e6b0bc724f4dfbef2001ab4ad00" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", - "sp-api", - "sp-runtime", + "sp-api 33.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -8442,18 +8548,18 @@ version = "15.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe7409458b7fedc5c7d46459da154ccc2dc22a843ce08e8ab6c1743ef5cf972c" dependencies = [ - "bounded-collections 0.2.0", + "bounded-collections", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-balances", "parity-scale-codec", "scale-info", "serde", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "staging-xcm", "staging-xcm-builder", @@ -8468,13 +8574,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f177a171203cc0bec3cff1bdd5d3b926abfbd0ecf347e044b147194e664f717" dependencies = [ "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "staging-xcm", "staging-xcm-builder", @@ -8489,13 +8595,13 @@ checksum = "f48bd38d4061a51f263f4c08021e66100e16cbda9978fba163d2544637b31dab" dependencies = [ "bp-xcm-bridge-hub-router", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "parity-scale-codec", "scale-info", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", "staging-xcm", "staging-xcm-builder", @@ -8509,8 +8615,8 @@ checksum = "9319e656eebdf161666e54a4d8e24f73137f702f01600247f7be650bc4d46167" dependencies = [ "cumulus-primitives-core", "cumulus-primitives-utility", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "log", "pallet-asset-tx-payment", "pallet-assets", @@ -8524,8 +8630,8 @@ dependencies = [ "scale-info", "sp-consensus-aura", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "staging-parachain-info", "staging-xcm", @@ -8544,8 +8650,8 @@ dependencies = [ "cumulus-primitives-core", "cumulus-primitives-parachain-inherent", "cumulus-test-relay-sproof-builder", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "pallet-balances", "pallet-collator-selection", "pallet-session", @@ -8555,8 +8661,8 @@ dependencies = [ "polkadot-parachain-primitives", "sp-consensus-aura", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "sp-tracing", "staging-parachain-info", @@ -9013,10 +9119,10 @@ dependencies = [ "sc-sysinfo", "sc-tracing", "sp-core", - "sp-io", + "sp-io 37.0.0", "sp-keyring", "sp-maybe-compressed-blob", - "sp-runtime", + "sp-runtime 38.0.0", "substrate-build-script-utils", "thiserror", ] @@ -9038,7 +9144,7 @@ dependencies = [ "polkadot-primitives", "sp-core", "sp-keystore", - "sp-runtime", + "sp-runtime 38.0.0", "thiserror", "tokio-util", "tracing-gum", @@ -9053,7 +9159,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -9077,7 +9183,7 @@ dependencies = [ "polkadot-primitives", "sc-network", "schnellru", - "sp-application-crypto", + "sp-application-crypto 37.0.0", "sp-keystore", "thiserror", "tracing-gum", @@ -9094,7 +9200,7 @@ dependencies = [ "polkadot-primitives", "reed-solomon-novelpoly", "sp-core", - "sp-trie", + "sp-trie 36.0.0", "thiserror", ] @@ -9114,7 +9220,7 @@ dependencies = [ "rand_chacha", "sc-network", "sc-network-common", - "sp-application-crypto", + "sp-application-crypto 37.0.0", "sp-core", "sp-crypto-hashing", "sp-keystore", @@ -9190,10 +9296,10 @@ dependencies = [ "sc-keystore", "schnellru", "schnorrkel 0.11.4", - "sp-application-crypto", + "sp-application-crypto 37.0.0", "sp-consensus", "sp-consensus-slots", - "sp-runtime", + "sp-runtime 38.0.0", "thiserror", "tracing-gum", ] @@ -9346,7 +9452,7 @@ dependencies = [ "polkadot-overseer", "polkadot-primitives", "sp-blockchain", - "sp-inherents", + "sp-inherents 33.0.0", "thiserror", "tracing-gum", ] @@ -9456,7 +9562,7 @@ dependencies = [ "sp-core", "sp-crypto-hashing", "sp-externalities", - "sp-io", + "sp-io 37.0.0", "sp-tracing", "thiserror", "tracing-gum", @@ -9539,7 +9645,7 @@ dependencies = [ "sc-authority-discovery", "sc-network", "sc-network-types", - "sp-runtime", + "sp-runtime 38.0.0", "strum 0.26.2", "thiserror", "tracing-gum", @@ -9559,12 +9665,12 @@ dependencies = [ "polkadot-primitives", "schnorrkel 0.11.4", "serde", - "sp-application-crypto", + "sp-application-crypto 37.0.0", "sp-consensus-babe", "sp-core", "sp-keystore", "sp-maybe-compressed-blob", - "sp-runtime", + "sp-runtime 38.0.0", "thiserror", "zstd 0.12.4", ] @@ -9602,11 +9708,11 @@ dependencies = [ "sc-network-types", "sc-transaction-pool-api", "smallvec", - "sp-api", + "sp-api 33.0.0", "sp-authority-discovery", "sp-blockchain", "sp-consensus-babe", - "sp-runtime", + "sp-runtime 38.0.0", "substrate-prometheus-endpoint", "thiserror", ] @@ -9641,7 +9747,7 @@ dependencies = [ "rand", "sc-client-api", "schnellru", - "sp-application-crypto", + "sp-application-crypto 37.0.0", "sp-core", "sp-keystore", "thiserror", @@ -9665,7 +9771,7 @@ dependencies = [ "polkadot-node-subsystem-types", "polkadot-primitives", "sc-client-api", - "sp-api", + "sp-api 33.0.0", "sp-core", "tikv-jemalloc-ctl", "tracing-gum", @@ -9677,14 +9783,14 @@ version = "13.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f61070d0ff28f596890def0e0d03c231860796130b2a43e293106fa86a50c9a9" dependencies = [ - "bounded-collections 0.2.0", + "bounded-collections", "derive_more", "parity-scale-codec", "polkadot-core-primitives", "scale-info", "serde", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", "sp-weights", ] @@ -9703,17 +9809,17 @@ dependencies = [ "polkadot-parachain-primitives", "scale-info", "serde", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-arithmetic", "sp-authority-discovery", "sp-consensus-slots", "sp-core", - "sp-inherents", - "sp-io", + "sp-inherents 33.0.0", + "sp-io 37.0.0", "sp-keystore", - "sp-runtime", - "sp-staking", + "sp-runtime 38.0.0", + "sp-staking 33.0.0", "sp-std", ] @@ -9740,15 +9846,15 @@ dependencies = [ "sc-rpc-spec-v2", "sc-sync-state-rpc", "sc-transaction-pool-api", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-block-builder", "sp-blockchain", "sp-consensus", "sp-consensus-babe", "sp-consensus-beefy", "sp-keystore", - "sp-runtime", + "sp-runtime 38.0.0", "substrate-frame-rpc-system", "substrate-state-trie-migration-rpc", ] @@ -9763,8 +9869,8 @@ dependencies = [ "frame-election-provider-support", "frame-executive", "frame-metadata-hash-extension", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "frame-system-benchmarking", "frame-system-rpc-runtime-api", "frame-try-runtime", @@ -9823,8 +9929,8 @@ dependencies = [ "polkadot-runtime-parachains", "scale-info", "serde_json", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-arithmetic", "sp-authority-discovery", "sp-block-builder", @@ -9832,18 +9938,18 @@ dependencies = [ "sp-consensus-beefy", "sp-core", "sp-debug-derive", - "sp-genesis-builder", - "sp-inherents", - "sp-io", + "sp-genesis-builder 0.14.0", + "sp-inherents 33.0.0", + "sp-io 37.0.0", "sp-npos-elections", "sp-offchain", - "sp-runtime", + "sp-runtime 38.0.0", "sp-session", - "sp-staking", + "sp-staking 33.0.0", "sp-std", "sp-storage", "sp-transaction-pool", - "sp-version", + "sp-version 36.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -9860,8 +9966,8 @@ dependencies = [ "bitvec", "frame-benchmarking", "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "impl-trait-for-tuples", "libsecp256k1", "log", @@ -9888,14 +9994,14 @@ dependencies = [ "serde", "serde_derive", "slot-range-helper", - "sp-api", + "sp-api 33.0.0", "sp-core", - "sp-inherents", - "sp-io", + "sp-inherents 33.0.0", + "sp-io 37.0.0", "sp-npos-elections", - "sp-runtime", + "sp-runtime 38.0.0", "sp-session", - "sp-staking", + "sp-staking 33.0.0", "sp-std", "staging-xcm", "staging-xcm-builder", @@ -9908,12 +10014,12 @@ name = "polkadot-runtime-constants" version = "1.0.0" source = "git+https://github.com/polkadot-fellows/runtimes#f42acab60edf4d6ded4d9e99b1a8fbacded85669" dependencies = [ - "frame-support", + "frame-support 36.0.0", "polkadot-primitives", "polkadot-runtime-common", "smallvec", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-weights", "staging-xcm-builder", ] @@ -9942,8 +10048,8 @@ dependencies = [ "bitvec", "derive_more", "frame-benchmarking", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "impl-trait-for-tuples", "log", "pallet-authority-discovery", @@ -9965,16 +10071,16 @@ dependencies = [ "rand_chacha", "scale-info", "serde", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-arithmetic", "sp-core", - "sp-inherents", - "sp-io", + "sp-inherents 33.0.0", + "sp-io 37.0.0", "sp-keystore", - "sp-runtime", + "sp-runtime 38.0.0", "sp-session", - "sp-staking", + "sp-staking 33.0.0", "sp-std", "staging-xcm", "staging-xcm-executor", @@ -9990,8 +10096,8 @@ dependencies = [ "async-trait", "frame-benchmarking", "frame-benchmarking-cli", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "frame-system-rpc-runtime-api", "futures", "hex-literal", @@ -10069,7 +10175,7 @@ dependencies = [ "schnellru", "serde", "serde_json", - "sp-api", + "sp-api 33.0.0", "sp-authority-discovery", "sp-block-builder", "sp-blockchain", @@ -10078,19 +10184,19 @@ dependencies = [ "sp-consensus-beefy", "sp-consensus-grandpa", "sp-core", - "sp-inherents", - "sp-io", + "sp-inherents 33.0.0", + "sp-io 37.0.0", "sp-keyring", "sp-keystore", "sp-mmr-primitives", "sp-offchain", - "sp-runtime", + "sp-runtime 38.0.0", "sp-session", - "sp-state-machine", + "sp-state-machine 0.42.0", "sp-storage", "sp-timestamp", "sp-transaction-pool", - "sp-version", + "sp-version 36.0.0", "sp-weights", "staging-xcm", "substrate-prometheus-endpoint", @@ -10119,7 +10225,7 @@ dependencies = [ "polkadot-node-subsystem-util", "polkadot-primitives", "sp-keystore", - "sp-staking", + "sp-staking 33.0.0", "thiserror", "tracing-gum", ] @@ -10273,6 +10379,22 @@ dependencies = [ "universal-hash", ] +[[package]] +name = "pop-chain-extension" +version = "0.1.0" +dependencies = [ + "frame-support 36.0.0", + "frame-system 36.1.0", + "impl-trait-for-tuples", + "log", + "pallet-contracts", + "parity-scale-codec", + "rand", + "sp-core", + "sp-runtime 38.0.0", + "sp-std", +] + [[package]] name = "pop-node" version = "0.2.0-alpha" @@ -10319,15 +10441,15 @@ dependencies = [ "sc-transaction-pool-api", "serde", "serde_json", - "sp-api", + "sp-api 33.0.0", "sp-block-builder", "sp-blockchain", "sp-consensus-aura", "sp-core", - "sp-io", + "sp-io 37.0.0", "sp-keystore", "sp-offchain", - "sp-runtime", + "sp-runtime 38.0.0", "sp-session", "sp-timestamp", "sp-transaction-pool", @@ -10341,7 +10463,6 @@ dependencies = [ name = "pop-primitives" version = "0.0.0" dependencies = [ - "bounded-collections 0.1.9", "parity-scale-codec", "scale-info", ] @@ -10350,12 +10471,12 @@ dependencies = [ name = "pop-runtime-common" version = "0.0.0" dependencies = [ - "frame-support", + "frame-support 36.0.0", "parachains-common", "parity-scale-codec", "polkadot-primitives", "scale-info", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -10372,19 +10493,19 @@ dependencies = [ "cumulus-primitives-core", "cumulus-primitives-storage-weight-reclaim", "cumulus-primitives-utility", - "enumflags2", "env_logger 0.11.5", "frame-benchmarking", "frame-executive", "frame-metadata-hash-extension", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "frame-system-benchmarking", "frame-system-rpc-runtime-api", "frame-try-runtime", "hex", "hex-literal", "log", + "pallet-api", "pallet-assets", "pallet-aura", "pallet-authorship", @@ -10410,23 +10531,24 @@ dependencies = [ "parity-scale-codec", "polkadot-parachain-primitives", "polkadot-runtime-common", + "pop-chain-extension", "pop-primitives", "pop-runtime-common", "scale-info", "smallvec", - "sp-api", + "sp-api 33.0.0", "sp-block-builder", "sp-consensus-aura", "sp-core", - "sp-genesis-builder", - "sp-inherents", - "sp-io", + "sp-genesis-builder 0.14.0", + "sp-inherents 33.0.0", + "sp-io 37.0.0", "sp-offchain", - "sp-runtime", + "sp-runtime 38.0.0", "sp-session", "sp-std", "sp-transaction-pool", - "sp-version", + "sp-version 36.0.0", "staging-parachain-info", "staging-xcm", "staging-xcm-builder", @@ -10447,13 +10569,12 @@ dependencies = [ "cumulus-primitives-core", "cumulus-primitives-storage-weight-reclaim", "cumulus-primitives-utility", - "enumflags2", "env_logger 0.11.5", "frame-benchmarking", "frame-executive", "frame-metadata-hash-extension", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "frame-system-benchmarking", "frame-system-rpc-runtime-api", "frame-try-runtime", @@ -10489,19 +10610,19 @@ dependencies = [ "pop-runtime-common", "scale-info", "smallvec", - "sp-api", + "sp-api 33.0.0", "sp-block-builder", "sp-consensus-aura", "sp-core", - "sp-genesis-builder", - "sp-inherents", - "sp-io", + "sp-genesis-builder 0.14.0", + "sp-inherents 33.0.0", + "sp-io 37.0.0", "sp-offchain", - "sp-runtime", + "sp-runtime 38.0.0", "sp-session", "sp-std", "sp-transaction-pool", - "sp-version", + "sp-version 36.0.0", "staging-parachain-info", "staging-xcm", "staging-xcm-builder", @@ -10567,6 +10688,16 @@ dependencies = [ "termtree", ] +[[package]] +name = "pretty_assertions" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af7cee1a6c8a5b9208b3cb1061f10c0cb689087b3d8ce85fb9d2dd7a29b6ba66" +dependencies = [ + "diff", + "yansi", +] + [[package]] name = "prettyplease" version = "0.1.25" @@ -11316,8 +11447,8 @@ dependencies = [ "frame-benchmarking", "frame-executive", "frame-metadata-hash-extension", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "frame-system-benchmarking", "frame-system-rpc-runtime-api", "frame-try-runtime", @@ -11379,7 +11510,7 @@ dependencies = [ "serde_derive", "serde_json", "smallvec", - "sp-api", + "sp-api 33.0.0", "sp-arithmetic", "sp-authority-discovery", "sp-block-builder", @@ -11387,18 +11518,18 @@ dependencies = [ "sp-consensus-beefy", "sp-consensus-grandpa", "sp-core", - "sp-genesis-builder", - "sp-inherents", - "sp-io", + "sp-genesis-builder 0.14.0", + "sp-inherents 33.0.0", + "sp-io 37.0.0", "sp-mmr-primitives", "sp-offchain", - "sp-runtime", + "sp-runtime 38.0.0", "sp-session", - "sp-staking", + "sp-staking 33.0.0", "sp-std", "sp-storage", "sp-transaction-pool", - "sp-version", + "sp-version 36.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -11413,12 +11544,12 @@ version = "15.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ef330dc0657ac9e4ff93ff320e2ee1a120493bceb91010c7ef7b08fe8e27950" dependencies = [ - "frame-support", + "frame-support 36.0.0", "polkadot-primitives", "polkadot-runtime-common", "smallvec", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-weights", "staging-xcm", "staging-xcm-builder", @@ -11484,6 +11615,15 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e75f6a532d0fd9f7f13144f392b6ad56a32696bfcd9c78f797f16bbb6f072d6" +[[package]] +name = "rustc_version" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" +dependencies = [ + "semver 0.9.0", +] + [[package]] name = "rustc_version" version = "0.4.0" @@ -11713,6 +11853,15 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" +[[package]] +name = "safe-mix" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d3d055a2582e6b00ed7a31c1524040aa391092bf636328350813f3a0605215c" +dependencies = [ + "rustc_version 0.2.3", +] + [[package]] name = "safe_arch" version = "0.7.2" @@ -11764,12 +11913,12 @@ dependencies = [ "sc-client-api", "sc-network", "sc-network-types", - "sp-api", + "sp-api 33.0.0", "sp-authority-discovery", "sp-blockchain", "sp-core", "sp-keystore", - "sp-runtime", + "sp-runtime 38.0.0", "substrate-prometheus-endpoint", "thiserror", ] @@ -11788,12 +11937,12 @@ dependencies = [ "sc-proposer-metrics", "sc-telemetry", "sc-transaction-pool-api", - "sp-api", + "sp-api 33.0.0", "sp-blockchain", "sp-consensus", "sp-core", - "sp-inherents", - "sp-runtime", + "sp-inherents 33.0.0", + "sp-runtime 38.0.0", "substrate-prometheus-endpoint", ] @@ -11804,13 +11953,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6345fb862e10aaa7d88d6689a7c247448c40ae465253c83566dc76a17ec1426" dependencies = [ "parity-scale-codec", - "sp-api", + "sp-api 33.0.0", "sp-block-builder", "sp-blockchain", "sp-core", - "sp-inherents", - "sp-runtime", - "sp-trie", + "sp-inherents 33.0.0", + "sp-runtime 38.0.0", + "sp-trie 36.0.0", ] [[package]] @@ -11834,10 +11983,10 @@ dependencies = [ "sp-blockchain", "sp-core", "sp-crypto-hashing", - "sp-genesis-builder", - "sp-io", - "sp-runtime", - "sp-state-machine", + "sp-genesis-builder 0.14.0", + "sp-io 37.0.0", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", "sp-tracing", ] @@ -11889,8 +12038,8 @@ dependencies = [ "sp-keyring", "sp-keystore", "sp-panic-handler", - "sp-runtime", - "sp-version", + "sp-runtime 38.0.0", + "sp-version 36.0.0", "thiserror", "tokio", ] @@ -11909,17 +12058,17 @@ dependencies = [ "sc-executor", "sc-transaction-pool-api", "sc-utils", - "sp-api", + "sp-api 33.0.0", "sp-blockchain", "sp-consensus", "sp-core", "sp-database", "sp-externalities", - "sp-runtime", - "sp-state-machine", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", "sp-statement-store", "sp-storage", - "sp-trie", + "sp-trie 36.0.0", "substrate-prometheus-endpoint", ] @@ -11945,9 +12094,9 @@ dependencies = [ "sp-blockchain", "sp-core", "sp-database", - "sp-runtime", - "sp-state-machine", - "sp-trie", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", + "sp-trie 36.0.0", ] [[package]] @@ -11965,12 +12114,12 @@ dependencies = [ "sc-network-types", "sc-utils", "serde", - "sp-api", + "sp-api 33.0.0", "sp-blockchain", "sp-consensus", "sp-core", - "sp-runtime", - "sp-state-machine", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", "substrate-prometheus-endpoint", "thiserror", ] @@ -11990,17 +12139,17 @@ dependencies = [ "sc-consensus", "sc-consensus-slots", "sc-telemetry", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-block-builder", "sp-blockchain", "sp-consensus", "sp-consensus-aura", "sp-consensus-slots", "sp-core", - "sp-inherents", + "sp-inherents 33.0.0", "sp-keystore", - "sp-runtime", + "sp-runtime 38.0.0", "substrate-prometheus-endpoint", "thiserror", ] @@ -12026,8 +12175,8 @@ dependencies = [ "sc-consensus-slots", "sc-telemetry", "sc-transaction-pool-api", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-block-builder", "sp-blockchain", "sp-consensus", @@ -12035,9 +12184,9 @@ dependencies = [ "sp-consensus-slots", "sp-core", "sp-crypto-hashing", - "sp-inherents", + "sp-inherents 33.0.0", "sp-keystore", - "sp-runtime", + "sp-runtime 38.0.0", "substrate-prometheus-endpoint", "thiserror", ] @@ -12054,14 +12203,14 @@ dependencies = [ "sc-consensus-epochs", "sc-rpc-api", "serde", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-blockchain", "sp-consensus", "sp-consensus-babe", "sp-core", "sp-keystore", - "sp-runtime", + "sp-runtime 38.0.0", "thiserror", ] @@ -12086,8 +12235,8 @@ dependencies = [ "sc-network-sync", "sc-network-types", "sc-utils", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-arithmetic", "sp-blockchain", "sp-consensus", @@ -12095,7 +12244,7 @@ dependencies = [ "sp-core", "sp-crypto-hashing", "sp-keystore", - "sp-runtime", + "sp-runtime 38.0.0", "substrate-prometheus-endpoint", "thiserror", "tokio", @@ -12116,10 +12265,10 @@ dependencies = [ "sc-consensus-beefy", "sc-rpc", "serde", - "sp-application-crypto", + "sp-application-crypto 37.0.0", "sp-consensus-beefy", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "thiserror", ] @@ -12134,7 +12283,7 @@ dependencies = [ "sc-client-api", "sc-consensus", "sp-blockchain", - "sp-runtime", + "sp-runtime 38.0.0", ] [[package]] @@ -12168,8 +12317,8 @@ dependencies = [ "sc-transaction-pool-api", "sc-utils", "serde_json", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-arithmetic", "sp-blockchain", "sp-consensus", @@ -12177,7 +12326,7 @@ dependencies = [ "sp-core", "sp-crypto-hashing", "sp-keystore", - "sp-runtime", + "sp-runtime 38.0.0", "substrate-prometheus-endpoint", "thiserror", ] @@ -12199,7 +12348,7 @@ dependencies = [ "serde", "sp-blockchain", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "thiserror", ] @@ -12222,9 +12371,9 @@ dependencies = [ "sp-consensus", "sp-consensus-slots", "sp-core", - "sp-inherents", - "sp-runtime", - "sp-state-machine", + "sp-inherents 33.0.0", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", ] [[package]] @@ -12239,14 +12388,14 @@ dependencies = [ "sc-executor-polkavm", "sc-executor-wasmtime", "schnellru", - "sp-api", + "sp-api 33.0.0", "sp-core", "sp-externalities", - "sp-io", + "sp-io 37.0.0", "sp-panic-handler", "sp-runtime-interface", - "sp-trie", - "sp-version", + "sp-trie 36.0.0", + "sp-version 36.0.0", "sp-wasm-interface", "tracing", ] @@ -12311,7 +12460,7 @@ dependencies = [ "sc-network-common", "sc-network-sync", "sp-blockchain", - "sp-runtime", + "sp-runtime 38.0.0", ] [[package]] @@ -12323,7 +12472,7 @@ dependencies = [ "array-bytes", "parking_lot 0.12.3", "serde_json", - "sp-application-crypto", + "sp-application-crypto 37.0.0", "sp-core", "sp-keystore", "thiserror", @@ -12350,12 +12499,12 @@ dependencies = [ "sc-network", "sc-network-types", "sc-transaction-pool-api", - "sp-api", + "sp-api 33.0.0", "sp-consensus", "sp-core", "sp-keystore", "sp-mixnet", - "sp-runtime", + "sp-runtime 38.0.0", "thiserror", ] @@ -12400,7 +12549,7 @@ dependencies = [ "sp-arithmetic", "sp-blockchain", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "substrate-prometheus-endpoint", "thiserror", "tokio", @@ -12427,7 +12576,7 @@ dependencies = [ "sc-network-types", "sp-consensus", "sp-consensus-grandpa", - "sp-runtime", + "sp-runtime 38.0.0", ] [[package]] @@ -12445,7 +12594,7 @@ dependencies = [ "sc-network-sync", "sc-network-types", "schnellru", - "sp-runtime", + "sp-runtime 38.0.0", "substrate-prometheus-endpoint", "tracing", ] @@ -12468,7 +12617,7 @@ dependencies = [ "sc-network-types", "sp-blockchain", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "thiserror", ] @@ -12503,7 +12652,7 @@ dependencies = [ "sp-consensus", "sp-consensus-grandpa", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "substrate-prometheus-endpoint", "thiserror", "tokio", @@ -12526,7 +12675,7 @@ dependencies = [ "sc-network-types", "sc-utils", "sp-consensus", - "sp-runtime", + "sp-runtime 38.0.0", "substrate-prometheus-endpoint", ] @@ -12573,12 +12722,12 @@ dependencies = [ "sc-network-types", "sc-transaction-pool-api", "sc-utils", - "sp-api", + "sp-api 33.0.0", "sp-core", "sp-externalities", "sp-keystore", "sp-offchain", - "sp-runtime", + "sp-runtime 38.0.0", "threadpool", "tracing", ] @@ -12613,16 +12762,16 @@ dependencies = [ "sc-transaction-pool-api", "sc-utils", "serde_json", - "sp-api", + "sp-api 33.0.0", "sp-blockchain", "sp-core", "sp-keystore", "sp-offchain", "sp-rpc", - "sp-runtime", + "sp-runtime 38.0.0", "sp-session", "sp-statement-store", - "sp-version", + "sp-version 36.0.0", "tokio", ] @@ -12642,8 +12791,8 @@ dependencies = [ "serde_json", "sp-core", "sp-rpc", - "sp-runtime", - "sp-version", + "sp-runtime 38.0.0", + "sp-version 36.0.0", "thiserror", ] @@ -12692,12 +12841,12 @@ dependencies = [ "sc-utils", "schnellru", "serde", - "sp-api", + "sp-api 33.0.0", "sp-blockchain", "sp-core", "sp-rpc", - "sp-runtime", - "sp-version", + "sp-runtime 38.0.0", + "sp-version 36.0.0", "thiserror", "tokio", "tokio-stream", @@ -12745,20 +12894,20 @@ dependencies = [ "schnellru", "serde", "serde_json", - "sp-api", + "sp-api 33.0.0", "sp-blockchain", "sp-consensus", "sp-core", "sp-externalities", "sp-keystore", - "sp-runtime", + "sp-runtime 38.0.0", "sp-session", - "sp-state-machine", + "sp-state-machine 0.42.0", "sp-storage", "sp-transaction-pool", "sp-transaction-storage-proof", - "sp-trie", - "sp-version", + "sp-trie 36.0.0", + "sp-version 36.0.0", "static_init", "substrate-prometheus-endpoint", "tempfile", @@ -12810,7 +12959,7 @@ dependencies = [ "serde", "serde_json", "sp-blockchain", - "sp-runtime", + "sp-runtime 38.0.0", "thiserror", ] @@ -12832,7 +12981,7 @@ dependencies = [ "serde_json", "sp-core", "sp-crypto-hashing", - "sp-io", + "sp-io 37.0.0", "sp-std", ] @@ -12876,11 +13025,11 @@ dependencies = [ "sc-client-api", "sc-tracing-proc-macro", "serde", - "sp-api", + "sp-api 33.0.0", "sp-blockchain", "sp-core", "sp-rpc", - "sp-runtime", + "sp-runtime 38.0.0", "sp-tracing", "thiserror", "tracing", @@ -12917,11 +13066,11 @@ dependencies = [ "sc-transaction-pool-api", "sc-utils", "serde", - "sp-api", + "sp-api 33.0.0", "sp-blockchain", "sp-core", "sp-crypto-hashing", - "sp-runtime", + "sp-runtime 38.0.0", "sp-tracing", "sp-transaction-pool", "substrate-prometheus-endpoint", @@ -12941,7 +13090,7 @@ dependencies = [ "serde", "sp-blockchain", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "thiserror", ] @@ -13192,6 +13341,15 @@ dependencies = [ "semver-parser", ] +[[package]] +name = "semver" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" +dependencies = [ + "semver-parser", +] + [[package]] name = "semver" version = "1.0.23" @@ -13452,7 +13610,7 @@ dependencies = [ "enumn", "parity-scale-codec", "paste", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -13596,7 +13754,7 @@ dependencies = [ "curve25519-dalek", "rand_core", "ring 0.17.8", - "rustc_version", + "rustc_version 0.4.0", "sha2 0.10.8", "subtle 2.5.0", ] @@ -13618,7 +13776,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0ad61e3ab1c48d4c8060c7ef8571c5b6007df26687e8dbfdb6c857d840cfd2c" dependencies = [ "byte-slice-cast", - "frame-support", + "frame-support 36.0.0", "hex", "parity-scale-codec", "rlp", @@ -13627,8 +13785,8 @@ dependencies = [ "snowbridge-ethereum", "snowbridge-milagro-bls", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "ssz_rs", "ssz_rs_derive", @@ -13641,8 +13799,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "668cd71582305168ed51cb0357a4b4ea814c68c7db3898a9ba4d492f712c54e1" dependencies = [ "ethabi-decode", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "hex-literal", "parity-scale-codec", "polkadot-parachain-primitives", @@ -13651,8 +13809,8 @@ dependencies = [ "snowbridge-beacon-primitives", "sp-arithmetic", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "staging-xcm", "staging-xcm-builder", @@ -13674,8 +13832,8 @@ dependencies = [ "scale-info", "serde", "serde-big-array", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", ] @@ -13700,15 +13858,15 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e8e6707ced1308d763117bfe68f85e3f22fcdca7987b32e438c0485570f6ac7" dependencies = [ - "frame-support", + "frame-support 36.0.0", "hex-literal", "log", "parity-scale-codec", "scale-info", "snowbridge-core", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "staging-xcm", "staging-xcm-executor", @@ -13779,12 +13937,35 @@ dependencies = [ "sp-core", "sp-externalities", "sp-metadata-ir", - "sp-runtime", + "sp-runtime 38.0.0", "sp-runtime-interface", - "sp-state-machine", + "sp-state-machine 0.42.0", "sp-std", - "sp-trie", - "sp-version", + "sp-trie 36.0.0", + "sp-version 36.0.0", + "thiserror", +] + +[[package]] +name = "sp-api" +version = "34.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbce492e0482134128b7729ea36f5ef1a9f9b4de2d48ff8dde7b5e464e28ce75" +dependencies = [ + "docify", + "hash-db", + "log", + "parity-scale-codec", + "scale-info", + "sp-api-proc-macro", + "sp-core", + "sp-externalities", + "sp-metadata-ir", + "sp-runtime 39.0.0", + "sp-runtime-interface", + "sp-state-machine 0.43.0", + "sp-trie 37.0.0", + "sp-version 37.0.0", "thiserror", ] @@ -13813,10 +13994,23 @@ dependencies = [ "scale-info", "serde", "sp-core", - "sp-io", + "sp-io 37.0.0", "sp-std", ] +[[package]] +name = "sp-application-crypto" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8133012faa5f75b2f0b1619d9f720c1424ac477152c143e5f7dbde2fe1a958" +dependencies = [ + "parity-scale-codec", + "scale-info", + "serde", + "sp-core", + "sp-io 38.0.0", +] + [[package]] name = "sp-arithmetic" version = "26.0.0" @@ -13841,9 +14035,9 @@ checksum = "6a4a1e45abc3277f18484ee0b0f9808e4206eb696ad38500c892c72f33480d69" dependencies = [ "parity-scale-codec", "scale-info", - "sp-api", - "sp-application-crypto", - "sp-runtime", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", + "sp-runtime 38.0.0", ] [[package]] @@ -13852,9 +14046,9 @@ version = "33.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2cf199dc4f9f77abd3fd91c409759118159ce6ffcd8bc90b229b684ccc8c981f" dependencies = [ - "sp-api", - "sp-inherents", - "sp-runtime", + "sp-api 33.0.0", + "sp-inherents 33.0.0", + "sp-runtime 38.0.0", ] [[package]] @@ -13868,11 +14062,11 @@ dependencies = [ "parity-scale-codec", "parking_lot 0.12.3", "schnellru", - "sp-api", + "sp-api 33.0.0", "sp-consensus", "sp-database", - "sp-runtime", - "sp-state-machine", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", "thiserror", ] @@ -13886,9 +14080,9 @@ dependencies = [ "futures", "log", "sp-core", - "sp-inherents", - "sp-runtime", - "sp-state-machine", + "sp-inherents 33.0.0", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", "thiserror", ] @@ -13901,11 +14095,11 @@ dependencies = [ "async-trait", "parity-scale-codec", "scale-info", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-consensus-slots", - "sp-inherents", - "sp-runtime", + "sp-inherents 33.0.0", + "sp-runtime 38.0.0", "sp-timestamp", ] @@ -13919,12 +14113,12 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-consensus-slots", "sp-core", - "sp-inherents", - "sp-runtime", + "sp-inherents 33.0.0", + "sp-runtime 38.0.0", "sp-timestamp", ] @@ -13938,14 +14132,14 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-core", "sp-crypto-hashing", - "sp-io", + "sp-io 37.0.0", "sp-keystore", "sp-mmr-primitives", - "sp-runtime", + "sp-runtime 38.0.0", "strum 0.26.2", ] @@ -13960,11 +14154,11 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-core", "sp-keystore", - "sp-runtime", + "sp-runtime 38.0.0", ] [[package]] @@ -13988,7 +14182,7 @@ dependencies = [ "array-bytes", "bitflags 1.3.2", "blake2 0.10.6", - "bounded-collections 0.2.0", + "bounded-collections", "bs58 0.5.1", "dyn-clonable", "ed25519-zebra", @@ -14092,8 +14286,21 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde_json", - "sp-api", - "sp-runtime", + "sp-api 33.0.0", + "sp-runtime 38.0.0", +] + +[[package]] +name = "sp-genesis-builder" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "182812315871732372325f0ad42bb8b85a093a06dd77ae1eec997259f4c32aef" +dependencies = [ + "parity-scale-codec", + "scale-info", + "serde_json", + "sp-api 34.0.0", + "sp-runtime 39.0.0", ] [[package]] @@ -14106,7 +14313,21 @@ dependencies = [ "impl-trait-for-tuples", "parity-scale-codec", "scale-info", - "sp-runtime", + "sp-runtime 38.0.0", + "thiserror", +] + +[[package]] +name = "sp-inherents" +version = "34.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afffbddc380d99a90c459ba1554bbbc01d62e892de9f1485af6940b89c4c0d57" +dependencies = [ + "async-trait", + "impl-trait-for-tuples", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.0", "thiserror", ] @@ -14129,10 +14350,37 @@ dependencies = [ "sp-externalities", "sp-keystore", "sp-runtime-interface", - "sp-state-machine", + "sp-state-machine 0.42.0", "sp-std", "sp-tracing", - "sp-trie", + "sp-trie 36.0.0", + "tracing", + "tracing-core", +] + +[[package]] +name = "sp-io" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ef7eb561bb4839cc8424ce58c5ea236cbcca83f26fcc0426d8decfe8aa97d4" +dependencies = [ + "bytes", + "docify", + "ed25519-dalek", + "libsecp256k1", + "log", + "parity-scale-codec", + "polkavm-derive", + "rustversion", + "secp256k1", + "sp-core", + "sp-crypto-hashing", + "sp-externalities", + "sp-keystore", + "sp-runtime-interface", + "sp-state-machine 0.43.0", + "sp-tracing", + "sp-trie 37.0.0", "tracing", "tracing-core", ] @@ -14144,7 +14392,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b03536e1ff3ec2bd8181eeaa26c0d682ebdcbd01548a055cf591077188b8c3f0" dependencies = [ "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "strum 0.26.2", ] @@ -14189,8 +14437,8 @@ checksum = "2f65a570519da820ce3dc35053497a65f9fbd3f5a7dc81fa03078ca263e9311e" dependencies = [ "parity-scale-codec", "scale-info", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", ] [[package]] @@ -14204,10 +14452,10 @@ dependencies = [ "polkadot-ckb-merkle-mountain-range", "scale-info", "serde", - "sp-api", + "sp-api 33.0.0", "sp-core", "sp-debug-derive", - "sp-runtime", + "sp-runtime 38.0.0", "thiserror", ] @@ -14222,7 +14470,7 @@ dependencies = [ "serde", "sp-arithmetic", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", ] [[package]] @@ -14231,9 +14479,9 @@ version = "33.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cbe721c367760bddf10fcfa24fb48edd64c442f71db971f043c8ac73f51aa6e9" dependencies = [ - "sp-api", + "sp-api 33.0.0", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", ] [[package]] @@ -14276,14 +14524,41 @@ dependencies = [ "scale-info", "serde", "simple-mermaid", - "sp-application-crypto", + "sp-application-crypto 37.0.0", "sp-arithmetic", "sp-core", - "sp-io", + "sp-io 37.0.0", "sp-std", "sp-weights", ] +[[package]] +name = "sp-runtime" +version = "39.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5641385c2cd8e2252aacf35e0aff2f236331dfaea8dc11c5a4ec6bb36544450" +dependencies = [ + "docify", + "either", + "hash256-std-hasher", + "impl-trait-for-tuples", + "log", + "num-traits", + "parity-scale-codec", + "paste", + "rand", + "scale-info", + "serde", + "simple-mermaid", + "sp-application-crypto 38.0.0", + "sp-arithmetic", + "sp-core", + "sp-io 38.0.0", + "sp-std", + "sp-weights", + "tracing", +] + [[package]] name = "sp-runtime-interface" version = "28.0.0" @@ -14326,11 +14601,11 @@ checksum = "4daf2e40ffc7e7e8de08efb860eb9534faf614a49c53dc282f430faedb4aed13" dependencies = [ "parity-scale-codec", "scale-info", - "sp-api", + "sp-api 33.0.0", "sp-core", "sp-keystore", - "sp-runtime", - "sp-staking", + "sp-runtime 38.0.0", + "sp-staking 33.0.0", ] [[package]] @@ -14344,7 +14619,21 @@ dependencies = [ "scale-info", "serde", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", +] + +[[package]] +name = "sp-staking" +version = "34.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "143a764cacbab58347d8b2fd4c8909031fb0888d7b02a0ec9fa44f81f780d732" +dependencies = [ + "impl-trait-for-tuples", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core", + "sp-runtime 39.0.0", ] [[package]] @@ -14362,7 +14651,28 @@ dependencies = [ "sp-core", "sp-externalities", "sp-panic-handler", - "sp-trie", + "sp-trie 36.0.0", + "thiserror", + "tracing", + "trie-db", +] + +[[package]] +name = "sp-state-machine" +version = "0.43.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "930104d6ae882626e8880d9b1578da9300655d337a3ffb45e130c608b6c89660" +dependencies = [ + "hash-db", + "log", + "parity-scale-codec", + "parking_lot 0.12.3", + "rand", + "smallvec", + "sp-core", + "sp-externalities", + "sp-panic-handler", + "sp-trie 37.0.0", "thiserror", "tracing", "trie-db", @@ -14382,12 +14692,12 @@ dependencies = [ "rand", "scale-info", "sha2 0.10.8", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-core", "sp-crypto-hashing", "sp-externalities", - "sp-runtime", + "sp-runtime 38.0.0", "sp-runtime-interface", "thiserror", "x25519-dalek", @@ -14420,8 +14730,8 @@ checksum = "78becf144a76f6fd108dfe94a90e20a185b38c0b310dc5482328196143c8266b" dependencies = [ "async-trait", "parity-scale-codec", - "sp-inherents", - "sp-runtime", + "sp-inherents 33.0.0", + "sp-runtime 38.0.0", "thiserror", ] @@ -14443,8 +14753,8 @@ version = "33.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a3c9d1604aadc15b70e95f4388d0b1aa380215520b7ddfd372531a6d8262269c" dependencies = [ - "sp-api", - "sp-runtime", + "sp-api 33.0.0", + "sp-runtime 38.0.0", ] [[package]] @@ -14457,9 +14767,9 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-inherents", - "sp-runtime", - "sp-trie", + "sp-inherents 33.0.0", + "sp-runtime 38.0.0", + "sp-trie 36.0.0", ] [[package]] @@ -14486,6 +14796,30 @@ dependencies = [ "trie-root", ] +[[package]] +name = "sp-trie" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6282aef9f4b6ecd95a67a45bcdb67a71f4a4155c09a53c10add4ffe823db18cd" +dependencies = [ + "ahash 0.8.11", + "hash-db", + "lazy_static", + "memory-db", + "nohash-hasher", + "parity-scale-codec", + "parking_lot 0.12.3", + "rand", + "scale-info", + "schnellru", + "sp-core", + "sp-externalities", + "thiserror", + "tracing", + "trie-db", + "trie-root", +] + [[package]] name = "sp-version" version = "36.0.0" @@ -14498,7 +14832,25 @@ dependencies = [ "scale-info", "serde", "sp-crypto-hashing-proc-macro", - "sp-runtime", + "sp-runtime 38.0.0", + "sp-std", + "sp-version-proc-macro", + "thiserror", +] + +[[package]] +name = "sp-version" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d521a405707b5be561367cd3d442ff67588993de24062ce3adefcf8437ee9fe1" +dependencies = [ + "impl-serde", + "parity-scale-codec", + "parity-wasm", + "scale-info", + "serde", + "sp-crypto-hashing-proc-macro", + "sp-runtime 39.0.0", "sp-std", "sp-version-proc-macro", "thiserror", @@ -14535,7 +14887,7 @@ version = "31.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93cdaf72a1dad537bbb130ba4d47307ebe5170405280ed1aa31fa712718a400e" dependencies = [ - "bounded-collections 0.2.0", + "bounded-collections", "parity-scale-codec", "scale-info", "serde", @@ -14626,11 +14978,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd00d586b0dac4f42736bdd0ad52213a891b240e011ea82b38938263dd821c25" dependencies = [ "cumulus-primitives-core", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "parity-scale-codec", "scale-info", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", ] @@ -14641,7 +14993,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2b7b5f531c6bf9629514ef8e5fda0e9e80dd84516957f710940d0e01d3fb36c" dependencies = [ "array-bytes", - "bounded-collections 0.2.0", + "bounded-collections", "derivative", "environmental", "impl-trait-for-tuples", @@ -14659,8 +15011,8 @@ version = "15.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "847fa2afe1bed2751eaabf7b91fa4043037947f17653d7cc59ea202cc44c6bb8" dependencies = [ - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "impl-trait-for-tuples", "log", "pallet-transaction-payment", @@ -14668,8 +15020,8 @@ dependencies = [ "polkadot-parachain-primitives", "scale-info", "sp-arithmetic", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "sp-weights", "staging-xcm", @@ -14684,15 +15036,15 @@ checksum = "26b98d8219449eaf02e71a7edf1a14b14d4c713dd01d9df66fde1ce30dba4d6d" dependencies = [ "environmental", "frame-benchmarking", - "frame-support", + "frame-support 36.0.0", "impl-trait-for-tuples", "log", "parity-scale-codec", "scale-info", "sp-arithmetic", "sp-core", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "sp-weights", "staging-xcm", @@ -14843,11 +15195,11 @@ dependencies = [ "parity-scale-codec", "sc-rpc-api", "sc-transaction-pool-api", - "sp-api", + "sp-api 33.0.0", "sp-block-builder", "sp-blockchain", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", ] [[package]] @@ -14875,9 +15227,9 @@ dependencies = [ "sc-rpc-api", "serde", "sp-core", - "sp-runtime", - "sp-state-machine", - "sp-trie", + "sp-runtime 38.0.0", + "sp-state-machine 0.42.0", + "sp-trie 36.0.0", "trie-db", ] @@ -14899,10 +15251,10 @@ dependencies = [ "polkavm-linker", "sc-executor", "sp-core", - "sp-io", + "sp-io 37.0.0", "sp-maybe-compressed-blob", "sp-tracing", - "sp-version", + "sp-version 36.0.0", "strum 0.26.2", "tempfile", "toml 0.8.14", @@ -14999,7 +15351,7 @@ name = "system-parachains-constants" version = "1.0.0" source = "git+https://github.com/polkadot-fellows/runtimes#f42acab60edf4d6ded4d9e99b1a8fbacded85669" dependencies = [ - "frame-support", + "frame-support 36.0.0", "kusama-runtime-constants", "parachains-common", "polkadot-core-primitives", @@ -15007,7 +15359,7 @@ dependencies = [ "polkadot-runtime-constants", "smallvec", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-std", "staging-xcm", ] @@ -15989,6 +16341,15 @@ version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" +[[package]] +name = "wasm-encoder" +version = "0.216.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04c23aebea22c8a75833ae08ed31ccc020835b12a41999e58c31464271b94a88" +dependencies = [ + "leb128", +] + [[package]] name = "wasm-instrument" version = "0.4.0" @@ -16338,6 +16699,28 @@ dependencies = [ "wasmparser", ] +[[package]] +name = "wast" +version = "216.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7eb1f2eecd913fdde0dc6c3439d0f24530a98ac6db6cb3d14d92a5328554a08" +dependencies = [ + "bumpalo", + "leb128", + "memchr", + "unicode-width", + "wasm-encoder", +] + +[[package]] +name = "wat" +version = "1.216.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac0409090fb5154f95fb5ba3235675fd9e579e731524d63b6a2f653e1280c82a" +dependencies = [ + "wast", +] + [[package]] name = "web-sys" version = "0.3.69" @@ -16385,8 +16768,8 @@ dependencies = [ "frame-election-provider-support", "frame-executive", "frame-metadata-hash-extension", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "frame-system-benchmarking", "frame-system-rpc-runtime-api", "frame-try-runtime", @@ -16452,27 +16835,27 @@ dependencies = [ "serde", "serde_derive", "smallvec", - "sp-api", - "sp-application-crypto", + "sp-api 33.0.0", + "sp-application-crypto 37.0.0", "sp-arithmetic", "sp-authority-discovery", "sp-block-builder", "sp-consensus-babe", "sp-consensus-beefy", "sp-core", - "sp-genesis-builder", - "sp-inherents", - "sp-io", + "sp-genesis-builder 0.14.0", + "sp-inherents 33.0.0", + "sp-io 37.0.0", "sp-mmr-primitives", "sp-npos-elections", "sp-offchain", - "sp-runtime", + "sp-runtime 38.0.0", "sp-session", - "sp-staking", + "sp-staking 33.0.0", "sp-std", "sp-storage", "sp-transaction-pool", - "sp-version", + "sp-version 36.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -16487,12 +16870,12 @@ version = "15.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8c7a91c27c398b11f7633cc2382cbba53b02e7196ebe8fff13c170e54a54e9d8" dependencies = [ - "frame-support", + "frame-support 36.0.0", "polkadot-primitives", "polkadot-runtime-common", "smallvec", "sp-core", - "sp-runtime", + "sp-runtime 38.0.0", "sp-weights", "staging-xcm", "staging-xcm-builder", @@ -16902,8 +17285,8 @@ dependencies = [ "cumulus-primitives-core", "cumulus-primitives-parachain-inherent", "cumulus-test-relay-sproof-builder", - "frame-support", - "frame-system", + "frame-support 36.0.0", + "frame-system 36.1.0", "impl-trait-for-tuples", "lazy_static", "log", @@ -16918,8 +17301,8 @@ dependencies = [ "sp-arithmetic", "sp-core", "sp-crypto-hashing", - "sp-io", - "sp-runtime", + "sp-io 37.0.0", + "sp-runtime 38.0.0", "sp-std", "sp-tracing", "staging-xcm", @@ -16944,10 +17327,10 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "30fffcd9128a46abd836c37dd001c2cbe122aeb8904cd7b9bac8358564fb7b56" dependencies = [ - "frame-support", + "frame-support 36.0.0", "parity-scale-codec", "scale-info", - "sp-api", + "sp-api 33.0.0", "sp-std", "sp-weights", "staging-xcm", @@ -16984,6 +17367,12 @@ dependencies = [ "static_assertions", ] +[[package]] +name = "yansi" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" + [[package]] name = "yasna" version = "0.5.2" diff --git a/Cargo.toml b/Cargo.toml index 19d5b011..46739fbe 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,91 +2,109 @@ panic = "unwind" [profile.production] +codegen-units = 1 inherits = "release" lto = true -codegen-units = 1 [workspace.package] authors = ["R0GUE "] +description = "Pop Network makes it easy for smart contract developers to use the Power of Polkadot." edition = "2021" homepage = "https://r0gue.io" license = "Unlicense" repository = "https://github.com/r0gue-io/pop-node/" -description = "Pop Network makes it easy for smart contract developers to use the Power of Polkadot." [workspace] +exclude = ["pop-api", "tests/contracts"] members = [ "node", "runtime/devnet", "runtime/testnet", "integration-tests", + "pallets/*", "primitives", ] -exclude = ["pop-api", "tests/contracts"] resolver = "2" [workspace.dependencies] +clap = { version = "4.4.18", features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ "derive", ] } +futures = "0.3.28" hex-literal = "0.4.1" +impl-trait-for-tuples = "0.2.2" +jsonrpsee = { version = "0.23.2", features = ["server"] } log = { version = "0.4.21", default-features = false } scale-info = { version = "2.11.1", default-features = false, features = [ "derive", ] } -smallvec = "1.11.2" serde = "1.0.197" -clap = { version = "4.4.18", features = ["derive"] } -jsonrpsee = { version = "0.23.2", features = ["server"] } -futures = "0.3.28" serde_json = "1.0.114" -tracing-subscriber = { version = "0.3", default-features = false } +smallvec = "1.11.2" subxt = "0.34.0" subxt-signer = "0.34.0" -tokio = { version = "1.36", features = ["macros", "time", "rt-multi-thread"] } +tokio = { version = "1.36", features = ["macros", "rt-multi-thread", "time"] } +tracing-subscriber = { version = "0.3", default-features = false } # Build substrate-build-script-utils = "11.0.0" substrate-wasm-builder = "23.0.0" +# Experimental pallet-revive dependencies +anyhow = { version = "1.0.81" } +array-bytes = { version = "6.2.2", default-features = false } +assert_matches = { version = "1.5.0" } +bitflags = { version = "1.3.2" } +environmental = { version = "1.1.4", default-features = false } +pallet-contracts = { path = "pallets/contracts", default-features = false } +pallet-contracts-fixtures = { path = "pallets/contracts/fixtures", default-features = false } +pallet-contracts-mock-network = { default-features = false, path = "pallets/contracts/mock-network" } +pallet-contracts-proc-macro = { path = "pallets/contracts/proc-macro", default-features = false } +pallet-contracts-uapi = { path = "pallets/contracts/uapi", default-features = false } +pallet-insecure-randomness-collective-flip = { version = "25.0.0", default-features = false } +pretty_assertions = { version = "1.3.0" } +proc-macro2 = { version = "1.0.64" } +polkavm-derive = "0.9.1" +polkavm-linker = "0.9.2" +parity-wasm = { version = "0.45.0" } +paste = { version = "1.0.15", default-features = false } +rand = { version = "0.8.5", default-features = false } +rand_pcg = { version = "0.3.1" } +wasm-instrument = { version = "0.4", default-features = false } +wasmi = { version = "0.32.3", default-features = false } +wat = { version = "1.0.0" } +sp-tracing = { version = "17.0.0", default-features = false } +syn = { version = "2.0.53" } +quote = { version = "1.0.36" } +tempfile = { version = "3.8.1" } +toml = { version = "0.8.8" } +twox-hash = { version = "1.6.3", default-features = false } + # Local +pallet-api = { path = "pallets/api", default-features = false } +pop-chain-extension = { path = "./extension", default-features = false } pop-runtime-devnet = { path = "runtime/devnet", default-features = true } # default-features=true required for `-p pop-node` builds pop-runtime-testnet = { path = "runtime/testnet", default-features = true } # default-features=true required for `-p pop-node` builds pop-runtime-common = { path = "runtime/common", default-features = false } pop-primitives = { path = "./primitives", default-features = false } # Substrate -sc-basic-authorship = "0.42.0" -sc-chain-spec = "35.0.0" -sc-cli = "0.44.0" -sc-client-api = "35.1.0" -sc-offchain = "37.0.0" -sc-consensus = "0.41.0" -sc-executor = "0.39.0" -sc-network = "0.42.0" -sc-network-sync = "0.41.0" -sc-rpc = "37.0.0" -sc-service = "0.43.0" -sc-sysinfo = "35.0.0" -sc-telemetry = "22.0.0" -sc-tracing = "35.0.0" -sc-transaction-pool = "35.0.0" -sc-transaction-pool-api = "35.0.0" frame-benchmarking = { version = "36.0.0", default-features = false } frame-benchmarking-cli = "40.0.0" frame-executive = { version = "36.0.0", default-features = false } +frame-metadata-hash-extension = { version = "0.4.0", default-features = false } frame-support = { version = "36.0.0", default-features = false } frame-system = { version = "36.1.0", default-features = false } frame-system-benchmarking = { version = "36.0.0", default-features = false } frame-system-rpc-runtime-api = { version = "33.0.0", default-features = false } frame-try-runtime = { version = "0.42.0", default-features = false } -frame-metadata-hash-extension = { version = "0.4.0", default-features = false } +pallet-assets = { version = "37.0.0", default-features = false } pallet-aura = { version = "35.0.0", default-features = false } pallet-authorship = { version = "36.0.0", default-features = false } -pallet-assets = { version = "37.0.0", default-features = false } pallet-balances = { version = "37.0.0", default-features = false } -pallet-contracts = { version = "35.0.0", default-features = false } +# pallet-contracts = { version = "35.0.0", default-features = false } pallet-message-queue = { version = "39.0.0", default-features = false } pallet-multisig = { version = "36.0.0", default-features = false } pallet-nft-fractionalization = { version = "18.0.0", default-features = false } @@ -103,6 +121,22 @@ pallet-transaction-payment-rpc = "38.0.0" pallet-transaction-payment-rpc-runtime-api = { version = "36.0.0", default-features = false } pallet-utility = { version = "36.0.0", default-features = false } prometheus-endpoint = { version = "0.17.0", default-features = false, package = "substrate-prometheus-endpoint" } +sc-basic-authorship = "0.42.0" +sc-chain-spec = "35.0.0" +sc-cli = "0.44.0" +sc-client-api = "35.1.0" +sc-consensus = "0.41.0" +sc-executor = "0.39.0" +sc-network = "0.42.0" +sc-network-sync = "0.41.0" +sc-offchain = "37.0.0" +sc-rpc = "37.0.0" +sc-service = "0.43.0" +sc-sysinfo = "35.0.0" +sc-telemetry = "22.0.0" +sc-tracing = "35.0.0" +sc-transaction-pool = "35.0.0" +sc-transaction-pool-api = "35.0.0" sp-api = { version = "33.0.0", default-features = false } sp-authority-discovery = { version = "33.0.0", default-features = false } sp-block-builder = { version = "33.0.0", default-features = false } @@ -112,28 +146,28 @@ sp-consensus-babe = { version = "0.39.0", default-features = false } sp-consensus-beefy = { version = "20.0.0", default-features = false } sp-consensus-grandpa = { version = "20.0.0", default-features = false } sp-core = { version = "34.0.0", default-features = false } -sp-keystore = "0.40.0" -sp-io = { version = "37.0.0", default-features = false } sp-genesis-builder = { version = "0.14.0", default-features = false } sp-inherents = { version = "33.0.0", default-features = false } +sp-io = { version = "37.0.0", default-features = false } +sp-keystore = "0.40.0" sp-offchain = { version = "33.0.0", default-features = false } sp-runtime = { version = "38.0.0", default-features = false } -sp-timestamp = "33.0.0" -substrate-frame-rpc-system = "36.0.0" sp-session = { version = "34.0.0", default-features = false } sp-std = { version = "14.0.0", default-features = false } +sp-timestamp = "33.0.0" sp-transaction-pool = { version = "33.0.0", default-features = false } sp-version = { version = "36.0.0", default-features = false } +substrate-frame-rpc-system = "36.0.0" # Polkadot pallet-xcm = { version = "15.0.0", default-features = false } polkadot-cli = "15.0.0" polkadot-parachain-primitives = { version = "13.0.0", default-features = false } -polkadot-runtime-parachains = { version = "15.0.3", default-features = false } polkadot-primitives = { version = "14.0.0", default-features = false } polkadot-runtime-common = { version = "15.0.0", default-features = false } -rococo-runtime-constants = { version = "15.0.0", default-features = false } +polkadot-runtime-parachains = { version = "15.0.3", default-features = false } rococo-runtime = { version = "15.0.0", default-features = false } +rococo-runtime-constants = { version = "15.0.0", default-features = false } xcm = { version = "14.0.3", package = "staging-xcm", default-features = false } xcm-builder = { version = "15.0.0", package = "staging-xcm-builder", default-features = false } xcm-executor = { version = "15.0.0", package = "staging-xcm-executor", default-features = false } @@ -141,6 +175,13 @@ xcm-executor = { version = "15.0.0", package = "staging-xcm-executor", default-f # Cumulus asset-hub-rococo-runtime = { version = "0.19.0", default-features = false } asset-test-utils = { version = "15.0.0", default-features = false } +color-print = "0.3.4" +cumulus-client-cli = "0.15.0" +cumulus-client-collator = "0.15.0" +cumulus-client-consensus-aura = "0.15.0" +cumulus-client-consensus-common = "0.15.0" +cumulus-client-consensus-proposer = "0.14.0" +cumulus-client-service = "0.15.0" cumulus-pallet-aura-ext = { version = "0.15.0", default-features = false } cumulus-pallet-parachain-system = { version = "0.15.0", default-features = false } cumulus-pallet-session-benchmarking = { version = "17.0.0", default-features = false } @@ -148,21 +189,14 @@ cumulus-pallet-xcm = { version = "0.15.0", default-features = false } cumulus-pallet-xcmp-queue = { version = "0.15.0", default-features = false } cumulus-primitives-aura = { version = "0.14.0", default-features = false } cumulus-primitives-core = { version = "0.14.0", default-features = false } +cumulus-primitives-parachain-inherent = "0.14.0" cumulus-primitives-storage-weight-reclaim = { version = "6.0.2", default-features = false } cumulus-primitives-utility = { version = "0.15.0", default-features = false } +cumulus-relay-chain-interface = "0.15.0" emulated-integration-tests-common = { version = "11.0.0", default-features = false } pallet-collator-selection = { version = "17.0.0", default-features = false } -parachains-common = { version = "15.0.0", default-features = false } parachain-info = { version = "0.15.0", package = "staging-parachain-info", default-features = false } -cumulus-primitives-parachain-inherent = "0.14.0" -cumulus-relay-chain-interface = "0.15.0" -color-print = "0.3.4" -cumulus-client-cli = "0.15.0" -cumulus-client-collator = "0.15.0" -cumulus-client-consensus-aura = "0.15.0" -cumulus-client-consensus-common = "0.15.0" -cumulus-client-consensus-proposer = "0.14.0" -cumulus-client-service = "0.15.0" +parachains-common = { version = "15.0.0", default-features = false } # TODO: Paseo (note: using polkadot as stopgap until paseo updated to polkadot sdk v1.14.0) asset-hub-paseo-runtime = { git = "https://github.com/polkadot-fellows/runtimes", default-features = false, package = "asset-hub-polkadot-runtime" } diff --git a/extension/Cargo.toml b/extension/Cargo.toml new file mode 100644 index 00000000..960febb3 --- /dev/null +++ b/extension/Cargo.toml @@ -0,0 +1,48 @@ +[package] +name = "pop-chain-extension" +version = "0.1.0" +authors.workspace = true +description.workspace = true +license.workspace = true +homepage.workspace = true +repository.workspace = true +edition.workspace = true +publish = false + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +codec.workspace = true +impl-trait-for-tuples.workspace = true +log.workspace = true + +# Substrate +frame-support.workspace = true +frame-system.workspace = true +pallet-contracts.workspace = true +sp-core.workspace = true +sp-runtime.workspace = true +sp-std.workspace = true + +[dev-dependencies] +rand = "0.8.5" + +[features] +default = ["std"] +std = [ + "log/std", + "codec/std", + "frame-support/std", + "frame-system/std", + "pallet-contracts/std", + "sp-runtime/std", + "sp-core/std", + "sp-std/std", +] +runtime-benchmarks = [ + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-contracts/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", +] diff --git a/extension/src/decoding.rs b/extension/src/decoding.rs new file mode 100644 index 00000000..eb9e21b5 --- /dev/null +++ b/extension/src/decoding.rs @@ -0,0 +1,53 @@ +use super::*; +use pallet_contracts::chain_extension::BufIn; +use pallet_contracts::WeightInfo; +use sp_runtime::DispatchError; +use sp_std::vec::Vec; + +/// Trait for decoding data read from contract memory. +pub trait Decode { + /// The output type to be decoded. + type Output: codec::Decode; + /// An optional processor, for performing any additional processing on data read from the contract before decoding. + type Processor: Processor>; + /// The error to return if decoding fails. + type Error: Get; + + /// The log target. + const LOG_TARGET: &'static str; + + /// Decodes data read from contract memory. + /// + /// # Parameters + /// - `env` - The current execution environment. + fn decode(env: &mut Environment) -> Result { + // Charge appropriate weight, based on input length, prior to decoding. + // reference: https://github.com/paritytech/polkadot-sdk/blob/117a9433dac88d5ac00c058c9b39c511d47749d2/substrate/frame/contracts/src/wasm/runtime.rs#L267 + let len = env.in_len(); + let weight = ::WeightInfo::seal_return(len); + env.charge_weight(weight)?; + log::debug!(target: Self::LOG_TARGET, "pre-decode weight charged: len={len}, weight={weight}"); + // Read encoded input supplied by contract for buffer. + let mut input = env.read(len)?; + log::debug!(target: Self::LOG_TARGET, "input read: input={input:?}"); + // Perform any additional processing required. Any implementation is expected to charge weight as appropriate. + input = Self::Processor::process(input, env); + // Finally decode and return. + Self::Output::decode(&mut &input[..]).map_err(|_| Self::Error::get()) + } +} + +/// Default implementation for decoding data read from contract memory. +pub struct Decodes(PhantomData<(O, E, P, L)>); +impl< + Output: codec::Decode, + Error: Get, + ValueProcessor: Processor>, + Logger: LogTarget, + > Decode for Decodes +{ + type Output = Output; + type Processor = ValueProcessor; + type Error = Error; + const LOG_TARGET: &'static str = Logger::LOG_TARGET; +} diff --git a/extension/src/functions.rs b/extension/src/functions.rs new file mode 100644 index 00000000..8c859d35 --- /dev/null +++ b/extension/src/functions.rs @@ -0,0 +1,158 @@ +use super::*; +use core::fmt::Debug; +pub use decoding::{Decode, Decodes}; +pub use matching::{Equals, FunctionId, Matches}; +use pallet_contracts::chain_extension::{BufIn, BufOut}; +use pallet_contracts::WeightInfo; + +/// A chain extension function. +pub trait Function { + /// The configuration of the contracts module. + type Config: pallet_contracts::Config; + + /// Executes the function. + /// + /// # Parameters + /// - `env` - The current execution environment. + fn execute, S: BufIn + BufOut>( + env: &mut Environment, + ) -> Result; +} + +#[impl_trait_for_tuples::impl_for_tuples(1, 3)] +#[tuple_types_custom_trait_bound(Function + Matches)] +impl Function for Tuple { + for_tuples!( where #( Tuple: Function )* ); + type Config = Runtime; + fn execute, S: BufIn + BufOut>( + env: &mut Environment, + ) -> Result { + // Attempts to match a specified extension/function identifier to its corresponding function, as configured by the runtime. + for_tuples!( #( + if Tuple::matches(&env) { + return Tuple::execute(env) + } + )* ); + + // Otherwise returns error indicating an unmatched request. + Err(pallet_contracts::Error::::DecodingFailed.into()) + } +} + +/// A function for dispatching a runtime call. +pub struct DispatchCall(PhantomData<(C, D, M, F, L)>); +impl< + Config: pallet_contracts::Config + + frame_system::Config< + RuntimeCall: GetDispatchInfo + Dispatchable, + >, + Decoder: Decode::RuntimeCall>>, + Matcher: Matches, + Filter: Contains<::RuntimeCall> + 'static, + Logger: LogTarget, + > Function for DispatchCall +{ + /// The configuration of the contracts module. + type Config = Config; + + /// Executes the function. + /// + /// # Parameters + /// - `env` - The current execution environment. + fn execute, S: BufIn + BufOut>( + env: &mut Environment, + ) -> Result { + // Decode runtime call. + let call = Decoder::decode(env)?.into(); + log::debug!(target: Logger::LOG_TARGET, "decoded: call={call:?}"); + // Charge weight before dispatch. + let dispatch_info = call.get_dispatch_info(); + log::debug!(target: Logger::LOG_TARGET, "pre-dispatch info: dispatch_info={dispatch_info:?}"); + let charged = env.charge_weight(dispatch_info.weight)?; + log::debug!(target: Logger::LOG_TARGET, "pre-dispatch weight charged: charged={charged:?}"); + // Contract is the origin by default. + let origin = RawOrigin::Signed(env.ext().address().clone()); + log::debug!(target: Logger::LOG_TARGET, "contract origin: origin={origin:?}"); + let mut origin: Config::RuntimeOrigin = origin.into(); + // Ensure call allowed. + origin.add_filter(Filter::contains); + // Dispatch call. + let result = call.dispatch(origin); + log::debug!(target: Logger::LOG_TARGET, "dispatched: result={result:?}"); + // Adjust weight. + let weight = frame_support::dispatch::extract_actual_weight(&result, &dispatch_info); + env.adjust_weight(charged, weight); + log::debug!(target: Logger::LOG_TARGET, "weight adjusted: weight={weight:?}"); + result.map(|_| Converging(0)).map_err(|e| e.error) + } +} + +impl Matches for DispatchCall { + fn matches(env: &Environment) -> bool { + M::matches(env) + } +} + +/// A function for reading runtime state. +pub struct ReadState::Result>, L = ()>( + PhantomData<(C, R, D, M, F, RC, L)>, +); +impl< + Config: pallet_contracts::Config, + Read: Readable + Debug, + Decoder: Decode>, + Matcher: Matches, + Filter: Contains, + ResultConverter: Converter>>, + Logger: LogTarget, + > Function for ReadState +{ + /// The configuration of the contracts module. + type Config = Config; + + /// Executes the function. + /// + /// # Parameters + /// - `env` - The current execution environment. + fn execute, S: BufIn + BufOut>( + env: &mut Environment, + ) -> Result { + // Decode runtime read + let read = Decoder::decode(env)?.into(); + log::debug!(target: Logger::LOG_TARGET, "decoded: read={read:?}"); + // Charge weight before read + let charged = env.charge_weight(read.weight())?; + log::trace!(target: Logger::LOG_TARGET, "pre-read weight charged: charged={charged:?}"); + // Ensure read allowed + ensure!(Filter::contains(&read), frame_system::Error::::CallFiltered); + let result = read.read(); + log::debug!(target: Logger::LOG_TARGET, "read: result={result:?}"); + // Perform any final conversion. Any implementation is expected to charge weight as appropriate. + let result = ResultConverter::convert(result, env).into(); + // To be conservative, we charge the weight for reading the input bytes of a fixed-size type. + let base_weight: Weight = Config::WeightInfo::seal_return(env.in_len()); + env.write(&result, false, Some(base_weight))?; + Ok(Converging(0)) + } +} + +impl Matches for ReadState { + fn matches(env: &Environment) -> bool { + M::matches(env) + } +} + +/// A default converter, for converting (encoding) from some type into a byte array. +pub struct DefaultConverter(PhantomData); +impl>> Converter for DefaultConverter { + type Source = T; + type Target = Vec; + const LOG_TARGET: &'static str = ""; + + fn convert( + value: Self::Source, + _env: &mut Environment, + ) -> Self::Target { + value.into() + } +} diff --git a/extension/src/lib.rs b/extension/src/lib.rs new file mode 100644 index 00000000..fc3127ca --- /dev/null +++ b/extension/src/lib.rs @@ -0,0 +1,160 @@ +#![cfg_attr(not(feature = "std"), no_std)] + +use codec::Decode as _; +use core::{fmt::Debug, marker::PhantomData}; +use frame_support::{ + dispatch::{GetDispatchInfo, PostDispatchInfo, RawOrigin}, + ensure, + traits::{Contains, OriginTrait}, + weights::Weight, +}; +pub use functions::{ + Decode, Decodes, DispatchCall, Equals, Function, FunctionId, Matches, ReadState, +}; +use pallet_contracts::chain_extension::{ChainExtension, InitState, RetVal::Converging}; +pub use pallet_contracts::chain_extension::{Environment, Ext, Result, RetVal, State}; +use pallet_contracts::WeightInfo; +use sp_core::Get; +use sp_runtime::{traits::Dispatchable, DispatchError}; +use sp_std::vec::Vec; + +mod decoding; +mod functions; +mod matching; +#[cfg(test)] +mod tests; + +/// A configurable chain extension. +#[derive(Default)] +pub struct Extension(PhantomData); +impl ChainExtension for Extension +where + Runtime: pallet_contracts::Config + + frame_system::Config< + RuntimeCall: GetDispatchInfo + Dispatchable, + >, + Config: self::Config> + 'static, +{ + /// Call the chain extension logic. + /// + /// # Parameters + /// - `env`: Access to the remaining arguments and the execution environment. + fn call>(&mut self, env: Environment) -> Result { + log::trace!(target: Config::LOG_TARGET, "extension called"); + let mut env = env.buf_in_buf_out(); + // debug_message weight is a good approximation of the additional overhead of going + // from contract layer to substrate layer. + // reference: https://github.com/paritytech/ink-examples/blob/b8d2caa52cf4691e0ddd7c919e4462311deb5ad0/psp22-extension/runtime/psp22-extension-example.rs#L236 + // TODO: Temporary value for testing purpose + let overhead: Weight = Runtime::WeightInfo::seal_random(); + env.charge_weight(overhead)?; + // Execute the function + match Config::Functions::execute(&mut env) { + Ok(r) => Ok(r), + Err(e) => Config::Error::convert(e, env), + } + } +} + +/// Trait for configuration of the chain extension. +pub trait Config { + /// The function(s) available with the chain extension. + type Functions: Function; + /// Optional error conversion. + type Error: ErrorConverter; + + /// The log target. + const LOG_TARGET: &'static str; +} + +/// Trait to be implemented for a type handling a read of runtime state. +pub trait Readable { + /// The corresponding type carrying the result of the runtime state read. + type Result: Debug; + + /// Determines the weight of the read, used to charge the appropriate weight before the read is performed. + fn weight(&self) -> Weight; + + /// Performs the read and returns the result. + fn read(self) -> Self::Result; +} + +/// Trait to enable specification of a log target. +pub trait LogTarget { + /// The log target. + const LOG_TARGET: &'static str; +} + +impl LogTarget for () { + const LOG_TARGET: &'static str = "pop-chain-extension"; +} + +/// Trait for error conversion. +pub trait ErrorConverter { + /// The log target. + const LOG_TARGET: &'static str; + + /// Converts the provided error. + /// + /// # Parameters + /// - `error` - The error to be converted. + /// - `env` - The current execution environment. + fn convert(error: DispatchError, env: Environment) -> Result; +} + +impl ErrorConverter for () { + const LOG_TARGET: &'static str = "pop-chain-extension::converters::error"; + + fn convert(error: DispatchError, _env: Environment) -> Result { + Err(error) + } +} + +/// Error to be returned when decoding fails. +pub struct DecodingFailed(PhantomData); +impl Get for DecodingFailed { + fn get() -> DispatchError { + pallet_contracts::Error::::DecodingFailed.into() + } +} + +/// Trait for processing a value based on additional information available from the environment. +pub trait Processor { + /// The type of value to be processed. + type Value; + + /// The log target. + const LOG_TARGET: &'static str; + + /// Processes the provided value. + /// + /// # Parameters + /// - `value` - The value to be processed. + /// - `env` - The current execution environment. + fn process(value: Self::Value, env: &mut Environment) -> Self::Value; +} + +impl Processor for () { + type Value = (); + const LOG_TARGET: &'static str = ""; + fn process(value: Self::Value, _env: &mut Environment) -> Self::Value { + value + } +} + +/// Trait for converting a value based on additional information available from the environment. +pub trait Converter { + /// The type of value to be converted. + type Source; + /// The target type. + type Target; + /// The log target. + const LOG_TARGET: &'static str; + + /// Converts the provided value. + /// + /// # Parameters + /// - `value` - The value to be converted. + /// - `env` - The current execution environment. + fn convert(value: Self::Source, env: &mut Environment) -> Self::Target; +} diff --git a/extension/src/matching.rs b/extension/src/matching.rs new file mode 100644 index 00000000..3b3aa6f4 --- /dev/null +++ b/extension/src/matching.rs @@ -0,0 +1,26 @@ +use super::*; + +/// Trait for matching a function. +pub trait Matches { + /// Determines whether a function is a match. + /// + /// # Parameters + /// - `env` - The current execution environment. + fn matches(env: &Environment) -> bool; +} + +/// Matches on an extension and function identifier. +pub struct Equals(PhantomData<(E, F)>); +impl, FuncId: Get> Matches for Equals { + fn matches(env: &Environment) -> bool { + env.ext_id() == ExtId::get() && env.func_id() == FuncId::get() + } +} + +/// Matches on a function identifier only. +pub struct FunctionId(PhantomData); +impl> Matches for FunctionId { + fn matches(env: &Environment) -> bool { + env.func_id() == T::get() + } +} diff --git a/extension/src/tests.rs b/extension/src/tests.rs new file mode 100644 index 00000000..a47feef9 --- /dev/null +++ b/extension/src/tests.rs @@ -0,0 +1,135 @@ +use codec::{Decode, Encode}; + +// Test ensuring `func_id()` and `ext_id()` work as expected, i.e. extracting the first two +// bytes and the last two bytes, respectively, from a 4 byte array. +#[test] +fn test_byte_extraction() { + use rand::Rng; + + // Helper functions + fn func_id(id: u32) -> u16 { + (id & 0x0000FFFF) as u16 + } + fn ext_id(id: u32) -> u16 { + (id >> 16) as u16 + } + + // Number of test iterations + let test_iterations = 1_000_000; + + // Create a random number generator + let mut rng = rand::thread_rng(); + + // Run the test for a large number of random 4-byte arrays + for _ in 0..test_iterations { + // Generate a random 4-byte array + let bytes: [u8; 4] = rng.gen(); + + // Convert the 4-byte array to a u32 value + let value = u32::from_le_bytes(bytes); + + // Extract the first two bytes (least significant 2 bytes) + let first_two_bytes = func_id(value); + + // Extract the last two bytes (most significant 2 bytes) + let last_two_bytes = ext_id(value); + + // Check if the first two bytes match the expected value + assert_eq!([bytes[0], bytes[1]], first_two_bytes.to_le_bytes()); + + // Check if the last two bytes match the expected value + assert_eq!([bytes[2], bytes[3]], last_two_bytes.to_le_bytes()); + } +} + +// Test showing all the different type of variants and its encoding. +#[test] +fn encoding_of_enum() { + #[derive(Debug, PartialEq, Encode, Decode)] + enum ComprehensiveEnum { + SimpleVariant, + DataVariant(u8), + NamedFields { w: u8 }, + NestedEnum(InnerEnum), + OptionVariant(Option), + VecVariant(Vec), + TupleVariant(u8, u8), + NestedStructVariant(NestedStruct), + NestedEnumStructVariant(NestedEnumStruct), + } + + #[derive(Debug, PartialEq, Encode, Decode)] + enum InnerEnum { + A, + B { inner_data: u8 }, + C(u8), + } + + #[derive(Debug, PartialEq, Encode, Decode)] + struct NestedStruct { + x: u8, + y: u8, + } + + #[derive(Debug, PartialEq, Encode, Decode)] + struct NestedEnumStruct { + inner_enum: InnerEnum, + } + + // Creating each possible variant for an enum. + let enum_simple = ComprehensiveEnum::SimpleVariant; + let enum_data = ComprehensiveEnum::DataVariant(42); + let enum_named = ComprehensiveEnum::NamedFields { w: 42 }; + let enum_nested = ComprehensiveEnum::NestedEnum(InnerEnum::B { inner_data: 42 }); + let enum_option = ComprehensiveEnum::OptionVariant(Some(42)); + let enum_vec = ComprehensiveEnum::VecVariant(vec![1, 2, 3, 4, 5]); + let enum_tuple = ComprehensiveEnum::TupleVariant(42, 42); + let enum_nested_struct = ComprehensiveEnum::NestedStructVariant(NestedStruct { x: 42, y: 42 }); + let enum_nested_enum_struct = ComprehensiveEnum::NestedEnumStructVariant(NestedEnumStruct { + inner_enum: InnerEnum::C(42), + }); + + // Encode and print each variant individually to see their encoded values. + println!("{:?} -> {:?}", enum_simple, enum_simple.encode()); + println!("{:?} -> {:?}", enum_data, enum_data.encode()); + println!("{:?} -> {:?}", enum_named, enum_named.encode()); + println!("{:?} -> {:?}", enum_nested, enum_nested.encode()); + println!("{:?} -> {:?}", enum_option, enum_option.encode()); + println!("{:?} -> {:?}", enum_vec, enum_vec.encode()); + println!("{:?} -> {:?}", enum_tuple, enum_tuple.encode()); + println!("{:?} -> {:?}", enum_nested_struct, enum_nested_struct.encode()); + println!("{:?} -> {:?}", enum_nested_enum_struct, enum_nested_enum_struct.encode()); +} + +#[test] +fn encoding_decoding_dispatch_error() { + use sp_runtime::{ArithmeticError, DispatchError, ModuleError, TokenError}; + + let error = DispatchError::Module(ModuleError { + index: 255, + error: [2, 0, 0, 0], + message: Some("error message"), + }); + let encoded = error.encode(); + let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); + assert_eq!(encoded, vec![3, 255, 2, 0, 0, 0]); + assert_eq!( + decoded, + // `message` is skipped for encoding. + DispatchError::Module(ModuleError { index: 255, error: [2, 0, 0, 0], message: None }) + ); + + // Example DispatchError::Token + let error = DispatchError::Token(TokenError::UnknownAsset); + let encoded = error.encode(); + let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); + assert_eq!(encoded, vec![7, 4]); + assert_eq!(decoded, error); + + // Example DispatchError::Arithmetic + let error = DispatchError::Arithmetic(ArithmeticError::Overflow); + let encoded = error.encode(); + let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); + assert_eq!(encoded, vec![8, 1]); + assert_eq!(decoded, error); +} diff --git a/pallets/api/Cargo.toml b/pallets/api/Cargo.toml new file mode 100644 index 00000000..32085c5c --- /dev/null +++ b/pallets/api/Cargo.toml @@ -0,0 +1,59 @@ +[package] +name = "pallet-api" +authors.workspace = true +description = "API pallet, enabling smart(er) contracts with the power of Polkadot" +edition.workspace = true +license.workspace = true +version = "0.1.0" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +codec.workspace = true +log.workspace = true +scale-info.workspace = true + +# Local +pop-chain-extension.workspace = true + +# Substrate +frame-benchmarking.workspace = true +frame-support.workspace = true +frame-system.workspace = true +pallet-assets.workspace = true +sp-runtime.workspace = true +sp-std.workspace = true + +[dev-dependencies] +pallet-balances.workspace = true +sp-core.workspace = true +sp-io.workspace = true + +[features] +default = ["std"] +runtime-benchmarks = [ + "frame-benchmarking/runtime-benchmarks", + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-assets/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", +] +std = [ + "codec/std", + "frame-benchmarking/std", + "frame-support/std", + "frame-system/std", + "pallet-assets/std", + "pallet-balances/std", + "scale-info/std", + "sp-core/std", + "sp-io/std", + "sp-runtime/std", + "sp-std/std", +] +try-runtime = [ + "frame-support/try-runtime", + "frame-system/try-runtime", + "sp-runtime/try-runtime", +] diff --git a/pallets/api/src/extension.rs b/pallets/api/src/extension.rs new file mode 100644 index 00000000..b65a7056 --- /dev/null +++ b/pallets/api/src/extension.rs @@ -0,0 +1,121 @@ +use core::{fmt::Debug, marker::PhantomData}; +use frame_support::traits::Get; +pub use pop_chain_extension::{Config, DecodingFailed, DispatchCall, ReadState, Readable}; +use pop_chain_extension::{ + Converter, Decodes, Environment, Ext, LogTarget, Matches, Processor, Result, RetVal, State, +}; +use sp_runtime::DispatchError; +use sp_std::vec::Vec; + +/// The logging target for the chain extension. +pub const LOG_TARGET: &str = "pop-api::extension"; + +/// The chain extension used by the API. +pub type Extension = pop_chain_extension::Extension; +/// Decodes output by prepending bytes from ext_id() + func_id() +pub type DecodesAs = Decodes; + +/// Prepends bytes from ext_id() + func_id() to prefix the encoded input bytes to determine the versioned output +pub struct Prepender; +impl Processor for Prepender { + /// The type of value to be processed. + type Value = Vec; + + /// The log target. + const LOG_TARGET: &'static str = "pop-api::extension::processor"; + + /// Processes the provided value. + /// + /// # Parameters + /// - `value` - The value to be processed. + /// - `env` - The current execution environment. + fn process( + mut value: Self::Value, + env: &mut Environment, + ) -> Self::Value { + // TODO: revisit the ordering based on specced standard + // Resolve version, pallet and call index from environment + let version = env.func_id().to_le_bytes()[0]; + let (pallet_index, call_index) = { + let bytes = env.ext_id().to_le_bytes(); + (bytes[0], bytes[1]) + }; + // Prepend bytes + value.insert(0, version); + value.insert(1, pallet_index); + value.insert(2, call_index); + log::debug!(target: Self::LOG_TARGET, "prepender: version={version}, module={pallet_index}, call={call_index}"); + value + } +} + +/// Matches on the first byte of a function identifier only. +pub struct IdentifiedByFirstByteOfFunctionId(PhantomData); +impl> Matches for IdentifiedByFirstByteOfFunctionId { + fn matches(env: &Environment) -> bool { + let bytes = env.func_id().to_le_bytes(); + bytes[1] == T::get() + } +} + +/// A log target for dispatched calls. +pub struct DispatchCallLogTarget; +impl LogTarget for DispatchCallLogTarget { + const LOG_TARGET: &'static str = "pop-api::extension::dispatch"; +} + +/// A log target for state reads. +pub struct ReadStateLogTarget; +impl LogTarget for ReadStateLogTarget { + const LOG_TARGET: &'static str = "pop-api::extension::read-state"; +} + +/// Conversion of a `DispatchError` to a versioned error. +pub struct VersionedErrorConverter(PhantomData); +impl + Into + Debug> pop_chain_extension::ErrorConverter + for VersionedErrorConverter +{ + /// The log target. + const LOG_TARGET: &'static str = "pop-api::extension::converters::versioned-error"; + + /// Converts the provided error. + /// + /// # Parameters + /// - `error` - The error to be converted. + /// - `env` - The current execution environment. + fn convert(error: DispatchError, env: Environment) -> Result { + // Defer to supplied versioned error conversion type + let version = env.func_id().to_le_bytes()[0]; + log::debug!(target: Self::LOG_TARGET, "versioned error converter: error={error:?}, version={version}"); + let error: Error = (error, version).into(); + log::debug!(target: Self::LOG_TARGET, "versioned error converter: converted error={error:?}"); + Ok(RetVal::Converging(error.into())) + } +} + +/// Conversion of a read result to a versioned read result. +pub struct VersionedResultConverter(PhantomData<(S, T)>); +impl + Debug> Converter + for VersionedResultConverter +{ + /// The type of value to be converted. + type Source = Source; + /// The target type. + type Target = Target; + /// The log target. + const LOG_TARGET: &'static str = "pop-api::extension::converters::versioned-result"; + + /// Converts the provided value. + /// + /// # Parameters + /// - `value` - The value to be converted. + /// - `env` - The current execution environment. + fn convert(value: Self::Source, env: &mut Environment) -> Self::Target { + // Defer to supplied versioned result conversion type + let version = env.func_id().to_le_bytes()[0]; + log::debug!(target: Self::LOG_TARGET, "versioned result converter: result={value:?}, version={version}"); + let converted: Target = (value, version).into(); + log::debug!(target: Self::LOG_TARGET, "versioned result converter: converted result={converted:?}"); + converted.into() + } +} diff --git a/pallets/api/src/fungibles/benchmarking.rs b/pallets/api/src/fungibles/benchmarking.rs new file mode 100644 index 00000000..d3d65b97 --- /dev/null +++ b/pallets/api/src/fungibles/benchmarking.rs @@ -0,0 +1,106 @@ +//! Benchmarking setup for pallet-api::fungibles + +use super::{AccountIdOf, AssetIdOf, AssetsInstanceOf, AssetsOf, BalanceOf, Call, Config, Pallet}; +use frame_benchmarking::{account, v2::*}; +use frame_support::{ + assert_ok, + traits::{ + fungibles::{ + approvals::{Inspect as ApprovalInspect, Mutate}, + Create, Inspect, + }, + Currency, + }, +}; +use frame_system::RawOrigin; +use sp_runtime::traits::Zero; + +const SEED: u32 = 1; + +// See if `generic_event` has been emitted. +fn assert_has_event( + generic_event: >>::RuntimeEvent, +) { + frame_system::Pallet::::assert_has_event(generic_event.into()); +} + +#[benchmarks( + where + > as Inspect<::AccountId>>::AssetId: Zero, +)] +mod benchmarks { + use super::*; + + // Parameter: + // - 'a': whether `approve_transfer` is required. + // - 'c': whether `cancel_approval` is required. + #[benchmark] + fn approve(a: Linear<0, 1>, c: Linear<0, 1>) -> Result<(), BenchmarkError> { + let asset_id = AssetIdOf::::zero(); + let min_balance = >::from(1u32); + let owner: AccountIdOf = account("Alice", 0, SEED); + let spender: AccountIdOf = account("Bob", 0, SEED); + let current_allowance = >::from(u32::MAX / 2); + T::Currency::make_free_balance_be(&owner, u32::MAX.into()); + // Set the `current_allowance`. + assert_ok!( as Create>>::create( + asset_id.clone(), + owner.clone(), + true, + min_balance + )); + assert_ok!( as Mutate>>::approve( + asset_id.clone(), + &owner, + &spender, + current_allowance, + )); + let approval_value = match (a, c) { + // Equal to the current allowance. + (0, 0) => current_allowance, + // Greater than the current allowance. + (1, 0) => >::from(u32::MAX), + // Zero. + (0, 1) => >::from(0u32), + // Smaller than the current allowance. + (1, 1) => >::from(u32::MAX / 4), + _ => unreachable!("values can only be 0 or 1"), + }; + + #[extrinsic_call] + _(RawOrigin::Signed(owner.clone()), asset_id.clone(), spender.clone(), approval_value); + + assert_eq!(AssetsOf::::allowance(asset_id.clone(), &owner, &spender), approval_value); + if c == 1 { + assert_has_event::( + pallet_assets::Event::ApprovalCancelled { + asset_id: asset_id.clone(), + owner: owner.clone(), + delegate: spender.clone(), + } + .into(), + ); + } + if a == 1 { + let amount = match c { + // When the allowance was cancelled and then approved with the new value. + 1 => approval_value, + // When the allowance was increased. + 0 => approval_value - current_allowance, + _ => unreachable!("`c` can only be 0 or 1"), + }; + assert_has_event::( + pallet_assets::Event::ApprovedTransfer { + asset_id, + source: owner, + delegate: spender, + amount, + } + .into(), + ); + } + Ok(()) + } + + impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Test); +} diff --git a/pallets/api/src/fungibles/mod.rs b/pallets/api/src/fungibles/mod.rs new file mode 100644 index 00000000..24c8b342 --- /dev/null +++ b/pallets/api/src/fungibles/mod.rs @@ -0,0 +1,551 @@ +//! The fungibles pallet offers a streamlined interface for interacting with fungible assets. The +//! goal is to provide a simplified, consistent API that adheres to standards in the smart contract +//! space. + +use frame_support::traits::fungibles::{metadata::Inspect as MetadataInspect, Inspect}; +pub use pallet::*; +use pallet_assets::WeightInfo as AssetsWeightInfoTrait; +use weights::WeightInfo; + +#[cfg(feature = "runtime-benchmarks")] +mod benchmarking; +#[cfg(test)] +mod tests; +pub mod weights; + +type AccountIdOf = ::AccountId; +type AssetIdOf = > as Inspect< + ::AccountId, +>>::AssetId; +type AssetIdParameterOf = >>::AssetIdParameter; +type AssetsOf = pallet_assets::Pallet>; +type AssetsInstanceOf = ::AssetsInstance; +type AssetsWeightInfoOf = >>::WeightInfo; +type BalanceOf = > as Inspect< + ::AccountId, +>>::Balance; + +#[frame_support::pallet] +pub mod pallet { + use super::*; + use core::cmp::Ordering::*; + use frame_support::{ + dispatch::{DispatchResult, DispatchResultWithPostInfo, WithPostDispatchInfo}, + pallet_prelude::*, + traits::fungibles::approvals::Inspect as ApprovalInspect, + }; + use frame_system::pallet_prelude::*; + use sp_runtime::{ + traits::{StaticLookup, Zero}, + Saturating, + }; + use sp_std::vec::Vec; + + /// State reads for the fungibles API with required input. + #[derive(Encode, Decode, Debug, MaxEncodedLen)] + #[repr(u8)] + #[allow(clippy::unnecessary_cast)] + pub enum Read { + /// Total token supply for a specified asset. + #[codec(index = 0)] + TotalSupply(AssetIdOf), + /// Account balance for a specified `asset` and `owner`. + #[codec(index = 1)] + BalanceOf { + /// The asset. + asset: AssetIdOf, + /// The owner of the asset. + owner: AccountIdOf, + }, + /// Allowance for a `spender` approved by an `owner`, for a specified `asset`. + #[codec(index = 2)] + Allowance { + /// The asset. + asset: AssetIdOf, + /// The owner of the asset. + owner: AccountIdOf, + /// The spender with an allowance. + spender: AccountIdOf, + }, + /// Name of the specified asset. + #[codec(index = 8)] + TokenName(AssetIdOf), + /// Symbol for the specified asset. + #[codec(index = 9)] + TokenSymbol(AssetIdOf), + /// Decimals for the specified asset. + #[codec(index = 10)] + TokenDecimals(AssetIdOf), + /// Check if a specified asset exists. + #[codec(index = 18)] + AssetExists(AssetIdOf), + } + + /// Results of state reads for the fungibles API. + #[derive(Debug)] + pub enum ReadResult { + /// Total token supply for a specified asset. + TotalSupply(BalanceOf), + /// Account balance for a specified `asset` and `owner`. + BalanceOf(BalanceOf), + /// Allowance for a `spender` approved by an `owner`, for a specified `asset`. + Allowance(BalanceOf), + /// Name of the specified asset. + TokenName(Vec), + /// Symbol for the specified asset. + TokenSymbol(Vec), + /// Decimals for the specified asset. + TokenDecimals(u8), + /// Whether the specified asset exists. + AssetExists(bool), + } + + impl ReadResult { + /// Encodes the result. + pub fn encode(&self) -> Vec { + use ReadResult::*; + match self { + TotalSupply(result) => result.encode(), + BalanceOf(result) => result.encode(), + Allowance(result) => result.encode(), + TokenName(result) => result.encode(), + TokenSymbol(result) => result.encode(), + TokenDecimals(result) => result.encode(), + AssetExists(result) => result.encode(), + } + } + } + + /// Configure the pallet by specifying the parameters and types on which it depends. + #[pallet::config] + pub trait Config: frame_system::Config + pallet_assets::Config { + /// Because this pallet emits events, it depends on the runtime's definition of an event. + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + /// The instance of pallet assets it is tightly coupled to. + type AssetsInstance; + /// Weight information for dispatchables in this pallet. + type WeightInfo: WeightInfo; + } + + #[pallet::pallet] + pub struct Pallet(_); + + /// The events that can be emitted. + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + /// Event emitted when allowance by `owner` to `spender` changes. + Approval { + /// The asset. + asset: AssetIdOf, + /// The owner providing the allowance. + owner: AccountIdOf, + /// The beneficiary of the allowance. + spender: AccountIdOf, + /// The new allowance amount. + value: BalanceOf, + }, + /// Event emitted when an asset transfer occurs. + Transfer { + /// The asset. + asset: AssetIdOf, + /// The source of the transfer. `None` when minting. + from: Option>, + /// The recipient of the transfer. `None` when burning. + to: Option>, + /// The amount transferred (or minted/burned). + value: BalanceOf, + }, + /// Event emitted when an asset is created. + Create { + /// The asset identifier. + id: AssetIdOf, + /// The creator of the asset. + creator: AccountIdOf, + /// The administrator of the asset. + admin: AccountIdOf, + }, + } + + #[pallet::call] + impl Pallet { + /// Transfers `value` amount of tokens from the caller's account to account `to`. + /// + /// # Parameters + /// - `asset` - The asset to transfer. + /// - `to` - The recipient account. + /// - `value` - The number of tokens to transfer. + #[pallet::call_index(3)] + #[pallet::weight(AssetsWeightInfoOf::::transfer_keep_alive())] + pub fn transfer( + origin: OriginFor, + asset: AssetIdOf, + to: AccountIdOf, + value: BalanceOf, + ) -> DispatchResult { + let from = ensure_signed(origin.clone())?; + AssetsOf::::transfer_keep_alive( + origin, + asset.clone().into(), + T::Lookup::unlookup(to.clone()), + value, + )?; + Self::deposit_event(Event::Transfer { asset, from: Some(from), to: Some(to), value }); + Ok(()) + } + + /// Transfers `value` amount tokens on behalf of `from` to account `to`. + /// + /// # Parameters + /// - `asset` - The asset to transfer. + /// - `from` - The account from which the asset balance will be withdrawn. + /// - `to` - The recipient account. + /// - `value` - The number of tokens to transfer. + #[pallet::call_index(4)] + #[pallet::weight(AssetsWeightInfoOf::::transfer_approved())] + pub fn transfer_from( + origin: OriginFor, + asset: AssetIdOf, + from: AccountIdOf, + to: AccountIdOf, + value: BalanceOf, + ) -> DispatchResult { + AssetsOf::::transfer_approved( + origin, + asset.clone().into(), + T::Lookup::unlookup(from.clone()), + T::Lookup::unlookup(to.clone()), + value, + )?; + Self::deposit_event(Event::Transfer { asset, from: Some(from), to: Some(to), value }); + Ok(()) + } + + /// Approves `spender` to spend `value` amount of tokens on behalf of the caller. + /// + /// # Parameters + /// - `asset` - The asset to approve. + /// - `spender` - The account that is allowed to spend the tokens. + /// - `value` - The number of tokens to approve. + #[pallet::call_index(5)] + #[pallet::weight(::WeightInfo::approve(1, 1))] + pub fn approve( + origin: OriginFor, + asset: AssetIdOf, + spender: AccountIdOf, + value: BalanceOf, + ) -> DispatchResultWithPostInfo { + let owner = ensure_signed(origin.clone()) + .map_err(|e| e.with_weight(Self::weight_approve(0, 0)))?; + let current_allowance = AssetsOf::::allowance(asset.clone(), &owner, &spender); + + let weight = match value.cmp(¤t_allowance) { + // If the new value is equal to the current allowance, do nothing. + Equal => Self::weight_approve(0, 0), + // If the new value is greater than the current allowance, approve the difference + // because `approve_transfer` works additively (see `pallet-assets`). + Greater => { + AssetsOf::::approve_transfer( + origin, + asset.clone().into(), + T::Lookup::unlookup(spender.clone()), + value.saturating_sub(current_allowance), + ) + .map_err(|e| e.with_weight(Self::weight_approve(1, 0)))?; + Self::weight_approve(1, 0) + }, + // If the new value is less than the current allowance, cancel the approval and + // set the new value. + Less => { + let asset_param: AssetIdParameterOf = asset.clone().into(); + let spender_source = T::Lookup::unlookup(spender.clone()); + AssetsOf::::cancel_approval( + origin.clone(), + asset_param.clone(), + spender_source.clone(), + ) + .map_err(|e| e.with_weight(Self::weight_approve(0, 1)))?; + if value.is_zero() { + Self::weight_approve(0, 1) + } else { + AssetsOf::::approve_transfer( + origin, + asset_param, + spender_source, + value, + )?; + Self::weight_approve(1, 1) + } + }, + }; + Self::deposit_event(Event::Approval { asset, owner, spender, value }); + Ok(Some(weight).into()) + } + + /// Increases the allowance of `spender` by `value` amount of tokens. + /// + /// # Parameters + /// - `asset` - The asset to have an allowance increased. + /// - `spender` - The account that is allowed to spend the tokens. + /// - `value` - The number of tokens to increase the allowance by. + #[pallet::call_index(6)] + #[pallet::weight(::WeightInfo::approve(1, 0))] + pub fn increase_allowance( + origin: OriginFor, + asset: AssetIdOf, + spender: AccountIdOf, + value: BalanceOf, + ) -> DispatchResultWithPostInfo { + let owner = ensure_signed(origin.clone()) + .map_err(|e| e.with_weight(Self::weight_approve(0, 0)))?; + AssetsOf::::approve_transfer( + origin, + asset.clone().into(), + T::Lookup::unlookup(spender.clone()), + value, + ) + .map_err(|e| e.with_weight(AssetsWeightInfoOf::::approve_transfer()))?; + let value = AssetsOf::::allowance(asset.clone(), &owner, &spender); + Self::deposit_event(Event::Approval { asset, owner, spender, value }); + Ok(().into()) + } + + /// Decreases the allowance of a `spender` by `value` amount of tokens. + /// + /// # Parameters + /// - `asset` - The asset to have an allowance decreased. + /// - `spender` - The account that is allowed to spend the tokens. + /// - `value` - The number of tokens to decrease the allowance by. + #[pallet::call_index(7)] + #[pallet::weight(::WeightInfo::approve(1, 1))] + pub fn decrease_allowance( + origin: OriginFor, + asset: AssetIdOf, + spender: AccountIdOf, + value: BalanceOf, + ) -> DispatchResultWithPostInfo { + let owner = ensure_signed(origin.clone()) + .map_err(|e| e.with_weight(Self::weight_approve(0, 0)))?; + if value.is_zero() { + return Ok(Some(Self::weight_approve(0, 0)).into()); + } + let current_allowance = AssetsOf::::allowance(asset.clone(), &owner, &spender); + let spender_source = T::Lookup::unlookup(spender.clone()); + let asset_param: AssetIdParameterOf = asset.clone().into(); + + // Cancel the approval and set the new value if `new_allowance` is more than zero. + AssetsOf::::cancel_approval( + origin.clone(), + asset_param.clone(), + spender_source.clone(), + ) + .map_err(|e| e.with_weight(Self::weight_approve(0, 1)))?; + let new_allowance = current_allowance.saturating_sub(value); + let weight = if new_allowance.is_zero() { + Self::weight_approve(0, 1) + } else { + AssetsOf::::approve_transfer( + origin, + asset_param, + spender_source, + new_allowance, + )?; + Self::weight_approve(1, 1) + }; + Self::deposit_event(Event::Approval { asset, owner, spender, value: new_allowance }); + Ok(Some(weight).into()) + } + + /// Create a new token with a given identifier. + /// + /// # Parameters + /// - `id` - The identifier of the asset. + /// - `admin` - The account that will administer the asset. + /// - `min_balance` - The minimum balance required for accounts holding this asset. + #[pallet::call_index(11)] + #[pallet::weight(AssetsWeightInfoOf::::create())] + pub fn create( + origin: OriginFor, + id: AssetIdOf, + admin: AccountIdOf, + min_balance: BalanceOf, + ) -> DispatchResult { + let creator = ensure_signed(origin.clone())?; + AssetsOf::::create( + origin, + id.clone().into(), + T::Lookup::unlookup(admin.clone()), + min_balance, + )?; + Self::deposit_event(Event::Create { id, creator, admin }); + Ok(()) + } + + /// Start the process of destroying a token. + /// + /// # Parameters + /// - `asset` - The asset to be destroyed. + #[pallet::call_index(12)] + #[pallet::weight(AssetsWeightInfoOf::::start_destroy())] + pub fn start_destroy(origin: OriginFor, asset: AssetIdOf) -> DispatchResult { + AssetsOf::::start_destroy(origin, asset.into()) + } + + /// Set the metadata for a token. + /// + /// # Parameters + /// - `asset`: The asset to update. + /// - `name`: The user friendly name of this asset. + /// - `symbol`: The exchange symbol for this asset. + /// - `decimals`: The number of decimals this asset uses to represent one unit. + #[pallet::call_index(16)] + #[pallet::weight(AssetsWeightInfoOf::::set_metadata(name.len() as u32, symbol.len() as u32))] + pub fn set_metadata( + origin: OriginFor, + asset: AssetIdOf, + name: Vec, + symbol: Vec, + decimals: u8, + ) -> DispatchResult { + AssetsOf::::set_metadata(origin, asset.into(), name, symbol, decimals) + } + + /// Clear the metadata for a token. + /// + /// # Parameters + /// - `asset` - The asset to update. + #[pallet::call_index(17)] + #[pallet::weight(AssetsWeightInfoOf::::clear_metadata())] + pub fn clear_metadata(origin: OriginFor, asset: AssetIdOf) -> DispatchResult { + AssetsOf::::clear_metadata(origin, asset.into()) + } + + /// Creates `value` amount of tokens and assigns them to `account`, increasing the total supply. + /// + /// # Parameters + /// - `asset` - The asset to mint. + /// - `account` - The account to be credited with the created tokens. + /// - `value` - The number of tokens to mint. + #[pallet::call_index(19)] + #[pallet::weight(AssetsWeightInfoOf::::mint())] + pub fn mint( + origin: OriginFor, + asset: AssetIdOf, + account: AccountIdOf, + value: BalanceOf, + ) -> DispatchResult { + AssetsOf::::mint( + origin, + asset.clone().into(), + T::Lookup::unlookup(account.clone()), + value, + )?; + Self::deposit_event(Event::Transfer { asset, from: None, to: Some(account), value }); + Ok(()) + } + + /// Destroys `value` amount of tokens from `account`, reducing the total supply. + /// + /// # Parameters + /// - `asset` - the asset to burn. + /// - `account` - The account from which the tokens will be destroyed. + /// - `value` - The number of tokens to destroy. + #[pallet::call_index(20)] + #[pallet::weight(AssetsWeightInfoOf::::burn())] + pub fn burn( + origin: OriginFor, + asset: AssetIdOf, + account: AccountIdOf, + value: BalanceOf, + ) -> DispatchResult { + AssetsOf::::burn( + origin, + asset.clone().into(), + T::Lookup::unlookup(account.clone()), + value, + )?; + Self::deposit_event(Event::Transfer { asset, from: Some(account), to: None, value }); + Ok(()) + } + } + + impl Pallet { + /// Reads fungible asset state based on the provided value. + /// + /// This function matches the value to determine the type of state query and returns the + /// encoded result. + /// + /// # Parameter + /// - `value` - An instance of `Read`, which specifies the type of state query and + /// the associated parameters. + #[deprecated] + pub fn read_state(value: Read) -> Vec { + use Read::*; + + match value { + TotalSupply(asset) => AssetsOf::::total_supply(asset).encode(), + BalanceOf { asset, owner } => AssetsOf::::balance(asset, owner).encode(), + Allowance { asset, owner, spender } => { + AssetsOf::::allowance(asset, &owner, &spender).encode() + }, + TokenName(asset) => { + as MetadataInspect>>::name(asset).encode() + }, + TokenSymbol(asset) => { + as MetadataInspect>>::symbol(asset).encode() + }, + TokenDecimals(asset) => { + as MetadataInspect>>::decimals(asset).encode() + }, + AssetExists(asset) => AssetsOf::::asset_exists(asset).encode(), + } + } + + fn weight_approve(approve: u32, cancel: u32) -> Weight { + ::WeightInfo::approve(cancel, approve) + } + } + + impl crate::Read for Pallet { + /// The type of read requested. + type Read = Read; + /// The type or result returned. + type Result = ReadResult; + + /// Determines the weight of the requested read, used to charge the appropriate weight before the read is performed. + /// + /// # Parameters + /// - `request` - The read request. + fn weight(_request: &Self::Read) -> Weight { + // TODO: match on request and return benchmarked weight + T::DbWeight::get().reads(1_u64) + } + + /// Performs the requested read and returns the result. + /// + /// # Parameters + /// - `request` - The read request. + fn read(request: Self::Read) -> Self::Result { + use Read::*; + match request { + TotalSupply(asset) => ReadResult::TotalSupply(AssetsOf::::total_supply(asset)), + BalanceOf { asset, owner } => { + ReadResult::BalanceOf(AssetsOf::::balance(asset, owner)) + }, + Allowance { asset, owner, spender } => { + ReadResult::Allowance(AssetsOf::::allowance(asset, &owner, &spender)) + }, + TokenName(asset) => ReadResult::TokenName( as MetadataInspect< + AccountIdOf, + >>::name(asset)), + TokenSymbol(asset) => ReadResult::TokenSymbol( as MetadataInspect< + AccountIdOf, + >>::symbol(asset)), + TokenDecimals(asset) => ReadResult::TokenDecimals( + as MetadataInspect>>::decimals(asset), + ), + AssetExists(asset) => ReadResult::AssetExists(AssetsOf::::asset_exists(asset)), + } + } + } +} diff --git a/pallets/api/src/fungibles/tests.rs b/pallets/api/src/fungibles/tests.rs new file mode 100644 index 00000000..d881a3c1 --- /dev/null +++ b/pallets/api/src/fungibles/tests.rs @@ -0,0 +1,334 @@ +use crate::{fungibles::Read::*, mock::*}; +use codec::Encode; +use frame_support::{ + assert_ok, + sp_runtime::traits::Zero, + traits::fungibles::{ + approvals::Inspect as ApprovalInspect, metadata::Inspect as MetadataInspect, Inspect, + }, +}; + +const ASSET: u32 = 42; + +type Event = crate::fungibles::Event; + +#[test] +fn transfer_works() { + new_test_ext().execute_with(|| { + let value: Balance = 100 * UNIT; + let asset = ASSET; + let from = Some(ALICE); + let to = Some(BOB); + + create_asset_and_mint_to(ALICE, asset, ALICE, value * 2); + let balance_before_transfer = Assets::balance(asset, &BOB); + assert_ok!(Fungibles::transfer(signed(ALICE), asset, BOB, value)); + let balance_after_transfer = Assets::balance(asset, &BOB); + assert_eq!(balance_after_transfer, balance_before_transfer + value); + System::assert_last_event(Event::Transfer { asset, from, to, value }.into()); + }); +} + +#[test] +fn transfer_from_works() { + new_test_ext().execute_with(|| { + let value: Balance = 100 * UNIT; + let asset = ASSET; + let from = Some(ALICE); + let to = Some(BOB); + + // Approve CHARLIE to transfer up to `value` to BOB. + create_asset_mint_and_approve(ALICE, asset, ALICE, value * 2, CHARLIE, value); + // Successfully call transfer from. + let alice_balance_before_transfer = Assets::balance(asset, &ALICE); + let bob_balance_before_transfer = Assets::balance(asset, &BOB); + assert_ok!(Fungibles::transfer_from(signed(CHARLIE), asset, ALICE, BOB, value)); + let alice_balance_after_transfer = Assets::balance(asset, &ALICE); + let bob_balance_after_transfer = Assets::balance(asset, &BOB); + // Check that BOB receives the `value` and ALICE `amount` is spent successfully by CHARLIE. + assert_eq!(bob_balance_after_transfer, bob_balance_before_transfer + value); + assert_eq!(alice_balance_after_transfer, alice_balance_before_transfer - value); + System::assert_last_event(Event::Transfer { asset, from, to, value }.into()); + }); +} + +// Non-additive, sets new value. +#[test] +fn approve_works() { + new_test_ext().execute_with(|| { + let value: Balance = 100 * UNIT; + let asset = ASSET; + let owner = ALICE; + let spender = BOB; + + create_asset_and_mint_to(ALICE, asset, ALICE, value); + assert_eq!(0, Assets::allowance(asset, &ALICE, &BOB)); + assert_ok!(Fungibles::approve(signed(ALICE), asset, BOB, value)); + assert_eq!(Assets::allowance(asset, &ALICE, &BOB), value); + System::assert_last_event(Event::Approval { asset, owner, spender, value }.into()); + // Approves an value to spend that is lower than the current allowance. + assert_ok!(Fungibles::approve(signed(ALICE), asset, BOB, value / 2)); + assert_eq!(Assets::allowance(asset, &ALICE, &BOB), value / 2); + System::assert_last_event( + Event::Approval { asset, owner, spender, value: value / 2 }.into(), + ); + // Approves an value to spend that is higher than the current allowance. + assert_ok!(Fungibles::approve(signed(ALICE), asset, BOB, value * 2)); + assert_eq!(Assets::allowance(asset, &ALICE, &BOB), value * 2); + System::assert_last_event( + Event::Approval { asset, owner, spender, value: value * 2 }.into(), + ); + // Approves an value to spend that is equal to the current allowance. + assert_ok!(Fungibles::approve(signed(ALICE), asset, BOB, value * 2)); + assert_eq!(Assets::allowance(asset, &ALICE, &BOB), value * 2); + System::assert_last_event( + Event::Approval { asset, owner, spender, value: value * 2 }.into(), + ); + // Sets allowance to zero. + assert_ok!(Fungibles::approve(signed(ALICE), asset, BOB, 0)); + assert_eq!(Assets::allowance(asset, &ALICE, &BOB), 0); + System::assert_last_event(Event::Approval { asset, owner, spender, value: 0 }.into()); + }); +} + +#[test] +fn increase_allowance_works() { + new_test_ext().execute_with(|| { + let value: Balance = 100 * UNIT; + let asset = ASSET; + let owner = ALICE; + let spender = BOB; + + create_asset_and_mint_to(ALICE, asset, ALICE, value); + assert_eq!(0, Assets::allowance(asset, &ALICE, &BOB)); + assert_ok!(Fungibles::increase_allowance(signed(ALICE), asset, BOB, value)); + assert_eq!(Assets::allowance(asset, &ALICE, &BOB), value); + System::assert_last_event(Event::Approval { asset, owner, spender, value }.into()); + // Additive. + assert_ok!(Fungibles::increase_allowance(signed(ALICE), asset, BOB, value)); + assert_eq!(Assets::allowance(asset, &ALICE, &BOB), value * 2); + System::assert_last_event( + Event::Approval { asset, owner, spender, value: value * 2 }.into(), + ); + }); +} + +#[test] +fn decrease_allowance_works() { + new_test_ext().execute_with(|| { + let value: Balance = 100 * UNIT; + let asset = ASSET; + let owner = ALICE; + let spender = BOB; + + create_asset_mint_and_approve(ALICE, asset, ALICE, value, BOB, value); + assert_eq!(Assets::allowance(asset, &ALICE, &BOB), value); + // Owner balance is not changed if decreased by zero. + assert_ok!(Fungibles::decrease_allowance(signed(ALICE), asset, BOB, 0)); + assert_eq!(Assets::allowance(asset, &ALICE, &BOB), value); + // Decrease allowance successfully. + assert_ok!(Fungibles::decrease_allowance(signed(ALICE), asset, BOB, value / 2)); + assert_eq!(Assets::allowance(asset, &ALICE, &BOB), value / 2); + System::assert_last_event( + Event::Approval { asset, owner, spender, value: value / 2 }.into(), + ); + // Saturating if current allowance is decreased more than the owner balance. + assert_ok!(Fungibles::decrease_allowance(signed(ALICE), asset, BOB, value)); + assert_eq!(Assets::allowance(asset, &ALICE, &BOB), 0); + System::assert_last_event(Event::Approval { asset, owner, spender, value: 0 }.into()); + }); +} + +#[test] +fn create_works() { + new_test_ext().execute_with(|| { + let id = ASSET; + let creator = ALICE; + let admin = ALICE; + + assert!(!Assets::asset_exists(id)); + assert_ok!(Fungibles::create(signed(creator), id, admin, 100)); + assert!(Assets::asset_exists(id)); + System::assert_last_event(Event::Create { id, creator, admin }.into()); + }); +} + +#[test] +fn start_destroy_works() { + new_test_ext().execute_with(|| { + let asset = ASSET; + + create_asset(ALICE, asset); + assert_ok!(Fungibles::start_destroy(signed(ALICE), asset)); + }); +} + +#[test] +fn set_metadata_works() { + new_test_ext().execute_with(|| { + let asset = ASSET; + let name = vec![42]; + let symbol = vec![42]; + let decimals = 42; + + create_asset(ALICE, asset); + assert_ok!(Fungibles::set_metadata( + signed(ALICE), + asset, + name.clone(), + symbol.clone(), + decimals + )); + assert_eq!(Assets::name(asset), name); + assert_eq!(Assets::symbol(asset), symbol); + assert_eq!(Assets::decimals(asset), decimals); + }); +} + +#[test] +fn clear_metadata_works() { + new_test_ext().execute_with(|| { + let asset = ASSET; + + create_asset_and_set_metadata(ALICE, asset, vec![42], vec![42], 42); + assert_ok!(Fungibles::clear_metadata(signed(ALICE), asset)); + assert!(Assets::name(asset).is_empty()); + assert!(Assets::symbol(asset).is_empty()); + assert!(Assets::decimals(asset).is_zero()); + }); +} + +#[test] +fn mint_works() { + new_test_ext().execute_with(|| { + let value: Balance = 100 * UNIT; + let asset = ASSET; + let from = None; + let to = Some(BOB); + + create_asset(ALICE, asset); + let balance_before_mint = Assets::balance(asset, &BOB); + assert_ok!(Fungibles::mint(signed(ALICE), asset, BOB, value)); + let balance_after_mint = Assets::balance(asset, &BOB); + assert_eq!(balance_after_mint, balance_before_mint + value); + System::assert_last_event(Event::Transfer { asset, from, to, value }.into()); + }); +} + +#[test] +fn burn_works() { + new_test_ext().execute_with(|| { + let value: Balance = 100 * UNIT; + let asset = ASSET; + let from = Some(BOB); + let to = None; + + create_asset_and_mint_to(ALICE, asset, BOB, value); + let balance_before_burn = Assets::balance(asset, &BOB); + assert_ok!(Fungibles::burn(signed(ALICE), asset, BOB, value)); + let balance_after_burn = Assets::balance(asset, &BOB); + assert_eq!(balance_after_burn, balance_before_burn - value); + System::assert_last_event(Event::Transfer { asset, from, to, value }.into()); + }); +} + +#[test] +fn total_supply_works() { + new_test_ext().execute_with(|| { + create_asset_and_mint_to(ALICE, ASSET, ALICE, 100); + assert_eq!(Assets::total_supply(ASSET).encode(), Fungibles::read_state(TotalSupply(ASSET))); + }); +} + +#[test] +fn balance_of_works() { + new_test_ext().execute_with(|| { + create_asset_and_mint_to(ALICE, ASSET, ALICE, 100); + assert_eq!( + Assets::balance(ASSET, ALICE).encode(), + Fungibles::read_state(BalanceOf { asset: ASSET, owner: ALICE }) + ); + }); +} + +#[test] +fn allowance_works() { + new_test_ext().execute_with(|| { + create_asset_mint_and_approve(ALICE, ASSET, BOB, 100, ALICE, 50); + assert_eq!( + Assets::allowance(ASSET, &ALICE, &BOB).encode(), + Fungibles::read_state(Allowance { asset: ASSET, owner: ALICE, spender: BOB }) + ); + }); +} + +#[test] +fn token_metadata_works() { + new_test_ext().execute_with(|| { + let name: Vec = vec![11, 12, 13]; + let symbol: Vec = vec![21, 22, 23]; + let decimals: u8 = 69; + create_asset_and_set_metadata(ALICE, ASSET, name.clone(), symbol.clone(), decimals); + assert_eq!(Assets::name(ASSET).encode(), Fungibles::read_state(TokenName(ASSET))); + assert_eq!(Assets::symbol(ASSET).encode(), Fungibles::read_state(TokenSymbol(ASSET))); + assert_eq!(Assets::decimals(ASSET).encode(), Fungibles::read_state(TokenDecimals(ASSET))); + }); +} + +#[test] +fn asset_exists_works() { + new_test_ext().execute_with(|| { + create_asset(ALICE, ASSET); + assert_eq!(Assets::asset_exists(ASSET).encode(), Fungibles::read_state(AssetExists(ASSET))); + }); +} + +fn signed(account: AccountId) -> RuntimeOrigin { + RuntimeOrigin::signed(account) +} + +fn create_asset(owner: AccountId, asset: AssetId) { + assert_ok!(Assets::create(signed(owner), asset, owner, 1)); +} + +fn mint_asset(owner: AccountId, asset: AssetId, to: AccountId, value: Balance) { + assert_ok!(Assets::mint(signed(owner), asset, to, value)); +} + +fn create_asset_and_mint_to(owner: AccountId, asset: AssetId, to: AccountId, value: Balance) { + create_asset(owner, asset); + mint_asset(owner, asset, to, value) +} + +fn create_asset_mint_and_approve( + owner: AccountId, + asset: AssetId, + to: AccountId, + mint: Balance, + spender: AccountId, + approve: Balance, +) { + create_asset_and_mint_to(owner, asset, to, mint); + assert_ok!(Assets::approve_transfer(signed(to), asset, spender, approve,)); +} + +fn create_asset_and_set_metadata( + owner: AccountId, + asset: AssetId, + name: Vec, + symbol: Vec, + decimals: u8, +) { + assert_ok!(Assets::create(signed(owner), asset, owner, 100)); + set_metadata_asset(owner, asset, name, symbol, decimals); +} + +fn set_metadata_asset( + owner: AccountId, + asset: AssetId, + name: Vec, + symbol: Vec, + decimals: u8, +) { + assert_ok!(Assets::set_metadata(signed(owner), asset, name, symbol, decimals)); +} diff --git a/pallets/api/src/fungibles/weights.rs b/pallets/api/src/fungibles/weights.rs new file mode 100644 index 00000000..a6c31654 --- /dev/null +++ b/pallets/api/src/fungibles/weights.rs @@ -0,0 +1,94 @@ + +//! Autogenerated weights for `pallet_api::fungibles` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 33.0.0 +//! DATE: 2024-07-25, STEPS: `20`, REPEAT: `5`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `R0GUE`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` + +// Executed Command: +// ./target/release/pop-node +// benchmark +// pallet +// --chain=dev +// --wasm-execution=compiled +// --pallet=pallet_api::fungibles +// --steps=20 +// --repeat=5 +// --json +// --template +// ./scripts/pallet-weights-template.hbs +// --output=./pallets/api/src/fungibles/weights.rs +// --extrinsic= + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use core::marker::PhantomData; + +/// Weight functions needed for `pallet_api::fungibles`. +pub trait WeightInfo { + fn approve(a: u32, c: u32, ) -> Weight; +} + +/// Weights for `pallet_api::fungibles` using the Substrate node and recommended hardware. +pub struct SubstrateWeight(PhantomData); +impl WeightInfo for SubstrateWeight { + /// Storage: `Assets::Approvals` (r:1 w:1) + /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 1]`. + /// The range of component `c` is `[0, 1]`. + fn approve(a: u32, c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `413 + c * (102 ±0)` + // Estimated: `3675 + c * (1797 ±0)` + // Minimum execution time: 35_000_000 picoseconds. + Weight::from_parts(1_207_482, 3675) + // Standard Error: 948_955 + .saturating_add(Weight::from_parts(34_649_659, 0).saturating_mul(a.into())) + // Standard Error: 948_955 + .saturating_add(Weight::from_parts(56_976_190, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(c.into()))) + .saturating_add(T::DbWeight::get().writes(2_u64)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(c.into()))) + .saturating_add(Weight::from_parts(0, 1797).saturating_mul(c.into())) + } +} + +// For backwards compatibility and tests. +impl WeightInfo for () { + /// Storage: `Assets::Approvals` (r:1 w:1) + /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 1]`. + /// The range of component `c` is `[0, 1]`. + fn approve(a: u32, c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `413 + c * (102 ±0)` + // Estimated: `3675 + c * (1797 ±0)` + // Minimum execution time: 35_000_000 picoseconds. + Weight::from_parts(1_207_482, 3675) + // Standard Error: 948_955 + .saturating_add(Weight::from_parts(34_649_659, 0).saturating_mul(a.into())) + // Standard Error: 948_955 + .saturating_add(Weight::from_parts(56_976_190, 0).saturating_mul(c.into())) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(c.into()))) + .saturating_add(RocksDbWeight::get().writes(2_u64)) + .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(c.into()))) + .saturating_add(Weight::from_parts(0, 1797).saturating_mul(c.into())) + } +} + diff --git a/pallets/api/src/lib.rs b/pallets/api/src/lib.rs new file mode 100644 index 00000000..b3cc533e --- /dev/null +++ b/pallets/api/src/lib.rs @@ -0,0 +1,29 @@ +#![cfg_attr(not(feature = "std"), no_std)] + +pub use extension::Extension; +use frame_support::pallet_prelude::Weight; + +pub mod extension; +pub mod fungibles; +#[cfg(test)] +mod mock; + +/// Trait for performing reads of runtime state. +pub trait Read { + /// The type of read requested. + type Read; + /// The type or result returned. + type Result; + + /// Determines the weight of the requested read, used to charge the appropriate weight before the read is performed. + /// + /// # Parameters + /// - `request` - The read request. + fn weight(read: &Self::Read) -> Weight; + + /// Performs the requested read and returns the result. + /// + /// # Parameters + /// - `request` - The read request. + fn read(request: Self::Read) -> Self::Result; +} diff --git a/pallets/api/src/mock.rs b/pallets/api/src/mock.rs new file mode 100644 index 00000000..77e17394 --- /dev/null +++ b/pallets/api/src/mock.rs @@ -0,0 +1,125 @@ +use frame_support::{ + derive_impl, parameter_types, + traits::{AsEnsureOriginWithArg, ConstU128, ConstU32, Everything}, +}; +use frame_system::{EnsureRoot, EnsureSigned}; +use sp_core::H256; +use sp_runtime::{ + traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, +}; + +type Block = frame_system::mocking::MockBlock; +pub(crate) type AccountId = u64; +pub(crate) type AssetId = u32; +pub(crate) type Balance = u128; + +// Configure a mock runtime to test the pallet. +frame_support::construct_runtime!( + pub enum Test + { + System: frame_system, + Assets: pallet_assets::, + Balances: pallet_balances, + Fungibles: crate::fungibles, + } +); + +parameter_types! { + pub const BlockHashCount: u64 = 250; + pub const SS58Prefix: u8 = 42; +} + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Test { + type BaseCallFilter = Everything; + type BlockWeights = (); + type BlockLength = (); + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type Nonce = u64; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type Block = Block; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = BlockHashCount; + type DbWeight = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = SS58Prefix; + type OnSetCode = (); + type MaxConsumers = ConstU32<16>; +} + +impl pallet_balances::Config for Test { + type Balance = Balance; + type DustRemoval = (); + type RuntimeEvent = RuntimeEvent; + type ExistentialDeposit = ConstU128<1>; + type AccountStore = System; + type FreezeIdentifier = (); + type MaxFreezes = ConstU32<0>; + type WeightInfo = (); + type MaxLocks = (); + type MaxReserves = (); + type ReserveIdentifier = [u8; 8]; + type RuntimeHoldReason = RuntimeHoldReason; + type RuntimeFreezeReason = RuntimeFreezeReason; +} + +type AssetsInstance = pallet_assets::Instance1; +impl pallet_assets::Config for Test { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type RemoveItemsLimit = ConstU32<5>; + type AssetId = AssetId; + type AssetIdParameter = u32; + type Currency = Balances; + type CreateOrigin = AsEnsureOriginWithArg>; + type ForceOrigin = EnsureRoot; + type AssetDeposit = ConstU128<1>; + type AssetAccountDeposit = ConstU128<10>; + type MetadataDepositBase = ConstU128<1>; + type MetadataDepositPerByte = ConstU128<1>; + type ApprovalDeposit = ConstU128<1>; + type StringLimit = ConstU32<50>; + type Freezer = (); + type Extra = (); + type CallbackHandle = (); + type WeightInfo = (); + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = (); +} +impl crate::fungibles::Config for Test { + type RuntimeEvent = RuntimeEvent; + type AssetsInstance = AssetsInstance; + type WeightInfo = (); +} + +pub(crate) const ALICE: AccountId = 1; +pub(crate) const BOB: AccountId = 2; +pub(crate) const CHARLIE: AccountId = 3; +pub(crate) const INIT_AMOUNT: Balance = 100_000_000 * UNIT; +pub(crate) const UNIT: Balance = 10_000_000_000; + +pub(crate) fn new_test_ext() -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .expect("Frame system builds valid default genesis config"); + + pallet_balances::GenesisConfig:: { + balances: vec![(ALICE, INIT_AMOUNT), (BOB, INIT_AMOUNT), (CHARLIE, INIT_AMOUNT)], + } + .assimilate_storage(&mut t) + .expect("Pallet balances storage can be assimilated"); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext +} diff --git a/pallets/contracts/Cargo.toml b/pallets/contracts/Cargo.toml new file mode 100644 index 00000000..9d0c77f9 --- /dev/null +++ b/pallets/contracts/Cargo.toml @@ -0,0 +1,128 @@ +[package] +name = "pallet-contracts" +version = "27.0.0" +authors.workspace = true +edition.workspace = true +build = "build.rs" +license = "Apache-2.0" +homepage.workspace = true +repository.workspace = true +description = "FRAME pallet for WASM contracts" +readme = "README.md" +include = ["CHANGELOG.md", "README.md", "benchmarks/**", "build.rs", "src/**/*"] + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +paste = { workspace = true } +bitflags = { workspace = true } +codec = { features = ["derive", "max-encoded-len"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +log = { workspace = true } +serde = { optional = true, features = [ + "derive", +], workspace = true, default-features = true } +smallvec = { features = ["const_generics"], workspace = true } +wasmi = { workspace = true } +impl-trait-for-tuples = { workspace = true } + +# Only used in benchmarking to generate contract code +wasm-instrument = { optional = true, workspace = true } +rand = { optional = true, workspace = true } +rand_pcg = { optional = true, workspace = true } + +# Substrate Dependencies +environmental = { workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-balances = { optional = true, workspace = true } +pallet-contracts-uapi = { workspace = true, default-features = true } +pallet-contracts-proc-macro = { workspace = true, default-features = true } +sp-api = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } + +xcm = { workspace = true } +xcm-builder = { workspace = true } + +[dev-dependencies] +array-bytes = { workspace = true, default-features = true } +assert_matches = { workspace = true } +pretty_assertions = { workspace = true } +wat = { workspace = true } +pallet-contracts-fixtures = { workspace = true } + +# Polkadot Dependencies +xcm-builder = { workspace = true, default-features = true } + +# Substrate Dependencies +pallet-balances = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +pallet-message-queue = { workspace = true, default-features = true } +pallet-insecure-randomness-collective-flip = { workspace = true, default-features = true } +pallet-utility = { workspace = true, default-features = true } +pallet-assets = { workspace = true, default-features = true } +pallet-proxy = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } + +[features] +default = ["std"] +std = [ + "codec/std", + "environmental/std", + "frame-benchmarking?/std", + "frame-support/std", + "frame-system/std", + "log/std", + "pallet-balances?/std", + "pallet-insecure-randomness-collective-flip/std", + "pallet-proxy/std", + "pallet-timestamp/std", + "pallet-utility/std", + "rand?/std", + "scale-info/std", + "serde", + "sp-api/std", + "sp-core/std", + "sp-io/std", + "sp-keystore/std", + "sp-runtime/std", + "sp-std/std", + "wasm-instrument?/std", + "wasmi/std", + "xcm-builder/std", + "xcm/std", +] +runtime-benchmarks = [ + "frame-benchmarking/runtime-benchmarks", + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-assets/runtime-benchmarks", + "pallet-balances/runtime-benchmarks", + "pallet-message-queue/runtime-benchmarks", + "pallet-proxy/runtime-benchmarks", + "pallet-timestamp/runtime-benchmarks", + "pallet-utility/runtime-benchmarks", + "rand", + "rand_pcg", + "sp-runtime/runtime-benchmarks", + "wasm-instrument", + "xcm-builder/runtime-benchmarks", +] +try-runtime = [ + "frame-support/try-runtime", + "frame-system/try-runtime", + "pallet-assets/try-runtime", + "pallet-balances/try-runtime", + "pallet-insecure-randomness-collective-flip/try-runtime", + "pallet-message-queue/try-runtime", + "pallet-proxy/try-runtime", + "pallet-timestamp/try-runtime", + "pallet-utility/try-runtime", + "sp-runtime/try-runtime", +] diff --git a/pallets/contracts/README.md b/pallets/contracts/README.md new file mode 100644 index 00000000..6440f14b --- /dev/null +++ b/pallets/contracts/README.md @@ -0,0 +1,160 @@ +# Contracts Module + +The Contracts module provides functionality for the runtime to deploy and execute WebAssembly smart-contracts. + +- [`Call`](https://paritytech.github.io/substrate/master/pallet_contracts/pallet/enum.Call.html) +- [`Config`](https://paritytech.github.io/substrate/master/pallet_contracts/pallet/trait.Config.html) +- [`Error`](https://paritytech.github.io/substrate/master/pallet_contracts/pallet/enum.Error.html) +- [`Event`](https://paritytech.github.io/substrate/master/pallet_contracts/pallet/enum.Event.html) + +## Overview + +This module extends accounts based on the [`frame_support::traits::fungible`] traits to have smart-contract +functionality. It can be used with other modules that implement accounts based on [`frame_support::traits::fungible`]. +These "smart-contract accounts" have the ability to instantiate smart-contracts and make calls to other contract and +non-contract accounts. + +The smart-contract code is stored once, and later retrievable via its `code_hash`. This means that multiple +smart-contracts can be instantiated from the same `code`, without replicating the code each time. + +When a smart-contract is called, its associated code is retrieved via the code hash and gets executed. This call can +alter the storage entries of the smart-contract account, instantiate new smart-contracts, or call other smart-contracts. + +Finally, when an account is reaped, its associated code and storage of the smart-contract account will also be deleted. + +### Weight + +Senders must specify a [`Weight`](https://paritytech.github.io/substrate/master/sp_weights/struct.Weight.html) limit +with every call, as all instructions invoked by the smart-contract require weight. Unused weight is refunded after the +call, regardless of the execution outcome. + +If the weight limit is reached, then all calls and state changes (including balance transfers) are only reverted at the +current call's contract level. For example, if contract A calls B and B runs out of weight mid-call, then all of B's +calls are reverted. Assuming correct error handling by contract A, A's other calls and state changes still persist. + +One `ref_time` `Weight` is defined as one picosecond of execution time on the runtime's reference machine. + +### Revert Behaviour + +Contract call failures are not cascading. When failures occur in a sub-call, they do not "bubble up", and the call will +only revert at the specific contract level. For example, if contract A calls contract B, and B fails, A can decide how +to handle that failure, either proceeding or reverting A's changes. + +### Off-chain Execution + +In general, a contract execution needs to be deterministic so that all nodes come to the same conclusion when executing +it. To that end we disallow any instructions that could cause indeterminism. Most notable are any floating point +arithmetic. That said, sometimes contracts are executed off-chain and hence are not subject to consensus. If code is +only executed by a single node and implicitly trusted by other actors is such a case. Trusted execution environments +come to mind. To that end we allow the execution of indeterministic code for off-chain usages with the following +constraints: + +1. No contract can ever be instantiated from an indeterministic code. The only way to execute the code is to use a +delegate call from a deterministic contract. +2. The code that wants to use this feature needs to depend on `pallet-contracts` and use +[`bare_call()`](https://paritytech.github.io/substrate/master/pallet_contracts/pallet/struct.Pallet.html#method.bare_call) +directly. This makes sure that by default `pallet-contracts` does not expose any indeterminism. + +#### How to use + +An indeterministic code can be deployed on-chain by passing `Determinism::Relaxed` to +[`upload_code()`](https://paritytech.github.io/substrate/master/pallet_contracts/pallet/struct.Pallet.html#method.upload_code). +A deterministic contract can then delegate call into it if and only if it is ran by using +[`bare_call()`](https://paritytech.github.io/substrate/master/pallet_contracts/pallet/struct.Pallet.html#method.bare_call) +and passing +[`Determinism::Relaxed`](https://paritytech.github.io/substrate/master/pallet_contracts/enum.Determinism.html#variant.Relaxed) +to it. **Never use this argument when the contract is called from an on-chain transaction.** + +## Interface + +### Dispatchable functions + +Those are documented in the [reference +documentation](https://paritytech.github.io/substrate/master/pallet_contracts/index.html#dispatchable-functions). + +### Interface exposed to contracts + +Each contract is one WebAssembly module that looks like this: + +```wat +(module + ;; Invoked by pallet-contracts when a contract is instantiated. + ;; No arguments and empty return type. + (func (export "deploy")) + + ;; Invoked by pallet-contracts when a contract is called. + ;; No arguments and empty return type. + (func (export "call")) + + ;; If a contract uses memory it must be imported. Memory is optional. + ;; The maximum allowed memory size depends on the pallet-contracts configuration. + (import "env" "memory" (memory 1 1)) + + ;; This is one of many functions that can be imported and is implemented by pallet-contracts. + ;; This function is used to copy the result buffer and flags back to the caller. + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) +) +``` + +The documentation of all importable functions can be found +[here](https://paritytech.github.io/substrate/master/pallet_contracts/api_doc/trait.Current.html). + +## Usage + +This module executes WebAssembly smart contracts. These can potentially be written in any language that compiles to +Wasm. However, using a language that specifically targets this module will make things a lot easier. One such language +is [`ink!`](https://use.ink). It enables writing WebAssembly-based smart-contracts in the Rust programming language. + +## Debugging + +Contracts can emit messages to the client when called as RPC through the +[`debug_message`](https://paritytech.github.io/substrate/master/pallet_contracts/api_doc/trait.Current.html#tymethod.debug_message) +API. This is exposed in [ink!](https://use.ink) via +[`ink_env::debug_message()`](https://paritytech.github.io/ink/ink_env/fn.debug_message.html). + +Those messages are gathered into an internal buffer and sent to the RPC client. It is up to the individual client if +and how those messages are presented to the user. + +This buffer is also printed as a debug message. In order to see these messages on the node console the log level for the +`runtime::contracts` target needs to be raised to at least the `debug` level. However, those messages are easy to +overlook because of the noise generated by block production. A good starting point for observing them on the console is +using this command line in the root directory of the Substrate repository: + +```bash +cargo run --release -- --dev -lerror,runtime::contracts=debug +``` + +This raises the log level of `runtime::contracts` to `debug` and all other targets to `error` in order to prevent them +from spamming the console. + +`--dev`: Use a dev chain spec `--tmp`: Use temporary storage for chain data (the chain state is deleted on exit) + +## Host function tracing + +For contract authors, it can be a helpful debugging tool to see which host functions are called, with which arguments, +and what the result was. + +In order to see these messages on the node console, the log level for the `runtime::contracts::strace` target needs to +be raised to the `trace` level. + +Example: + +```bash +cargo run --release -- --dev -lerror,runtime::contracts::strace=trace,runtime::contracts=debug +``` + +## Unstable Interfaces + +Driven by the desire to have an iterative approach in developing new contract interfaces this pallet contains the +concept of an unstable interface. Akin to the rust nightly compiler it allows us to add new interfaces but mark them as +unstable so that contract languages can experiment with them and give feedback before we stabilize those. + +In order to access interfaces marked as `#[unstable]` in [`runtime.rs`](src/wasm/runtime.rs) one need to set +`pallet_contracts::Config::UnsafeUnstableInterface` to `ConstU32`. **It should be obvious that any production +runtime should never be compiled with this feature: In addition to be subject to change or removal those interfaces +might not have proper weights associated with them and are therefore considered unsafe**. + +New interfaces are generally added as unstable and might go through several iterations before they are promoted to a +stable interface. + +License: Apache-2.0 diff --git a/pallets/contracts/build.rs b/pallets/contracts/build.rs new file mode 100644 index 00000000..83d5d368 --- /dev/null +++ b/pallets/contracts/build.rs @@ -0,0 +1,72 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::io::Write; + +/// Get the latest migration version. +/// +/// Find the highest version number from the available migration files. +/// Each migration file should follow the naming convention `vXX.rs`, where `XX` is the version +/// number. +fn get_latest_version() -> u16 { + std::fs::read_dir("src/migration") + .expect("Folder `src/migration` not found.") + .filter_map(|entry| { + let file_name = entry.as_ref().ok()?.file_name(); + let file_name = file_name.to_str()?; + if file_name.starts_with('v') && file_name.ends_with(".rs") { + let version = &file_name[1..&file_name.len() - 3]; + let version = version.parse::().ok()?; + + // Ensure that the version matches the one defined in the file. + let path = entry.unwrap().path(); + let file_content = std::fs::read_to_string(&path).ok()?; + assert!( + file_content.contains(&format!("const VERSION: u16 = {}", version)), + "Invalid MigrationStep::VERSION in {:?}", + path + ); + + return Some(version) + } + None + }) + .max() + .expect("Failed to find any files matching the 'src/migration/vxx.rs' pattern.") +} + +/// Generates a module that exposes the latest migration version, and the benchmark migrations type. +fn main() -> Result<(), Box> { + let out_dir = std::env::var("OUT_DIR")?; + let path = std::path::Path::new(&out_dir).join("migration_codegen.rs"); + let mut f = std::fs::File::create(path)?; + let version = get_latest_version(); + write!( + f, + " + pub mod codegen {{ + use crate::NoopMigration; + /// The latest migration version, pulled from the latest migration file. + pub const LATEST_MIGRATION_VERSION: u16 = {version}; + /// The Migration Steps used for benchmarking the migration framework. + pub type BenchMigrations = (NoopMigration<{}>, NoopMigration<{version}>); + }}", + version - 1, + )?; + + Ok(()) +} diff --git a/pallets/contracts/fixtures/Cargo.toml b/pallets/contracts/fixtures/Cargo.toml new file mode 100644 index 00000000..625c6ebc --- /dev/null +++ b/pallets/contracts/fixtures/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "pallet-contracts-fixtures" +publish = false +version = "1.0.0" +authors.workspace = true +edition.workspace = true +license.workspace = true +description = "Fixtures for testing contracts pallet." + +[dependencies] +frame-system = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +anyhow = { workspace = true } + +[build-dependencies] +parity-wasm = { workspace = true } +tempfile = { workspace = true } +toml = { workspace = true } +twox-hash = { workspace = true, default-features = true } +polkavm-linker = { workspace = true, optional = true } +anyhow = { workspace = true } + +[features] +riscv = ["polkavm-linker"] diff --git a/pallets/contracts/fixtures/build.rs b/pallets/contracts/fixtures/build.rs new file mode 100644 index 00000000..baaeaf03 --- /dev/null +++ b/pallets/contracts/fixtures/build.rs @@ -0,0 +1,355 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Compile contracts to wasm and RISC-V binaries. +use anyhow::{bail, Context, Result}; +use parity_wasm::elements::{deserialize_file, serialize_to_file, Internal}; +use std::{ + env, fs, + hash::Hasher, + path::{Path, PathBuf}, + process::Command, +}; +use twox_hash::XxHash32; + +/// Read the file at `path` and return its hash as a hex string. +fn file_hash(path: &Path) -> String { + let data = fs::read(path).expect("file exists; qed"); + let mut hasher = XxHash32::default(); + hasher.write(&data); + hasher.write(include_bytes!("build.rs")); + let hash = hasher.finish(); + format!("{:x}", hash) +} + +/// A contract entry. +struct Entry { + /// The path to the contract source file. + path: PathBuf, + /// The hash of the contract source file. + hash: String, +} + +impl Entry { + /// Create a new contract entry from the given path. + fn new(path: PathBuf) -> Self { + let hash = file_hash(&path); + Self { path, hash } + } + + /// Return the path to the contract source file. + fn path(&self) -> &str { + self.path.to_str().expect("path is valid unicode; qed") + } + + /// Return the name of the contract. + fn name(&self) -> &str { + self.path + .file_stem() + .expect("file exits; qed") + .to_str() + .expect("name is valid unicode; qed") + } + + /// Return whether the contract has already been compiled. + fn is_cached(&self, out_dir: &Path) -> bool { + out_dir.join(self.name()).join(&self.hash).exists() + } + + /// Update the cache file for the contract. + fn update_cache(&self, out_dir: &Path) -> Result<()> { + let cache_dir = out_dir.join(self.name()); + + // clear the cache dir if it exists + if cache_dir.exists() { + fs::remove_dir_all(&cache_dir)?; + } + + // re-populate the cache dir with the new hash + fs::create_dir_all(&cache_dir)?; + fs::write(out_dir.join(&self.hash), "")?; + Ok(()) + } + + /// Return the name of the output wasm file. + fn out_wasm_filename(&self) -> String { + format!("{}.wasm", self.name()) + } + + /// Return the name of the RISC-V polkavm file. + #[cfg(feature = "riscv")] + fn out_riscv_filename(&self) -> String { + format!("{}.polkavm", self.name()) + } +} + +/// Collect all contract entries from the given source directory. +/// Contracts that have already been compiled are filtered out. +fn collect_entries(contracts_dir: &Path, out_dir: &Path) -> Vec { + fs::read_dir(contracts_dir) + .expect("src dir exists; qed") + .filter_map(|file| { + let path = file.expect("file exists; qed").path(); + if path.extension().map_or(true, |ext| ext != "rs") { + return None + } + + let entry = Entry::new(path); + if entry.is_cached(out_dir) { + None + } else { + Some(entry) + } + }) + .collect::>() +} + +/// Create a `Cargo.toml` to compile the given contract entries. +fn create_cargo_toml<'a>( + fixtures_dir: &Path, + root_cargo_toml: &Path, + entries: impl Iterator, + output_dir: &Path, +) -> Result<()> { + let root_toml: toml::Value = toml::from_str(&fs::read_to_string(root_cargo_toml)?)?; + let mut cargo_toml: toml::Value = toml::from_str(include_str!("./build/Cargo.toml"))?; + let mut set_dep = |name, path| -> Result<()> { + cargo_toml["dependencies"][name]["path"] = toml::Value::String( + fixtures_dir.join(path).canonicalize()?.to_str().unwrap().to_string(), + ); + Ok(()) + }; + set_dep("uapi", "../uapi")?; + set_dep("common", "./contracts/common")?; + cargo_toml["dependencies"]["polkavm-derive"]["version"] = + root_toml["workspace"]["dependencies"]["polkavm-derive"].clone(); + + cargo_toml["bin"] = toml::Value::Array( + entries + .map(|entry| { + let name = entry.name(); + let path = entry.path(); + toml::Value::Table(toml::toml! { + name = name + path = path + }) + }) + .collect::>(), + ); + + let cargo_toml = toml::to_string_pretty(&cargo_toml)?; + fs::write(output_dir.join("Cargo.toml"), cargo_toml).map_err(Into::into) +} + +/// Invoke `cargo fmt` to check that fixtures files are formatted. +fn invoke_cargo_fmt<'a>( + config_path: &Path, + files: impl Iterator, + contract_dir: &Path, +) -> Result<()> { + // If rustfmt is not installed, skip the check. + if !Command::new("rustup") + .args(["nightly-2024-04-10", "run", "rustfmt", "--version"]) + .output() + .map_or(false, |o| o.status.success()) + { + return Ok(()) + } + + let fmt_res = Command::new("rustup") + .args(["nightly-2024-04-10", "run", "rustfmt", "--check", "--config-path"]) + .arg(config_path) + .args(files) + .output() + .expect("failed to execute process"); + + if fmt_res.status.success() { + return Ok(()) + } + + let stdout = String::from_utf8_lossy(&fmt_res.stdout); + let stderr = String::from_utf8_lossy(&fmt_res.stderr); + eprintln!("{}\n{}", stdout, stderr); + eprintln!( + "Fixtures files are not formatted.\n + Please run `rustup nightly-2024-04-10 run rustfmt --config-path {} {}/*.rs`", + config_path.display(), + contract_dir.display() + ); + + anyhow::bail!("Fixtures files are not formatted") +} + +/// Build contracts for wasm. +fn invoke_wasm_build(current_dir: &Path) -> Result<()> { + let encoded_rustflags = [ + "-Clink-arg=-zstack-size=65536", + "-Clink-arg=--import-memory", + "-Clinker-plugin-lto", + "-Ctarget-cpu=mvp", + "-Dwarnings", + ] + .join("\x1f"); + + let build_res = Command::new(env::var("CARGO")?) + .current_dir(current_dir) + .env("CARGO_TARGET_DIR", current_dir.join("target").display().to_string()) + .env("CARGO_ENCODED_RUSTFLAGS", encoded_rustflags) + .args(["build", "--release", "--target=wasm32-unknown-unknown"]) + .output() + .expect("failed to execute process"); + + if build_res.status.success() { + return Ok(()) + } + + let stderr = String::from_utf8_lossy(&build_res.stderr); + eprintln!("{}", stderr); + bail!("Failed to build wasm contracts"); +} + +/// Post-process the compiled wasm contracts. +fn post_process_wasm(input_path: &Path, output_path: &Path) -> Result<()> { + let mut module = + deserialize_file(input_path).with_context(|| format!("Failed to read {:?}", input_path))?; + if let Some(section) = module.export_section_mut() { + section.entries_mut().retain(|entry| { + matches!(entry.internal(), Internal::Function(_)) && + (entry.field() == "call" || entry.field() == "deploy") + }); + } + + serialize_to_file(output_path, module).map_err(Into::into) +} + +/// Build contracts for RISC-V. +#[cfg(feature = "riscv")] +fn invoke_riscv_build(current_dir: &Path) -> Result<()> { + let encoded_rustflags = [ + "-Crelocation-model=pie", + "-Clink-arg=--emit-relocs", + "-Clink-arg=--export-dynamic-symbol=__polkavm_symbol_export_hack__*", + ] + .join("\x1f"); + + let build_res = Command::new(env::var("CARGO")?) + .current_dir(current_dir) + .env_clear() + .env("PATH", env::var("PATH").unwrap_or_default()) + .env("CARGO_ENCODED_RUSTFLAGS", encoded_rustflags) + .env("RUSTUP_TOOLCHAIN", "rve-nightly") + .env("RUSTUP_HOME", env::var("RUSTUP_HOME").unwrap_or_default()) + .args(["build", "--release", "--target=riscv32ema-unknown-none-elf"]) + .output() + .expect("failed to execute process"); + + if build_res.status.success() { + return Ok(()) + } + + let stderr = String::from_utf8_lossy(&build_res.stderr); + + if stderr.contains("'rve-nightly' is not installed") { + eprintln!("RISC-V toolchain is not installed.\nDownload and install toolchain from https://github.com/paritytech/rustc-rv32e-toolchain."); + eprintln!("{}", stderr); + } else { + eprintln!("{}", stderr); + } + + bail!("Failed to build contracts"); +} +/// Post-process the compiled wasm contracts. +#[cfg(feature = "riscv")] +fn post_process_riscv(input_path: &Path, output_path: &Path) -> Result<()> { + let mut config = polkavm_linker::Config::default(); + config.set_strip(true); + let orig = fs::read(input_path).with_context(|| format!("Failed to read {:?}", input_path))?; + let linked = polkavm_linker::program_from_elf(config, orig.as_ref()) + .map_err(|err| anyhow::format_err!("Failed to link polkavm program: {}", err))?; + fs::write(output_path, linked.as_bytes()).map_err(Into::into) +} + +/// Write the compiled contracts to the given output directory. +fn write_output(build_dir: &Path, out_dir: &Path, entries: Vec) -> Result<()> { + for entry in entries { + let wasm_output = entry.out_wasm_filename(); + post_process_wasm( + &build_dir.join("target/wasm32-unknown-unknown/release").join(&wasm_output), + &out_dir.join(&wasm_output), + )?; + + #[cfg(feature = "riscv")] + post_process_riscv( + &build_dir.join("target/riscv32ema-unknown-none-elf/release").join(entry.name()), + &out_dir.join(entry.out_riscv_filename()), + )?; + + entry.update_cache(out_dir)?; + } + + Ok(()) +} + +/// Returns the root path of the wasm workspace. +fn find_workspace_root(current_dir: &Path) -> Option { + let mut current_dir = current_dir.to_path_buf(); + + while current_dir.parent().is_some() { + if current_dir.join("Cargo.toml").exists() { + let cargo_toml_contents = + std::fs::read_to_string(current_dir.join("Cargo.toml")).ok()?; + if cargo_toml_contents.contains("[workspace]") { + return Some(current_dir); + } + } + + current_dir.pop(); + } + + None +} + +fn main() -> Result<()> { + let fixtures_dir: PathBuf = env::var("CARGO_MANIFEST_DIR")?.into(); + let contracts_dir = fixtures_dir.join("contracts"); + let out_dir: PathBuf = env::var("OUT_DIR")?.into(); + let workspace_root = find_workspace_root(&fixtures_dir).expect("workspace root exists; qed"); + let root_cargo_toml = workspace_root.join("Cargo.toml"); + + let entries = collect_entries(&contracts_dir, &out_dir); + if entries.is_empty() { + return Ok(()) + } + + let tmp_dir = tempfile::tempdir()?; + let tmp_dir_path = tmp_dir.path(); + + create_cargo_toml(&fixtures_dir, &root_cargo_toml, entries.iter(), tmp_dir.path())?; + invoke_cargo_fmt( + &workspace_root.join(".rustfmt.toml"), + entries.iter().map(|entry| &entry.path as _), + &contracts_dir, + )?; + + invoke_wasm_build(tmp_dir_path)?; + + #[cfg(feature = "riscv")] + invoke_riscv_build(tmp_dir_path)?; + + write_output(tmp_dir_path, &out_dir, entries)?; + Ok(()) +} diff --git a/pallets/contracts/fixtures/build/Cargo.toml b/pallets/contracts/fixtures/build/Cargo.toml new file mode 100644 index 00000000..ba487a2b --- /dev/null +++ b/pallets/contracts/fixtures/build/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "contracts" +version = "0.6.3" +edition = "2021" + +# Binary targets are injected dynamically by the build script. +[[bin]] + +# All paths or versions are injected dynamically by the build script. +[dependencies] +uapi = { package = 'pallet-contracts-uapi', path = "", default-features = false } +common = { package = 'pallet-contracts-fixtures-common', path = "" } +polkavm-derive = { version = "" } + +[profile.release] +opt-level = 3 +lto = true +codegen-units = 1 diff --git a/pallets/contracts/fixtures/contracts/account_reentrance_count_call.rs b/pallets/contracts/fixtures/contracts/account_reentrance_count_call.rs new file mode 100644 index 00000000..9da4eb6d --- /dev/null +++ b/pallets/contracts/fixtures/contracts/account_reentrance_count_call.rs @@ -0,0 +1,39 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This fixture tests if account_reentrance_count works as expected. +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!(callee: [u8; 32],); + + #[allow(deprecated)] + let reentrance_count = api::account_reentrance_count(callee); + + // Return the reentrance count. + api::return_value(uapi::ReturnFlags::empty(), &reentrance_count.to_le_bytes()); +} diff --git a/pallets/contracts/fixtures/contracts/balance.rs b/pallets/contracts/fixtures/contracts/balance.rs new file mode 100644 index 00000000..4011b837 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/balance.rs @@ -0,0 +1,36 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::output; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + // Initialize buffer with 1s so that we can check that it is overwritten. + output!(balance, [1u8; 8], api::balance,); + + // Assert that the balance is 0. + assert_eq!(&[0u8; 8], balance); +} diff --git a/pallets/contracts/fixtures/contracts/call.rs b/pallets/contracts/fixtures/contracts/call.rs new file mode 100644 index 00000000..535745ff --- /dev/null +++ b/pallets/contracts/fixtures/contracts/call.rs @@ -0,0 +1,49 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This calls another contract as passed as its account id. +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + callee_input: [u8; 4], + callee_addr: [u8; 32], + ); + + // Call the callee + api::call_v2( + uapi::CallFlags::empty(), + callee_addr, + 0u64, // How much ref_time to devote for the execution. 0 = all. + 0u64, // How much proof_size to devote for the execution. 0 = all. + None, // No deposit limit. + &0u64.to_le_bytes(), // Value transferred to the contract. + callee_input, + None, + ) + .unwrap(); +} diff --git a/pallets/contracts/fixtures/contracts/call_return_code.rs b/pallets/contracts/fixtures/contracts/call_return_code.rs new file mode 100644 index 00000000..3d5a1073 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/call_return_code.rs @@ -0,0 +1,56 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This calls the supplied dest and transfers 100 balance during this call and copies +//! the return code of this call to the output buffer. +//! It also forwards its input to the callee. +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + 100, + callee_addr: [u8; 32], + input: [u8], + ); + + // Call the callee + let err_code = match api::call_v2( + uapi::CallFlags::empty(), + callee_addr, + 0u64, // How much ref_time to devote for the execution. 0 = all. + 0u64, // How much proof_size to devote for the execution. 0 = all. + None, // No deposit limit. + &100u64.to_le_bytes(), // Value transferred to the contract. + input, + None, + ) { + Ok(_) => 0u32, + Err(code) => code as u32, + }; + + api::return_value(uapi::ReturnFlags::empty(), &err_code.to_le_bytes()); +} diff --git a/pallets/contracts/fixtures/contracts/call_runtime.rs b/pallets/contracts/fixtures/contracts/call_runtime.rs new file mode 100644 index 00000000..2b132398 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/call_runtime.rs @@ -0,0 +1,42 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This passes its input to `call_runtime` and returns the return value to its caller. +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + // Fixture calls should fit into 100 bytes. + input!(100, call: [u8], ); + + // Use the call passed as input to call the runtime. + let err_code = match api::call_runtime(call) { + Ok(_) => 0u32, + Err(code) => code as u32, + }; + + api::return_value(uapi::ReturnFlags::empty(), &err_code.to_le_bytes()); +} diff --git a/pallets/contracts/fixtures/contracts/call_runtime_and_call.rs b/pallets/contracts/fixtures/contracts/call_runtime_and_call.rs new file mode 100644 index 00000000..1321d36d --- /dev/null +++ b/pallets/contracts/fixtures/contracts/call_runtime_and_call.rs @@ -0,0 +1,53 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + 512, + callee_input: [u8; 4], + callee_addr: [u8; 32], + call: [u8], + ); + + // Use the call passed as input to call the runtime. + api::call_runtime(call).unwrap(); + + // Call the callee + api::call_v2( + uapi::CallFlags::empty(), + callee_addr, + 0u64, // How much ref_time to devote for the execution. 0 = all. + 0u64, // How much proof_size to devote for the execution. 0 = all. + None, // No deposit limit. + &0u64.to_le_bytes(), // Value transferred to the contract. + callee_input, + None, + ) + .unwrap(); +} diff --git a/pallets/contracts/fixtures/contracts/call_with_flags_and_value.rs b/pallets/contracts/fixtures/contracts/call_with_flags_and_value.rs new file mode 100644 index 00000000..16a85eff --- /dev/null +++ b/pallets/contracts/fixtures/contracts/call_with_flags_and_value.rs @@ -0,0 +1,51 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This fixture calls the account_id with the flags and value. +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + 256, + callee_addr: [u8; 32], + flags: u32, + value: u64, + forwarded_input: [u8], + ); + + api::call_v2( + uapi::CallFlags::from_bits(flags).unwrap(), + callee_addr, + 0u64, // How much ref_time to devote for the execution. 0 = all. + 0u64, // How much proof_size to devote for the execution. 0 = all. + None, // No deposit limit. + &value.to_le_bytes(), // Value transferred to the contract. + forwarded_input, + None, + ) + .unwrap(); +} diff --git a/pallets/contracts/fixtures/contracts/call_with_limit.rs b/pallets/contracts/fixtures/contracts/call_with_limit.rs new file mode 100644 index 00000000..f0851f32 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/call_with_limit.rs @@ -0,0 +1,52 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This fixture calls the account_id with the 2D Weight limit. +//! It returns the result of the call as output data. +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + 256, + callee_addr: [u8; 32], + ref_time: u64, + proof_size: u64, + forwarded_input: [u8], + ); + + api::call_v2( + uapi::CallFlags::empty(), + callee_addr, + ref_time, + proof_size, + None, // No deposit limit. + &0u64.to_le_bytes(), // value transferred to the contract. + forwarded_input, + None, + ) + .unwrap(); +} diff --git a/pallets/contracts/fixtures/contracts/caller_contract.rs b/pallets/contracts/fixtures/contracts/caller_contract.rs new file mode 100644 index 00000000..fffdb66a --- /dev/null +++ b/pallets/contracts/fixtures/contracts/caller_contract.rs @@ -0,0 +1,145 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api, ReturnErrorCode}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!(code_hash: [u8; 32],); + + // The value to transfer on instantiation and calls. Chosen to be greater than existential + // deposit. + let value = 32768u64.to_le_bytes(); + let salt = [0u8; 0]; + + // Callee will use the first 4 bytes of the input to return an exit status. + let input = [0u8, 1, 34, 51, 68, 85, 102, 119]; + let reverted_input = [1u8, 34, 51, 68, 85, 102, 119]; + + // Fail to deploy the contract since it returns a non-zero exit status. + let res = api::instantiate_v2( + code_hash, + 0u64, // How much ref_time weight to devote for the execution. 0 = all. + 0u64, // How much proof_size weight to devote for the execution. 0 = all. + None, // No deposit limit. + &value, + &reverted_input, + None, + None, + &salt, + ); + assert!(matches!(res, Err(ReturnErrorCode::CalleeReverted))); + + // Fail to deploy the contract due to insufficient ref_time weight. + let res = api::instantiate_v2( + code_hash, 1u64, // too little ref_time weight + 0u64, // How much proof_size weight to devote for the execution. 0 = all. + None, // No deposit limit. + &value, &input, None, None, &salt, + ); + assert!(matches!(res, Err(ReturnErrorCode::CalleeTrapped))); + + // Fail to deploy the contract due to insufficient proof_size weight. + let res = api::instantiate_v2( + code_hash, 0u64, // How much ref_time weight to devote for the execution. 0 = all. + 1u64, // Too little proof_size weight + None, // No deposit limit. + &value, &input, None, None, &salt, + ); + assert!(matches!(res, Err(ReturnErrorCode::CalleeTrapped))); + + // Deploy the contract successfully. + let mut callee = [0u8; 32]; + let callee = &mut &mut callee[..]; + + api::instantiate_v2( + code_hash, + 0u64, // How much ref_time weight to devote for the execution. 0 = all. + 0u64, // How much proof_size weight to devote for the execution. 0 = all. + None, // No deposit limit. + &value, + &input, + Some(callee), + None, + &salt, + ) + .unwrap(); + assert_eq!(callee.len(), 32); + + // Call the new contract and expect it to return failing exit code. + let res = api::call_v2( + uapi::CallFlags::empty(), + callee, + 0u64, // How much ref_time weight to devote for the execution. 0 = all. + 0u64, // How much proof_size weight to devote for the execution. 0 = all. + None, // No deposit limit. + &value, + &reverted_input, + None, + ); + assert!(matches!(res, Err(ReturnErrorCode::CalleeReverted))); + + // Fail to call the contract due to insufficient ref_time weight. + let res = api::call_v2( + uapi::CallFlags::empty(), + callee, + 1u64, // Too little ref_time weight. + 0u64, // How much proof_size weight to devote for the execution. 0 = all. + None, // No deposit limit. + &value, + &input, + None, + ); + assert!(matches!(res, Err(ReturnErrorCode::CalleeTrapped))); + + // Fail to call the contract due to insufficient proof_size weight. + let res = api::call_v2( + uapi::CallFlags::empty(), + callee, + 0u64, // How much ref_time weight to devote for the execution. 0 = all. + 1u64, // too little proof_size weight + None, // No deposit limit. + &value, + &input, + None, + ); + assert!(matches!(res, Err(ReturnErrorCode::CalleeTrapped))); + + // Call the contract successfully. + let mut output = [0u8; 4]; + api::call_v2( + uapi::CallFlags::empty(), + callee, + 0u64, // How much ref_time weight to devote for the execution. 0 = all. + 0u64, // How much proof_size weight to devote for the execution. 0 = all. + None, // No deposit limit. + &value, + &input, + Some(&mut &mut output[..]), + ) + .unwrap(); + assert_eq!(&output, &input[4..]) +} diff --git a/pallets/contracts/fixtures/contracts/caller_is_origin_n.rs b/pallets/contracts/fixtures/contracts/caller_is_origin_n.rs new file mode 100644 index 00000000..fd6f5980 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/caller_is_origin_n.rs @@ -0,0 +1,38 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This fixture calls caller_is_origin `n` times. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!(n: u32, ); + + for _ in 0..n { + let _ = api::caller_is_origin(); + } +} diff --git a/pallets/contracts/fixtures/contracts/chain_extension.rs b/pallets/contracts/fixtures/contracts/chain_extension.rs new file mode 100644 index 00000000..474df00d --- /dev/null +++ b/pallets/contracts/fixtures/contracts/chain_extension.rs @@ -0,0 +1,42 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Call chain extension by passing through input and output of this contract. +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!(input, 8, func_id: u32,); + + // the chain extension passes through the input and returns it as output + let mut output_buffer = [0u8; 32]; + let output = &mut &mut output_buffer[0..input.len()]; + + let ret_id = api::call_chain_extension(func_id, input, Some(output)); + assert_eq!(ret_id, func_id); + + api::return_value(uapi::ReturnFlags::empty(), output); +} diff --git a/pallets/contracts/fixtures/contracts/chain_extension_temp_storage.rs b/pallets/contracts/fixtures/contracts/chain_extension_temp_storage.rs new file mode 100644 index 00000000..2e15fb02 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/chain_extension_temp_storage.rs @@ -0,0 +1,65 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Call chain extension two times with the specified func_ids +//! It then calls itself once +#![no_std] +#![no_main] + +use common::{input, output}; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + input, + func_id1: u32, + func_id2: u32, + stop_recurse: u8, + ); + + api::call_chain_extension(func_id1, input, None); + api::call_chain_extension(func_id2, input, None); + + if stop_recurse == 0 { + // Setup next call + input[0..4].copy_from_slice(&((3 << 16) | 2u32).to_le_bytes()); + input[4..8].copy_from_slice(&((3 << 16) | 3u32).to_le_bytes()); + input[8] = 1u8; + + // Read the contract address. + output!(addr, [0u8; 32], api::address,); + + // call self + api::call_v2( + uapi::CallFlags::ALLOW_REENTRY, + addr, + 0u64, // How much ref_time to devote for the execution. 0 = all. + 0u64, // How much proof_size to devote for the execution. 0 = all. + None, // No deposit limit. + &0u64.to_le_bytes(), // Value transferred to the contract. + input, + None, + ) + .unwrap(); + } +} diff --git a/pallets/contracts/fixtures/contracts/common/Cargo.toml b/pallets/contracts/fixtures/contracts/common/Cargo.toml new file mode 100644 index 00000000..296f408d --- /dev/null +++ b/pallets/contracts/fixtures/contracts/common/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "pallet-contracts-fixtures-common" +publish = false +version = "1.0.0" +authors.workspace = true +edition.workspace = true +license.workspace = true +description = "Common utilities for pallet-contracts-fixtures." + +[dependencies] +uapi = { package = 'pallet-contracts-uapi', path = "../../../uapi", default-features = false } diff --git a/pallets/contracts/fixtures/contracts/common/src/lib.rs b/pallets/contracts/fixtures/contracts/common/src/lib.rs new file mode 100644 index 00000000..80e1f543 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/common/src/lib.rs @@ -0,0 +1,161 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#![no_std] + +pub use uapi::{HostFn, HostFnImpl as api}; + +#[panic_handler] +fn panic(_info: &core::panic::PanicInfo) -> ! { + #[cfg(target_arch = "wasm32")] + core::arch::wasm32::unreachable(); + + #[cfg(target_arch = "riscv32")] + // Safety: The unimp instruction is guaranteed to trap + unsafe { + core::arch::asm!("unimp"); + core::hint::unreachable_unchecked(); + } +} + +/// Utility macro to read input passed to a contract. +/// +/// Example: +/// +/// ``` +/// input$!( +/// var1: u32, // [0, 4) var1 decoded as u32 +/// var2: [u8; 32], // [4, 36) var2 decoded as a [u8] slice +/// var3: u8, // [36, 37) var3 decoded as a u8 +/// ); +/// +/// // Input and size can be specified as well: +/// input$!( +/// input, // input buffer (optional) +/// 512, // input size (optional) +/// var4: u32, // [0, 4) var4 decoded as u32 +/// var5: [u8], // [4, ..) var5 decoded as a [u8] slice +/// ); +/// ``` +#[macro_export] +macro_rules! input { + (@inner $input:expr, $cursor:expr,) => {}; + (@size $size:expr, ) => { $size }; + + // Match a u8 variable. + // e.g input!(var1: u8, ); + (@inner $input:expr, $cursor:expr, $var:ident: u8, $($rest:tt)*) => { + let $var = $input[$cursor]; + input!(@inner $input, $cursor + 1, $($rest)*); + }; + + // Size of u8 variable. + (@size $size:expr, $var:ident: u8, $($rest:tt)*) => { + input!(@size $size + 1, $($rest)*) + }; + + // Match a u64 variable. + // e.g input!(var1: u64, ); + (@inner $input:expr, $cursor:expr, $var:ident: u64, $($rest:tt)*) => { + let $var = u64::from_le_bytes($input[$cursor..$cursor + 8].try_into().unwrap()); + input!(@inner $input, $cursor + 8, $($rest)*); + }; + + // Size of u64 variable. + (@size $size:expr, $var:ident: u64, $($rest:tt)*) => { + input!(@size $size + 8, $($rest)*) + }; + + // Match a u32 variable. + // e.g input!(var1: u32, ); + (@inner $input:expr, $cursor:expr, $var:ident: u32, $($rest:tt)*) => { + let $var = u32::from_le_bytes($input[$cursor..$cursor + 4].try_into().unwrap()); + input!(@inner $input, $cursor + 4, $($rest)*); + }; + + // Size of u32 variable. + (@size $size:expr, $var:ident: u32, $($rest:tt)*) => { + input!(@size $size + 4, $($rest)*) + }; + + // Match a u8 slice with the remaining bytes. + // e.g input!(512, var1: [u8; 32], var2: [u8], ); + (@inner $input:expr, $cursor:expr, $var:ident: [u8],) => { + let $var = &$input[$cursor..]; + }; + + // Match a u8 slice of the given size. + // e.g input!(var1: [u8; 32], ); + (@inner $input:expr, $cursor:expr, $var:ident: [u8; $n:expr], $($rest:tt)*) => { + let $var = &$input[$cursor..$cursor+$n]; + input!(@inner $input, $cursor + $n, $($rest)*); + }; + + // Size of a u8 slice. + (@size $size:expr, $var:ident: [u8; $n:expr], $($rest:tt)*) => { + input!(@size $size + $n, $($rest)*) + }; + + // Entry point, with the buffer and it's size specified first. + // e.g input!(buffer, 512, var1: u32, var2: [u8], ); + ($buffer:ident, $size:expr, $($rest:tt)*) => { + let mut $buffer = [0u8; $size]; + let $buffer = &mut &mut $buffer[..]; + $crate::api::input($buffer); + input!(@inner $buffer, 0, $($rest)*); + }; + + // Entry point, with the name of the buffer specified and size of the input buffer computed. + // e.g input!(buffer, var1: u32, var2: u64, ); + ($buffer: ident, $($rest:tt)*) => { + input!($buffer, input!(@size 0, $($rest)*), $($rest)*); + }; + + // Entry point, with the size of the input buffer computed. + // e.g input!(var1: u32, var2: u64, ); + ($($rest:tt)*) => { + input!(buffer, $($rest)*); + }; +} + +/// Utility macro to invoke a host function that expect a `output: &mut &mut [u8]` as last argument. +/// +/// Example: +/// ``` +/// // call `api::caller` and store the output in `caller` +/// output!(caller, [0u8; 32], api::caller,); +/// +/// // call `api::get_storage` and store the output in `address` +/// output!(address, [0u8; 32], api::get_storage, &[1u8; 32]); +/// ``` +#[macro_export] +macro_rules! output { + ($output: ident, $buffer: expr, $host_fn:path, $($arg:expr),*) => { + let mut $output = $buffer; + let $output = &mut &mut $output[..]; + $host_fn($($arg,)* $output); + }; +} + +/// Similar to `output!` but unwraps the result. +#[macro_export] +macro_rules! unwrap_output { + ($output: ident, $buffer: expr, $host_fn:path, $($arg:expr),*) => { + let mut $output = $buffer; + let $output = &mut &mut $output[..]; + $host_fn($($arg,)* $output).unwrap(); + }; +} diff --git a/pallets/contracts/fixtures/contracts/create_storage_and_call.rs b/pallets/contracts/fixtures/contracts/create_storage_and_call.rs new file mode 100644 index 00000000..f8ce0ff4 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/create_storage_and_call.rs @@ -0,0 +1,58 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This calls another contract as passed as its account id. It also creates some storage. +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + buffer, + input: [u8; 4], + callee: [u8; 32], + deposit_limit: [u8; 8], + ); + + // create 4 byte of storage before calling + api::set_storage(buffer, &[1u8; 4]); + + // Call the callee + api::call_v2( + uapi::CallFlags::empty(), + callee, + 0u64, // How much ref_time weight to devote for the execution. 0 = all. + 0u64, // How much proof_size weight to devote for the execution. 0 = all. + Some(deposit_limit), + &0u64.to_le_bytes(), // Value transferred to the contract. + input, + None, + ) + .unwrap(); + + // create 8 byte of storage after calling + // item of 12 bytes because we override 4 bytes + api::set_storage(buffer, &[1u8; 12]); +} diff --git a/pallets/contracts/fixtures/contracts/create_storage_and_instantiate.rs b/pallets/contracts/fixtures/contracts/create_storage_and_instantiate.rs new file mode 100644 index 00000000..fa3b9000 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/create_storage_and_instantiate.rs @@ -0,0 +1,58 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This instantiates another contract and passes some input to its constructor. +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + input: [u8; 4], + code_hash: [u8; 32], + deposit_limit: [u8; 8], + ); + + let value = 10_000u64.to_le_bytes(); + let salt = [0u8; 0]; + let mut address = [0u8; 32]; + let address = &mut &mut address[..]; + + api::instantiate_v2( + code_hash, + 0u64, // How much ref_time weight to devote for the execution. 0 = all. + 0u64, // How much proof_size weight to devote for the execution. 0 = all. + Some(deposit_limit), + &value, + input, + Some(address), + None, + &salt, + ) + .unwrap(); + + // Return the deployed contract address. + api::return_value(uapi::ReturnFlags::empty(), address); +} diff --git a/pallets/contracts/fixtures/contracts/create_transient_storage_and_call.rs b/pallets/contracts/fixtures/contracts/create_transient_storage_and_call.rs new file mode 100644 index 00000000..6bafee55 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/create_transient_storage_and_call.rs @@ -0,0 +1,56 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This calls another contract as passed as its account id. It also creates some transient storage. +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + buffer, + len: u32, + input: [u8; 4], + callee: [u8; 32], + ); + + let data = [0u8; 16 * 1024]; + let value = &data[..len as usize]; + #[allow(deprecated)] + api::set_transient_storage(buffer, value); + + // Call the callee + api::call_v2( + uapi::CallFlags::empty(), + callee, + 0u64, // How much ref_time weight to devote for the execution. 0 = all. + 0u64, // How much proof_size weight to devote for the execution. 0 = all. + None, + &0u64.to_le_bytes(), // Value transferred to the contract. + input, + None, + ) + .unwrap(); +} diff --git a/pallets/contracts/fixtures/contracts/crypto_hashes.rs b/pallets/contracts/fixtures/contracts/crypto_hashes.rs new file mode 100644 index 00000000..35cc03f1 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/crypto_hashes.rs @@ -0,0 +1,84 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +/// Called by the tests. +/// +/// The `call` function expects data in a certain format in the input buffer. +/// +/// 1. The first byte encodes an identifier for the crypto hash function under test. (*) +/// 2. The rest encodes the input data that is directly fed into the crypto hash function chosen in +/// 1. +/// +/// The `deploy` function then computes the chosen crypto hash function +/// given the input and puts the result into the output buffer. +/// After contract execution the test driver then asserts that the returned +/// values are equal to the expected bytes for the input and chosen hash +/// function. +/// +/// (*) The possible value for the crypto hash identifiers can be found below: +/// +/// | value | Algorithm | Bit Width | +/// |-------|-----------|-----------| +/// | 0 | SHA2 | 256 | +/// | 1 | KECCAK | 256 | +/// | 2 | BLAKE2 | 256 | +/// | 3 | BLAKE2 | 128 | +/// --------------------------------- + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + 256, + chosen_hash_fn: u8, + input: [u8], + ); + + match chosen_hash_fn { + 1 => { + let mut output = [0u8; 32]; + api::hash_sha2_256(input, &mut output); + api::return_value(uapi::ReturnFlags::empty(), &output); + }, + 2 => { + let mut output = [0u8; 32]; + api::hash_keccak_256(input, &mut output); + api::return_value(uapi::ReturnFlags::empty(), &output); + }, + 3 => { + let mut output = [0u8; 32]; + api::hash_blake2_256(input, &mut output); + api::return_value(uapi::ReturnFlags::empty(), &output); + }, + 4 => { + let mut output = [0u8; 16]; + api::hash_blake2_128(input, &mut output); + api::return_value(uapi::ReturnFlags::empty(), &output); + }, + _ => panic!("unknown crypto hash function identifier"), + } +} diff --git a/pallets/contracts/fixtures/contracts/debug_message_invalid_utf8.rs b/pallets/contracts/fixtures/contracts/debug_message_invalid_utf8.rs new file mode 100644 index 00000000..6c850a9e --- /dev/null +++ b/pallets/contracts/fixtures/contracts/debug_message_invalid_utf8.rs @@ -0,0 +1,33 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Emit a debug message with an invalid utf-8 code. +#![no_std] +#![no_main] + +extern crate common; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + api::debug_message(b"\xFC").unwrap(); +} diff --git a/pallets/contracts/fixtures/contracts/debug_message_logging_disabled.rs b/pallets/contracts/fixtures/contracts/debug_message_logging_disabled.rs new file mode 100644 index 00000000..b9f62adb --- /dev/null +++ b/pallets/contracts/fixtures/contracts/debug_message_logging_disabled.rs @@ -0,0 +1,33 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Emit a "Hello World!" debug message but assume that logging is disabled. +#![no_std] +#![no_main] + +extern crate common; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + api::debug_message(b"Hello World!").unwrap(); +} diff --git a/pallets/contracts/fixtures/contracts/debug_message_works.rs b/pallets/contracts/fixtures/contracts/debug_message_works.rs new file mode 100644 index 00000000..3a250950 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/debug_message_works.rs @@ -0,0 +1,33 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Emit a "Hello World!" debug message. +#![no_std] +#![no_main] + +extern crate common; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + api::debug_message(b"Hello World!").unwrap(); +} diff --git a/pallets/contracts/fixtures/contracts/delegate_call.rs b/pallets/contracts/fixtures/contracts/delegate_call.rs new file mode 100644 index 00000000..f109e8a6 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/delegate_call.rs @@ -0,0 +1,49 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!(code_hash: [u8; 32],); + + let mut key = [0u8; 32]; + key[0] = 1u8; + + let mut value = [0u8; 32]; + let value = &mut &mut value[..]; + value[0] = 2u8; + + api::set_storage(&key, value); + api::get_storage(&key, value).unwrap(); + assert!(value[0] == 2u8); + + let input = [0u8; 0]; + api::delegate_call(uapi::CallFlags::empty(), code_hash, &input, None).unwrap(); + + api::get_storage(&[1u8], value).unwrap(); + assert!(value[0] == 1u8); +} diff --git a/pallets/contracts/fixtures/contracts/delegate_call_lib.rs b/pallets/contracts/fixtures/contracts/delegate_call_lib.rs new file mode 100644 index 00000000..197b396c --- /dev/null +++ b/pallets/contracts/fixtures/contracts/delegate_call_lib.rs @@ -0,0 +1,49 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::output; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + let mut key = [0u8; 32]; + key[0] = 1u8; + + // Place a value in storage. + let mut value = [0u8; 32]; + let value = &mut &mut value[..]; + value[0] = 1u8; + api::set_storage(&key, value); + + // Assert that `value_transferred` is equal to the value + // passed to the `caller` contract: 1337. + output!(value_transferred, [0u8; 8], api::value_transferred,); + let value_transferred = u64::from_le_bytes(value_transferred[..].try_into().unwrap()); + assert_eq!(value_transferred, 1337); + + // Assert that ALICE is the caller of the contract. + output!(caller, [0u8; 32], api::caller,); + assert_eq!(&caller[..], &[1u8; 32]); +} diff --git a/pallets/contracts/fixtures/contracts/delegate_call_simple.rs b/pallets/contracts/fixtures/contracts/delegate_call_simple.rs new file mode 100644 index 00000000..cf3351c5 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/delegate_call_simple.rs @@ -0,0 +1,36 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!(code_hash: [u8; 32],); + + // Delegate call into passed code hash. + let input = [0u8; 0]; + api::delegate_call(uapi::CallFlags::empty(), code_hash, &input, None).unwrap(); +} diff --git a/pallets/contracts/fixtures/contracts/destroy_and_transfer.rs b/pallets/contracts/fixtures/contracts/destroy_and_transfer.rs new file mode 100644 index 00000000..62fb63b5 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/destroy_and_transfer.rs @@ -0,0 +1,86 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +const ADDRESS_KEY: [u8; 32] = [0u8; 32]; +const VALUE: [u8; 8] = [0, 0, 1u8, 0, 0, 0, 0, 0]; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() { + input!(code_hash: [u8; 32],); + + let input = [0u8; 0]; + let mut address = [0u8; 32]; + let address = &mut &mut address[..]; + let salt = [71u8, 17u8]; + + api::instantiate_v2( + code_hash, + 0u64, // How much ref_time weight to devote for the execution. 0 = all. + 0u64, // How much proof_size weight to devote for the execution. 0 = all. + None, // No deposit limit. + &VALUE, + &input, + Some(address), + None, + &salt, + ) + .unwrap(); + + // Return the deployed contract address. + api::set_storage(&ADDRESS_KEY, address); +} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + let mut callee_addr = [0u8; 32]; + let callee_addr = &mut &mut callee_addr[..]; + api::get_storage(&ADDRESS_KEY, callee_addr).unwrap(); + + // Calling the destination contract with non-empty input data should fail. + let res = api::call_v2( + uapi::CallFlags::empty(), + callee_addr, + 0u64, // How much ref_time weight to devote for the execution. 0 = all. + 0u64, // How much proof_size weight to devote for the execution. 0 = all. + None, // No deposit limit. + &VALUE, + &[0u8; 1], + None, + ); + assert!(matches!(res, Err(uapi::ReturnErrorCode::CalleeTrapped))); + + // Call the destination contract regularly, forcing it to self-destruct. + api::call_v2( + uapi::CallFlags::empty(), + callee_addr, + 0u64, // How much ref_time weight to devote for the execution. 0 = all. + 0u64, // How much proof_size weight to devote for the execution. 0 = all. + None, // No deposit limit. + &VALUE, + &[0u8; 0], + None, + ) + .unwrap(); +} diff --git a/pallets/contracts/fixtures/contracts/drain.rs b/pallets/contracts/fixtures/contracts/drain.rs new file mode 100644 index 00000000..f5c8681c --- /dev/null +++ b/pallets/contracts/fixtures/contracts/drain.rs @@ -0,0 +1,44 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::output; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + output!(balance, [0u8; 8], api::balance,); + let balance = u64::from_le_bytes(balance[..].try_into().unwrap()); + + output!(minimum_balance, [0u8; 8], api::minimum_balance,); + let minimum_balance = u64::from_le_bytes(minimum_balance[..].try_into().unwrap()); + + // Make the transferred value exceed the balance by adding the minimum balance. + let balance = balance + minimum_balance; + + // Try to self-destruct by sending more balance to the 0 address. + // The call will fail because a contract transfer has a keep alive requirement. + let res = api::transfer(&[0u8; 32], &balance.to_le_bytes()); + assert!(matches!(res, Err(uapi::ReturnErrorCode::TransferFailed))); +} diff --git a/pallets/contracts/fixtures/contracts/dummy.rs b/pallets/contracts/fixtures/contracts/dummy.rs new file mode 100644 index 00000000..bde0d15e --- /dev/null +++ b/pallets/contracts/fixtures/contracts/dummy.rs @@ -0,0 +1,28 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#![no_std] +#![no_main] + +extern crate common; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() {} diff --git a/pallets/contracts/fixtures/contracts/ecdsa_recover.rs b/pallets/contracts/fixtures/contracts/ecdsa_recover.rs new file mode 100644 index 00000000..0f28ca2c --- /dev/null +++ b/pallets/contracts/fixtures/contracts/ecdsa_recover.rs @@ -0,0 +1,44 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + signature: [u8; 65], + hash: [u8; 32], + ); + + let mut output = [0u8; 33]; + api::ecdsa_recover( + &signature[..].try_into().unwrap(), + &hash[..].try_into().unwrap(), + &mut output, + ) + .unwrap(); + api::return_value(uapi::ReturnFlags::empty(), &output); +} diff --git a/pallets/contracts/fixtures/contracts/event_and_return_on_deploy.rs b/pallets/contracts/fixtures/contracts/event_and_return_on_deploy.rs new file mode 100644 index 00000000..9186835d --- /dev/null +++ b/pallets/contracts/fixtures/contracts/event_and_return_on_deploy.rs @@ -0,0 +1,36 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +extern crate common; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() { + let buffer = [1u8, 2, 3, 4]; + api::deposit_event(&[0u8; 0], &buffer); + api::return_value(uapi::ReturnFlags::empty(), &buffer); +} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + unreachable!() +} diff --git a/pallets/contracts/fixtures/contracts/event_size.rs b/pallets/contracts/fixtures/contracts/event_size.rs new file mode 100644 index 00000000..e95130d3 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/event_size.rs @@ -0,0 +1,37 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!(len: u32,); + + let buffer = [0u8; 16 * 1024 + 1]; + let data = &buffer[..len as usize]; + + api::deposit_event(&[0u8; 0], data); +} diff --git a/pallets/contracts/fixtures/contracts/float_instruction.rs b/pallets/contracts/fixtures/contracts/float_instruction.rs new file mode 100644 index 00000000..b1eaaf85 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/float_instruction.rs @@ -0,0 +1,34 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +extern crate common; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() {} + +#[no_mangle] +pub extern "C" fn add(a: f32, b: f32) -> f32 { + a + b +} diff --git a/pallets/contracts/fixtures/contracts/instantiate_return_code.rs b/pallets/contracts/fixtures/contracts/instantiate_return_code.rs new file mode 100644 index 00000000..de194abe --- /dev/null +++ b/pallets/contracts/fixtures/contracts/instantiate_return_code.rs @@ -0,0 +1,52 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!(buffer, 36, code_hash: [u8; 32],); + let input = &buffer[32..]; + + let err_code = match api::instantiate_v2( + code_hash, + 0u64, // How much ref_time weight to devote for the execution. 0 = all. + 0u64, /* How much proof_size weight to devote for the execution. 0 = + * all. */ + None, // No deposit limit. + &10_000u64.to_le_bytes(), // Value to transfer. + input, + None, + None, + &[0u8; 0], // Empty salt. + ) { + Ok(_) => 0u32, + Err(code) => code as u32, + }; + + // Exit with success and take transfer return code to the output buffer. + api::return_value(uapi::ReturnFlags::empty(), &err_code.to_le_bytes()); +} diff --git a/pallets/contracts/fixtures/contracts/locking_delegate_dependency.rs b/pallets/contracts/fixtures/contracts/locking_delegate_dependency.rs new file mode 100644 index 00000000..bb76c942 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/locking_delegate_dependency.rs @@ -0,0 +1,68 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This contract tests the behavior of locking / unlocking delegate_dependencies when delegate +//! calling into a contract. +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +const ALICE: [u8; 32] = [1u8; 32]; + +/// Load input data and perform the action specified by the input. +/// If `delegate_call` is true, then delegate call into the contract. +fn load_input(delegate_call: bool) { + input!( + action: u32, + code_hash: [u8; 32], + ); + + match action { + // 1 = Lock delegate dependency + 1 => { + api::lock_delegate_dependency(code_hash); + }, + // 2 = Unlock delegate dependency + 2 => { + api::unlock_delegate_dependency(code_hash); + }, + // 3 = Terminate + 3 => { + api::terminate_v1(&ALICE); + }, + // Everything else is a noop + _ => {}, + } + + if delegate_call { + api::delegate_call(uapi::CallFlags::empty(), code_hash, &[], None).unwrap(); + } +} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() { + load_input(false); +} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + load_input(true); +} diff --git a/pallets/contracts/fixtures/contracts/multi_store.rs b/pallets/contracts/fixtures/contracts/multi_store.rs new file mode 100644 index 00000000..a78115f0 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/multi_store.rs @@ -0,0 +1,43 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Does two stores to two separate storage items +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + size1: u32, + size2: u32, + ); + + let buffer = [0u8; 16 * 1024]; + + // Place a values in storage sizes are specified in the input buffer. + // We don't care about the contents of the storage item. + api::set_storage(&[1u8; 32], &buffer[0..size1 as _]); + api::set_storage(&[2u8; 32], &buffer[0..size2 as _]); +} diff --git a/pallets/contracts/fixtures/contracts/new_set_code_hash_contract.rs b/pallets/contracts/fixtures/contracts/new_set_code_hash_contract.rs new file mode 100644 index 00000000..2a59b6e3 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/new_set_code_hash_contract.rs @@ -0,0 +1,32 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +extern crate common; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + api::return_value(uapi::ReturnFlags::empty(), &2u32.to_le_bytes()); +} diff --git a/pallets/contracts/fixtures/contracts/ok_trap_revert.rs b/pallets/contracts/fixtures/contracts/ok_trap_revert.rs new file mode 100644 index 00000000..55115f86 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/ok_trap_revert.rs @@ -0,0 +1,44 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() { + ok_trap_revert(); +} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + ok_trap_revert(); +} + +#[no_mangle] +fn ok_trap_revert() { + input!(buffer, 4,); + match buffer.first().unwrap_or(&0) { + 1 => api::return_value(uapi::ReturnFlags::REVERT, &[0u8; 0]), + 2 => panic!(), + _ => {}, + }; +} diff --git a/pallets/contracts/fixtures/contracts/read_only_call.rs b/pallets/contracts/fixtures/contracts/read_only_call.rs new file mode 100644 index 00000000..524fe50b --- /dev/null +++ b/pallets/contracts/fixtures/contracts/read_only_call.rs @@ -0,0 +1,50 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This fixture tests if read-only call works as expected. +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + 256, + callee_addr: [u8; 32], + callee_input: [u8], + ); + + // Call the callee + api::call_v2( + uapi::CallFlags::READ_ONLY, + callee_addr, + 0u64, // How much ref_time to devote for the execution. 0 = all. + 0u64, // How much proof_size to devote for the execution. 0 = all. + None, // No deposit limit. + &0u64.to_le_bytes(), // Value transferred to the contract. + callee_input, + None, + ) + .unwrap(); +} diff --git a/pallets/contracts/fixtures/contracts/recurse.rs b/pallets/contracts/fixtures/contracts/recurse.rs new file mode 100644 index 00000000..b1ded608 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/recurse.rs @@ -0,0 +1,53 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This fixture calls itself as many times as passed as argument. + +#![no_std] +#![no_main] + +use common::{input, output}; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!(calls_left: u32, ); + + // own address + output!(addr, [0u8; 32], api::address,); + + if calls_left == 0 { + return + } + + api::call_v2( + uapi::CallFlags::ALLOW_REENTRY, + addr, + 0u64, // How much ref_time to devote for the execution. 0 = all. + 0u64, // How much deposit_limit to devote for the execution. 0 = all. + None, // No deposit limit. + &0u64.to_le_bytes(), // Value transferred to the contract. + &(calls_left - 1).to_le_bytes(), + None, + ) + .unwrap(); +} diff --git a/pallets/contracts/fixtures/contracts/reentrance_count_call.rs b/pallets/contracts/fixtures/contracts/reentrance_count_call.rs new file mode 100644 index 00000000..0acfe017 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/reentrance_count_call.rs @@ -0,0 +1,57 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This fixture tests if account_reentrance_count works as expected. +#![no_std] +#![no_main] + +use common::{input, output}; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!(expected_reentrance_count: u32,); + + // Read the contract address. + output!(addr, [0u8; 32], api::address,); + + #[allow(deprecated)] + let reentrance_count = api::reentrance_count(); + assert_eq!(reentrance_count, expected_reentrance_count); + + // Re-enter 5 times in a row and assert that the reentrant counter works as expected. + if expected_reentrance_count != 5 { + let count = (expected_reentrance_count + 1).to_le_bytes(); + + api::call_v2( + uapi::CallFlags::ALLOW_REENTRY, + addr, + 0u64, // How much ref_time to devote for the execution. 0 = all. + 0u64, // How much proof_size to devote for the execution. 0 = all. + None, // No deposit limit. + &0u64.to_le_bytes(), // Value transferred to the contract. + &count, + None, + ) + .unwrap(); + } +} diff --git a/pallets/contracts/fixtures/contracts/reentrance_count_delegated_call.rs b/pallets/contracts/fixtures/contracts/reentrance_count_delegated_call.rs new file mode 100644 index 00000000..9baf9503 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/reentrance_count_delegated_call.rs @@ -0,0 +1,53 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This fixture tests if account_reentrance_count works as expected. +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + input, + code_hash: [u8; 32], + call_stack_height: u32, + ); + + let call_stack_height = call_stack_height + 1; + + #[allow(deprecated)] + let reentrance_count = api::reentrance_count(); + + // Reentrance count stays 0. + assert_eq!(reentrance_count, 0); + + // Re-enter 5 times in a row and assert that the reentrant counter works as expected. + if call_stack_height != 5 { + let mut input = [0u8; 36]; + input[0..32].copy_from_slice(code_hash); + input[32..36].copy_from_slice(&call_stack_height.to_le_bytes()); + api::delegate_call(uapi::CallFlags::empty(), code_hash, &input, None).unwrap(); + } +} diff --git a/pallets/contracts/fixtures/contracts/return_with_data.rs b/pallets/contracts/fixtures/contracts/return_with_data.rs new file mode 100644 index 00000000..26f74edb --- /dev/null +++ b/pallets/contracts/fixtures/contracts/return_with_data.rs @@ -0,0 +1,47 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() { + call(); +} + +/// Reads the first byte as the exit status and copy all but the first 4 bytes of the input as +/// output data. +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + input, 128, + exit_status: [u8; 4], + output: [u8], + ); + + // Burn some PoV, clear_storage consumes some PoV as in order to clear the storage we need to we + // need to read its size first. + api::clear_storage_v1(b""); + + let exit_status = uapi::ReturnFlags::from_bits(exit_status[0] as u32).unwrap(); + api::return_value(exit_status, output); +} diff --git a/pallets/contracts/fixtures/contracts/run_out_of_gas.rs b/pallets/contracts/fixtures/contracts/run_out_of_gas.rs new file mode 100644 index 00000000..11eaaa7c --- /dev/null +++ b/pallets/contracts/fixtures/contracts/run_out_of_gas.rs @@ -0,0 +1,32 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +extern crate common; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + #[allow(clippy::empty_loop)] + loop {} +} diff --git a/pallets/contracts/fixtures/contracts/self_destruct.rs b/pallets/contracts/fixtures/contracts/self_destruct.rs new file mode 100644 index 00000000..d3836d2d --- /dev/null +++ b/pallets/contracts/fixtures/contracts/self_destruct.rs @@ -0,0 +1,55 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::{input, output}; +use uapi::{HostFn, HostFnImpl as api}; + +const DJANGO: [u8; 32] = [4u8; 32]; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + // If the input data is not empty, then recursively call self with empty input data. + // This should trap instead of self-destructing since a contract cannot be removed, while it's + // in the execution stack. If the recursive call traps, then trap here as well. + input!(input, 4,); + + if !input.is_empty() { + output!(addr, [0u8; 32], api::address,); + api::call_v2( + uapi::CallFlags::ALLOW_REENTRY, + addr, + 0u64, // How much ref_time to devote for the execution. 0 = all. + 0u64, // How much proof_size to devote for the execution. 0 = all. + None, // No deposit limit. + &0u64.to_le_bytes(), // Value to transfer. + &[0u8; 0], + None, + ) + .unwrap(); + } else { + // Try to terminate and give balance to django. + api::terminate_v1(&DJANGO); + } +} diff --git a/pallets/contracts/fixtures/contracts/self_destructing_constructor.rs b/pallets/contracts/fixtures/contracts/self_destructing_constructor.rs new file mode 100644 index 00000000..97b6759b --- /dev/null +++ b/pallets/contracts/fixtures/contracts/self_destructing_constructor.rs @@ -0,0 +1,32 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +extern crate common; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() { + api::terminate_v1(&[0u8; 32]); +} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() {} diff --git a/pallets/contracts/fixtures/contracts/set_code_hash.rs b/pallets/contracts/fixtures/contracts/set_code_hash.rs new file mode 100644 index 00000000..e3cf4bec --- /dev/null +++ b/pallets/contracts/fixtures/contracts/set_code_hash.rs @@ -0,0 +1,37 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!(addr: [u8; 32],); + api::set_code_hash(addr).unwrap(); + + // we return 1 after setting new code_hash + // next `call` will NOT return this value, because contract code has been changed + api::return_value(uapi::ReturnFlags::empty(), &1u32.to_le_bytes()); +} diff --git a/pallets/contracts/fixtures/contracts/set_empty_storage.rs b/pallets/contracts/fixtures/contracts/set_empty_storage.rs new file mode 100644 index 00000000..e7366630 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/set_empty_storage.rs @@ -0,0 +1,32 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +extern crate common; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + api::set_storage(&[0u8; 32], &[0u8; 4]); +} diff --git a/pallets/contracts/fixtures/contracts/set_transient_storage.rs b/pallets/contracts/fixtures/contracts/set_transient_storage.rs new file mode 100644 index 00000000..e4fde083 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/set_transient_storage.rs @@ -0,0 +1,42 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!(len: u32, ); + + let buffer = [0u8; 16 * 1024]; + let data = &buffer[..len as usize]; + + // Place a garbage value in the transient storage, with the size specified by the call input. + let mut key = [0u8; 32]; + key[0] = 1; + + #[allow(deprecated)] + api::set_transient_storage(&key, data); +} diff --git a/pallets/contracts/fixtures/contracts/sr25519_verify.rs b/pallets/contracts/fixtures/contracts/sr25519_verify.rs new file mode 100644 index 00000000..8920ce0d --- /dev/null +++ b/pallets/contracts/fixtures/contracts/sr25519_verify.rs @@ -0,0 +1,48 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + signature: [u8; 64], + pub_key: [u8; 32], + msg: [u8; 11], + ); + + let exit_status = match api::sr25519_verify( + &signature.try_into().unwrap(), + msg, + &pub_key.try_into().unwrap(), + ) { + Ok(_) => 0u32, + Err(code) => code as u32, + }; + + // Exit with success and take transfer return code to the output buffer. + api::return_value(uapi::ReturnFlags::empty(), &exit_status.to_le_bytes()); +} diff --git a/pallets/contracts/fixtures/contracts/storage.rs b/pallets/contracts/fixtures/contracts/storage.rs new file mode 100644 index 00000000..6fa97224 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/storage.rs @@ -0,0 +1,63 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This contract tests the storage APIs. It sets and clears storage values using the different +//! versions of the storage APIs. +#![no_std] +#![no_main] + +use common::unwrap_output; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + const KEY: [u8; 32] = [1u8; 32]; + const VALUE_1: [u8; 4] = [1u8; 4]; + const VALUE_2: [u8; 4] = [2u8; 4]; + const VALUE_3: [u8; 4] = [3u8; 4]; + + api::set_storage(&KEY, &VALUE_1); + assert_eq!(api::contains_storage(&KEY), Some(VALUE_1.len() as _)); + unwrap_output!(val, [0u8; 4], api::get_storage, &KEY); + assert_eq!(**val, VALUE_1); + + let existing = api::set_storage_v1(&KEY, &VALUE_2); + assert_eq!(existing, Some(VALUE_1.len() as _)); + unwrap_output!(val, [0u8; 4], api::get_storage, &KEY); + assert_eq!(**val, VALUE_2); + + api::clear_storage(&KEY); + assert_eq!(api::contains_storage(&KEY), None); + + let existing = api::set_storage_v2(&KEY, &VALUE_3); + assert_eq!(existing, None); + assert_eq!(api::contains_storage_v1(&KEY), Some(VALUE_1.len() as _)); + unwrap_output!(val, [0u8; 32], api::get_storage_v1, &KEY); + assert_eq!(**val, VALUE_3); + + api::clear_storage_v1(&KEY); + assert_eq!(api::contains_storage_v1(&KEY), None); + let existing = api::set_storage_v2(&KEY, &VALUE_3); + assert_eq!(existing, None); + unwrap_output!(val, [0u8; 32], api::take_storage, &KEY); + assert_eq!(**val, VALUE_3); +} diff --git a/pallets/contracts/fixtures/contracts/storage_size.rs b/pallets/contracts/fixtures/contracts/storage_size.rs new file mode 100644 index 00000000..744ffe85 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/storage_size.rs @@ -0,0 +1,45 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!(len: u32, ); + + let mut buffer = [0u8; 16 * 1024 + 1]; + let data = &buffer[..len as usize]; + + // Place a garbage value in storage, the size of which is specified by the call input. + let mut key = [0u8; 32]; + key[0] = 1; + + api::set_storage(&key, data); + + let data = &mut &mut buffer[..]; + api::get_storage(&key, data).unwrap(); + assert_eq!(data.len(), len as usize); +} diff --git a/pallets/contracts/fixtures/contracts/store_call.rs b/pallets/contracts/fixtures/contracts/store_call.rs new file mode 100644 index 00000000..d20d811c --- /dev/null +++ b/pallets/contracts/fixtures/contracts/store_call.rs @@ -0,0 +1,41 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!(len: u32, ); + + let buffer = [0u8; 16 * 1024 + 1]; + let data = &buffer[..len as usize]; + + // Place a garbage value in storage, the size of which is specified by the call input. + let mut key = [0u8; 32]; + key[0] = 1; + + api::set_storage(&key, data); +} diff --git a/pallets/contracts/fixtures/contracts/store_deploy.rs b/pallets/contracts/fixtures/contracts/store_deploy.rs new file mode 100644 index 00000000..26f3b86b --- /dev/null +++ b/pallets/contracts/fixtures/contracts/store_deploy.rs @@ -0,0 +1,41 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() { + input!(len: u32, ); + + let buffer = [0u8; 16 * 1024 + 1]; + let data = &buffer[..len as usize]; + + // place a garbage value in storage, the size of which is specified by the call input. + let mut key = [0u8; 32]; + key[0] = 1; + + api::set_storage(&key, data); +} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() {} diff --git a/pallets/contracts/fixtures/contracts/transfer_return_code.rs b/pallets/contracts/fixtures/contracts/transfer_return_code.rs new file mode 100644 index 00000000..d3f6a1dd --- /dev/null +++ b/pallets/contracts/fixtures/contracts/transfer_return_code.rs @@ -0,0 +1,38 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +extern crate common; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + let ret_code = match api::transfer(&[0u8; 32], &100u64.to_le_bytes()) { + Ok(_) => 0u32, + Err(code) => code as u32, + }; + + // Exit with success and take transfer return code to the output buffer. + api::return_value(uapi::ReturnFlags::empty(), &ret_code.to_le_bytes()); +} diff --git a/pallets/contracts/fixtures/contracts/transient_storage.rs b/pallets/contracts/fixtures/contracts/transient_storage.rs new file mode 100644 index 00000000..c797e178 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/transient_storage.rs @@ -0,0 +1,58 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This contract tests the transient storage APIs. +#![no_std] +#![no_main] + +use common::unwrap_output; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + const KEY: [u8; 32] = [1u8; 32]; + const VALUE_1: [u8; 4] = [1u8; 4]; + const VALUE_2: [u8; 4] = [2u8; 4]; + const VALUE_3: [u8; 4] = [3u8; 4]; + + #[allow(deprecated)] + { + let existing = api::set_transient_storage(&KEY, &VALUE_1); + assert_eq!(existing, None); + assert_eq!(api::contains_transient_storage(&KEY), Some(VALUE_1.len() as _)); + unwrap_output!(val, [0u8; 4], api::get_transient_storage, &KEY); + assert_eq!(**val, VALUE_1); + + let existing = api::set_transient_storage(&KEY, &VALUE_2); + assert_eq!(existing, Some(VALUE_1.len() as _)); + unwrap_output!(val, [0u8; 4], api::get_transient_storage, &KEY); + assert_eq!(**val, VALUE_2); + + api::clear_transient_storage(&KEY); + assert_eq!(api::contains_transient_storage(&KEY), None); + + let existing = api::set_transient_storage(&KEY, &VALUE_3); + assert_eq!(existing, None); + unwrap_output!(val, [0u8; 32], api::take_transient_storage, &KEY); + assert_eq!(**val, VALUE_3); + } +} diff --git a/pallets/contracts/fixtures/contracts/xcm_execute.rs b/pallets/contracts/fixtures/contracts/xcm_execute.rs new file mode 100644 index 00000000..1d570ffe --- /dev/null +++ b/pallets/contracts/fixtures/contracts/xcm_execute.rs @@ -0,0 +1,40 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!(512, msg: [u8],); + + #[allow(deprecated)] + let err_code = match api::xcm_execute(msg) { + Ok(_) => 0u32, + Err(code) => code as u32, + }; + + api::return_value(uapi::ReturnFlags::empty(), &err_code.to_le_bytes()); +} diff --git a/pallets/contracts/fixtures/contracts/xcm_send.rs b/pallets/contracts/fixtures/contracts/xcm_send.rs new file mode 100644 index 00000000..6d4629e7 --- /dev/null +++ b/pallets/contracts/fixtures/contracts/xcm_send.rs @@ -0,0 +1,42 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + 512, + dest: [u8; 3], + msg: [u8], + ); + + let mut message_id = [0u8; 32]; + + #[allow(deprecated)] + api::xcm_send(dest, msg, &mut message_id).unwrap(); + api::return_value(uapi::ReturnFlags::empty(), &message_id); +} diff --git a/pallets/contracts/fixtures/src/lib.rs b/pallets/contracts/fixtures/src/lib.rs new file mode 100644 index 00000000..56a8e232 --- /dev/null +++ b/pallets/contracts/fixtures/src/lib.rs @@ -0,0 +1,45 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use sp_runtime::traits::Hash; +use std::{fs, path::PathBuf}; + +/// Load a given wasm module and returns a wasm binary contents along with it's hash. +/// Use the legacy compile_module as fallback, if the rust fixture does not exist yet. +pub fn compile_module( + fixture_name: &str, +) -> anyhow::Result<(Vec, ::Output)> +where + T: frame_system::Config, +{ + let out_dir: PathBuf = env!("OUT_DIR").into(); + let fixture_path = out_dir.join(format!("{fixture_name}.wasm")); + let binary = fs::read(fixture_path)?; + let code_hash = T::Hashing::hash(&binary); + Ok((binary, code_hash)) +} + +#[cfg(test)] +mod test { + #[test] + fn out_dir_should_have_compiled_mocks() { + let out_dir: std::path::PathBuf = env!("OUT_DIR").into(); + assert!(out_dir.join("dummy.wasm").exists()); + #[cfg(feature = "riscv")] + assert!(out_dir.join("dummy.polkavm").exists()); + } +} diff --git a/pallets/contracts/mock-network/Cargo.toml b/pallets/contracts/mock-network/Cargo.toml new file mode 100644 index 00000000..810304c2 --- /dev/null +++ b/pallets/contracts/mock-network/Cargo.toml @@ -0,0 +1,87 @@ +[package] +name = "pallet-contracts-mock-network" +version = "3.0.0" +authors.workspace = true +edition.workspace = true +license.workspace = true +homepage.workspace = true +repository.workspace = true +description = "A mock network for testing pallet-contracts" + +[dependencies] +codec = { features = ["derive", "max-encoded-len"], workspace = true } + +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-assets = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-contracts = { workspace = true, default-features = true } +pallet-contracts-uapi = { workspace = true } +pallet-contracts-proc-macro = { workspace = true, default-features = true } +pallet-insecure-randomness-collective-flip = { workspace = true, default-features = true } +pallet-message-queue = { workspace = true, default-features = true } +pallet-proxy = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +pallet-utility = { workspace = true, default-features = true } +pallet-xcm = { workspace = true } +polkadot-parachain-primitives = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-runtime-parachains = { workspace = true, default-features = true } +scale-info = { features = ["derive"], workspace = true } +sp-api = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-keystore = { workspace = true, default-features = true } +sp-runtime = { workspace = true } +sp-tracing = { workspace = true, default-features = true } +xcm = { workspace = true } +xcm-builder = { workspace = true, default-features = true } +xcm-executor = { workspace = true } +xcm-simulator = { workspace = true, default-features = true } + +[dev-dependencies] +assert_matches = { workspace = true } +pretty_assertions = { workspace = true } +pallet-contracts-fixtures = { workspace = true } + +[features] +default = ["std"] +std = [ + "codec/std", + "frame-support/std", + "frame-system/std", + "pallet-balances/std", + "pallet-contracts/std", + "pallet-insecure-randomness-collective-flip/std", + "pallet-proxy/std", + "pallet-timestamp/std", + "pallet-utility/std", + "pallet-xcm/std", + "scale-info/std", + "sp-api/std", + "sp-core/std", + "sp-io/std", + "sp-keystore/std", + "sp-runtime/std", + "xcm-executor/std", + "xcm/std", +] + +runtime-benchmarks = [ + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-assets/runtime-benchmarks", + "pallet-balances/runtime-benchmarks", + "pallet-contracts/runtime-benchmarks", + "pallet-message-queue/runtime-benchmarks", + "pallet-proxy/runtime-benchmarks", + "pallet-timestamp/runtime-benchmarks", + "pallet-utility/runtime-benchmarks", + "pallet-xcm/runtime-benchmarks", + "polkadot-parachain-primitives/runtime-benchmarks", + "polkadot-primitives/runtime-benchmarks", + "polkadot-runtime-parachains/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "xcm-builder/runtime-benchmarks", + "xcm-executor/runtime-benchmarks", +] diff --git a/pallets/contracts/mock-network/src/lib.rs b/pallets/contracts/mock-network/src/lib.rs new file mode 100644 index 00000000..34cc95f2 --- /dev/null +++ b/pallets/contracts/mock-network/src/lib.rs @@ -0,0 +1,152 @@ +// Copyright Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +pub mod mocks; +pub mod parachain; +pub mod primitives; +pub mod relay_chain; + +#[cfg(test)] +mod tests; + +use crate::primitives::{AccountId, UNITS}; +pub use pallet_contracts::test_utils::{ALICE, BOB}; +use sp_runtime::BuildStorage; +use xcm::latest::prelude::*; +use xcm_executor::traits::ConvertLocation; +pub use xcm_simulator::TestExt; +use xcm_simulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain}; + +// Accounts +pub const ADMIN: sp_runtime::AccountId32 = sp_runtime::AccountId32::new([0u8; 32]); + +// Balances +pub const INITIAL_BALANCE: u128 = 1_000_000_000 * UNITS; + +decl_test_parachain! { + pub struct ParaA { + Runtime = parachain::Runtime, + XcmpMessageHandler = parachain::MsgQueue, + DmpMessageHandler = parachain::MsgQueue, + new_ext = para_ext(1), + } +} + +decl_test_relay_chain! { + pub struct Relay { + Runtime = relay_chain::Runtime, + RuntimeCall = relay_chain::RuntimeCall, + RuntimeEvent = relay_chain::RuntimeEvent, + XcmConfig = relay_chain::XcmConfig, + MessageQueue = relay_chain::MessageQueue, + System = relay_chain::System, + new_ext = relay_ext(), + } +} + +decl_test_network! { + pub struct MockNet { + relay_chain = Relay, + parachains = vec![ + (1, ParaA), + ], + } +} + +pub fn relay_sovereign_account_id() -> AccountId { + let location: Location = (Parent,).into(); + parachain::SovereignAccountOf::convert_location(&location).unwrap() +} + +pub fn parachain_sovereign_account_id(para: u32) -> AccountId { + let location: Location = (Parachain(para),).into(); + relay_chain::SovereignAccountOf::convert_location(&location).unwrap() +} + +pub fn parachain_account_sovereign_account_id( + para: u32, + who: sp_runtime::AccountId32, +) -> AccountId { + let location: Location = ( + Parachain(para), + AccountId32 { network: Some(relay_chain::RelayNetwork::get()), id: who.into() }, + ) + .into(); + relay_chain::SovereignAccountOf::convert_location(&location).unwrap() +} + +pub fn para_ext(para_id: u32) -> sp_io::TestExternalities { + use parachain::{MsgQueue, Runtime, System}; + + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + + pallet_balances::GenesisConfig:: { + balances: vec![ + (ALICE, INITIAL_BALANCE), + (relay_sovereign_account_id(), INITIAL_BALANCE), + (BOB, INITIAL_BALANCE), + ], + } + .assimilate_storage(&mut t) + .unwrap(); + + pallet_assets::GenesisConfig:: { + assets: vec![ + (0u128, ADMIN, false, 1u128), // Create derivative asset for relay's native token + ], + metadata: Default::default(), + accounts: vec![ + (0u128, ALICE, INITIAL_BALANCE), + (0u128, relay_sovereign_account_id(), INITIAL_BALANCE), + ], + next_asset_id: None, + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| { + sp_tracing::try_init_simple(); + System::set_block_number(1); + MsgQueue::set_para_id(para_id.into()); + }); + ext +} + +pub fn relay_ext() -> sp_io::TestExternalities { + use relay_chain::{Runtime, System}; + + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + + pallet_balances::GenesisConfig:: { + balances: vec![ + (ALICE, INITIAL_BALANCE), + (parachain_sovereign_account_id(1), INITIAL_BALANCE), + (parachain_account_sovereign_account_id(1, ALICE), INITIAL_BALANCE), + ], + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| { + System::set_block_number(1); + }); + ext +} + +pub type ParachainPalletXcm = pallet_xcm::Pallet; +pub type ParachainBalances = pallet_balances::Pallet; diff --git a/pallets/contracts/mock-network/src/mocks.rs b/pallets/contracts/mock-network/src/mocks.rs new file mode 100644 index 00000000..bf3baec7 --- /dev/null +++ b/pallets/contracts/mock-network/src/mocks.rs @@ -0,0 +1,18 @@ +// Copyright Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +pub mod msg_queue; +pub mod relay_message_queue; diff --git a/pallets/contracts/mock-network/src/mocks/msg_queue.rs b/pallets/contracts/mock-network/src/mocks/msg_queue.rs new file mode 100644 index 00000000..6e922c16 --- /dev/null +++ b/pallets/contracts/mock-network/src/mocks/msg_queue.rs @@ -0,0 +1,186 @@ +// Copyright Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +//! Parachain runtime mock. + +use codec::{Decode, Encode}; + +use frame_support::weights::Weight; +use polkadot_parachain_primitives::primitives::{ + DmpMessageHandler, Id as ParaId, XcmpMessageFormat, XcmpMessageHandler, +}; +use polkadot_primitives::BlockNumber as RelayBlockNumber; +use sp_runtime::traits::{Get, Hash}; + +use xcm::{latest::prelude::*, VersionedXcm}; + +#[frame_support::pallet] +pub mod pallet { + use super::*; + use frame_support::pallet_prelude::*; + + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + type XcmExecutor: ExecuteXcm; + } + + #[pallet::call] + impl Pallet {} + + #[pallet::pallet] + #[pallet::without_storage_info] + pub struct Pallet(_); + + #[pallet::storage] + pub(super) type ParachainId = StorageValue<_, ParaId, ValueQuery>; + + #[pallet::storage] + /// A queue of received DMP messages + pub(super) type ReceivedDmp = StorageValue<_, Vec>, ValueQuery>; + + impl Get for Pallet { + fn get() -> ParaId { + ParachainId::::get() + } + } + + pub type MessageId = [u8; 32]; + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + /// Some XCM was executed OK. + Success(Option), + /// Some XCM failed. + Fail(Option, XcmError), + /// Bad XCM version used. + BadVersion(Option), + /// Bad XCM format used. + BadFormat(Option), + + // DMP + /// Downward message is invalid XCM. + InvalidFormat(MessageId), + /// Downward message is unsupported version of XCM. + UnsupportedVersion(MessageId), + /// Downward message executed with the given outcome. + ExecutedDownward(MessageId, Outcome), + } + + impl Pallet { + pub fn set_para_id(para_id: ParaId) { + ParachainId::::put(para_id); + } + + pub fn parachain_id() -> ParaId { + ParachainId::::get() + } + + pub fn received_dmp() -> Vec> { + ReceivedDmp::::get() + } + + fn handle_xcmp_message( + sender: ParaId, + _sent_at: RelayBlockNumber, + xcm: VersionedXcm, + max_weight: Weight, + ) -> Result { + let hash = Encode::using_encoded(&xcm, T::Hashing::hash); + let mut message_hash = Encode::using_encoded(&xcm, sp_io::hashing::blake2_256); + let (result, event) = match Xcm::::try_from(xcm) { + Ok(xcm) => { + let location = (Parent, Parachain(sender.into())); + match T::XcmExecutor::prepare_and_execute( + location, + xcm, + &mut message_hash, + max_weight, + Weight::zero(), + ) { + Outcome::Error { error } => (Err(error), Event::Fail(Some(hash), error)), + Outcome::Complete { used } => (Ok(used), Event::Success(Some(hash))), + // As far as the caller is concerned, this was dispatched without error, so + // we just report the weight used. + Outcome::Incomplete { used, error } => + (Ok(used), Event::Fail(Some(hash), error)), + } + }, + Err(()) => (Err(XcmError::UnhandledXcmVersion), Event::BadVersion(Some(hash))), + }; + Self::deposit_event(event); + result + } + } + + impl XcmpMessageHandler for Pallet { + fn handle_xcmp_messages<'a, I: Iterator>( + iter: I, + max_weight: Weight, + ) -> Weight { + for (sender, sent_at, data) in iter { + let mut data_ref = data; + let _ = XcmpMessageFormat::decode(&mut data_ref) + .expect("Simulator encodes with versioned xcm format; qed"); + + let mut remaining_fragments = data_ref; + while !remaining_fragments.is_empty() { + if let Ok(xcm) = + VersionedXcm::::decode(&mut remaining_fragments) + { + let _ = Self::handle_xcmp_message(sender, sent_at, xcm, max_weight); + } else { + debug_assert!(false, "Invalid incoming XCMP message data"); + } + } + } + max_weight + } + } + + impl DmpMessageHandler for Pallet { + fn handle_dmp_messages( + iter: impl Iterator)>, + limit: Weight, + ) -> Weight { + for (_i, (_sent_at, data)) in iter.enumerate() { + let mut id = sp_io::hashing::blake2_256(&data[..]); + let maybe_versioned = VersionedXcm::::decode(&mut &data[..]); + match maybe_versioned { + Err(_) => { + Self::deposit_event(Event::InvalidFormat(id)); + }, + Ok(versioned) => match Xcm::try_from(versioned) { + Err(()) => Self::deposit_event(Event::UnsupportedVersion(id)), + Ok(x) => { + let outcome = T::XcmExecutor::prepare_and_execute( + Parent, + x.clone(), + &mut id, + limit, + Weight::zero(), + ); + ReceivedDmp::::append(x); + Self::deposit_event(Event::ExecutedDownward(id, outcome)); + }, + }, + } + } + limit + } + } +} diff --git a/pallets/contracts/mock-network/src/mocks/relay_message_queue.rs b/pallets/contracts/mock-network/src/mocks/relay_message_queue.rs new file mode 100644 index 00000000..14099965 --- /dev/null +++ b/pallets/contracts/mock-network/src/mocks/relay_message_queue.rs @@ -0,0 +1,52 @@ +// Copyright Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +use frame_support::{parameter_types, weights::Weight}; +use xcm::latest::prelude::*; +use xcm_simulator::{ + AggregateMessageOrigin, ProcessMessage, ProcessMessageError, UmpQueueId, WeightMeter, +}; + +use crate::relay_chain::{RuntimeCall, XcmConfig}; + +parameter_types! { + /// Amount of weight that can be spent per block to service messages. + pub MessageQueueServiceWeight: Weight = Weight::from_parts(1_000_000_000, 1_000_000); + pub const MessageQueueHeapSize: u32 = 65_536; + pub const MessageQueueMaxStale: u32 = 16; +} + +/// Message processor to handle any messages that were enqueued into the `MessageQueue` pallet. +pub struct MessageProcessor; +impl ProcessMessage for MessageProcessor { + type Origin = AggregateMessageOrigin; + + fn process_message( + message: &[u8], + origin: Self::Origin, + meter: &mut WeightMeter, + id: &mut [u8; 32], + ) -> Result { + let para = match origin { + AggregateMessageOrigin::Ump(UmpQueueId::Para(para)) => para, + }; + xcm_builder::ProcessXcmMessage::< + Junction, + xcm_executor::XcmExecutor, + RuntimeCall, + >::process_message(message, Junction::Parachain(para.into()), meter, id) + } +} diff --git a/pallets/contracts/mock-network/src/parachain.rs b/pallets/contracts/mock-network/src/parachain.rs new file mode 100644 index 00000000..3579b46e --- /dev/null +++ b/pallets/contracts/mock-network/src/parachain.rs @@ -0,0 +1,346 @@ +// Copyright Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +//! Parachain runtime mock. + +mod contracts_config; +use crate::{ + mocks::msg_queue::pallet as mock_msg_queue, + primitives::{AccountId, AssetIdForAssets, Balance}, +}; +use core::marker::PhantomData; +use frame_support::{ + construct_runtime, derive_impl, parameter_types, + traits::{AsEnsureOriginWithArg, Contains, ContainsPair, Everything, EverythingBut, Nothing}, + weights::{ + constants::{WEIGHT_PROOF_SIZE_PER_MB, WEIGHT_REF_TIME_PER_SECOND}, + Weight, + }, +}; +use frame_system::{EnsureRoot, EnsureSigned}; +use pallet_xcm::XcmPassthrough; +use sp_core::{ConstU32, ConstU64, H256}; +use sp_runtime::traits::{Get, IdentityLookup, MaybeEquivalence}; + +use xcm::latest::prelude::*; +use xcm_builder::{ + AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom, + ConvertedConcreteId, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, + FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, IsConcrete, NativeAsset, + NoChecking, ParentAsSuperuser, ParentIsPreset, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, WithComputedOrigin, +}; +use xcm_executor::{traits::JustTry, Config, XcmExecutor}; + +pub type SovereignAccountOf = + (AccountId32Aliases, ParentIsPreset); + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] +impl frame_system::Config for Runtime { + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type Nonce = u64; + type Block = Block; + type Hash = H256; + type Hashing = ::sp_runtime::traits::BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type RuntimeEvent = RuntimeEvent; + type BlockWeights = (); + type BlockLength = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type DbWeight = (); + type BaseCallFilter = Everything; + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = ConstU32<16>; +} + +parameter_types! { + pub ExistentialDeposit: Balance = 1; + pub const MaxLocks: u32 = 50; + pub const MaxReserves: u32 = 50; +} + +impl pallet_balances::Config for Runtime { + type AccountStore = System; + type Balance = Balance; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type FreezeIdentifier = (); + type MaxFreezes = ConstU32<0>; + type MaxLocks = MaxLocks; + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; + type RuntimeEvent = RuntimeEvent; + type RuntimeHoldReason = RuntimeHoldReason; + type RuntimeFreezeReason = RuntimeFreezeReason; + type WeightInfo = (); +} + +parameter_types! { + pub const AssetDeposit: u128 = 1_000_000; + pub const MetadataDepositBase: u128 = 1_000_000; + pub const MetadataDepositPerByte: u128 = 100_000; + pub const AssetAccountDeposit: u128 = 1_000_000; + pub const ApprovalDeposit: u128 = 1_000_000; + pub const AssetsStringLimit: u32 = 50; + pub const RemoveItemsLimit: u32 = 50; +} + +impl pallet_assets::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type AssetId = AssetIdForAssets; + type Currency = Balances; + type CreateOrigin = AsEnsureOriginWithArg>; + type ForceOrigin = EnsureRoot; + type AssetDeposit = AssetDeposit; + type MetadataDepositBase = MetadataDepositBase; + type MetadataDepositPerByte = MetadataDepositPerByte; + type AssetAccountDeposit = AssetAccountDeposit; + type ApprovalDeposit = ApprovalDeposit; + type StringLimit = AssetsStringLimit; + type Freezer = (); + type Extra = (); + type WeightInfo = (); + type RemoveItemsLimit = RemoveItemsLimit; + type AssetIdParameter = AssetIdForAssets; + type CallbackHandle = (); + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = (); +} + +parameter_types! { + pub const ReservedXcmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0); + pub const ReservedDmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0); +} + +parameter_types! { + pub const KsmLocation: Location = Location::parent(); + pub const TokenLocation: Location = Here.into_location(); + pub const RelayNetwork: NetworkId = ByGenesis([0; 32]); + pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::parachain_id().into())].into(); +} + +pub type XcmOriginToCallOrigin = ( + SovereignSignedViaLocation, + ParentAsSuperuser, + SignedAccountId32AsNative, + XcmPassthrough, +); + +parameter_types! { + pub const XcmInstructionWeight: Weight = Weight::from_parts(1_000, 1_000); + pub TokensPerSecondPerMegabyte: (AssetId, u128, u128) = (AssetId(Parent.into()), 1_000_000_000_000, 1024 * 1024); + pub const MaxInstructions: u32 = 100; + pub const MaxAssetsIntoHolding: u32 = 64; + pub ForeignPrefix: Location = (Parent,).into(); + pub CheckingAccount: AccountId = PolkadotXcm::check_account(); + pub TrustedLockPairs: (Location, AssetFilter) = + (Parent.into(), Wild(AllOf { id: AssetId(Parent.into()), fun: WildFungible })); +} + +pub fn estimate_message_fee(number_of_instructions: u64) -> u128 { + let weight = estimate_weight(number_of_instructions); + + estimate_fee_for_weight(weight) +} + +pub fn estimate_weight(number_of_instructions: u64) -> Weight { + XcmInstructionWeight::get().saturating_mul(number_of_instructions) +} + +pub fn estimate_fee_for_weight(weight: Weight) -> u128 { + let (_, units_per_second, units_per_mb) = TokensPerSecondPerMegabyte::get(); + + units_per_second * (weight.ref_time() as u128) / (WEIGHT_REF_TIME_PER_SECOND as u128) + + units_per_mb * (weight.proof_size() as u128) / (WEIGHT_PROOF_SIZE_PER_MB as u128) +} + +pub type LocalBalancesTransactor = + FungibleAdapter, SovereignAccountOf, AccountId, ()>; + +pub struct FromLocationToAsset(PhantomData<(Location, AssetId)>); +impl MaybeEquivalence + for FromLocationToAsset +{ + fn convert(value: &Location) -> Option { + match value.unpack() { + (1, []) => Some(0 as AssetIdForAssets), + (1, [Parachain(para_id)]) => Some(*para_id as AssetIdForAssets), + _ => None, + } + } + + fn convert_back(_id: &AssetIdForAssets) -> Option { + None + } +} + +pub type ForeignAssetsTransactor = FungiblesAdapter< + Assets, + ConvertedConcreteId< + AssetIdForAssets, + Balance, + FromLocationToAsset, + JustTry, + >, + SovereignAccountOf, + AccountId, + NoChecking, + CheckingAccount, +>; + +/// Means for transacting assets on this chain +pub type AssetTransactors = (LocalBalancesTransactor, ForeignAssetsTransactor); + +pub struct ParentRelay; +impl Contains for ParentRelay { + fn contains(location: &Location) -> bool { + location.contains_parents_only(1) + } +} +pub struct ThisParachain; +impl Contains for ThisParachain { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (0, [Junction::AccountId32 { .. }])) + } +} + +pub type XcmRouter = crate::ParachainXcmRouter; + +pub type Barrier = ( + xcm_builder::AllowUnpaidExecutionFrom, + WithComputedOrigin< + (AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom), + UniversalLocation, + ConstU32<1>, + >, +); + +parameter_types! { + pub NftCollectionOne: AssetFilter + = Wild(AllOf { fun: WildNonFungible, id: AssetId((Parent, GeneralIndex(1)).into()) }); + pub NftCollectionOneForRelay: (AssetFilter, Location) + = (NftCollectionOne::get(), Parent.into()); + pub RelayNativeAsset: AssetFilter = Wild(AllOf { fun: WildFungible, id: AssetId((Parent, Here).into()) }); + pub RelayNativeAssetForRelay: (AssetFilter, Location) = (RelayNativeAsset::get(), Parent.into()); +} +pub type TrustedTeleporters = + (xcm_builder::Case, xcm_builder::Case); +pub type TrustedReserves = EverythingBut>; + +pub struct XcmConfig; +impl Config for XcmConfig { + type RuntimeCall = RuntimeCall; + type XcmSender = XcmRouter; + type AssetTransactor = AssetTransactors; + type OriginConverter = XcmOriginToCallOrigin; + type IsReserve = (NativeAsset, TrustedReserves); + type IsTeleporter = TrustedTeleporters; + type UniversalLocation = UniversalLocation; + type Barrier = Barrier; + type Weigher = FixedWeightBounds; + type Trader = FixedRateOfFungible; + type ResponseHandler = PolkadotXcm; + type AssetTrap = PolkadotXcm; + type AssetLocker = PolkadotXcm; + type AssetExchanger = (); + type AssetClaims = PolkadotXcm; + type SubscriptionService = PolkadotXcm; + type PalletInstancesInfo = AllPalletsWithSystem; + type FeeManager = (); + type MaxAssetsIntoHolding = MaxAssetsIntoHolding; + type MessageExporter = (); + type UniversalAliases = Nothing; + type CallDispatcher = RuntimeCall; + type SafeCallFilter = Everything; + type Aliasers = Nothing; + type TransactionalProcessor = FrameTransactionalProcessor; + type HrmpNewChannelOpenRequestHandler = (); + type HrmpChannelAcceptedHandler = (); + type HrmpChannelClosingHandler = (); + type XcmRecorder = PolkadotXcm; +} + +impl mock_msg_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type XcmExecutor = XcmExecutor; +} + +pub type LocalOriginToLocation = SignedToAccountId32; + +pub struct TrustedLockerCase(PhantomData); +impl> ContainsPair for TrustedLockerCase { + fn contains(origin: &Location, asset: &Asset) -> bool { + let (o, a) = T::get(); + a.matches(asset) && &o == origin + } +} + +impl pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type SendXcmOrigin = EnsureXcmOrigin; + type XcmRouter = XcmRouter; + type ExecuteXcmOrigin = EnsureXcmOrigin; + type XcmExecuteFilter = Everything; + type XcmExecutor = XcmExecutor; + type XcmTeleportFilter = Nothing; + type XcmReserveTransferFilter = Everything; + type Weigher = FixedWeightBounds; + type UniversalLocation = UniversalLocation; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + type Currency = Balances; + type CurrencyMatcher = IsConcrete; + type TrustedLockers = TrustedLockerCase; + type SovereignAccountOf = SovereignAccountOf; + type MaxLockers = ConstU32<8>; + type MaxRemoteLockConsumers = ConstU32<0>; + type RemoteLockConsumerIdentifier = (); + type WeightInfo = pallet_xcm::TestWeightInfo; + type AdminOrigin = EnsureRoot; +} + +type Block = frame_system::mocking::MockBlock; + +impl pallet_timestamp::Config for Runtime { + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = ConstU64<1>; + type WeightInfo = (); +} + +construct_runtime!( + pub enum Runtime + { + System: frame_system, + Balances: pallet_balances, + Timestamp: pallet_timestamp, + MsgQueue: mock_msg_queue, + PolkadotXcm: pallet_xcm, + Contracts: pallet_contracts, + Assets: pallet_assets, + } +); diff --git a/pallets/contracts/mock-network/src/parachain/contracts_config.rs b/pallets/contracts/mock-network/src/parachain/contracts_config.rs new file mode 100644 index 00000000..bf3c00b3 --- /dev/null +++ b/pallets/contracts/mock-network/src/parachain/contracts_config.rs @@ -0,0 +1,33 @@ +// Copyright Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +use super::{Balances, Runtime, RuntimeCall, RuntimeEvent}; +use crate::parachain::RuntimeHoldReason; +use frame_support::{derive_impl, parameter_types}; + +parameter_types! { + pub Schedule: pallet_contracts::Schedule = Default::default(); +} + +#[derive_impl(pallet_contracts::config_preludes::TestDefaultConfig)] +impl pallet_contracts::Config for Runtime { + type AddressGenerator = pallet_contracts::DefaultAddressGenerator; + type CallStack = [pallet_contracts::Frame; 5]; + type Currency = Balances; + type Schedule = Schedule; + type Time = super::Timestamp; + type Xcm = pallet_xcm::Pallet; +} diff --git a/pallets/contracts/mock-network/src/primitives.rs b/pallets/contracts/mock-network/src/primitives.rs new file mode 100644 index 00000000..efc42772 --- /dev/null +++ b/pallets/contracts/mock-network/src/primitives.rs @@ -0,0 +1,23 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +pub type Balance = u128; + +pub const UNITS: Balance = 10_000_000_000; +pub const CENTS: Balance = UNITS / 100; // 100_000_000 + +pub type AccountId = sp_runtime::AccountId32; +pub type AssetIdForAssets = u128; diff --git a/pallets/contracts/mock-network/src/relay_chain.rs b/pallets/contracts/mock-network/src/relay_chain.rs new file mode 100644 index 00000000..8829fff3 --- /dev/null +++ b/pallets/contracts/mock-network/src/relay_chain.rs @@ -0,0 +1,239 @@ +// Copyright Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +//! Relay chain runtime mock. + +use frame_support::{ + construct_runtime, derive_impl, parameter_types, + traits::{Contains, Everything, Nothing}, + weights::Weight, +}; + +use frame_system::EnsureRoot; +use sp_core::{ConstU32, H256}; +use sp_runtime::traits::IdentityLookup; + +use polkadot_parachain_primitives::primitives::Id as ParaId; +use polkadot_runtime_parachains::{configuration, origin, shared}; +use xcm::latest::prelude::*; +use xcm_builder::{ + AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, ChildParachainAsNative, ChildParachainConvertsVia, + ChildSystemParachainAsSuperuser, DescribeAllTerminal, DescribeFamily, FixedRateOfFungible, + FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, HashedDescription, IsConcrete, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, WithComputedOrigin, +}; +use xcm_executor::{Config, XcmExecutor}; + +use super::{ + mocks::relay_message_queue::*, + primitives::{AccountId, Balance}, +}; + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] +impl frame_system::Config for Runtime { + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type Block = Block; + type Nonce = u64; + type Hash = H256; + type Hashing = ::sp_runtime::traits::BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type RuntimeEvent = RuntimeEvent; + type BlockWeights = (); + type BlockLength = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type DbWeight = (); + type BaseCallFilter = Everything; + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = ConstU32<16>; +} + +parameter_types! { + pub ExistentialDeposit: Balance = 1; + pub const MaxLocks: u32 = 50; + pub const MaxReserves: u32 = 50; +} + +impl pallet_balances::Config for Runtime { + type MaxLocks = MaxLocks; + type Balance = Balance; + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = (); + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; + type FreezeIdentifier = (); + type MaxFreezes = ConstU32<0>; + type RuntimeHoldReason = RuntimeHoldReason; + type RuntimeFreezeReason = RuntimeFreezeReason; +} + +impl shared::Config for Runtime { + type DisabledValidators = (); +} + +impl configuration::Config for Runtime { + type WeightInfo = configuration::TestWeightInfo; +} + +parameter_types! { + pub RelayNetwork: NetworkId = ByGenesis([0; 32]); + pub const TokenLocation: Location = Here.into_location(); + pub UniversalLocation: InteriorLocation = RelayNetwork::get().into(); + pub UnitWeightCost: u64 = 1_000; +} + +pub type SovereignAccountOf = ( + HashedDescription>, + AccountId32Aliases, + ChildParachainConvertsVia, +); + +pub type LocalBalancesTransactor = + FungibleAdapter, SovereignAccountOf, AccountId, ()>; + +pub type AssetTransactors = LocalBalancesTransactor; + +type LocalOriginConverter = ( + SovereignSignedViaLocation, + ChildParachainAsNative, + SignedAccountId32AsNative, + ChildSystemParachainAsSuperuser, +); + +parameter_types! { + pub const XcmInstructionWeight: Weight = Weight::from_parts(1_000, 1_000); + pub TokensPerSecondPerMegabyte: (AssetId, u128, u128) = + (AssetId(TokenLocation::get()), 1_000_000_000_000, 1024 * 1024); + pub const MaxInstructions: u32 = 100; + pub const MaxAssetsIntoHolding: u32 = 64; +} + +pub struct ChildrenParachains; +impl Contains for ChildrenParachains { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (0, [Parachain(_)])) + } +} + +pub type XcmRouter = crate::RelayChainXcmRouter; +pub type Barrier = WithComputedOrigin< + ( + AllowExplicitUnpaidExecutionFrom, + AllowTopLevelPaidExecutionFrom, + AllowSubscriptionsFrom, + ), + UniversalLocation, + ConstU32<1>, +>; + +pub struct XcmConfig; +impl Config for XcmConfig { + type RuntimeCall = RuntimeCall; + type XcmSender = XcmRouter; + type AssetTransactor = AssetTransactors; + type OriginConverter = LocalOriginConverter; + type IsReserve = (); + type IsTeleporter = (); + type UniversalLocation = UniversalLocation; + type Barrier = Barrier; + type Weigher = FixedWeightBounds; + type Trader = FixedRateOfFungible; + type ResponseHandler = XcmPallet; + type AssetTrap = XcmPallet; + type AssetLocker = XcmPallet; + type AssetExchanger = (); + type AssetClaims = XcmPallet; + type SubscriptionService = XcmPallet; + type PalletInstancesInfo = AllPalletsWithSystem; + type FeeManager = (); + type MaxAssetsIntoHolding = MaxAssetsIntoHolding; + type MessageExporter = (); + type UniversalAliases = Nothing; + type CallDispatcher = RuntimeCall; + type SafeCallFilter = Everything; + type Aliasers = Nothing; + type TransactionalProcessor = FrameTransactionalProcessor; + type HrmpNewChannelOpenRequestHandler = (); + type HrmpChannelAcceptedHandler = (); + type HrmpChannelClosingHandler = (); + type XcmRecorder = XcmPallet; +} + +pub type LocalOriginToLocation = SignedToAccountId32; + +impl pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type SendXcmOrigin = xcm_builder::EnsureXcmOrigin; + type XcmRouter = XcmRouter; + type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin; + type XcmExecuteFilter = Everything; + type XcmExecutor = XcmExecutor; + type XcmTeleportFilter = Everything; + type XcmReserveTransferFilter = Everything; + type Weigher = FixedWeightBounds; + type UniversalLocation = UniversalLocation; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + type Currency = Balances; + type CurrencyMatcher = IsConcrete; + type TrustedLockers = (); + type SovereignAccountOf = SovereignAccountOf; + type MaxLockers = ConstU32<8>; + type MaxRemoteLockConsumers = ConstU32<0>; + type RemoteLockConsumerIdentifier = (); + type WeightInfo = pallet_xcm::TestWeightInfo; + type AdminOrigin = EnsureRoot; +} + +impl origin::Config for Runtime {} + +type Block = frame_system::mocking::MockBlock; + +impl pallet_message_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Size = u32; + type HeapSize = MessageQueueHeapSize; + type MaxStale = MessageQueueMaxStale; + type ServiceWeight = MessageQueueServiceWeight; + type IdleMaxServiceWeight = (); + type MessageProcessor = MessageProcessor; + type QueueChangeHandler = (); + type WeightInfo = (); + type QueuePausedQuery = (); +} + +construct_runtime!( + pub enum Runtime { + System: frame_system, + Balances: pallet_balances, + ParasOrigin: origin, + XcmPallet: pallet_xcm, + MessageQueue: pallet_message_queue, + } +); diff --git a/pallets/contracts/mock-network/src/tests.rs b/pallets/contracts/mock-network/src/tests.rs new file mode 100644 index 00000000..48a94e17 --- /dev/null +++ b/pallets/contracts/mock-network/src/tests.rs @@ -0,0 +1,200 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::{ + parachain::{self, Runtime}, + parachain_account_sovereign_account_id, + primitives::{AccountId, CENTS}, + relay_chain, MockNet, ParaA, ParachainBalances, Relay, ALICE, BOB, INITIAL_BALANCE, +}; +use codec::{Decode, Encode}; +use frame_support::traits::{fungibles::Mutate, Currency}; +use pallet_contracts::{test_utils::builder::*, Code}; +use pallet_contracts_fixtures::compile_module; +use pallet_contracts_uapi::ReturnErrorCode; +use xcm::{v4::prelude::*, VersionedLocation, VersionedXcm}; +use xcm_simulator::TestExt; + +macro_rules! assert_return_code { + ( $x:expr , $y:expr $(,)? ) => {{ + assert_eq!(u32::from_le_bytes($x.data[..].try_into().unwrap()), $y as u32); + }}; +} + +fn bare_call(dest: sp_runtime::AccountId32) -> BareCallBuilder { + BareCallBuilder::::bare_call(ALICE, dest) +} + +/// Instantiate the tests contract, and fund it with some balance and assets. +fn instantiate_test_contract(name: &str) -> AccountId { + let (wasm, _) = compile_module::(name).unwrap(); + + // Instantiate contract. + let contract_addr = ParaA::execute_with(|| { + BareInstantiateBuilder::::bare_instantiate(ALICE, Code::Upload(wasm)) + .build_and_unwrap_account_id() + }); + + // Funds contract account with some balance and assets. + ParaA::execute_with(|| { + parachain::Balances::make_free_balance_be(&contract_addr, INITIAL_BALANCE); + parachain::Assets::mint_into(0u32.into(), &contract_addr, INITIAL_BALANCE).unwrap(); + }); + Relay::execute_with(|| { + let sovereign_account = parachain_account_sovereign_account_id(1u32, contract_addr.clone()); + relay_chain::Balances::make_free_balance_be(&sovereign_account, INITIAL_BALANCE); + }); + + contract_addr +} + +#[test] +fn test_xcm_execute() { + MockNet::reset(); + + let contract_addr = instantiate_test_contract("xcm_execute"); + + // Execute XCM instructions through the contract. + ParaA::execute_with(|| { + let amount: u128 = 10 * CENTS; + let assets: Asset = (Here, amount).into(); + let beneficiary = AccountId32 { network: None, id: BOB.clone().into() }; + + // The XCM used to transfer funds to Bob. + let message: Xcm<()> = Xcm::builder_unsafe() + .withdraw_asset(assets.clone()) + .deposit_asset(assets, beneficiary) + .build(); + + let result = bare_call(contract_addr.clone()) + .data(VersionedXcm::V4(message).encode()) + .build(); + + assert_eq!(result.gas_consumed, result.gas_required); + assert_return_code!(&result.result.unwrap(), ReturnErrorCode::Success); + + // Check if the funds are subtracted from the account of Alice and added to the account of + // Bob. + let initial = INITIAL_BALANCE; + assert_eq!(ParachainBalances::free_balance(BOB), initial + amount); + assert_eq!(ParachainBalances::free_balance(&contract_addr), initial - amount); + }); +} + +#[test] +fn test_xcm_execute_incomplete() { + MockNet::reset(); + + let contract_addr = instantiate_test_contract("xcm_execute"); + let amount = 10 * CENTS; + + // Execute XCM instructions through the contract. + ParaA::execute_with(|| { + let assets: Asset = (Here, amount).into(); + let beneficiary = AccountId32 { network: None, id: BOB.clone().into() }; + + // The XCM used to transfer funds to Bob. + let message: Xcm<()> = Xcm::builder_unsafe() + .withdraw_asset(assets.clone()) + // This will fail as the contract does not have enough balance to complete both + // withdrawals. + .withdraw_asset((Here, INITIAL_BALANCE)) + .buy_execution(assets.clone(), Unlimited) + .deposit_asset(assets, beneficiary) + .build(); + + let result = bare_call(contract_addr.clone()) + .data(VersionedXcm::V4(message).encode()) + .build(); + + assert_eq!(result.gas_consumed, result.gas_required); + assert_return_code!(&result.result.unwrap(), ReturnErrorCode::XcmExecutionFailed); + + assert_eq!(ParachainBalances::free_balance(BOB), INITIAL_BALANCE); + assert_eq!(ParachainBalances::free_balance(&contract_addr), INITIAL_BALANCE - amount); + }); +} + +#[test] +fn test_xcm_execute_reentrant_call() { + MockNet::reset(); + + let contract_addr = instantiate_test_contract("xcm_execute"); + + ParaA::execute_with(|| { + let transact_call = parachain::RuntimeCall::Contracts(pallet_contracts::Call::call { + dest: contract_addr.clone(), + gas_limit: 1_000_000.into(), + storage_deposit_limit: None, + data: vec![], + value: 0u128, + }); + + // The XCM used to transfer funds to Bob. + let message: Xcm = Xcm::builder_unsafe() + .transact(OriginKind::Native, 1_000_000_000, transact_call.encode()) + .expect_transact_status(MaybeErrorCode::Success) + .build(); + + let result = bare_call(contract_addr.clone()) + .data(VersionedXcm::V4(message).encode()) + .build_and_unwrap_result(); + + assert_return_code!(&result, ReturnErrorCode::XcmExecutionFailed); + + // Funds should not change hands as the XCM transact failed. + assert_eq!(ParachainBalances::free_balance(BOB), INITIAL_BALANCE); + }); +} + +#[test] +fn test_xcm_send() { + MockNet::reset(); + let contract_addr = instantiate_test_contract("xcm_send"); + let amount = 1_000 * CENTS; + let fee = parachain::estimate_message_fee(4); // Accounts for the `DescendOrigin` instruction added by `send_xcm` + + // Send XCM instructions through the contract, to transfer some funds from the contract + // derivative account to Alice on the relay chain. + ParaA::execute_with(|| { + let dest = VersionedLocation::V4(Parent.into()); + let assets: Asset = (Here, amount).into(); + let beneficiary = AccountId32 { network: None, id: ALICE.clone().into() }; + + let message: Xcm<()> = Xcm::builder() + .withdraw_asset(assets.clone()) + .buy_execution((Here, fee), Unlimited) + .deposit_asset(assets, beneficiary) + .build(); + + let result = bare_call(contract_addr.clone()) + .data((dest, VersionedXcm::V4(message)).encode()) + .build_and_unwrap_result(); + + let mut data = &result.data[..]; + XcmHash::decode(&mut data).expect("Failed to decode xcm_send message_id"); + }); + + Relay::execute_with(|| { + let derived_contract_addr = ¶chain_account_sovereign_account_id(1, contract_addr); + assert_eq!( + INITIAL_BALANCE - amount, + relay_chain::Balances::free_balance(derived_contract_addr) + ); + assert_eq!(INITIAL_BALANCE + amount - fee, relay_chain::Balances::free_balance(ALICE)); + }); +} diff --git a/pallets/contracts/proc-macro/Cargo.toml b/pallets/contracts/proc-macro/Cargo.toml new file mode 100644 index 00000000..a97e6e73 --- /dev/null +++ b/pallets/contracts/proc-macro/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "pallet-contracts-proc-macro" +version = "18.0.0" +authors.workspace = true +edition.workspace = true +license = "Apache-2.0" +homepage.workspace = true +repository.workspace = true +description = "Procedural macros used in pallet_contracts" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = { workspace = true } +quote = { workspace = true } +syn = { features = ["full"], workspace = true } diff --git a/pallets/contracts/proc-macro/src/lib.rs b/pallets/contracts/proc-macro/src/lib.rs new file mode 100644 index 00000000..84ea7de0 --- /dev/null +++ b/pallets/contracts/proc-macro/src/lib.rs @@ -0,0 +1,923 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Procedural macros used in the contracts module. +//! +//! Most likely you should use the [`#[define_env]`][`macro@define_env`] attribute macro which hides +//! boilerplate of defining external environment for a wasm module. + +use core::cmp::Reverse; +use proc_macro::TokenStream; +use proc_macro2::{Span, TokenStream as TokenStream2}; +use quote::{quote, quote_spanned, ToTokens}; +use syn::{ + parse_macro_input, punctuated::Punctuated, spanned::Spanned, token::Comma, Data, DeriveInput, + Fields, FnArg, Ident, +}; + +/// This derives `Debug` for a struct where each field must be of some numeric type. +/// It interprets each field as its represents some weight and formats it as times so that +/// it is readable by humans. +#[proc_macro_derive(WeightDebug)] +pub fn derive_weight_debug(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + let name = &input.ident; + let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); + let data = if let Data::Struct(data) = &input.data { + data + } else { + return quote_spanned! { + name.span() => + compile_error!("WeightDebug is only supported for structs."); + } + .into() + }; + + let fields = match &data.fields { + Fields::Named(fields) => { + let recurse = fields.named.iter().filter_map(|f| { + let name = f.ident.as_ref()?; + if name.to_string().starts_with('_') { + return None + } + let ret = quote_spanned! { f.span() => + formatter.field(stringify!(#name), &HumanWeight(self.#name)); + }; + Some(ret) + }); + quote! { + #( #recurse )* + } + }, + Fields::Unnamed(fields) => quote_spanned! { + fields.span() => + compile_error!("Unnamed fields are not supported") + }, + Fields::Unit => quote!(), + }; + + let tokens = quote! { + impl #impl_generics ::core::fmt::Debug for #name #ty_generics #where_clause { + fn fmt(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> core::fmt::Result { + use ::sp_runtime::{FixedPointNumber, FixedU128 as Fixed}; + use ::core::{fmt, write}; + + struct HumanWeight(Weight); + + impl fmt::Debug for HumanWeight { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.0.ref_time() > 1_000_000_000 { + write!( + formatter, + "{} ms, {} bytes", + Fixed::saturating_from_rational(self.0.ref_time(), 1_000_000_000).into_inner() / Fixed::accuracy(), + self.0.proof_size() + ) + } else if self.0.ref_time() > 1_000_000 { + write!( + formatter, + "{} µs, {} bytes", + Fixed::saturating_from_rational(self.0.ref_time(), 1_000_000).into_inner() / Fixed::accuracy(), + self.0.proof_size() + ) + } else if self.0.ref_time() > 1_000 { + write!( + formatter, + "{} ns, {} bytes", + Fixed::saturating_from_rational(self.0.ref_time(), 1_000).into_inner() / Fixed::accuracy(), + self.0.proof_size() + ) + } else { + write!(formatter, "{} ps, {} bytes", self.0.ref_time(), self.0.proof_size()) + } + } + } + + let mut formatter = formatter.debug_struct(stringify!(#name)); + #fields + formatter.finish() + } + } + }; + + tokens.into() +} + +/// Parsed environment definition. +struct EnvDef { + host_funcs: Vec, +} + +/// Parsed host function definition. +struct HostFn { + item: syn::ItemFn, + version: u8, + name: String, + returns: HostFnReturn, + is_stable: bool, + alias_to: Option, + /// Formulating the predicate inverted makes the expression using it simpler. + not_deprecated: bool, + cfg: Option, +} + +enum HostFnReturn { + Unit, + U32, + U64, + ReturnCode, +} + +impl HostFnReturn { + fn to_wasm_sig(&self) -> TokenStream2 { + let ok = match self { + Self::Unit => quote! { () }, + Self::U32 | Self::ReturnCode => quote! { ::core::primitive::u32 }, + Self::U64 => quote! { ::core::primitive::u64 }, + }; + quote! { + ::core::result::Result<#ok, ::wasmi::Error> + } + } +} + +impl ToTokens for HostFn { + fn to_tokens(&self, tokens: &mut TokenStream2) { + self.item.to_tokens(tokens); + } +} + +impl HostFn { + pub fn try_from(mut item: syn::ItemFn) -> syn::Result { + let err = |span, msg| { + let msg = format!("Invalid host function definition.\n{}", msg); + syn::Error::new(span, msg) + }; + + // process attributes + let msg = + "Only #[version()], #[unstable], #[prefixed_alias], #[cfg], #[mutating] and #[deprecated] attributes are allowed."; + let span = item.span(); + let mut attrs = item.attrs.clone(); + attrs.retain(|a| !a.path().is_ident("doc")); + let mut maybe_version = None; + let mut is_stable = true; + let mut alias_to = None; + let mut not_deprecated = true; + let mut mutating = false; + let mut cfg = None; + while let Some(attr) = attrs.pop() { + let ident = attr.path().get_ident().ok_or(err(span, msg))?.to_string(); + match ident.as_str() { + "version" => { + if maybe_version.is_some() { + return Err(err(span, "#[version] can only be specified once")) + } + maybe_version = + Some(attr.parse_args::().and_then(|lit| lit.base10_parse())?); + }, + "unstable" => { + if !is_stable { + return Err(err(span, "#[unstable] can only be specified once")) + } + is_stable = false; + }, + "prefixed_alias" => { + alias_to = Some(item.sig.ident.to_string()); + item.sig.ident = syn::Ident::new( + &format!("seal_{}", &item.sig.ident.to_string()), + item.sig.ident.span(), + ); + }, + "deprecated" => { + if !not_deprecated { + return Err(err(span, "#[deprecated] can only be specified once")) + } + not_deprecated = false; + }, + "mutating" => { + if mutating { + return Err(err(span, "#[mutating] can only be specified once")) + } + mutating = true; + }, + "cfg" => { + if cfg.is_some() { + return Err(err(span, "#[cfg] can only be specified once")) + } + cfg = Some(attr); + }, + id => return Err(err(span, &format!("Unsupported attribute \"{id}\". {msg}"))), + } + } + + if mutating { + let stmt = syn::parse_quote! { + if ctx.ext().is_read_only() { + return Err(Error::::StateChangeDenied.into()); + } + }; + item.block.stmts.insert(0, stmt); + } + + let name = item.sig.ident.to_string(); + + if !(is_stable || not_deprecated) { + return Err(err(span, "#[deprecated] is mutually exclusive with #[unstable]")) + } + + // process arguments: The first and second args are treated differently (ctx, memory) + // they must exist and be `ctx: _` and `memory: _`. + let msg = "Every function must start with two inferred parameters: ctx: _ and memory: _"; + let special_args = item + .sig + .inputs + .iter() + .take(2) + .enumerate() + .map(|(i, arg)| is_valid_special_arg(i, arg)) + .fold(0u32, |acc, valid| if valid { acc + 1 } else { acc }); + + if special_args != 2 { + return Err(err(span, msg)) + } + + // process return type + let msg = r#"Should return one of the following: + - Result<(), TrapReason>, + - Result, + - Result, + - Result"#; + let ret_ty = match item.clone().sig.output { + syn::ReturnType::Type(_, ty) => Ok(ty.clone()), + _ => Err(err(span, &msg)), + }?; + match *ret_ty { + syn::Type::Path(tp) => { + let result = &tp.path.segments.last().ok_or(err(span, &msg))?; + let (id, span) = (result.ident.to_string(), result.ident.span()); + id.eq(&"Result".to_string()).then_some(()).ok_or(err(span, &msg))?; + + match &result.arguments { + syn::PathArguments::AngleBracketed(group) => { + if group.args.len() != 2 { + return Err(err(span, &msg)) + }; + + let arg2 = group.args.last().ok_or(err(span, &msg))?; + + let err_ty = match arg2 { + syn::GenericArgument::Type(ty) => Ok(ty.clone()), + _ => Err(err(arg2.span(), &msg)), + }?; + + match err_ty { + syn::Type::Path(tp) => Ok(tp + .path + .segments + .first() + .ok_or(err(arg2.span(), &msg))? + .ident + .to_string()), + _ => Err(err(tp.span(), &msg)), + }? + .eq("TrapReason") + .then_some(()) + .ok_or(err(span, &msg))?; + + let arg1 = group.args.first().ok_or(err(span, &msg))?; + let ok_ty = match arg1 { + syn::GenericArgument::Type(ty) => Ok(ty.clone()), + _ => Err(err(arg1.span(), &msg)), + }?; + let ok_ty_str = match ok_ty { + syn::Type::Path(tp) => Ok(tp + .path + .segments + .first() + .ok_or(err(arg1.span(), &msg))? + .ident + .to_string()), + syn::Type::Tuple(tt) => { + if !tt.elems.is_empty() { + return Err(err(arg1.span(), &msg)) + }; + Ok("()".to_string()) + }, + _ => Err(err(ok_ty.span(), &msg)), + }?; + let returns = match ok_ty_str.as_str() { + "()" => Ok(HostFnReturn::Unit), + "u32" => Ok(HostFnReturn::U32), + "u64" => Ok(HostFnReturn::U64), + "ReturnErrorCode" => Ok(HostFnReturn::ReturnCode), + _ => Err(err(arg1.span(), &msg)), + }?; + + Ok(Self { + item, + version: maybe_version.unwrap_or_default(), + name, + returns, + is_stable, + alias_to, + not_deprecated, + cfg, + }) + }, + _ => Err(err(span, &msg)), + } + }, + _ => Err(err(span, &msg)), + } + } + + fn module(&self) -> String { + format!("seal{}", self.version) + } +} + +impl EnvDef { + pub fn try_from(item: syn::ItemMod) -> syn::Result { + let span = item.span(); + let err = |msg| syn::Error::new(span, msg); + let items = &item + .content + .as_ref() + .ok_or(err("Invalid environment definition, expected `mod` to be inlined."))? + .1; + + let extract_fn = |i: &syn::Item| match i { + syn::Item::Fn(i_fn) => Some(i_fn.clone()), + _ => None, + }; + + let selector = |a: &syn::Attribute| a.path().is_ident("prefixed_alias"); + + let aliases = items + .iter() + .filter_map(extract_fn) + .filter(|i| i.attrs.iter().any(selector)) + .map(|i| HostFn::try_from(i)); + + let host_funcs = items + .iter() + .filter_map(extract_fn) + .map(|mut i| { + i.attrs.retain(|i| !selector(i)); + i + }) + .map(|i| HostFn::try_from(i)) + .chain(aliases) + .collect::, _>>()?; + + Ok(Self { host_funcs }) + } +} + +fn is_valid_special_arg(idx: usize, arg: &FnArg) -> bool { + let FnArg::Typed(pat) = arg else { return false }; + let ident = if let syn::Pat::Ident(ref ident) = *pat.pat { &ident.ident } else { return false }; + let name_ok = match idx { + 0 => ident == "ctx" || ident == "_ctx", + 1 => ident == "memory" || ident == "_memory", + _ => false, + }; + if !name_ok { + return false + } + matches!(*pat.ty, syn::Type::Infer(_)) +} + +fn expand_func_doc(func: &HostFn) -> TokenStream2 { + // Remove auxiliary args: `ctx: _` and `memory: _` + let func_decl = { + let mut sig = func.item.sig.clone(); + sig.inputs = sig + .inputs + .iter() + .skip(2) + .map(|p| p.clone()) + .collect::>(); + sig.to_token_stream() + }; + let func_doc = { + let func_docs = if let Some(origin_fn) = &func.alias_to { + let alias_doc = format!( + "This is just an alias function to [`{0}()`][`Self::{0}`] with backwards-compatible prefixed identifier.", + origin_fn, + ); + quote! { #[doc = #alias_doc] } + } else { + let docs = func.item.attrs.iter().filter(|a| a.path().is_ident("doc")).map(|d| { + let docs = d.to_token_stream(); + quote! { #docs } + }); + quote! { #( #docs )* } + }; + let deprecation_notice = if !func.not_deprecated { + let warning = "\n # Deprecated\n\n \ + This function is deprecated and will be removed in future versions.\n \ + No new code or contracts with this API can be deployed."; + quote! { #[doc = #warning] } + } else { + quote! {} + }; + let import_notice = { + let info = format!( + "\n# Wasm Import Statement\n```wat\n(import \"seal{}\" \"{}\" (func ...))\n```", + func.version, func.name, + ); + quote! { #[doc = #info] } + }; + let unstable_notice = if !func.is_stable { + let warning = "\n # Unstable\n\n \ + This function is unstable and it is a subject to change (or removal) in the future.\n \ + Do not deploy a contract using it to a production chain."; + quote! { #[doc = #warning] } + } else { + quote! {} + }; + quote! { + #deprecation_notice + #func_docs + #import_notice + #unstable_notice + } + }; + quote! { + #func_doc + #func_decl; + } +} + +/// Expands documentation for host functions. +fn expand_docs(def: &EnvDef) -> TokenStream2 { + // Create the `Current` trait with only the newest versions + // we sort so that only the newest versions make it into `docs` + let mut current_docs = std::collections::HashMap::new(); + let mut funcs: Vec<_> = def.host_funcs.iter().filter(|f| f.alias_to.is_none()).collect(); + funcs.sort_unstable_by_key(|func| Reverse(func.version)); + for func in funcs { + if current_docs.contains_key(&func.name) { + continue + } + current_docs.insert(func.name.clone(), expand_func_doc(&func)); + } + let current_docs = current_docs.values(); + + // Create the `legacy` module with all functions + // Maps from version to list of functions that have this version + let mut legacy_doc = std::collections::BTreeMap::>::new(); + for func in def.host_funcs.iter() { + legacy_doc.entry(func.version).or_default().push(expand_func_doc(&func)); + } + let legacy_doc = legacy_doc.into_iter().map(|(version, funcs)| { + let doc = format!("All functions available in the **seal{}** module", version); + let version = Ident::new(&format!("Version{version}"), Span::call_site()); + quote! { + #[doc = #doc] + pub trait #version { + #( #funcs )* + } + } + }); + + quote! { + /// Contains only the latest version of each function. + /// + /// In reality there are more functions available but they are all obsolete: When a function + /// is updated a new **version** is added and the old versions stays available as-is. + /// We only list the newest version here. Some functions are available under additional + /// names (aliases) for historic reasons which are omitted here. + /// + /// If you want an overview of all the functions available to a contact all you need + /// to look at is this trait. It contains only the latest version of each + /// function and no aliases. If you are writing a contract(language) from scratch + /// this is where you should look at. + pub trait Current { + #( #current_docs )* + } + #( #legacy_doc )* + } +} + +/// Expands environment definition. +/// Should generate source code for: +/// - implementations of the host functions to be added to the wasm runtime environment (see +/// `expand_impls()`). +fn expand_env(def: &EnvDef, docs: bool) -> TokenStream2 { + let impls = expand_impls(def); + let docs = docs.then_some(expand_docs(def)).unwrap_or(TokenStream2::new()); + let stable_api_count = def.host_funcs.iter().filter(|f| f.is_stable).count(); + + quote! { + pub struct Env; + + #[cfg(test)] + pub const STABLE_API_COUNT: usize = #stable_api_count; + + #impls + /// Documentation of the API (host functions) available to contracts. + /// + /// The `Current` trait might be the most useful doc to look at. The versioned + /// traits only exist for reference: If trying to find out if a specific version of + /// `pallet-contracts` contains a certain function. + /// + /// # Note + /// + /// This module is not meant to be used by any code. Rather, it is meant to be + /// consumed by humans through rustdoc. + #[cfg(doc)] + pub mod api_doc { + use super::{TrapReason, ReturnErrorCode}; + #docs + } + } +} + +/// Generates for every host function: +/// - real implementation, to register it in the contract execution environment; +/// - dummy implementation, to be used as mocks for contract validation step. +fn expand_impls(def: &EnvDef) -> TokenStream2 { + let impls = expand_functions(def, ExpandMode::Impl); + let dummy_impls = expand_functions(def, ExpandMode::MockImpl); + let bench_impls = expand_functions(def, ExpandMode::BenchImpl); + + quote! { + impl<'a, E: Ext> crate::wasm::Environment> for Env + { + fn define( + store: &mut ::wasmi::Store>, + linker: &mut ::wasmi::Linker>, + allow_unstable: AllowUnstableInterface, + allow_deprecated: AllowDeprecatedInterface, + ) -> Result<(),::wasmi::errors::LinkerError> { + #impls + Ok(()) + } + } + + #[cfg(feature = "runtime-benchmarks")] + pub struct BenchEnv(::core::marker::PhantomData); + + #[cfg(feature = "runtime-benchmarks")] + impl BenchEnv { + #bench_impls + } + + impl crate::wasm::Environment<()> for Env + { + fn define( + store: &mut ::wasmi::Store<()>, + linker: &mut ::wasmi::Linker<()>, + allow_unstable: AllowUnstableInterface, + allow_deprecated: AllowDeprecatedInterface, + ) -> Result<(), ::wasmi::errors::LinkerError> { + #dummy_impls + Ok(()) + } + } + } +} + +enum ExpandMode { + Impl, + BenchImpl, + MockImpl, +} + +impl ExpandMode { + fn expand_blocks(&self) -> bool { + match *self { + ExpandMode::Impl | ExpandMode::BenchImpl => true, + ExpandMode::MockImpl => false, + } + } + + fn host_state(&self) -> TokenStream2 { + match *self { + ExpandMode::Impl | ExpandMode::BenchImpl => quote! { crate::wasm::runtime::Runtime }, + ExpandMode::MockImpl => quote! { () }, + } + } +} + +fn expand_functions(def: &EnvDef, expand_mode: ExpandMode) -> TokenStream2 { + let impls = def.host_funcs.iter().map(|f| { + // skip the context and memory argument + let params = f.item.sig.inputs.iter().skip(2); + let module = f.module(); + let cfg = &f.cfg; + let name = &f.name; + let body = &f.item.block; + let wasm_output = f.returns.to_wasm_sig(); + let output = &f.item.sig.output; + let is_stable = f.is_stable; + let not_deprecated = f.not_deprecated; + + // wrapped host function body call with host function traces + // see https://github.com/paritytech/polkadot-sdk/tree/master/substrate/frame/contracts#host-function-tracing + let wrapped_body_with_trace = { + let trace_fmt_args = params.clone().filter_map(|arg| match arg { + syn::FnArg::Receiver(_) => None, + syn::FnArg::Typed(p) => { + match *p.pat.clone() { + syn::Pat::Ident(ref pat_ident) => Some(pat_ident.ident.clone()), + _ => None, + } + }, + }); + + let params_fmt_str = trace_fmt_args.clone().map(|s| format!("{s}: {{:?}}")).collect::>().join(", "); + let trace_fmt_str = format!("{}::{}({}) = {{:?}}\n", module, name, params_fmt_str); + + quote! { + let result = #body; + if ::log::log_enabled!(target: "runtime::contracts::strace", ::log::Level::Trace) { + use core::fmt::Write; + let mut w = sp_std::Writer::default(); + let _ = core::write!(&mut w, #trace_fmt_str, #( #trace_fmt_args, )* result); + let msg = core::str::from_utf8(&w.inner()).unwrap_or_default(); + ctx.ext().append_debug_buffer(msg); + } + result + } + }; + + // If we don't expand blocks (implementing for `()`) we change a few things: + // - We replace any code by unreachable! + // - Allow unused variables as the code that uses is not expanded + // - We don't need to map the error as we simply panic if they code would ever be executed + let expand_blocks = expand_mode.expand_blocks(); + let inner = match expand_mode { + ExpandMode::Impl => { + quote! { || #output { + let (memory, ctx) = __caller__ + .data() + .memory() + .expect("Memory must be set when setting up host data; qed") + .data_and_store_mut(&mut __caller__); + #wrapped_body_with_trace + } } + }, + ExpandMode::BenchImpl => { + let body = &body.stmts; + quote!{ + #(#body)* + } + }, + ExpandMode::MockImpl => { + quote! { || -> #wasm_output { + // This is part of the implementation for `Environment<()>` which is not + // meant to be actually executed. It is only for validation which will + // never call host functions. + ::core::unreachable!() + } } + }, + }; + + let into_host = if expand_blocks { + quote! { + |reason| { + ::wasmi::Error::host(reason) + } + } + } else { + quote! { + |reason| { reason } + } + }; + let allow_unused = if expand_blocks { + quote! { } + } else { + quote! { #[allow(unused_variables)] } + }; + let sync_gas_before = if expand_blocks { + quote! { + // Write gas from wasmi into pallet-contracts before entering the host function. + let __gas_left_before__ = { + let fuel = + __caller__.get_fuel().expect("Fuel metering is enabled; qed"); + __caller__ + .data_mut() + .ext() + .gas_meter_mut() + .sync_from_executor(fuel) + .map_err(TrapReason::from) + .map_err(#into_host)? + }; + + // Charge gas for host function execution. + __caller__.data_mut().charge_gas(crate::wasm::RuntimeCosts::HostFn) + .map_err(TrapReason::from) + .map_err(#into_host)?; + } + } else { + quote! { } + }; + // Write gas from pallet-contracts into wasmi after leaving the host function. + let sync_gas_after = if expand_blocks { + quote! { + let fuel = __caller__ + .data_mut() + .ext() + .gas_meter_mut() + .sync_to_executor(__gas_left_before__) + .map_err(|err| { + let err = TrapReason::from(err); + wasmi::Error::host(err) + })?; + __caller__ + .set_fuel(fuel.into()) + .expect("Fuel metering is enabled; qed"); + } + } else { + quote! { } + }; + + match expand_mode { + ExpandMode::BenchImpl => { + let name = Ident::new(&format!("{module}_{name}"), Span::call_site()); + quote! { + pub fn #name(ctx: &mut crate::wasm::Runtime, memory: &mut [u8], #(#params),*) #output { + #inner + } + } + }, + _ => { + let host_state = expand_mode.host_state(); + quote! { + // We need to allow all interfaces when runtime benchmarks are performed because + // we generate the weights even when those interfaces are not enabled. This + // is necessary as the decision whether we allow unstable or deprecated functions + // is a decision made at runtime. Generation of the weights happens statically. + #cfg + if ::core::cfg!(feature = "runtime-benchmarks") || + ((#is_stable || __allow_unstable__) && (#not_deprecated || __allow_deprecated__)) + { + #allow_unused + linker.define(#module, #name, ::wasmi::Func::wrap(&mut*store, |mut __caller__: ::wasmi::Caller<#host_state>, #( #params, )*| -> #wasm_output { + #sync_gas_before + let mut func = #inner; + let result = func().map_err(#into_host).map(::core::convert::Into::into); + #sync_gas_after + result + }))?; + } + } + }, + } + }); + + match expand_mode { + ExpandMode::BenchImpl => { + quote! { + #( #impls )* + } + }, + _ => quote! { + let __allow_unstable__ = matches!(allow_unstable, AllowUnstableInterface::Yes); + let __allow_deprecated__ = matches!(allow_deprecated, AllowDeprecatedInterface::Yes); + #( #impls )* + }, + } +} + +/// Defines a host functions set that can be imported by contract wasm code. +/// +/// **NB**: Be advised that all functions defined by this macro +/// will panic if called with unexpected arguments. +/// +/// It's up to you as the user of this macro to check signatures of wasm code to be executed +/// and reject the code if any imported function has a mismatched signature. +/// +/// ## Example +/// +/// ```nocompile +/// #[define_env] +/// pub mod some_env { +/// fn foo(ctx: _, memory: _, key_ptr: u32, value_ptr: u32, value_len: u32) -> Result<(), TrapReason> { +/// ctx.some_host_fn(KeyType::Fix, key_ptr, value_ptr, value_len).map(|_| ()) +/// } +/// } +/// ``` +/// This example will expand to the `foo()` defined in the wasm module named `seal0`. This is +/// because the module `seal0` is the default when no module is specified. +/// +/// To define a host function in `seal2` and `seal3` modules, it should be annotated with the +/// appropriate attribute as follows: +/// +/// ## Example +/// +/// ```nocompile +/// #[define_env] +/// pub mod some_env { +/// #[version(2)] +/// fn foo(ctx: _, memory: _, key_ptr: u32, value_ptr: u32, value_len: u32) -> Result { +/// ctx.some_host_fn(KeyType::Fix, key_ptr, value_ptr, value_len).map(|_| ()) +/// } +/// +/// #[version(3)] +/// #[unstable] +/// fn bar(ctx: _, memory: _, key_ptr: u32, value_ptr: u32, value_len: u32) -> Result { +/// ctx.some_host_fn(KeyType::Fix, key_ptr, value_ptr, value_len).map(|_| ()) +/// } +/// } +/// ``` +/// The function `bar` is additionally annotated with `unstable` which removes it from the stable +/// interface. Check out the README to learn about unstable functions. +/// +/// In legacy versions of pallet_contracts, it was a naming convention that all host functions had +/// to be named with the `seal_` prefix. For the sake of backwards compatibility, each host function +/// now can get a such prefix-named alias function generated by marking it by the +/// `#[prefixed_alias]` attribute: +/// +/// ## Example +/// +/// ```nocompile +/// #[define_env] +/// pub mod some_env { +/// #[version(1)] +/// #[prefixed_alias] +/// fn foo(ctx: _, memory: _, key_ptr: u32, value_ptr: u32, value_len: u32) -> Result { +/// ctx.some_host_fn(KeyType::Fix, key_ptr, value_ptr, value_len).map(|_| ()) +/// } +/// +/// #[version(42)] +/// fn bar(ctx: _, memory: _, key_ptr: u32, value_ptr: u32, value_len: u32) -> Result { +/// ctx.some_host_fn(KeyType::Fix, key_ptr, value_ptr, value_len).map(|_| ()) +/// } +/// } +/// ``` +/// +/// In this example, the following host functions will be generated by the macro: +/// - `foo()` in module `seal1`, +/// - `seal_foo()` in module `seal1`, +/// - `bar()` in module `seal42`. +/// +/// Only following return types are allowed for the host functions defined with the macro: +/// - `Result<(), TrapReason>`, +/// - `Result`, +/// - `Result`. +/// +/// The macro expands to `pub struct Env` declaration, with the following traits implementations: +/// - `pallet_contracts::wasm::Environment> where E: Ext` +/// - `pallet_contracts::wasm::Environment<()>` +/// +/// The implementation on `()` can be used in places where no `Ext` exists, yet. This is useful +/// when only checking whether a code can be instantiated without actually executing any code. +/// +/// # Generating Documentation +/// +/// Passing `doc` attribute to the macro (like `#[define_env(doc)]`) will make it also expand +/// additional `pallet_contracts::api_doc::seal0`, `pallet_contracts::api_doc::seal1`, +/// `...` modules each having its `Api` trait containing functions holding documentation for every +/// host function defined by the macro. +/// +/// # Deprecated Interfaces +/// +/// An interface can be annotated with `#[deprecated]`. It is mutually exclusive with `#[unstable]`. +/// Deprecated interfaces have the following properties: +/// - New contract codes utilizing those interfaces cannot be uploaded. +/// - New contracts from existing codes utilizing those interfaces cannot be instantiated. +/// - Existing contracts containing those interfaces still work. +/// +/// Those interfaces will eventually be removed. +/// +/// To build up these docs, run: +/// +/// ```nocompile +/// cargo doc +/// ``` +#[proc_macro_attribute] +pub fn define_env(attr: TokenStream, item: TokenStream) -> TokenStream { + if !attr.is_empty() && !(attr.to_string() == "doc".to_string()) { + let msg = r#"Invalid `define_env` attribute macro: expected either no attributes or a single `doc` attribute: + - `#[define_env]` + - `#[define_env(doc)]`"#; + let span = TokenStream2::from(attr).span(); + return syn::Error::new(span, msg).to_compile_error().into() + } + + let item = syn::parse_macro_input!(item as syn::ItemMod); + + match EnvDef::try_from(item) { + Ok(mut def) => expand_env(&mut def, !attr.is_empty()).into(), + Err(e) => e.to_compile_error().into(), + } +} diff --git a/pallets/contracts/src/address.rs b/pallets/contracts/src/address.rs new file mode 100644 index 00000000..5758daf7 --- /dev/null +++ b/pallets/contracts/src/address.rs @@ -0,0 +1,68 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Functions that deal with address derivation. + +use crate::{CodeHash, Config}; +use codec::{Decode, Encode}; +use sp_runtime::traits::{Hash, TrailingZeroInput}; + +/// Provides the contract address generation method. +/// +/// See [`DefaultAddressGenerator`] for the default implementation. +/// +/// # Note for implementors +/// +/// 1. Make sure that there are no collisions, different inputs never lead to the same output. +/// 2. Make sure that the same inputs lead to the same output. +pub trait AddressGenerator { + /// The address of a contract based on the given instantiate parameters. + /// + /// Changing the formular for an already deployed chain is fine as long as no collisions + /// with the old formular. Changes only affect existing contracts. + fn contract_address( + deploying_address: &T::AccountId, + code_hash: &CodeHash, + input_data: &[u8], + salt: &[u8], + ) -> T::AccountId; +} + +/// Default address generator. +/// +/// This is the default address generator used by contract instantiation. Its result +/// is only dependent on its inputs. It can therefore be used to reliably predict the +/// address of a contract. This is akin to the formula of eth's CREATE2 opcode. There +/// is no CREATE equivalent because CREATE2 is strictly more powerful. +/// Formula: +/// `hash("contract_addr_v1" ++ deploying_address ++ code_hash ++ input_data ++ salt)` +pub struct DefaultAddressGenerator; + +impl AddressGenerator for DefaultAddressGenerator { + /// Formula: `hash("contract_addr_v1" ++ deploying_address ++ code_hash ++ input_data ++ salt)` + fn contract_address( + deploying_address: &T::AccountId, + code_hash: &CodeHash, + input_data: &[u8], + salt: &[u8], + ) -> T::AccountId { + let entropy = (b"contract_addr_v1", deploying_address, code_hash, input_data, salt) + .using_encoded(T::Hashing::hash); + Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref())) + .expect("infinite length input; no invalid inputs for type; qed") + } +} diff --git a/pallets/contracts/src/benchmarking/call_builder.rs b/pallets/contracts/src/benchmarking/call_builder.rs new file mode 100644 index 00000000..5833639d --- /dev/null +++ b/pallets/contracts/src/benchmarking/call_builder.rs @@ -0,0 +1,236 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::{ + benchmarking::{Contract, WasmModule}, + exec::{Ext, Key, Stack}, + storage::meter::Meter, + transient_storage::MeterEntry, + wasm::Runtime, + BalanceOf, Config, DebugBufferVec, Determinism, Error, ExecReturnValue, GasMeter, Origin, + Schedule, TypeInfo, WasmBlob, Weight, +}; +use alloc::{vec, vec::Vec}; +use codec::{Encode, HasCompact}; +use core::fmt::Debug; +use frame_benchmarking::benchmarking; +use sp_core::Get; + +type StackExt<'a, T> = Stack<'a, T, WasmBlob>; + +/// A prepared contract call ready to be executed. +pub struct PreparedCall<'a, T: Config> { + func: wasmi::Func, + store: wasmi::Store>>, +} + +impl<'a, T: Config> PreparedCall<'a, T> { + pub fn call(mut self) -> ExecReturnValue { + let result = self.func.call(&mut self.store, &[], &mut []); + WasmBlob::::process_result(self.store, result).unwrap() + } +} + +/// A builder used to prepare a contract call. +pub struct CallSetup { + contract: Contract, + dest: T::AccountId, + origin: Origin, + gas_meter: GasMeter, + storage_meter: Meter, + schedule: Schedule, + value: BalanceOf, + debug_message: Option>, + determinism: Determinism, + data: Vec, + transient_storage_size: u32, +} + +impl Default for CallSetup +where + T: Config + pallet_balances::Config, + as HasCompact>::Type: Clone + Eq + PartialEq + Debug + TypeInfo + Encode, +{ + fn default() -> Self { + Self::new(WasmModule::dummy()) + } +} + +impl CallSetup +where + T: Config + pallet_balances::Config, + as HasCompact>::Type: Clone + Eq + PartialEq + Debug + TypeInfo + Encode, +{ + /// Setup a new call for the given module. + pub fn new(module: WasmModule) -> Self { + let contract = Contract::::new(module.clone(), vec![]).unwrap(); + let dest = contract.account_id.clone(); + let origin = Origin::from_account_id(contract.caller.clone()); + + let storage_meter = Meter::new(&origin, None, 0u32.into()).unwrap(); + + // Whitelist contract account, as it is already accounted for in the call benchmark + benchmarking::add_to_whitelist( + frame_system::Account::::hashed_key_for(&contract.account_id).into(), + ); + + // Whitelist the contract's contractInfo as it is already accounted for in the call + // benchmark + benchmarking::add_to_whitelist( + crate::ContractInfoOf::::hashed_key_for(&contract.account_id).into(), + ); + + Self { + contract, + dest, + origin, + gas_meter: GasMeter::new(Weight::MAX), + storage_meter, + schedule: T::Schedule::get(), + value: 0u32.into(), + debug_message: None, + determinism: Determinism::Enforced, + data: vec![], + transient_storage_size: 0, + } + } + + /// Set the meter's storage deposit limit. + pub fn set_storage_deposit_limit(&mut self, balance: BalanceOf) { + self.storage_meter = Meter::new(&self.origin, Some(balance), 0u32.into()).unwrap(); + } + + /// Set the call's origin. + pub fn set_origin(&mut self, origin: Origin) { + self.origin = origin; + } + + /// Set the contract's balance. + pub fn set_balance(&mut self, value: BalanceOf) { + self.contract.set_balance(value); + } + + /// Set the call's input data. + pub fn set_data(&mut self, value: Vec) { + self.data = value; + } + + /// Set the transient storage size. + pub fn set_transient_storage_size(&mut self, size: u32) { + self.transient_storage_size = size; + } + + /// Set the debug message. + pub fn enable_debug_message(&mut self) { + self.debug_message = Some(Default::default()); + } + + /// Get the debug message. + pub fn debug_message(&self) -> Option> { + self.debug_message.clone() + } + + /// Get the call's input data. + pub fn data(&self) -> Vec { + self.data.clone() + } + + /// Get the call's contract. + pub fn contract(&self) -> Contract { + self.contract.clone() + } + + /// Build the call stack. + pub fn ext(&mut self) -> (StackExt<'_, T>, WasmBlob) { + let mut ext = StackExt::bench_new_call( + self.dest.clone(), + self.origin.clone(), + &mut self.gas_meter, + &mut self.storage_meter, + &self.schedule, + self.value, + self.debug_message.as_mut(), + self.determinism, + ); + if self.transient_storage_size > 0 { + Self::with_transient_storage(&mut ext.0, self.transient_storage_size).unwrap(); + } + ext + } + + /// Prepare a call to the module. + pub fn prepare_call<'a>( + ext: &'a mut StackExt<'a, T>, + module: WasmBlob, + input: Vec, + ) -> PreparedCall<'a, T> { + let (func, store) = module.bench_prepare_call(ext, input); + PreparedCall { func, store } + } + + /// Add transient_storage + fn with_transient_storage(ext: &mut StackExt, size: u32) -> Result<(), &'static str> { + let &MeterEntry { amount, limit } = ext.transient_storage().meter().current(); + ext.transient_storage().meter().current_mut().limit = size; + for i in 1u32.. { + let mut key_data = i.to_le_bytes().to_vec(); + while key_data.last() == Some(&0) { + key_data.pop(); + } + let key = Key::::try_from_var(key_data).unwrap(); + if let Err(e) = ext.set_transient_storage(&key, Some(Vec::new()), false) { + // Restore previous settings. + ext.transient_storage().meter().current_mut().limit = limit; + ext.transient_storage().meter().current_mut().amount = amount; + if e == Error::::OutOfTransientStorage.into() { + break; + } else { + return Err("Initialization of the transient storage failed"); + } + } + } + Ok(()) + } +} + +#[macro_export] +macro_rules! memory( + ($($bytes:expr,)*) => { + vec![] + .into_iter() + $(.chain($bytes))* + .collect::>() + }; +); + +#[macro_export] +macro_rules! build_runtime( + ($runtime:ident, $memory:ident: [$($segment:expr,)*]) => { + $crate::build_runtime!($runtime, _contract, $memory: [$($segment,)*]); + }; + ($runtime:ident, $contract:ident, $memory:ident: [$($bytes:expr,)*]) => { + $crate::build_runtime!($runtime, $contract); + let mut $memory = $crate::memory!($($bytes,)*); + }; + ($runtime:ident, $contract:ident) => { + let mut setup = CallSetup::::default(); + let $contract = setup.contract(); + let input = setup.data(); + let (mut ext, _) = setup.ext(); + let mut $runtime = crate::wasm::Runtime::new(&mut ext, input); + }; +); diff --git a/pallets/contracts/src/benchmarking/code.rs b/pallets/contracts/src/benchmarking/code.rs new file mode 100644 index 00000000..1473022b --- /dev/null +++ b/pallets/contracts/src/benchmarking/code.rs @@ -0,0 +1,364 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Functions to procedurally construct contract code used for benchmarking. +//! +//! In order to be able to benchmark events that are triggered by contract execution +//! (API calls into seal, individual instructions), we need to generate contracts that +//! perform those events. Because those contracts can get very big we cannot simply define +//! them as text (.wat) as this will be too slow and consume too much memory. Therefore +//! we define this simple definition of a contract that can be passed to `create_code` that +//! compiles it down into a `WasmModule` that can be used as a contract's code. + +use crate::Config; +use alloc::{borrow::ToOwned, vec, vec::Vec}; +use frame_support::traits::Get; +use sp_runtime::{traits::Hash, Saturating}; +use wasm_instrument::parity_wasm::{ + builder, + elements::{ + self, BlockType, CustomSection, FuncBody, Instruction, Instructions, Local, Section, + ValueType, + }, +}; + +/// The location where to put the generated code. +pub enum Location { + /// Generate all code into the `call` exported function. + Call, + /// Generate all code into the `deploy` exported function. + Deploy, +} + +/// Pass to `create_code` in order to create a compiled `WasmModule`. +/// +/// This exists to have a more declarative way to describe a wasm module than to use +/// parity-wasm directly. It is tailored to fit the structure of contracts that are +/// needed for benchmarking. +#[derive(Default)] +pub struct ModuleDefinition { + /// Imported memory attached to the module. No memory is imported if `None`. + pub memory: Option, + /// Initializers for the imported memory. + pub data_segments: Vec, + /// Creates the supplied amount of i64 mutable globals initialized with random values. + pub num_globals: u32, + /// List of functions that the module should import. They start with index 0. + pub imported_functions: Vec, + /// Function body of the exported `deploy` function. Body is empty if `None`. + /// Its index is `imported_functions.len()`. + pub deploy_body: Option, + /// Function body of the exported `call` function. Body is empty if `None`. + /// Its index is `imported_functions.len() + 1`. + pub call_body: Option, + /// Function body of a non-exported function with index `imported_functions.len() + 2`. + pub aux_body: Option, + /// The amount of I64 arguments the aux function should have. + pub aux_arg_num: u32, + /// Create a table containing function pointers. + pub table: Option, + /// Create a section named "dummy" of the specified size. This is useful in order to + /// benchmark the overhead of loading and storing codes of specified sizes. The dummy + /// section only contributes to the size of the contract but does not affect execution. + pub dummy_section: u32, +} + +pub struct TableSegment { + /// How many elements should be created inside the table. + pub num_elements: u32, + /// The function index with which all table elements should be initialized. + pub function_index: u32, +} + +pub struct DataSegment { + pub offset: u32, + pub value: Vec, +} + +#[derive(Clone)] +pub struct ImportedMemory { + pub min_pages: u32, + pub max_pages: u32, +} + +impl ImportedMemory { + pub fn max() -> Self { + let pages = max_pages::(); + Self { min_pages: pages, max_pages: pages } + } +} + +pub struct ImportedFunction { + pub module: &'static str, + pub name: &'static str, + pub params: Vec, + pub return_type: Option, +} + +/// A wasm module ready to be put on chain. +#[derive(Clone)] +pub struct WasmModule { + pub code: Vec, + pub hash: ::Output, + pub memory: Option, +} + +impl From for WasmModule { + fn from(def: ModuleDefinition) -> Self { + // internal functions start at that offset. + let func_offset = u32::try_from(def.imported_functions.len()).unwrap(); + + // Every contract must export "deploy" and "call" functions. + let mut contract = builder::module() + // deploy function (first internal function) + .function() + .signature() + .build() + .with_body( + def.deploy_body + .unwrap_or_else(|| FuncBody::new(Vec::new(), Instructions::empty())), + ) + .build() + // call function (second internal function) + .function() + .signature() + .build() + .with_body( + def.call_body + .unwrap_or_else(|| FuncBody::new(Vec::new(), Instructions::empty())), + ) + .build() + .export() + .field("deploy") + .internal() + .func(func_offset) + .build() + .export() + .field("call") + .internal() + .func(func_offset + 1) + .build(); + + // If specified we add an additional internal function + if let Some(body) = def.aux_body { + let mut signature = contract.function().signature(); + for _ in 0..def.aux_arg_num { + signature = signature.with_param(ValueType::I64); + } + contract = signature.build().with_body(body).build(); + } + + // Grant access to linear memory. + // Every contract module is required to have an imported memory. + // If no memory is specified in the passed ModuleDefinition, then + // default to (1, 1). + let (init, max) = if let Some(memory) = &def.memory { + (memory.min_pages, Some(memory.max_pages)) + } else { + (1, Some(1)) + }; + + contract = contract.import().path("env", "memory").external().memory(init, max).build(); + + // Import supervisor functions. They start with idx 0. + for func in def.imported_functions { + let sig = builder::signature() + .with_params(func.params) + .with_results(func.return_type) + .build_sig(); + let sig = contract.push_signature(sig); + contract = contract + .import() + .module(func.module) + .field(func.name) + .with_external(elements::External::Function(sig)) + .build(); + } + + // Initialize memory + for data in def.data_segments { + contract = contract + .data() + .offset(Instruction::I32Const(data.offset as i32)) + .value(data.value) + .build() + } + + // Add global variables + if def.num_globals > 0 { + use rand::{distributions::Standard, prelude::*}; + let rng = rand_pcg::Pcg32::seed_from_u64(3112244599778833558); + for val in rng.sample_iter(Standard).take(def.num_globals as usize) { + contract = contract + .global() + .value_type() + .i64() + .mutable() + .init_expr(Instruction::I64Const(val)) + .build() + } + } + + // Add function pointer table + if let Some(table) = def.table { + contract = contract + .table() + .with_min(table.num_elements) + .with_max(Some(table.num_elements)) + .with_element(0, vec![table.function_index; table.num_elements as usize]) + .build(); + } + + // Add the dummy section + if def.dummy_section > 0 { + contract = contract.with_section(Section::Custom(CustomSection::new( + "dummy".to_owned(), + vec![42; def.dummy_section as usize], + ))); + } + + let code = contract.build().into_bytes().unwrap(); + let hash = T::Hashing::hash(&code); + Self { code: code.into(), hash, memory: def.memory } + } +} + +impl WasmModule { + /// Creates a wasm module with an empty `call` and `deploy` function and nothing else. + pub fn dummy() -> Self { + ModuleDefinition::default().into() + } + + /// Same as `dummy` but with maximum sized linear memory and a dummy section of specified size. + pub fn dummy_with_bytes(dummy_bytes: u32) -> Self { + // We want the module to have the size `dummy_bytes`. + // This is not completely correct as the overhead grows when the contract grows + // because of variable length integer encoding. However, it is good enough to be that + // close for benchmarking purposes. + let module_overhead = 65; + ModuleDefinition { + memory: Some(ImportedMemory::max::()), + dummy_section: dummy_bytes.saturating_sub(module_overhead), + ..Default::default() + } + .into() + } + + /// Creates a wasm module of `target_bytes` size. Used to benchmark the performance of + /// `instantiate_with_code` for different sizes of wasm modules. The generated module maximizes + /// instrumentation runtime by nesting blocks as deeply as possible given the byte budget. + /// `code_location`: Whether to place the code into `deploy` or `call`. + pub fn sized(target_bytes: u32, code_location: Location, use_float: bool) -> Self { + use self::elements::Instruction::{End, GetLocal, If, Return}; + // Base size of a contract is 63 bytes and each expansion adds 6 bytes. + // We do one expansion less to account for the code section and function body + // size fields inside the binary wasm module representation which are leb128 encoded + // and therefore grow in size when the contract grows. We are not allowed to overshoot + // because of the maximum code size that is enforced by `instantiate_with_code`. + let mut expansions = (target_bytes.saturating_sub(63) / 6).saturating_sub(1); + const EXPANSION: [Instruction; 4] = [GetLocal(0), If(BlockType::NoResult), Return, End]; + let mut locals = vec![Local::new(1, ValueType::I32)]; + if use_float { + locals.push(Local::new(1, ValueType::F32)); + locals.push(Local::new(2, ValueType::F32)); + locals.push(Local::new(3, ValueType::F32)); + expansions.saturating_dec(); + } + let mut module = + ModuleDefinition { memory: Some(ImportedMemory::max::()), ..Default::default() }; + let body = Some(body::repeated_with_locals(&locals, expansions, &EXPANSION)); + match code_location { + Location::Call => module.call_body = body, + Location::Deploy => module.deploy_body = body, + } + module.into() + } + + /// Creates a wasm module that calls the imported function `noop` `repeat` times. + pub fn noop(repeat: u32) -> Self { + let pages = max_pages::(); + ModuleDefinition { + memory: Some(ImportedMemory::max::()), + imported_functions: vec![ImportedFunction { + module: "seal0", + name: "noop", + params: vec![], + return_type: None, + }], + // Write the output buffer size. The output size will be overwritten by the + // supervisor with the real size when calling the getter. Since this size does not + // change between calls it suffices to start with an initial value and then just + // leave as whatever value was written there. + data_segments: vec![DataSegment { + offset: 0, + value: (pages * 64 * 1024 - 4).to_le_bytes().to_vec(), + }], + call_body: Some(body::repeated( + repeat, + &[ + Instruction::Call(0), // call the imported function + ], + )), + ..Default::default() + } + .into() + } +} + +/// Mechanisms to generate a function body that can be used inside a `ModuleDefinition`. +pub mod body { + use super::*; + + pub fn repeated(repetitions: u32, instructions: &[Instruction]) -> FuncBody { + repeated_with_locals(&[], repetitions, instructions) + } + + pub fn repeated_with_locals( + locals: &[Local], + repetitions: u32, + instructions: &[Instruction], + ) -> FuncBody { + let instructions = Instructions::new( + instructions + .iter() + .cycle() + .take(instructions.len() * usize::try_from(repetitions).unwrap()) + .cloned() + .chain(core::iter::once(Instruction::End)) + .collect(), + ); + FuncBody::new(locals.to_vec(), instructions) + } + + pub fn repeated_with_locals_using( + locals: &[Local], + repetitions: u32, + mut f: impl FnMut() -> [Instruction; N], + ) -> FuncBody { + let mut instructions = Vec::new(); + for _ in 0..repetitions { + instructions.extend(f()); + } + instructions.push(Instruction::End); + FuncBody::new(locals.to_vec(), Instructions::new(instructions)) + } +} + +/// The maximum amount of pages any contract is allowed to have according to the current `Schedule`. +pub fn max_pages() -> u32 { + T::Schedule::get().limits.memory_pages +} diff --git a/pallets/contracts/src/benchmarking/mod.rs b/pallets/contracts/src/benchmarking/mod.rs new file mode 100644 index 00000000..669279f1 --- /dev/null +++ b/pallets/contracts/src/benchmarking/mod.rs @@ -0,0 +1,2074 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Benchmarks for the contracts pallet +#![cfg(feature = "runtime-benchmarks")] + +mod call_builder; +mod code; +mod sandbox; +use self::{ + call_builder::CallSetup, + code::{body, ImportedMemory, Location, ModuleDefinition, WasmModule}, + sandbox::Sandbox, +}; +use crate::{ + exec::{Key, SeedOf}, + migration::{ + codegen::LATEST_MIGRATION_VERSION, v09, v10, v11, v12, v13, v14, v15, v16, MigrationStep, + }, + storage::WriteOutcome, + wasm::BenchEnv, + Pallet as Contracts, *, +}; +use alloc::{vec, vec::Vec}; +use codec::{Encode, MaxEncodedLen}; +use frame_benchmarking::v2::*; +use frame_support::{ + self, assert_ok, + pallet_prelude::StorageVersion, + storage::child, + traits::{fungible::InspectHold, Currency}, + weights::{Weight, WeightMeter}, +}; +use frame_system::RawOrigin; +use pallet_balances; +use pallet_contracts_uapi::{CallFlags, ReturnErrorCode}; +use sp_runtime::traits::{Bounded, Hash}; +use wasm_instrument::parity_wasm::elements::{Instruction, Local, ValueType}; + +/// How many runs we do per API benchmark. +/// +/// This is picked more or less arbitrary. We experimented with different numbers until +/// the results appeared to be stable. Reducing the number would speed up the benchmarks +/// but might make the results less precise. +const API_BENCHMARK_RUNS: u32 = 1600; + +/// How many runs we do per instruction benchmark. +/// +/// Same rationale as for [`API_BENCHMARK_RUNS`]. The number is bigger because instruction +/// benchmarks are faster. +const INSTR_BENCHMARK_RUNS: u32 = 5000; + +/// Number of layers in a Radix16 unbalanced trie. +const UNBALANCED_TRIE_LAYERS: u32 = 20; + +/// An instantiated and deployed contract. +#[derive(Clone)] +struct Contract { + caller: T::AccountId, + account_id: T::AccountId, + addr: AccountIdLookupOf, + value: BalanceOf, +} + +impl Contract +where + T: Config + pallet_balances::Config, + as HasCompact>::Type: Clone + Eq + PartialEq + Debug + TypeInfo + Encode, +{ + /// Create new contract and use a default account id as instantiator. + fn new(module: WasmModule, data: Vec) -> Result, &'static str> { + Self::with_index(0, module, data) + } + + /// Create new contract and use an account id derived from the supplied index as instantiator. + fn with_index( + index: u32, + module: WasmModule, + data: Vec, + ) -> Result, &'static str> { + Self::with_caller(account("instantiator", index, 0), module, data) + } + + /// Create new contract and use the supplied `caller` as instantiator. + fn with_caller( + caller: T::AccountId, + module: WasmModule, + data: Vec, + ) -> Result, &'static str> { + let value = Pallet::::min_balance(); + T::Currency::set_balance(&caller, caller_funding::()); + let salt = vec![0xff]; + let addr = Contracts::::contract_address(&caller, &module.hash, &data, &salt); + + Contracts::::store_code_raw(module.code, caller.clone())?; + Contracts::::instantiate( + RawOrigin::Signed(caller.clone()).into(), + value, + Weight::MAX, + None, + module.hash, + data, + salt, + )?; + + let result = + Contract { caller, account_id: addr.clone(), addr: T::Lookup::unlookup(addr), value }; + + ContractInfoOf::::insert(&result.account_id, result.info()?); + + Ok(result) + } + + /// Create a new contract with the supplied storage item count and size each. + fn with_storage( + code: WasmModule, + stor_num: u32, + stor_size: u32, + ) -> Result { + let contract = Contract::::new(code, vec![])?; + let storage_items = (0..stor_num) + .map(|i| { + let hash = T::Hashing::hash_of(&i) + .as_ref() + .try_into() + .map_err(|_| "Hash too big for storage key")?; + Ok((hash, vec![42u8; stor_size as usize])) + }) + .collect::, &'static str>>()?; + contract.store(&storage_items)?; + Ok(contract) + } + + /// Store the supplied storage items into this contracts storage. + fn store(&self, items: &Vec<([u8; 32], Vec)>) -> Result<(), &'static str> { + let info = self.info()?; + for item in items { + info.write(&Key::Fix(item.0), Some(item.1.clone()), None, false) + .map_err(|_| "Failed to write storage to restoration dest")?; + } + >::insert(&self.account_id, info); + Ok(()) + } + + /// Create a new contract with the specified unbalanced storage trie. + fn with_unbalanced_storage_trie(code: WasmModule, key: &[u8]) -> Result { + if (key.len() as u32) < (UNBALANCED_TRIE_LAYERS + 1) / 2 { + return Err("Key size too small to create the specified trie"); + } + + let value = vec![16u8; T::Schedule::get().limits.payload_len as usize]; + let contract = Contract::::new(code, vec![])?; + let info = contract.info()?; + let child_trie_info = info.child_trie_info(); + child::put_raw(&child_trie_info, &key, &value); + for l in 0..UNBALANCED_TRIE_LAYERS { + let pos = l as usize / 2; + let mut key_new = key.to_vec(); + for i in 0u8..16 { + key_new[pos] = if l % 2 == 0 { + (key_new[pos] & 0xF0) | i + } else { + (key_new[pos] & 0x0F) | (i << 4) + }; + + if key == &key_new { + continue + } + child::put_raw(&child_trie_info, &key_new, &value); + } + } + Ok(contract) + } + + /// Get the `ContractInfo` of the `addr` or an error if it no longer exists. + fn address_info(addr: &T::AccountId) -> Result, &'static str> { + ContractInfoOf::::get(addr).ok_or("Expected contract to exist at this point.") + } + + /// Get the `ContractInfo` of this contract or an error if it no longer exists. + fn info(&self) -> Result, &'static str> { + Self::address_info(&self.account_id) + } + + /// Set the balance of the contract to the supplied amount. + fn set_balance(&self, balance: BalanceOf) { + T::Currency::set_balance(&self.account_id, balance); + } + + /// Returns `true` iff all storage entries related to code storage exist. + fn code_exists(hash: &CodeHash) -> bool { + >::contains_key(hash) && >::contains_key(&hash) + } + + /// Returns `true` iff no storage entry related to code storage exist. + fn code_removed(hash: &CodeHash) -> bool { + !>::contains_key(hash) && !>::contains_key(&hash) + } +} + +/// The funding that each account that either calls or instantiates contracts is funded with. +fn caller_funding() -> BalanceOf { + // Minting can overflow, so we can't abuse of the funding. This value happens to be big enough, + // but not too big to make the total supply overflow. + BalanceOf::::max_value() / 10_000u32.into() +} + +#[benchmarks( + where + as codec::HasCompact>::Type: Clone + Eq + PartialEq + core::fmt::Debug + scale_info::TypeInfo + codec::Encode, + T: Config + pallet_balances::Config, + BalanceOf: From< as Currency>::Balance>, + as Currency>::Balance: From>, +)] +mod benchmarks { + use super::*; + + // The base weight consumed on processing contracts deletion queue. + #[benchmark(pov_mode = Measured)] + fn on_process_deletion_queue_batch() { + #[block] + { + ContractInfo::::process_deletion_queue_batch(&mut WeightMeter::new()) + } + } + + #[benchmark(skip_meta, pov_mode = Measured)] + fn on_initialize_per_trie_key(k: Linear<0, 1024>) -> Result<(), BenchmarkError> { + let instance = Contract::::with_storage( + WasmModule::dummy(), + k, + T::Schedule::get().limits.payload_len, + )?; + instance.info()?.queue_trie_for_deletion(); + + #[block] + { + ContractInfo::::process_deletion_queue_batch(&mut WeightMeter::new()) + } + + Ok(()) + } + + // This benchmarks the v9 migration step (update codeStorage). + #[benchmark(pov_mode = Measured)] + fn v9_migration_step(c: Linear<0, { T::MaxCodeLen::get() }>) { + v09::store_old_dummy_code::(c as usize); + let mut m = v09::Migration::::default(); + #[block] + { + m.step(&mut WeightMeter::new()); + } + } + + // This benchmarks the v10 migration step (use dedicated deposit_account). + #[benchmark(pov_mode = Measured)] + fn v10_migration_step() -> Result<(), BenchmarkError> { + let contract = + >::with_caller(whitelisted_caller(), WasmModule::dummy(), vec![])?; + + v10::store_old_contract_info::>( + contract.account_id.clone(), + contract.info()?, + ); + let mut m = v10::Migration::>::default(); + + #[block] + { + m.step(&mut WeightMeter::new()); + } + + Ok(()) + } + + // This benchmarks the v11 migration step (Don't rely on reserved balances keeping an account + // alive). + #[benchmark(pov_mode = Measured)] + fn v11_migration_step(k: Linear<0, 1024>) { + v11::fill_old_queue::(k as usize); + let mut m = v11::Migration::::default(); + + #[block] + { + m.step(&mut WeightMeter::new()); + } + } + + // This benchmarks the v12 migration step (Move `OwnerInfo` to `CodeInfo`, + // add `determinism` field to the latter, clear `CodeStorage` + // and repay deposits). + #[benchmark(pov_mode = Measured)] + fn v12_migration_step(c: Linear<0, { T::MaxCodeLen::get() }>) { + v12::store_old_dummy_code::>( + c as usize, + account::("account", 0, 0), + ); + let mut m = v12::Migration::>::default(); + + #[block] + { + m.step(&mut WeightMeter::new()); + } + } + + // This benchmarks the v13 migration step (Add delegate_dependencies field). + #[benchmark(pov_mode = Measured)] + fn v13_migration_step() -> Result<(), BenchmarkError> { + let contract = + >::with_caller(whitelisted_caller(), WasmModule::dummy(), vec![])?; + + v13::store_old_contract_info::(contract.account_id.clone(), contract.info()?); + let mut m = v13::Migration::::default(); + + #[block] + { + m.step(&mut WeightMeter::new()); + } + Ok(()) + } + + // This benchmarks the v14 migration step (Move code owners' reserved balance to be held + // instead). + #[benchmark(pov_mode = Measured)] + fn v14_migration_step() { + let account = account::("account", 0, 0); + T::Currency::set_balance(&account, caller_funding::()); + v14::store_dummy_code::>(account); + let mut m = v14::Migration::>::default(); + + #[block] + { + m.step(&mut WeightMeter::new()); + } + } + + // This benchmarks the v15 migration step (remove deposit account). + #[benchmark(pov_mode = Measured)] + fn v15_migration_step() -> Result<(), BenchmarkError> { + let contract = + >::with_caller(whitelisted_caller(), WasmModule::dummy(), vec![])?; + + v15::store_old_contract_info::(contract.account_id.clone(), contract.info()?); + let mut m = v15::Migration::::default(); + + #[block] + { + m.step(&mut WeightMeter::new()); + } + + Ok(()) + } + + // This benchmarks the v16 migration step (Remove ED from base_deposit). + #[benchmark(pov_mode = Measured)] + fn v16_migration_step() -> Result<(), BenchmarkError> { + let contract = + >::with_caller(whitelisted_caller(), WasmModule::dummy(), vec![])?; + + let info = contract.info()?; + let base_deposit = v16::store_old_contract_info::(contract.account_id.clone(), &info); + let mut m = v16::Migration::::default(); + + #[block] + { + m.step(&mut WeightMeter::new()); + } + let ed = Pallet::::min_balance(); + let info = v16::ContractInfoOf::::get(&contract.account_id).unwrap(); + assert_eq!(info.storage_base_deposit, base_deposit - ed); + Ok(()) + } + + // This benchmarks the weight of executing Migration::migrate to execute a noop migration. + #[benchmark(pov_mode = Measured)] + fn migration_noop() { + let version = LATEST_MIGRATION_VERSION; + StorageVersion::new(version).put::>(); + #[block] + { + Migration::::migrate(&mut WeightMeter::new()); + } + assert_eq!(StorageVersion::get::>(), version); + } + + // This benchmarks the weight of dispatching migrate to execute 1 `NoopMigration` + #[benchmark(pov_mode = Measured)] + fn migrate() { + let latest_version = LATEST_MIGRATION_VERSION; + StorageVersion::new(latest_version - 2).put::>(); + as frame_support::traits::OnRuntimeUpgrade>::on_runtime_upgrade(); + + #[extrinsic_call] + _(RawOrigin::Signed(whitelisted_caller()), Weight::MAX); + + assert_eq!(StorageVersion::get::>(), latest_version - 1); + } + + // This benchmarks the weight of running on_runtime_upgrade when there are no migration in + // progress. + #[benchmark(pov_mode = Measured)] + fn on_runtime_upgrade_noop() { + let latest_version = LATEST_MIGRATION_VERSION; + StorageVersion::new(latest_version).put::>(); + #[block] + { + as frame_support::traits::OnRuntimeUpgrade>::on_runtime_upgrade(); + } + assert!(MigrationInProgress::::get().is_none()); + } + + // This benchmarks the weight of running on_runtime_upgrade when there is a migration in + // progress. + #[benchmark(pov_mode = Measured)] + fn on_runtime_upgrade_in_progress() { + let latest_version = LATEST_MIGRATION_VERSION; + StorageVersion::new(latest_version - 2).put::>(); + let v = vec![42u8].try_into().ok(); + MigrationInProgress::::set(v.clone()); + #[block] + { + as frame_support::traits::OnRuntimeUpgrade>::on_runtime_upgrade(); + } + assert!(MigrationInProgress::::get().is_some()); + assert_eq!(MigrationInProgress::::get(), v); + } + + // This benchmarks the weight of running on_runtime_upgrade when there is a migration to + // process. + #[benchmark(pov_mode = Measured)] + fn on_runtime_upgrade() { + let latest_version = LATEST_MIGRATION_VERSION; + StorageVersion::new(latest_version - 2).put::>(); + #[block] + { + as frame_support::traits::OnRuntimeUpgrade>::on_runtime_upgrade(); + } + assert!(MigrationInProgress::::get().is_some()); + } + + // This benchmarks the overhead of loading a code of size `c` byte from storage and into + // the sandbox. This does **not** include the actual execution for which the gas meter + // is responsible. This is achieved by generating all code to the `deploy` function + // which is in the wasm module but not executed on `call`. + // The results are supposed to be used as `call_with_code_per_byte(c) - + // call_with_code_per_byte(0)`. + #[benchmark(pov_mode = Measured)] + fn call_with_code_per_byte( + c: Linear<0, { T::MaxCodeLen::get() }>, + ) -> Result<(), BenchmarkError> { + let instance = Contract::::with_caller( + whitelisted_caller(), + WasmModule::sized(c, Location::Deploy, false), + vec![], + )?; + let value = Pallet::::min_balance(); + let callee = instance.addr; + + #[extrinsic_call] + call(RawOrigin::Signed(instance.caller.clone()), callee, value, Weight::MAX, None, vec![]); + + Ok(()) + } + + // `c`: Size of the code in bytes. + // `i`: Size of the input in bytes. + // `s`: Size of the salt in bytes. + #[benchmark(pov_mode = Measured)] + fn instantiate_with_code( + c: Linear<0, { T::MaxCodeLen::get() }>, + i: Linear<0, { code::max_pages::() * 64 * 1024 }>, + s: Linear<0, { code::max_pages::() * 64 * 1024 }>, + ) { + let input = vec![42u8; i as usize]; + let salt = vec![42u8; s as usize]; + let value = Pallet::::min_balance(); + let caller = whitelisted_caller(); + T::Currency::set_balance(&caller, caller_funding::()); + let WasmModule { code, hash, .. } = WasmModule::::sized(c, Location::Call, false); + let origin = RawOrigin::Signed(caller.clone()); + let addr = Contracts::::contract_address(&caller, &hash, &input, &salt); + #[extrinsic_call] + _(origin, value, Weight::MAX, None, code, input, salt); + + let deposit = + T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr); + // uploading the code reserves some balance in the callers account + let code_deposit = + T::Currency::balance_on_hold(&HoldReason::CodeUploadDepositReserve.into(), &caller); + assert_eq!( + T::Currency::balance(&caller), + caller_funding::() - value - deposit - code_deposit - Pallet::::min_balance(), + ); + // contract has the full value + assert_eq!(T::Currency::balance(&addr), value + Pallet::::min_balance()); + } + + // `i`: Size of the input in bytes. + // `s`: Size of the salt in bytes. + #[benchmark(pov_mode = Measured)] + fn instantiate( + i: Linear<0, { code::max_pages::() * 64 * 1024 }>, + s: Linear<0, { code::max_pages::() * 64 * 1024 }>, + ) -> Result<(), BenchmarkError> { + let input = vec![42u8; i as usize]; + let salt = vec![42u8; s as usize]; + let value = Pallet::::min_balance(); + let caller = whitelisted_caller(); + T::Currency::set_balance(&caller, caller_funding::()); + let WasmModule { code, hash, .. } = WasmModule::::dummy(); + let addr = Contracts::::contract_address(&caller, &hash, &input, &salt); + Contracts::::store_code_raw(code, caller.clone())?; + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), value, Weight::MAX, None, hash, input, salt); + + let deposit = + T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr); + // value was removed from the caller + assert_eq!( + T::Currency::balance(&caller), + caller_funding::() - value - deposit - Pallet::::min_balance(), + ); + // contract has the full value + assert_eq!(T::Currency::balance(&addr), value + Pallet::::min_balance()); + + Ok(()) + } + + // We just call a dummy contract to measure the overhead of the call extrinsic. + // The size of the data has no influence on the costs of this extrinsic as long as the contract + // won't call `seal_input` in its constructor to copy the data to contract memory. + // The dummy contract used here does not do this. The costs for the data copy is billed as + // part of `seal_input`. The costs for invoking a contract of a specific size are not part + // of this benchmark because we cannot know the size of the contract when issuing a call + // transaction. See `call_with_code_per_byte` for this. + #[benchmark(pov_mode = Measured)] + fn call() -> Result<(), BenchmarkError> { + let data = vec![42u8; 1024]; + let instance = + Contract::::with_caller(whitelisted_caller(), WasmModule::dummy(), vec![])?; + let value = Pallet::::min_balance(); + let origin = RawOrigin::Signed(instance.caller.clone()); + let callee = instance.addr.clone(); + let before = T::Currency::balance(&instance.account_id); + #[extrinsic_call] + _(origin, callee, value, Weight::MAX, None, data); + let deposit = T::Currency::balance_on_hold( + &HoldReason::StorageDepositReserve.into(), + &instance.account_id, + ); + // value and value transferred via call should be removed from the caller + assert_eq!( + T::Currency::balance(&instance.caller), + caller_funding::() - instance.value - value - deposit - Pallet::::min_balance(), + ); + // contract should have received the value + assert_eq!(T::Currency::balance(&instance.account_id), before + value); + // contract should still exist + instance.info()?; + + Ok(()) + } + + // This constructs a contract that is maximal expensive to instrument. + // It creates a maximum number of metering blocks per byte. + // `c`: Size of the code in bytes. + #[benchmark(pov_mode = Measured)] + fn upload_code_determinism_enforced(c: Linear<0, { T::MaxCodeLen::get() }>) { + let caller = whitelisted_caller(); + T::Currency::set_balance(&caller, caller_funding::()); + let WasmModule { code, hash, .. } = WasmModule::::sized(c, Location::Call, false); + let origin = RawOrigin::Signed(caller.clone()); + #[extrinsic_call] + upload_code(origin, code, None, Determinism::Enforced); + // uploading the code reserves some balance in the callers account + assert!(T::Currency::total_balance_on_hold(&caller) > 0u32.into()); + assert!(>::code_exists(&hash)); + } + + // Uploading code with [`Determinism::Relaxed`] should be more expensive than uploading code + // with [`Determinism::Enforced`], as we always try to save the code with + // [`Determinism::Enforced`] first. + #[benchmark(pov_mode = Measured)] + fn upload_code_determinism_relaxed(c: Linear<0, { T::MaxCodeLen::get() }>) { + let caller = whitelisted_caller(); + T::Currency::set_balance(&caller, caller_funding::()); + let WasmModule { code, hash, .. } = WasmModule::::sized(c, Location::Call, true); + let origin = RawOrigin::Signed(caller.clone()); + #[extrinsic_call] + upload_code(origin, code, None, Determinism::Relaxed); + assert!(T::Currency::total_balance_on_hold(&caller) > 0u32.into()); + assert!(>::code_exists(&hash)); + // Ensure that the benchmark follows the most expensive path, i.e., the code is saved with + assert_eq!(CodeInfoOf::::get(&hash).unwrap().determinism(), Determinism::Relaxed); + } + + // Removing code does not depend on the size of the contract because all the information + // needed to verify the removal claim (refcount, owner) is stored in a separate storage + // item (`CodeInfoOf`). + #[benchmark(pov_mode = Measured)] + fn remove_code() -> Result<(), BenchmarkError> { + let caller = whitelisted_caller(); + T::Currency::set_balance(&caller, caller_funding::()); + let WasmModule { code, hash, .. } = WasmModule::::dummy(); + let origin = RawOrigin::Signed(caller.clone()); + let uploaded = + >::bare_upload_code(caller.clone(), code, None, Determinism::Enforced)?; + assert_eq!(uploaded.code_hash, hash); + assert_eq!(uploaded.deposit, T::Currency::total_balance_on_hold(&caller)); + assert!(>::code_exists(&hash)); + #[extrinsic_call] + _(origin, hash); + // removing the code should have unreserved the deposit + assert_eq!(T::Currency::total_balance_on_hold(&caller), 0u32.into()); + assert!(>::code_removed(&hash)); + Ok(()) + } + + #[benchmark(pov_mode = Measured)] + fn set_code() -> Result<(), BenchmarkError> { + let instance = + >::with_caller(whitelisted_caller(), WasmModule::dummy(), vec![])?; + // we just add some bytes so that the code hash is different + let WasmModule { code, hash, .. } = >::dummy_with_bytes(128); + >::store_code_raw(code, instance.caller.clone())?; + let callee = instance.addr.clone(); + assert_ne!(instance.info()?.code_hash, hash); + #[extrinsic_call] + _(RawOrigin::Root, callee, hash); + assert_eq!(instance.info()?.code_hash, hash); + Ok(()) + } + + #[benchmark(pov_mode = Measured)] + fn noop_host_fn(r: Linear<0, API_BENCHMARK_RUNS>) { + let mut setup = CallSetup::::new(WasmModule::noop(r)); + let (mut ext, module) = setup.ext(); + let func = CallSetup::::prepare_call(&mut ext, module, vec![]); + #[block] + { + func.call(); + } + } + + #[benchmark(pov_mode = Measured)] + fn seal_caller() { + let len = ::max_encoded_len() as u32; + build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], ]); + + let result; + #[block] + { + result = BenchEnv::seal0_caller(&mut runtime, &mut memory, 4, 0); + } + + assert_ok!(result); + assert_eq!( + &::decode(&mut &memory[4..]).unwrap(), + runtime.ext().caller().account_id().unwrap() + ); + } + + #[benchmark(pov_mode = Measured)] + fn seal_is_contract() { + let Contract { account_id, .. } = + Contract::::with_index(1, WasmModule::dummy(), vec![]).unwrap(); + + build_runtime!(runtime, memory: [account_id.encode(), ]); + + let result; + #[block] + { + result = BenchEnv::seal0_is_contract(&mut runtime, &mut memory, 0); + } + + assert_eq!(result.unwrap(), 1); + } + + #[benchmark(pov_mode = Measured)] + fn seal_code_hash() { + let contract = Contract::::with_index(1, WasmModule::dummy(), vec![]).unwrap(); + let len = as MaxEncodedLen>::max_encoded_len() as u32; + build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], contract.account_id.encode(), ]); + + let result; + #[block] + { + result = BenchEnv::seal0_code_hash(&mut runtime, &mut memory, 4 + len, 4, 0); + } + + assert_ok!(result); + assert_eq!( + as Decode>::decode(&mut &memory[4..]).unwrap(), + contract.info().unwrap().code_hash + ); + } + + #[benchmark(pov_mode = Measured)] + fn seal_own_code_hash() { + let len = as MaxEncodedLen>::max_encoded_len() as u32; + build_runtime!(runtime, contract, memory: [len.to_le_bytes(), vec![0u8; len as _], ]); + let result; + #[block] + { + result = BenchEnv::seal0_own_code_hash(&mut runtime, &mut memory, 4, 0); + } + + assert_ok!(result); + assert_eq!( + as Decode>::decode(&mut &memory[4..]).unwrap(), + contract.info().unwrap().code_hash + ); + } + + #[benchmark(pov_mode = Measured)] + fn seal_caller_is_origin() { + build_runtime!(runtime, memory: []); + + let result; + #[block] + { + result = BenchEnv::seal0_caller_is_origin(&mut runtime, &mut memory); + } + assert_eq!(result.unwrap(), 1u32); + } + + #[benchmark(pov_mode = Measured)] + fn seal_caller_is_root() { + let mut setup = CallSetup::::default(); + setup.set_origin(Origin::Root); + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]); + + let result; + #[block] + { + result = BenchEnv::seal0_caller_is_root(&mut runtime, &mut [0u8; 0]); + } + assert_eq!(result.unwrap(), 1u32); + } + + #[benchmark(pov_mode = Measured)] + fn seal_address() { + let len = as MaxEncodedLen>::max_encoded_len() as u32; + build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], ]); + + let result; + #[block] + { + result = BenchEnv::seal0_address(&mut runtime, &mut memory, 4, 0); + } + assert_ok!(result); + assert_eq!( + &::decode(&mut &memory[4..]).unwrap(), + runtime.ext().address() + ); + } + + #[benchmark(pov_mode = Measured)] + fn seal_gas_left() { + // use correct max_encoded_len when new version of parity-scale-codec is released + let len = 18u32; + assert!(::max_encoded_len() as u32 != len); + build_runtime!(runtime, memory: [32u32.to_le_bytes(), vec![0u8; len as _], ]); + + let result; + #[block] + { + result = BenchEnv::seal1_gas_left(&mut runtime, &mut memory, 4, 0); + } + assert_ok!(result); + assert_eq!( + ::decode(&mut &memory[4..]).unwrap(), + runtime.ext().gas_meter().gas_left() + ); + } + + #[benchmark(pov_mode = Measured)] + fn seal_balance() { + let len = ::max_encoded_len() as u32; + build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], ]); + let result; + #[block] + { + result = BenchEnv::seal0_seal_balance(&mut runtime, &mut memory, 4, 0); + } + assert_ok!(result); + assert_eq!( + ::decode(&mut &memory[4..]).unwrap(), + runtime.ext().balance().into() + ); + } + + #[benchmark(pov_mode = Measured)] + fn seal_value_transferred() { + let len = ::max_encoded_len() as u32; + build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], ]); + let result; + #[block] + { + result = BenchEnv::seal0_value_transferred(&mut runtime, &mut memory, 4, 0); + } + assert_ok!(result); + assert_eq!( + ::decode(&mut &memory[4..]).unwrap(), + runtime.ext().value_transferred().into() + ); + } + + #[benchmark(pov_mode = Measured)] + fn seal_minimum_balance() { + let len = ::max_encoded_len() as u32; + build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], ]); + let result; + #[block] + { + result = BenchEnv::seal0_minimum_balance(&mut runtime, &mut memory, 4, 0); + } + assert_ok!(result); + assert_eq!( + ::decode(&mut &memory[4..]).unwrap(), + runtime.ext().minimum_balance().into() + ); + } + + #[benchmark(pov_mode = Measured)] + fn seal_block_number() { + let len = as MaxEncodedLen>::max_encoded_len() as u32; + build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], ]); + let result; + #[block] + { + result = BenchEnv::seal0_seal_block_number(&mut runtime, &mut memory, 4, 0); + } + assert_ok!(result); + assert_eq!( + >::decode(&mut &memory[4..]).unwrap(), + runtime.ext().block_number() + ); + } + + #[benchmark(pov_mode = Measured)] + fn seal_now() { + let len = as MaxEncodedLen>::max_encoded_len() as u32; + build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], ]); + let result; + #[block] + { + result = BenchEnv::seal0_seal_now(&mut runtime, &mut memory, 4, 0); + } + assert_ok!(result); + assert_eq!(>::decode(&mut &memory[4..]).unwrap(), *runtime.ext().now()); + } + + #[benchmark(pov_mode = Measured)] + fn seal_weight_to_fee() { + let len = ::max_encoded_len() as u32; + build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], ]); + let weight = Weight::from_parts(500_000, 300_000); + let result; + #[block] + { + result = BenchEnv::seal1_weight_to_fee( + &mut runtime, + &mut memory, + weight.ref_time(), + weight.proof_size(), + 4, + 0, + ); + } + assert_ok!(result); + assert_eq!( + >::decode(&mut &memory[4..]).unwrap(), + runtime.ext().get_weight_price(weight) + ); + } + + #[benchmark(pov_mode = Measured)] + fn seal_input(n: Linear<0, { code::max_pages::() * 64 * 1024 - 4 }>) { + let mut setup = CallSetup::::default(); + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![42u8; n as usize]); + let mut memory = memory!(n.to_le_bytes(), vec![0u8; n as usize],); + let result; + #[block] + { + result = BenchEnv::seal0_input(&mut runtime, &mut memory, 4, 0); + } + assert_ok!(result); + assert_eq!(&memory[4..], &vec![42u8; n as usize]); + } + + #[benchmark(pov_mode = Measured)] + fn seal_return(n: Linear<0, { code::max_pages::() * 64 * 1024 - 4 }>) { + build_runtime!(runtime, memory: [n.to_le_bytes(), vec![42u8; n as usize], ]); + + let result; + #[block] + { + result = BenchEnv::seal0_seal_return(&mut runtime, &mut memory, 0, 0, n); + } + + assert!(matches!( + result, + Err(crate::wasm::TrapReason::Return(crate::wasm::ReturnData { .. })) + )); + } + + #[benchmark(pov_mode = Measured)] + fn seal_terminate( + n: Linear<0, { T::MaxDelegateDependencies::get() }>, + ) -> Result<(), BenchmarkError> { + let beneficiary = account::("beneficiary", 0, 0); + let caller = whitelisted_caller(); + + build_runtime!(runtime, memory: [beneficiary.encode(),]); + + T::Currency::set_balance(&caller, caller_funding::()); + + (0..n).for_each(|i| { + let new_code = WasmModule::::dummy_with_bytes(65 + i); + Contracts::::store_code_raw(new_code.code, caller.clone()).unwrap(); + runtime.ext().lock_delegate_dependency(new_code.hash).unwrap(); + }); + + let result; + #[block] + { + result = BenchEnv::seal1_terminate(&mut runtime, &mut memory, 0); + } + + assert!(matches!(result, Err(crate::wasm::TrapReason::Termination))); + + Ok(()) + } + + // We benchmark only for the maximum subject length. We assume that this is some lowish + // number (< 1 KB). Therefore we are not overcharging too much in case a smaller subject is + // used. + #[benchmark(pov_mode = Measured)] + fn seal_random() { + let subject_len = T::Schedule::get().limits.subject_len; + assert!(subject_len < 1024); + + let output_len = + <(SeedOf, BlockNumberFor) as MaxEncodedLen>::max_encoded_len() as u32; + + build_runtime!(runtime, memory: [ + output_len.to_le_bytes(), + vec![42u8; subject_len as _], + vec![0u8; output_len as _], + ]); + + let result; + #[block] + { + result = BenchEnv::seal0_random( + &mut runtime, + &mut memory, + 4, // subject_ptr + subject_len, // subject_len + subject_len + 4, // output_ptr + 0, // output_len_ptr + ); + } + + assert_ok!(result); + assert_ok!(<(SeedOf, BlockNumberFor)>::decode(&mut &memory[subject_len as _..])); + } + + // Benchmark the overhead that topics generate. + // `t`: Number of topics + // `n`: Size of event payload in bytes + #[benchmark(pov_mode = Measured)] + fn seal_deposit_event( + t: Linear<0, { T::Schedule::get().limits.event_topics }>, + n: Linear<0, { T::Schedule::get().limits.payload_len }>, + ) { + let topics = (0..t).map(|i| T::Hashing::hash_of(&i)).collect::>().encode(); + let topics_len = topics.len() as u32; + + build_runtime!(runtime, memory: [ + n.to_le_bytes(), + topics, + vec![0u8; n as _], + ]); + + let result; + #[block] + { + result = BenchEnv::seal0_deposit_event( + &mut runtime, + &mut memory, + 4, // topics_ptr + topics_len, // topics_len + 4 + topics_len, // data_ptr + 0, // data_len + ); + } + + assert_ok!(result); + } + + // Benchmark debug_message call + // Whereas this function is used in RPC mode only, it still should be secured + // against an excessive use. + // + // i: size of input in bytes up to maximum allowed contract memory or maximum allowed debug + // buffer size, whichever is less. + #[benchmark] + fn seal_debug_message( + i: Linear< + 0, + { + (T::Schedule::get().limits.memory_pages * 64 * 1024) + .min(T::MaxDebugBufferLen::get()) + }, + >, + ) { + let mut setup = CallSetup::::default(); + setup.enable_debug_message(); + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]); + // Fill memory with printable ASCII bytes. + let mut memory = (0..i).zip((32..127).cycle()).map(|i| i.1).collect::>(); + + let result; + #[block] + { + result = BenchEnv::seal0_debug_message(&mut runtime, &mut memory, 0, i); + } + assert_ok!(result); + assert_eq!(setup.debug_message().unwrap().len() as u32, i); + } + + #[benchmark(skip_meta, pov_mode = Measured)] + fn get_storage_empty() -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = vec![0u8; max_key_len as usize]; + let max_value_len = T::Schedule::get().limits.payload_len as usize; + let value = vec![1u8; max_value_len]; + + let instance = Contract::::new(WasmModule::dummy(), vec![])?; + let info = instance.info()?; + let child_trie_info = info.child_trie_info(); + info.bench_write_raw(&key, Some(value.clone()), false) + .map_err(|_| "Failed to write to storage during setup.")?; + + let result; + #[block] + { + result = child::get_raw(&child_trie_info, &key); + } + + assert_eq!(result, Some(value)); + Ok(()) + } + + #[benchmark(skip_meta, pov_mode = Measured)] + fn get_storage_full() -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = vec![0u8; max_key_len as usize]; + let max_value_len = T::Schedule::get().limits.payload_len; + let value = vec![1u8; max_value_len as usize]; + + let instance = Contract::::with_unbalanced_storage_trie(WasmModule::dummy(), &key)?; + let info = instance.info()?; + let child_trie_info = info.child_trie_info(); + info.bench_write_raw(&key, Some(value.clone()), false) + .map_err(|_| "Failed to write to storage during setup.")?; + + let result; + #[block] + { + result = child::get_raw(&child_trie_info, &key); + } + + assert_eq!(result, Some(value)); + Ok(()) + } + + #[benchmark(skip_meta, pov_mode = Measured)] + fn set_storage_empty() -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = vec![0u8; max_key_len as usize]; + let max_value_len = T::Schedule::get().limits.payload_len as usize; + let value = vec![1u8; max_value_len]; + + let instance = Contract::::new(WasmModule::dummy(), vec![])?; + let info = instance.info()?; + let child_trie_info = info.child_trie_info(); + info.bench_write_raw(&key, Some(vec![42u8; max_value_len]), false) + .map_err(|_| "Failed to write to storage during setup.")?; + + let val = Some(value.clone()); + let result; + #[block] + { + result = info.bench_write_raw(&key, val, true); + } + + assert_ok!(result); + assert_eq!(child::get_raw(&child_trie_info, &key).unwrap(), value); + Ok(()) + } + + #[benchmark(skip_meta, pov_mode = Measured)] + fn set_storage_full() -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = vec![0u8; max_key_len as usize]; + let max_value_len = T::Schedule::get().limits.payload_len; + let value = vec![1u8; max_value_len as usize]; + + let instance = Contract::::with_unbalanced_storage_trie(WasmModule::dummy(), &key)?; + let info = instance.info()?; + let child_trie_info = info.child_trie_info(); + info.bench_write_raw(&key, Some(vec![42u8; max_value_len as usize]), false) + .map_err(|_| "Failed to write to storage during setup.")?; + + let val = Some(value.clone()); + let result; + #[block] + { + result = info.bench_write_raw(&key, val, true); + } + + assert_ok!(result); + assert_eq!(child::get_raw(&child_trie_info, &key).unwrap(), value); + Ok(()) + } + + // n: new byte size + // o: old byte size + #[benchmark(skip_meta, pov_mode = Measured)] + fn seal_set_storage( + n: Linear<0, { T::Schedule::get().limits.payload_len }>, + o: Linear<0, { T::Schedule::get().limits.payload_len }>, + ) -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + let value = vec![1u8; n as usize]; + + build_runtime!(runtime, instance, memory: [ key.to_vec(), value.clone(), ]); + let info = instance.info()?; + + info.write(&key, Some(vec![42u8; o as usize]), None, false) + .map_err(|_| "Failed to write to storage during setup.")?; + + let result; + #[block] + { + result = BenchEnv::seal2_set_storage( + &mut runtime, + &mut memory, + 0, // key_ptr + max_key_len, // key_len + max_key_len, // value_ptr + n, // value_len + ); + } + + assert_ok!(result); + assert_eq!(info.read(&key).unwrap(), value); + Ok(()) + } + + #[benchmark(skip_meta, pov_mode = Measured)] + fn seal_clear_storage( + n: Linear<0, { T::Schedule::get().limits.payload_len }>, + ) -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + build_runtime!(runtime, instance, memory: [ key.to_vec(), ]); + let info = instance.info()?; + + info.write(&key, Some(vec![42u8; n as usize]), None, false) + .map_err(|_| "Failed to write to storage during setup.")?; + + let result; + #[block] + { + result = BenchEnv::seal1_clear_storage(&mut runtime, &mut memory, 0, max_key_len); + } + + assert_ok!(result); + assert!(info.read(&key).is_none()); + Ok(()) + } + + #[benchmark(skip_meta, pov_mode = Measured)] + fn seal_get_storage( + n: Linear<0, { T::Schedule::get().limits.payload_len }>, + ) -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + build_runtime!(runtime, instance, memory: [ key.to_vec(), n.to_le_bytes(), vec![0u8; n as _], ]); + let info = instance.info()?; + + info.write(&key, Some(vec![42u8; n as usize]), None, false) + .map_err(|_| "Failed to write to storage during setup.")?; + + let out_ptr = max_key_len + 4; + let result; + #[block] + { + result = BenchEnv::seal1_get_storage( + &mut runtime, + &mut memory, + 0, // key_ptr + max_key_len, // key_len + out_ptr, // out_ptr + max_key_len, // out_len_ptr + ); + } + + assert_ok!(result); + assert_eq!(&info.read(&key).unwrap(), &memory[out_ptr as usize..]); + Ok(()) + } + + #[benchmark(skip_meta, pov_mode = Measured)] + fn seal_contains_storage( + n: Linear<0, { T::Schedule::get().limits.payload_len }>, + ) -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + build_runtime!(runtime, instance, memory: [ key.to_vec(), ]); + let info = instance.info()?; + + info.write(&key, Some(vec![42u8; n as usize]), None, false) + .map_err(|_| "Failed to write to storage during setup.")?; + + let result; + #[block] + { + result = BenchEnv::seal1_contains_storage(&mut runtime, &mut memory, 0, max_key_len); + } + + assert_eq!(result.unwrap(), n); + Ok(()) + } + + #[benchmark(skip_meta, pov_mode = Measured)] + fn seal_take_storage( + n: Linear<0, { T::Schedule::get().limits.payload_len }>, + ) -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + build_runtime!(runtime, instance, memory: [ key.to_vec(), n.to_le_bytes(), vec![0u8; n as _], ]); + let info = instance.info()?; + + let value = vec![42u8; n as usize]; + info.write(&key, Some(value.clone()), None, false) + .map_err(|_| "Failed to write to storage during setup.")?; + + let out_ptr = max_key_len + 4; + let result; + #[block] + { + result = BenchEnv::seal0_take_storage( + &mut runtime, + &mut memory, + 0, // key_ptr + max_key_len, // key_len + out_ptr, // out_ptr + max_key_len, // out_len_ptr + ); + } + + assert_ok!(result); + assert!(&info.read(&key).is_none()); + assert_eq!(&value, &memory[out_ptr as usize..]); + Ok(()) + } + + // We use both full and empty benchmarks here instead of benchmarking transient_storage + // (BTreeMap) directly. This approach is necessary because benchmarking this BTreeMap is very + // slow. Additionally, we use linear regression for our benchmarks, and the BTreeMap's log(n) + // complexity can introduce approximation errors. + #[benchmark(pov_mode = Ignored)] + fn set_transient_storage_empty() -> Result<(), BenchmarkError> { + let max_value_len = T::Schedule::get().limits.payload_len; + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + let value = Some(vec![42u8; max_value_len as _]); + let mut setup = CallSetup::::default(); + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + let result; + #[block] + { + result = runtime.ext().set_transient_storage(&key, value, false); + } + + assert_eq!(result, Ok(WriteOutcome::New)); + assert_eq!(runtime.ext().get_transient_storage(&key), Some(vec![42u8; max_value_len as _])); + Ok(()) + } + + #[benchmark(pov_mode = Ignored)] + fn set_transient_storage_full() -> Result<(), BenchmarkError> { + let max_value_len = T::Schedule::get().limits.payload_len; + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + let value = Some(vec![42u8; max_value_len as _]); + let mut setup = CallSetup::::default(); + setup.set_transient_storage_size(T::MaxTransientStorageSize::get()); + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + let result; + #[block] + { + result = runtime.ext().set_transient_storage(&key, value, false); + } + + assert_eq!(result, Ok(WriteOutcome::New)); + assert_eq!(runtime.ext().get_transient_storage(&key), Some(vec![42u8; max_value_len as _])); + Ok(()) + } + + #[benchmark(pov_mode = Ignored)] + fn get_transient_storage_empty() -> Result<(), BenchmarkError> { + let max_value_len = T::Schedule::get().limits.payload_len; + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + + let mut setup = CallSetup::::default(); + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + runtime + .ext() + .set_transient_storage(&key, Some(vec![42u8; max_value_len as _]), false) + .map_err(|_| "Failed to write to transient storage during setup.")?; + let result; + #[block] + { + result = runtime.ext().get_transient_storage(&key); + } + + assert_eq!(result, Some(vec![42u8; max_value_len as _])); + Ok(()) + } + + #[benchmark(pov_mode = Ignored)] + fn get_transient_storage_full() -> Result<(), BenchmarkError> { + let max_value_len = T::Schedule::get().limits.payload_len; + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + + let mut setup = CallSetup::::default(); + setup.set_transient_storage_size(T::MaxTransientStorageSize::get()); + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + runtime + .ext() + .set_transient_storage(&key, Some(vec![42u8; max_value_len as _]), false) + .map_err(|_| "Failed to write to transient storage during setup.")?; + let result; + #[block] + { + result = runtime.ext().get_transient_storage(&key); + } + + assert_eq!(result, Some(vec![42u8; max_value_len as _])); + Ok(()) + } + + // The weight of journal rollbacks should be taken into account when setting storage. + #[benchmark(pov_mode = Ignored)] + fn rollback_transient_storage() -> Result<(), BenchmarkError> { + let max_value_len = T::Schedule::get().limits.payload_len; + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + + let mut setup = CallSetup::::default(); + setup.set_transient_storage_size(T::MaxTransientStorageSize::get()); + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + runtime.ext().transient_storage().start_transaction(); + runtime + .ext() + .set_transient_storage(&key, Some(vec![42u8; max_value_len as _]), false) + .map_err(|_| "Failed to write to transient storage during setup.")?; + #[block] + { + runtime.ext().transient_storage().rollback_transaction(); + } + + assert_eq!(runtime.ext().get_transient_storage(&key), None); + Ok(()) + } + + // n: new byte size + // o: old byte size + #[benchmark(pov_mode = Measured)] + fn seal_set_transient_storage( + n: Linear<0, { T::Schedule::get().limits.payload_len }>, + o: Linear<0, { T::Schedule::get().limits.payload_len }>, + ) -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + let value = vec![1u8; n as usize]; + build_runtime!(runtime, memory: [ key.to_vec(), value.clone(), ]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + runtime + .ext() + .set_transient_storage(&key, Some(vec![42u8; o as usize]), false) + .map_err(|_| "Failed to write to transient storage during setup.")?; + + let result; + #[block] + { + result = BenchEnv::seal0_set_transient_storage( + &mut runtime, + &mut memory, + 0, // key_ptr + max_key_len, // key_len + max_key_len, // value_ptr + n, // value_len + ); + } + + assert_ok!(result); + assert_eq!(runtime.ext().get_transient_storage(&key).unwrap(), value); + Ok(()) + } + + #[benchmark(pov_mode = Measured)] + fn seal_clear_transient_storage( + n: Linear<0, { T::Schedule::get().limits.payload_len }>, + ) -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + build_runtime!(runtime, memory: [ key.to_vec(), ]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + runtime + .ext() + .set_transient_storage(&key, Some(vec![42u8; n as usize]), false) + .map_err(|_| "Failed to write to transient storage during setup.")?; + + let result; + #[block] + { + result = + BenchEnv::seal0_clear_transient_storage(&mut runtime, &mut memory, 0, max_key_len); + } + + assert_ok!(result); + assert!(runtime.ext().get_transient_storage(&key).is_none()); + Ok(()) + } + + #[benchmark(pov_mode = Measured)] + fn seal_get_transient_storage( + n: Linear<0, { T::Schedule::get().limits.payload_len }>, + ) -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + build_runtime!(runtime, memory: [ key.to_vec(), n.to_le_bytes(), vec![0u8; n as _], ]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + runtime + .ext() + .set_transient_storage(&key, Some(vec![42u8; n as usize]), false) + .map_err(|_| "Failed to write to transient storage during setup.")?; + + let out_ptr = max_key_len + 4; + let result; + #[block] + { + result = BenchEnv::seal0_get_transient_storage( + &mut runtime, + &mut memory, + 0, // key_ptr + max_key_len, // key_len + out_ptr, // out_ptr + max_key_len, // out_len_ptr + ); + } + + assert_ok!(result); + assert_eq!( + &runtime.ext().get_transient_storage(&key).unwrap(), + &memory[out_ptr as usize..] + ); + Ok(()) + } + + #[benchmark(pov_mode = Measured)] + fn seal_contains_transient_storage( + n: Linear<0, { T::Schedule::get().limits.payload_len }>, + ) -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + build_runtime!(runtime, memory: [ key.to_vec(), ]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + runtime + .ext() + .set_transient_storage(&key, Some(vec![42u8; n as usize]), false) + .map_err(|_| "Failed to write to transient storage during setup.")?; + + let result; + #[block] + { + result = BenchEnv::seal0_contains_transient_storage( + &mut runtime, + &mut memory, + 0, + max_key_len, + ); + } + + assert_eq!(result.unwrap(), n); + Ok(()) + } + + #[benchmark(pov_mode = Measured)] + fn seal_take_transient_storage( + n: Linear<0, { T::Schedule::get().limits.payload_len }>, + ) -> Result<(), BenchmarkError> { + let n = T::Schedule::get().limits.payload_len; + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + build_runtime!(runtime, memory: [ key.to_vec(), n.to_le_bytes(), vec![0u8; n as _], ]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + let value = vec![42u8; n as usize]; + runtime + .ext() + .set_transient_storage(&key, Some(value.clone()), false) + .map_err(|_| "Failed to write to transient storage during setup.")?; + + let out_ptr = max_key_len + 4; + let result; + #[block] + { + result = BenchEnv::seal0_take_transient_storage( + &mut runtime, + &mut memory, + 0, // key_ptr + max_key_len, // key_len + out_ptr, // out_ptr + max_key_len, // out_len_ptr + ); + } + + assert_ok!(result); + assert!(&runtime.ext().get_transient_storage(&key).is_none()); + assert_eq!(&value, &memory[out_ptr as usize..]); + Ok(()) + } + + // We transfer to unique accounts. + #[benchmark(pov_mode = Measured)] + fn seal_transfer() { + let account = account::("receiver", 0, 0); + let value = Pallet::::min_balance(); + assert!(value > 0u32.into()); + + let mut setup = CallSetup::::default(); + setup.set_balance(value); + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]); + + let account_bytes = account.encode(); + let account_len = account_bytes.len() as u32; + let value_bytes = value.encode(); + let value_len = value_bytes.len() as u32; + let mut memory = memory!(account_bytes, value_bytes,); + + let result; + #[block] + { + result = BenchEnv::seal0_transfer( + &mut runtime, + &mut memory, + 0, // account_ptr + account_len, + account_len, + value_len, + ); + } + + assert_ok!(result); + } + + // t: with or without some value to transfer + // i: size of the input data + #[benchmark(pov_mode = Measured)] + fn seal_call(t: Linear<0, 1>, i: Linear<0, { code::max_pages::() * 64 * 1024 }>) { + let Contract { account_id: callee, .. } = + Contract::::with_index(1, WasmModule::dummy(), vec![]).unwrap(); + let callee_bytes = callee.encode(); + let callee_len = callee_bytes.len() as u32; + + let value: BalanceOf = t.into(); + let value_bytes = value.encode(); + + let deposit: BalanceOf = (u32::MAX - 100).into(); + let deposit_bytes = deposit.encode(); + let deposit_len = deposit_bytes.len() as u32; + + let mut setup = CallSetup::::default(); + setup.set_storage_deposit_limit(deposit); + setup.set_data(vec![42; i as usize]); + setup.set_origin(Origin::from_account_id(setup.contract().account_id.clone())); + + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]); + let mut memory = memory!(callee_bytes, deposit_bytes, value_bytes,); + + let result; + #[block] + { + result = BenchEnv::seal2_call( + &mut runtime, + &mut memory, + CallFlags::CLONE_INPUT.bits(), // flags + 0, // callee_ptr + 0, // ref_time_limit + 0, // proof_size_limit + callee_len, // deposit_ptr + callee_len + deposit_len, // value_ptr + 0, // input_data_ptr + 0, // input_data_len + SENTINEL, // output_ptr + 0, // output_len_ptr + ); + } + + assert_ok!(result); + } + + #[benchmark(pov_mode = Measured)] + fn seal_delegate_call() -> Result<(), BenchmarkError> { + let hash = Contract::::with_index(1, WasmModule::dummy(), vec![])?.info()?.code_hash; + + let mut setup = CallSetup::::default(); + setup.set_origin(Origin::from_account_id(setup.contract().account_id.clone())); + + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]); + let mut memory = memory!(hash.encode(),); + + let result; + #[block] + { + result = BenchEnv::seal0_delegate_call( + &mut runtime, + &mut memory, + 0, // flags + 0, // code_hash_ptr + 0, // input_data_ptr + 0, // input_data_len + SENTINEL, // output_ptr + 0, + ); + } + + assert_ok!(result); + Ok(()) + } + + // t: value to transfer + // i: size of input in bytes + // s: size of salt in bytes + #[benchmark(pov_mode = Measured)] + fn seal_instantiate( + i: Linear<0, { (code::max_pages::() - 1) * 64 * 1024 }>, + s: Linear<0, { (code::max_pages::() - 1) * 64 * 1024 }>, + ) -> Result<(), BenchmarkError> { + let hash = Contract::::with_index(1, WasmModule::dummy(), vec![])?.info()?.code_hash; + let hash_bytes = hash.encode(); + let hash_len = hash_bytes.len() as u32; + + let value: BalanceOf = 1u32.into(); + let value_bytes = value.encode(); + let value_len = value_bytes.len() as u32; + + let deposit: BalanceOf = 0u32.into(); + let deposit_bytes = deposit.encode(); + let deposit_len = deposit_bytes.len() as u32; + + let mut setup = CallSetup::::default(); + setup.set_origin(Origin::from_account_id(setup.contract().account_id.clone())); + setup.set_balance(value + (Pallet::::min_balance() * 2u32.into())); + + let account_id = &setup.contract().account_id.clone(); + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]); + + let input = vec![42u8; i as _]; + let salt = vec![42u8; s as _]; + let addr = Contracts::::contract_address(&account_id, &hash, &input, &salt); + let mut memory = memory!(hash_bytes, deposit_bytes, value_bytes, input, salt,); + + let mut offset = { + let mut current = 0u32; + move |after: u32| { + current += after; + current + } + }; + + assert!(ContractInfoOf::::get(&addr).is_none()); + + let result; + #[block] + { + result = BenchEnv::seal2_instantiate( + &mut runtime, + &mut memory, + 0, // code_hash_ptr + 0, // ref_time_limit + 0, // proof_size_limit + offset(hash_len), // deposit_ptr + offset(deposit_len), // value_ptr + offset(value_len), // input_data_ptr + i, // input_data_len + SENTINEL, // address_ptr + 0, // address_len_ptr + SENTINEL, // output_ptr + 0, // output_len_ptr + offset(i), // salt_ptr + s, // salt_len + ); + } + + assert_ok!(result); + assert!(ContractInfoOf::::get(&addr).is_some()); + assert_eq!(T::Currency::balance(&addr), Pallet::::min_balance() + value); + Ok(()) + } + + // `n`: Input to hash in bytes + #[benchmark(pov_mode = Measured)] + fn seal_hash_sha2_256(n: Linear<0, { code::max_pages::() * 64 * 1024 }>) { + build_runtime!(runtime, memory: [[0u8; 32], vec![0u8; n as usize], ]); + + let result; + #[block] + { + result = BenchEnv::seal0_hash_sha2_256(&mut runtime, &mut memory, 32, n, 0); + } + assert_eq!(sp_io::hashing::sha2_256(&memory[32..]), &memory[0..32]); + assert_ok!(result); + } + + // `n`: Input to hash in bytes + #[benchmark(pov_mode = Measured)] + fn seal_hash_keccak_256(n: Linear<0, { code::max_pages::() * 64 * 1024 }>) { + build_runtime!(runtime, memory: [[0u8; 32], vec![0u8; n as usize], ]); + + let result; + #[block] + { + result = BenchEnv::seal0_hash_keccak_256(&mut runtime, &mut memory, 32, n, 0); + } + assert_eq!(sp_io::hashing::keccak_256(&memory[32..]), &memory[0..32]); + assert_ok!(result); + } + + // `n`: Input to hash in bytes + #[benchmark(pov_mode = Measured)] + fn seal_hash_blake2_256(n: Linear<0, { code::max_pages::() * 64 * 1024 }>) { + build_runtime!(runtime, memory: [[0u8; 32], vec![0u8; n as usize], ]); + + let result; + #[block] + { + result = BenchEnv::seal0_hash_blake2_256(&mut runtime, &mut memory, 32, n, 0); + } + assert_eq!(sp_io::hashing::blake2_256(&memory[32..]), &memory[0..32]); + assert_ok!(result); + } + + // `n`: Input to hash in bytes + #[benchmark(pov_mode = Measured)] + fn seal_hash_blake2_128(n: Linear<0, { code::max_pages::() * 64 * 1024 }>) { + build_runtime!(runtime, memory: [[0u8; 16], vec![0u8; n as usize], ]); + + let result; + #[block] + { + result = BenchEnv::seal0_hash_blake2_128(&mut runtime, &mut memory, 16, n, 0); + } + assert_eq!(sp_io::hashing::blake2_128(&memory[16..]), &memory[0..16]); + assert_ok!(result); + } + + // `n`: Message input length to verify in bytes. + // need some buffer so the code size does not exceed the max code size. + #[benchmark(pov_mode = Measured)] + fn seal_sr25519_verify(n: Linear<0, { T::MaxCodeLen::get() - 255 }>) { + let message = (0..n).zip((32u8..127u8).cycle()).map(|(_, c)| c).collect::>(); + let message_len = message.len() as u32; + + let key_type = sp_core::crypto::KeyTypeId(*b"code"); + let pub_key = sp_io::crypto::sr25519_generate(key_type, None); + let sig = + sp_io::crypto::sr25519_sign(key_type, &pub_key, &message).expect("Generates signature"); + let sig = AsRef::<[u8; 64]>::as_ref(&sig).to_vec(); + let sig_len = sig.len() as u32; + + build_runtime!(runtime, memory: [sig, pub_key.to_vec(), message, ]); + + let result; + #[block] + { + result = BenchEnv::seal0_sr25519_verify( + &mut runtime, + &mut memory, + 0, // signature_ptr + sig_len, // pub_key_ptr + message_len, // message_len + sig_len + pub_key.len() as u32, // message_ptr + ); + } + + assert_eq!(result.unwrap(), ReturnErrorCode::Success); + } + + #[benchmark(pov_mode = Measured)] + fn seal_ecdsa_recover() { + let message_hash = sp_io::hashing::blake2_256("Hello world".as_bytes()); + let key_type = sp_core::crypto::KeyTypeId(*b"code"); + let signature = { + let pub_key = sp_io::crypto::ecdsa_generate(key_type, None); + let sig = sp_io::crypto::ecdsa_sign_prehashed(key_type, &pub_key, &message_hash) + .expect("Generates signature"); + AsRef::<[u8; 65]>::as_ref(&sig).to_vec() + }; + + build_runtime!(runtime, memory: [signature, message_hash, [0u8; 33], ]); + + let result; + #[block] + { + result = BenchEnv::seal0_ecdsa_recover( + &mut runtime, + &mut memory, + 0, // signature_ptr + 65, // message_hash_ptr + 65 + 32, // output_ptr + ); + } + + assert_eq!(result.unwrap(), ReturnErrorCode::Success); + } + + // Only calling the function itself for the list of + // generated different ECDSA keys. + // This is a slow call: We reduce the number of runs. + #[benchmark(pov_mode = Measured)] + fn seal_ecdsa_to_eth_address() { + let key_type = sp_core::crypto::KeyTypeId(*b"code"); + let pub_key_bytes = sp_io::crypto::ecdsa_generate(key_type, None).0; + build_runtime!(runtime, memory: [[0u8; 20], pub_key_bytes,]); + + let result; + #[block] + { + result = BenchEnv::seal0_ecdsa_to_eth_address( + &mut runtime, + &mut memory, + 20, // key_ptr + 0, // output_ptr + ); + } + + assert_ok!(result); + assert_eq!(&memory[..20], runtime.ext().ecdsa_to_eth_address(&pub_key_bytes).unwrap()); + } + + #[benchmark(pov_mode = Measured)] + fn seal_set_code_hash() -> Result<(), BenchmarkError> { + let code_hash = + Contract::::with_index(1, WasmModule::dummy(), vec![])?.info()?.code_hash; + + build_runtime!(runtime, memory: [ code_hash.encode(),]); + + let result; + #[block] + { + result = BenchEnv::seal0_set_code_hash(&mut runtime, &mut memory, 0); + } + + assert_ok!(result); + Ok(()) + } + + #[benchmark(pov_mode = Measured)] + fn lock_delegate_dependency() -> Result<(), BenchmarkError> { + let code_hash = Contract::::with_index(1, WasmModule::dummy_with_bytes(1), vec![])? + .info()? + .code_hash; + + build_runtime!(runtime, memory: [ code_hash.encode(),]); + + let result; + #[block] + { + result = BenchEnv::seal0_lock_delegate_dependency(&mut runtime, &mut memory, 0); + } + + assert_ok!(result); + Ok(()) + } + + #[benchmark] + fn unlock_delegate_dependency() -> Result<(), BenchmarkError> { + let code_hash = Contract::::with_index(1, WasmModule::dummy_with_bytes(1), vec![])? + .info()? + .code_hash; + + build_runtime!(runtime, memory: [ code_hash.encode(),]); + BenchEnv::seal0_lock_delegate_dependency(&mut runtime, &mut memory, 0).unwrap(); + + let result; + #[block] + { + result = BenchEnv::seal0_unlock_delegate_dependency(&mut runtime, &mut memory, 0); + } + + assert_ok!(result); + Ok(()) + } + + #[benchmark(pov_mode = Measured)] + fn seal_reentrance_count() { + build_runtime!(runtime, memory: []); + let result; + #[block] + { + result = BenchEnv::seal0_reentrance_count(&mut runtime, &mut memory) + } + + assert_eq!(result.unwrap(), 0); + } + + #[benchmark(pov_mode = Measured)] + fn seal_account_reentrance_count() { + let Contract { account_id, .. } = + Contract::::with_index(1, WasmModule::dummy(), vec![]).unwrap(); + build_runtime!(runtime, memory: [account_id.encode(),]); + + let result; + #[block] + { + result = BenchEnv::seal0_account_reentrance_count(&mut runtime, &mut memory, 0); + } + + assert_eq!(result.unwrap(), 0); + } + + #[benchmark(pov_mode = Measured)] + fn seal_instantiation_nonce() { + build_runtime!(runtime, memory: []); + + let result; + #[block] + { + result = BenchEnv::seal0_instantiation_nonce(&mut runtime, &mut memory); + } + + assert_eq!(result.unwrap(), 1); + } + + // We load `i64` values from random linear memory locations and store the loaded + // values back into yet another random linear memory location. + // The random addresses are uniformly distributed across the entire span of the linear memory. + // We do this to enforce random memory accesses which are particularly expensive. + // + // The combination of this computation is our weight base `w_base`. + #[benchmark(pov_mode = Ignored)] + fn instr_i64_load_store(r: Linear<0, INSTR_BENCHMARK_RUNS>) -> Result<(), BenchmarkError> { + use rand::prelude::*; + + // We do not need to be secure here. Fixed seed allows for deterministic results. + let mut rng = rand_pcg::Pcg32::seed_from_u64(8446744073709551615); + + let memory = ImportedMemory::max::(); + let bytes_per_page = 65536; + let bytes_per_memory = memory.max_pages * bytes_per_page; + let mut sbox = Sandbox::from(&WasmModule::::from(ModuleDefinition { + memory: Some(memory), + call_body: Some(body::repeated_with_locals_using( + &[Local::new(1, ValueType::I64)], + r, + || { + // Instruction sequence to load a `i64` from linear memory + // at a random memory location and store it back into another + // location of the linear memory. + let c0: i32 = rng.gen_range(0..bytes_per_memory as i32); + let c1: i32 = rng.gen_range(0..bytes_per_memory as i32); + [ + Instruction::I32Const(c0), // address for `i64.load_8s` + Instruction::I64Load8S(0, 0), + Instruction::SetLocal(0), /* temporarily store value loaded in + * `i64.load_8s` */ + Instruction::I32Const(c1), // address for `i64.store8` + Instruction::GetLocal(0), // value to be stores in `i64.store8` + Instruction::I64Store8(0, 0), + ] + }, + )), + ..Default::default() + })); + #[block] + { + sbox.invoke(); + } + Ok(()) + } + + // This is no benchmark. It merely exist to have an easy way to pretty print the currently + // configured `Schedule` during benchmark development. Check the README on how to print this. + #[benchmark(extra, pov_mode = Ignored)] + fn print_schedule() -> Result<(), BenchmarkError> { + let max_weight = ::BlockWeights::get().max_block; + let (weight_per_key, key_budget) = + ContractInfo::::deletion_budget(&mut WeightMeter::with_limit(max_weight)); + let schedule = T::Schedule::get(); + log::info!(target: LOG_TARGET, " + {schedule:#?} + ############################################### + Lazy deletion weight per key: {weight_per_key} + Lazy deletion keys per block: {key_budget} + "); + #[block] + {} + + Err(BenchmarkError::Skip) + } + + impl_benchmark_test_suite!( + Contracts, + crate::tests::ExtBuilder::default().build(), + crate::tests::Test, + ); +} diff --git a/pallets/contracts/src/benchmarking/sandbox.rs b/pallets/contracts/src/benchmarking/sandbox.rs new file mode 100644 index 00000000..1bcf0c40 --- /dev/null +++ b/pallets/contracts/src/benchmarking/sandbox.rs @@ -0,0 +1,91 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/// ! For instruction benchmarking we do not instantiate a full contract but merely the +/// ! sandbox to execute the Wasm code. This is because we do not need the full +/// ! environment that provides the seal interface as imported functions. +use super::{code::WasmModule, Config}; +use crate::wasm::{ + AllowDeprecatedInterface, AllowUnstableInterface, Determinism, Environment, LoadedModule, + LoadingMode, WasmBlob, +}; +use sp_core::Get; +use wasmi::{errors::LinkerError, CompilationMode, Func, Linker, StackLimits, Store}; + +/// Minimal execution environment without any imported functions. +pub struct Sandbox { + entry_point: Func, + store: Store<()>, +} + +impl Sandbox { + /// Invoke the `call` function of a contract code and panic on any execution error. + pub fn invoke(&mut self) { + self.entry_point.call(&mut self.store, &[], &mut []).unwrap(); + } +} + +impl From<&WasmModule> for Sandbox { + /// Creates an instance from the supplied module. + /// Sets the execution engine fuel level to `u64::MAX`. + fn from(module: &WasmModule) -> Self { + let contract = LoadedModule::new::( + &module.code, + Determinism::Relaxed, + Some(StackLimits::default()), + LoadingMode::Checked, + CompilationMode::Eager, + ) + .expect("Failed to load Wasm module"); + + let (mut store, _memory, instance) = WasmBlob::::instantiate::( + contract, + (), + &::Schedule::get(), + // We are testing with an empty environment anyways + AllowDeprecatedInterface::No, + ) + .expect("Failed to create benchmarking Sandbox instance"); + + // Set fuel for wasmi execution. + store + .set_fuel(u64::MAX) + .expect("We've set up engine to fuel consuming mode; qed"); + + let entry_point = instance + .start(&mut store) + .unwrap() + .get_export(&store, "call") + .unwrap() + .into_func() + .unwrap(); + Self { entry_point, store } + } +} + +struct EmptyEnv; + +impl Environment<()> for EmptyEnv { + fn define( + _: &mut Store<()>, + _: &mut Linker<()>, + _: AllowUnstableInterface, + _: AllowDeprecatedInterface, + ) -> Result<(), LinkerError> { + Ok(()) + } +} diff --git a/pallets/contracts/src/chain_extension.rs b/pallets/contracts/src/chain_extension.rs new file mode 100644 index 00000000..b9bb451f --- /dev/null +++ b/pallets/contracts/src/chain_extension.rs @@ -0,0 +1,495 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! A mechanism for runtime authors to augment the functionality of contracts. +//! +//! The runtime is able to call into any contract and retrieve the result using +//! [`bare_call`](crate::Pallet::bare_call). This already allows customization of runtime +//! behaviour by user generated code (contracts). However, often it is more straightforward +//! to allow the reverse behaviour: The contract calls into the runtime. We call the latter +//! one a "chain extension" because it allows the chain to extend the set of functions that are +//! callable by a contract. +//! +//! In order to create a chain extension the runtime author implements the [`ChainExtension`] +//! trait and declares it in this pallet's [configuration Trait](crate::Config). All types +//! required for this endeavour are defined or re-exported in this module. There is an +//! implementation on `()` which can be used to signal that no chain extension is available. +//! +//! # Using multiple chain extensions +//! +//! Often there is a need for having multiple chain extensions. This is often the case when +//! some generally useful off-the-shelf extensions should be included. To have multiple chain +//! extensions they can be put into a tuple which is then passed to [`Config::ChainExtension`] like +//! this `type Extensions = (ExtensionA, ExtensionB)`. +//! +//! However, only extensions implementing [`RegisteredChainExtension`] can be put into a tuple. +//! This is because the [`RegisteredChainExtension::ID`] is used to decide which of those extensions +//! should be used when the contract calls a chain extensions. Extensions which are generally +//! useful should claim their `ID` with [the registry](https://github.com/paritytech/chainextension-registry) +//! so that no collisions with other vendors will occur. +//! +//! **Chain specific extensions must use the reserved `ID = 0` so that they can't be registered with +//! the registry.** +//! +//! # Security +//! +//! The chain author alone is responsible for the security of the chain extension. +//! This includes avoiding the exposure of exploitable functions and charging the +//! appropriate amount of weight. In order to do so benchmarks must be written and the +//! [`charge_weight`](Environment::charge_weight) function must be called **before** +//! carrying out any action that causes the consumption of the chargeable weight. +//! It cannot be overstated how delicate of a process the creation of a chain extension +//! is. Check whether using [`bare_call`](crate::Pallet::bare_call) suffices for the +//! use case at hand. +//! +//! # Benchmarking +//! +//! The builtin contract callable functions that pallet-contracts provides all have +//! benchmarks that determine the correct weight that an invocation of these functions +//! induces. In order to be able to charge the correct weight for the functions defined +//! by a chain extension benchmarks must be written, too. In the near future this crate +//! will provide the means for easier creation of those specialized benchmarks. +//! +//! # Example +//! +//! The ink-examples repository maintains an +//! [end-to-end example](https://github.com/paritytech/ink-examples/tree/main/rand-extension) +//! on how to use a chain extension in order to provide new features to ink! contracts. + +use crate::{ + wasm::{Runtime, RuntimeCosts}, + Error, +}; +use alloc::vec::Vec; +use codec::{Decode, MaxEncodedLen}; +use core::marker::PhantomData; +use frame_support::weights::Weight; +use sp_runtime::DispatchError; + +pub use crate::{exec::Ext, gas::ChargedAmount, storage::meter::Diff, Config}; +pub use frame_system::Config as SysConfig; +pub use pallet_contracts_uapi::ReturnFlags; + +/// Result that returns a [`DispatchError`] on error. +pub type Result = core::result::Result; + +/// A trait used to extend the set of contract callable functions. +/// +/// In order to create a custom chain extension this trait must be implemented and supplied +/// to the pallet contracts configuration trait as the associated type of the same name. +/// Consult the [module documentation](self) for a general explanation of chain extensions. +/// +/// # Lifetime +/// +/// The extension will be [`Default`] initialized at the beginning of each call +/// (**not** per call stack) and dropped afterwards. Hence any value held inside the extension +/// can be used as a per-call scratch buffer. +pub trait ChainExtension { + /// Call the chain extension logic. + /// + /// This is the only function that needs to be implemented in order to write a + /// chain extensions. It is called whenever a contract calls the `seal_call_chain_extension` + /// imported wasm function. + /// + /// # Parameters + /// - `env`: Access to the remaining arguments and the execution environment. + /// + /// # Return + /// + /// In case of `Err` the contract execution is immediately suspended and the passed error + /// is returned to the caller. Otherwise the value of [`RetVal`] determines the exit + /// behaviour. + /// + /// # Note + /// + /// The [`Self::call`] can be invoked within a read-only context, where any state-changing calls + /// are disallowed. This information can be obtained using `env.ext().is_read_only()`. It is + /// crucial for the implementer to handle this scenario appropriately. + fn call>(&mut self, env: Environment) -> Result; + + /// Determines whether chain extensions are enabled for this chain. + /// + /// The default implementation returns `true`. Therefore it is not necessary to overwrite + /// this function when implementing a chain extension. In case of `false` the deployment of + /// a contract that references `seal_call_chain_extension` will be denied and calling this + /// function will return [`NoChainExtension`](Error::NoChainExtension) without first calling + /// into [`call`](Self::call). + fn enabled() -> bool { + true + } +} + +/// A [`ChainExtension`] that can be composed with other extensions using a tuple. +/// +/// An extension that implements this trait can be put in a tuple in order to have multiple +/// extensions available. The tuple implementation routes requests based on the first two +/// most significant bytes of the `id` passed to `call`. +/// +/// If this extensions is to be used by multiple runtimes consider +/// [registering it](https://github.com/paritytech/chainextension-registry) to ensure that there +/// are no collisions with other vendors. +/// +/// # Note +/// +/// Currently, we support tuples of up to ten registered chain extensions. If more chain extensions +/// are needed consider opening an issue. +pub trait RegisteredChainExtension: ChainExtension { + /// The extensions globally unique identifier. + const ID: u16; +} + +#[impl_trait_for_tuples::impl_for_tuples(10)] +#[tuple_types_custom_trait_bound(RegisteredChainExtension)] +impl ChainExtension for Tuple { + fn call>(&mut self, mut env: Environment) -> Result { + for_tuples!( + #( + if (Tuple::ID == env.ext_id()) && Tuple::enabled() { + return Tuple.call(env); + } + )* + ); + Err(Error::::NoChainExtension.into()) + } + + fn enabled() -> bool { + for_tuples!( + #( + if Tuple::enabled() { + return true; + } + )* + ); + false + } +} + +/// Determines the exit behaviour and return value of a chain extension. +pub enum RetVal { + /// The chain extensions returns the supplied value to its calling contract. + Converging(u32), + /// The control does **not** return to the calling contract. + /// + /// Use this to stop the execution of the contract when the chain extension returns. + /// The semantic is the same as for calling `seal_return`: The control returns to + /// the caller of the currently executing contract yielding the supplied buffer and + /// flags. + Diverging { flags: ReturnFlags, data: Vec }, +} + +/// Grants the chain extension access to its parameters and execution environment. +/// +/// It uses [typestate programming](https://docs.rust-embedded.org/book/static-guarantees/typestate-programming.html) +/// to enforce the correct usage of the parameters passed to the chain extension. +pub struct Environment<'a, 'b, E: Ext, S: State> { + /// The actual data of this type. + inner: Inner<'a, 'b, E>, + /// `S` is only used in the type system but never as value. + phantom: PhantomData, +} + +/// Functions that are available in every state of this type. +impl<'a, 'b, E: Ext, S: State> Environment<'a, 'b, E, S> { + /// The function id within the `id` passed by a contract. + /// + /// It returns the two least significant bytes of the `id` passed by a contract as the other + /// two bytes represent the chain extension itself (the code which is calling this function). + pub fn func_id(&self) -> u16 { + (self.inner.id & 0x0000FFFF) as u16 + } + + /// The chain extension id within the `id` passed by a contract. + /// + /// It returns the two most significant bytes of the `id` passed by a contract which represent + /// the chain extension itself (the code which is calling this function). + pub fn ext_id(&self) -> u16 { + (self.inner.id >> 16) as u16 + } + + /// Charge the passed `amount` of weight from the overall limit. + /// + /// It returns `Ok` when there the remaining weight budget is larger than the passed + /// `weight`. It returns `Err` otherwise. In this case the chain extension should + /// abort the execution and pass through the error. + /// + /// The returned value can be used to with [`Self::adjust_weight`]. Other than that + /// it has no purpose. + /// + /// # Note + /// + /// Weight is synonymous with gas in substrate. + pub fn charge_weight(&mut self, amount: Weight) -> Result { + self.inner.runtime.charge_gas(RuntimeCosts::ChainExtension(amount)) + } + + /// Adjust a previously charged amount down to its actual amount. + /// + /// This is when a maximum a priori amount was charged and then should be partially + /// refunded to match the actual amount. + pub fn adjust_weight(&mut self, charged: ChargedAmount, actual_weight: Weight) { + self.inner + .runtime + .adjust_gas(charged, RuntimeCosts::ChainExtension(actual_weight)) + } + + /// Grants access to the execution environment of the current contract call. + /// + /// Consult the functions on the returned type before re-implementing those functions. + pub fn ext(&mut self) -> &mut E { + self.inner.runtime.ext() + } +} + +/// Functions that are only available in the initial state of this type. +/// +/// Those are the functions that determine how the arguments to the chain extensions +/// should be consumed. +impl<'a, 'b, E: Ext> Environment<'a, 'b, E, InitState> { + /// Creates a new environment for consumption by a chain extension. + /// + /// It is only available to this crate because only the wasm runtime module needs to + /// ever create this type. Chain extensions merely consume it. + pub(crate) fn new( + runtime: &'a mut Runtime<'b, E>, + memory: &'a mut [u8], + id: u32, + input_ptr: u32, + input_len: u32, + output_ptr: u32, + output_len_ptr: u32, + ) -> Self { + Environment { + inner: Inner { runtime, memory, id, input_ptr, input_len, output_ptr, output_len_ptr }, + phantom: PhantomData, + } + } + + /// Use all arguments as integer values. + pub fn only_in(self) -> Environment<'a, 'b, E, OnlyInState> { + Environment { inner: self.inner, phantom: PhantomData } + } + + /// Use input arguments as integer and output arguments as pointer to a buffer. + pub fn prim_in_buf_out(self) -> Environment<'a, 'b, E, PrimInBufOutState> { + Environment { inner: self.inner, phantom: PhantomData } + } + + /// Use input and output arguments as pointers to a buffer. + pub fn buf_in_buf_out(self) -> Environment<'a, 'b, E, BufInBufOutState> { + Environment { inner: self.inner, phantom: PhantomData } + } +} + +/// Functions to use the input arguments as integers. +impl<'a, 'b, E: Ext, S: PrimIn> Environment<'a, 'b, E, S> { + /// The `input_ptr` argument. + pub fn val0(&self) -> u32 { + self.inner.input_ptr + } + + /// The `input_len` argument. + pub fn val1(&self) -> u32 { + self.inner.input_len + } +} + +/// Functions to use the output arguments as integers. +impl<'a, 'b, E: Ext, S: PrimOut> Environment<'a, 'b, E, S> { + /// The `output_ptr` argument. + pub fn val2(&self) -> u32 { + self.inner.output_ptr + } + + /// The `output_len_ptr` argument. + pub fn val3(&self) -> u32 { + self.inner.output_len_ptr + } +} + +/// Functions to use the input arguments as pointer to a buffer. +impl<'a, 'b, E: Ext, S: BufIn> Environment<'a, 'b, E, S> { + /// Reads `min(max_len, in_len)` from contract memory. + /// + /// This does **not** charge any weight. The caller must make sure that the an + /// appropriate amount of weight is charged **before** reading from contract memory. + /// The reason for that is that usually the costs for reading data and processing + /// said data cannot be separated in a benchmark. Therefore a chain extension would + /// charge the overall costs either using `max_len` (worst case approximation) or using + /// [`in_len()`](Self::in_len). + pub fn read(&self, max_len: u32) -> Result> { + self.inner.runtime.read_sandbox_memory( + self.inner.memory, + self.inner.input_ptr, + self.inner.input_len.min(max_len), + ) + } + + /// Reads `min(buffer.len(), in_len) from contract memory. + /// + /// This takes a mutable pointer to a buffer fills it with data and shrinks it to + /// the size of the actual data. Apart from supporting pre-allocated buffers it is + /// equivalent to to [`read()`](Self::read). + pub fn read_into(&self, buffer: &mut &mut [u8]) -> Result<()> { + let len = buffer.len(); + let sliced = { + let buffer = core::mem::take(buffer); + &mut buffer[..len.min(self.inner.input_len as usize)] + }; + self.inner.runtime.read_sandbox_memory_into_buf( + self.inner.memory, + self.inner.input_ptr, + sliced, + )?; + *buffer = sliced; + Ok(()) + } + + /// Reads and decodes a type with a size fixed at compile time from contract memory. + /// + /// This function is secure and recommended for all input types of fixed size + /// as long as the cost of reading the memory is included in the overall already charged + /// weight of the chain extension. This should usually be the case when fixed input types + /// are used. + pub fn read_as(&mut self) -> Result { + self.inner + .runtime + .read_sandbox_memory_as(self.inner.memory, self.inner.input_ptr) + } + + /// Reads and decodes a type with a dynamic size from contract memory. + /// + /// Make sure to include `len` in your weight calculations. + pub fn read_as_unbounded(&mut self, len: u32) -> Result { + self.inner.runtime.read_sandbox_memory_as_unbounded( + self.inner.memory, + self.inner.input_ptr, + len, + ) + } + + /// The length of the input as passed in as `input_len`. + /// + /// A chain extension would use this value to calculate the dynamic part of its + /// weight. For example a chain extension that calculates the hash of some passed in + /// bytes would use `in_len` to charge the costs of hashing that amount of bytes. + /// This also subsumes the act of copying those bytes as a benchmarks measures both. + pub fn in_len(&self) -> u32 { + self.inner.input_len + } +} + +/// Functions to use the output arguments as pointer to a buffer. +impl<'a, 'b, E: Ext, S: BufOut> Environment<'a, 'b, E, S> { + /// Write the supplied buffer to contract memory. + /// + /// If the contract supplied buffer is smaller than the passed `buffer` an `Err` is returned. + /// If `allow_skip` is set to true the contract is allowed to skip the copying of the buffer + /// by supplying the guard value of `pallet-contracts::SENTINEL` as `out_ptr`. The + /// `weight_per_byte` is only charged when the write actually happens and is not skipped or + /// failed due to a too small output buffer. + pub fn write( + &mut self, + buffer: &[u8], + allow_skip: bool, + weight_per_byte: Option, + ) -> Result<()> { + self.inner.runtime.write_sandbox_output( + self.inner.memory, + self.inner.output_ptr, + self.inner.output_len_ptr, + buffer, + allow_skip, + |len| { + weight_per_byte.map(|w| RuntimeCosts::ChainExtension(w.saturating_mul(len.into()))) + }, + ) + } +} + +/// The actual data of an `Environment`. +/// +/// All data is put into this struct to easily pass it around as part of the typestate +/// pattern. Also it creates the opportunity to box this struct in the future in case it +/// gets too large. +struct Inner<'a, 'b, E: Ext> { + /// The runtime contains all necessary functions to interact with the running contract. + runtime: &'a mut Runtime<'b, E>, + /// Reference to the contracts memory. + memory: &'a mut [u8], + /// Verbatim argument passed to `seal_call_chain_extension`. + id: u32, + /// Verbatim argument passed to `seal_call_chain_extension`. + input_ptr: u32, + /// Verbatim argument passed to `seal_call_chain_extension`. + input_len: u32, + /// Verbatim argument passed to `seal_call_chain_extension`. + output_ptr: u32, + /// Verbatim argument passed to `seal_call_chain_extension`. + output_len_ptr: u32, +} + +/// Any state of an [`Environment`] implements this trait. +/// See [typestate programming](https://docs.rust-embedded.org/book/static-guarantees/typestate-programming.html). +pub trait State: sealed::Sealed {} + +/// A state that uses primitive inputs. +pub trait PrimIn: State {} + +/// A state that uses primitive outputs. +pub trait PrimOut: State {} + +/// A state that uses a buffer as input. +pub trait BufIn: State {} + +/// A state that uses a buffer as output. +pub trait BufOut: State {} + +/// The initial state of an [`Environment`]. +pub enum InitState {} + +/// A state that uses all arguments as primitive inputs. +pub enum OnlyInState {} + +/// A state that uses two arguments as primitive inputs and the other two as buffer output. +pub enum PrimInBufOutState {} + +/// Uses a buffer for input and a buffer for output. +pub enum BufInBufOutState {} + +mod sealed { + use super::*; + + /// Trait to prevent users from implementing `State` for anything else. + pub trait Sealed {} + + impl Sealed for InitState {} + impl Sealed for OnlyInState {} + impl Sealed for PrimInBufOutState {} + impl Sealed for BufInBufOutState {} + + impl State for InitState {} + impl State for OnlyInState {} + impl State for PrimInBufOutState {} + impl State for BufInBufOutState {} + + impl PrimIn for OnlyInState {} + impl PrimOut for OnlyInState {} + impl PrimIn for PrimInBufOutState {} + impl BufOut for PrimInBufOutState {} + impl BufIn for BufInBufOutState {} + impl BufOut for BufInBufOutState {} +} diff --git a/pallets/contracts/src/debug.rs b/pallets/contracts/src/debug.rs new file mode 100644 index 00000000..6cdca7aa --- /dev/null +++ b/pallets/contracts/src/debug.rs @@ -0,0 +1,112 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub use crate::{ + exec::{ExecResult, ExportedFunction}, + primitives::ExecReturnValue, +}; +use crate::{Config, LOG_TARGET}; + +/// Umbrella trait for all interfaces that serves for debugging. +pub trait Debugger: Tracing + CallInterceptor {} + +impl Debugger for V where V: Tracing + CallInterceptor {} + +/// Defines methods to capture contract calls, enabling external observers to +/// measure, trace, and react to contract interactions. +pub trait Tracing { + /// The type of [`CallSpan`] that is created by this trait. + type CallSpan: CallSpan; + + /// Creates a new call span to encompass the upcoming contract execution. + /// + /// This method should be invoked just before the execution of a contract and + /// marks the beginning of a traceable span of execution. + /// + /// # Arguments + /// + /// * `contract_address` - The address of the contract that is about to be executed. + /// * `entry_point` - Describes whether the call is the constructor or a regular call. + /// * `input_data` - The raw input data of the call. + fn new_call_span( + contract_address: &T::AccountId, + entry_point: ExportedFunction, + input_data: &[u8], + ) -> Self::CallSpan; +} + +/// Defines a span of execution for a contract call. +pub trait CallSpan { + /// Called just after the execution of a contract. + /// + /// # Arguments + /// + /// * `output` - The raw output of the call. + fn after_call(self, output: &ExecReturnValue); +} + +impl Tracing for () { + type CallSpan = (); + + fn new_call_span( + contract_address: &T::AccountId, + entry_point: ExportedFunction, + input_data: &[u8], + ) { + log::trace!(target: LOG_TARGET, "call {entry_point:?} account: {contract_address:?}, input_data: {input_data:?}") + } +} + +impl CallSpan for () { + fn after_call(self, output: &ExecReturnValue) { + log::trace!(target: LOG_TARGET, "call result {output:?}") + } +} + +/// Provides an interface for intercepting contract calls. +pub trait CallInterceptor { + /// Allows to intercept contract calls and decide whether they should be executed or not. + /// If the call is intercepted, the mocked result of the call is returned. + /// + /// # Arguments + /// + /// * `contract_address` - The address of the contract that is about to be executed. + /// * `entry_point` - Describes whether the call is the constructor or a regular call. + /// * `input_data` - The raw input data of the call. + /// + /// # Expected behavior + /// + /// This method should return: + /// * `Some(ExecResult)` - if the call should be intercepted and the mocked result of the call + /// is returned. + /// * `None` - otherwise, i.e. the call should be executed normally. + fn intercept_call( + contract_address: &T::AccountId, + entry_point: &ExportedFunction, + input_data: &[u8], + ) -> Option; +} + +impl CallInterceptor for () { + fn intercept_call( + _contract_address: &T::AccountId, + _entry_point: &ExportedFunction, + _input_data: &[u8], + ) -> Option { + None + } +} diff --git a/pallets/contracts/src/exec.rs b/pallets/contracts/src/exec.rs new file mode 100644 index 00000000..31e0bf50 --- /dev/null +++ b/pallets/contracts/src/exec.rs @@ -0,0 +1,4284 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::{ + debug::{CallInterceptor, CallSpan, Tracing}, + gas::GasMeter, + primitives::{ExecReturnValue, StorageDeposit}, + storage::{self, meter::Diff, WriteOutcome}, + transient_storage::TransientStorage, + BalanceOf, CodeHash, CodeInfo, CodeInfoOf, Config, ContractInfo, ContractInfoOf, + DebugBufferVec, Determinism, Error, Event, Nonce, Origin, Pallet as Contracts, Schedule, + LOG_TARGET, +}; +use alloc::vec::Vec; +use core::{fmt::Debug, marker::PhantomData, mem}; +use frame_support::{ + crypto::ecdsa::ECDSAExt, + dispatch::{DispatchResult, DispatchResultWithPostInfo}, + ensure, + storage::{with_transaction, TransactionOutcome}, + traits::{ + fungible::{Inspect, Mutate}, + tokens::{Fortitude, Preservation}, + Contains, OriginTrait, Randomness, Time, + }, + weights::Weight, + Blake2_128Concat, BoundedVec, StorageHasher, +}; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; +use smallvec::{Array, SmallVec}; +use sp_core::{ + ecdsa::Public as ECDSAPublic, + sr25519::{Public as SR25519Public, Signature as SR25519Signature}, + Get, +}; +use sp_io::{crypto::secp256k1_ecdsa_recover_compressed, hashing::blake2_256}; +use sp_runtime::{ + traits::{Convert, Dispatchable, Zero}, + DispatchError, +}; + +pub type AccountIdOf = ::AccountId; +pub type MomentOf = <::Time as Time>::Moment; +pub type SeedOf = ::Hash; +pub type ExecResult = Result; + +/// A type that represents a topic of an event. At the moment a hash is used. +pub type TopicOf = ::Hash; + +/// Type for variable sized storage key. Used for transparent hashing. +type VarSizedKey = BoundedVec::MaxStorageKeyLen>; + +/// Combined key type for both fixed and variable sized storage keys. +pub enum Key { + /// Variant for fixed sized keys. + Fix([u8; 32]), + /// Variant for variable sized keys. + Var(VarSizedKey), +} + +impl Key { + /// Copies self into a new vec. + pub fn to_vec(&self) -> Vec { + match self { + Key::Fix(v) => v.to_vec(), + Key::Var(v) => v.to_vec(), + } + } + + pub fn hash(&self) -> Vec { + match self { + Key::Fix(v) => blake2_256(v.as_slice()).to_vec(), + Key::Var(v) => Blake2_128Concat::hash(v.as_slice()), + } + } + + pub fn try_from_fix(v: Vec) -> Result> { + <[u8; 32]>::try_from(v).map(Self::Fix) + } + + pub fn try_from_var(v: Vec) -> Result> { + VarSizedKey::::try_from(v).map(Self::Var) + } +} + +/// Origin of the error. +/// +/// Call or instantiate both called into other contracts and pass through errors happening +/// in those to the caller. This enum is for the caller to distinguish whether the error +/// happened during the execution of the callee or in the current execution context. +#[derive(Copy, Clone, PartialEq, Eq, Debug, codec::Decode, codec::Encode)] +pub enum ErrorOrigin { + /// Caller error origin. + /// + /// The error happened in the current execution context rather than in the one + /// of the contract that is called into. + Caller, + /// The error happened during execution of the called contract. + Callee, +} + +/// Error returned by contract execution. +#[derive(Copy, Clone, PartialEq, Eq, Debug, codec::Decode, codec::Encode)] +pub struct ExecError { + /// The reason why the execution failed. + pub error: DispatchError, + /// Origin of the error. + pub origin: ErrorOrigin, +} + +impl> From for ExecError { + fn from(error: T) -> Self { + Self { error: error.into(), origin: ErrorOrigin::Caller } + } +} + +/// An interface that provides access to the external environment in which the +/// smart-contract is executed. +/// +/// This interface is specialized to an account of the executing code, so all +/// operations are implicitly performed on that account. +/// +/// # Note +/// +/// This trait is sealed and cannot be implemented by downstream crates. +pub trait Ext: sealing::Sealed { + type T: Config; + + /// Call (possibly transferring some amount of funds) into the specified account. + /// + /// Returns the code size of the called contract. + fn call( + &mut self, + gas_limit: Weight, + deposit_limit: BalanceOf, + to: AccountIdOf, + value: BalanceOf, + input_data: Vec, + allows_reentry: bool, + read_only: bool, + ) -> Result; + + /// Execute code in the current frame. + /// + /// Returns the code size of the called contract. + fn delegate_call( + &mut self, + code: CodeHash, + input_data: Vec, + ) -> Result; + + /// Instantiate a contract from the given code. + /// + /// Returns the original code size of the called contract. + /// The newly created account will be associated with `code`. `value` specifies the amount of + /// value transferred from the caller to the newly created account. + fn instantiate( + &mut self, + gas_limit: Weight, + deposit_limit: BalanceOf, + code: CodeHash, + value: BalanceOf, + input_data: Vec, + salt: &[u8], + ) -> Result<(AccountIdOf, ExecReturnValue), ExecError>; + + /// Transfer all funds to `beneficiary` and delete the contract. + /// + /// Since this function removes the self contract eagerly, if succeeded, no further actions + /// should be performed on this `Ext` instance. + /// + /// This function will fail if the same contract is present on the contract + /// call stack. + fn terminate(&mut self, beneficiary: &AccountIdOf) -> DispatchResult; + + /// Transfer some amount of funds into the specified account. + fn transfer(&mut self, to: &AccountIdOf, value: BalanceOf) -> DispatchResult; + + /// Returns the storage entry of the executing account by the given `key`. + /// + /// Returns `None` if the `key` wasn't previously set by `set_storage` or + /// was deleted. + fn get_storage(&mut self, key: &Key) -> Option>; + + /// Returns `Some(len)` (in bytes) if a storage item exists at `key`. + /// + /// Returns `None` if the `key` wasn't previously set by `set_storage` or + /// was deleted. + fn get_storage_size(&mut self, key: &Key) -> Option; + + /// Sets the storage entry by the given key to the specified value. If `value` is `None` then + /// the storage entry is deleted. + fn set_storage( + &mut self, + key: &Key, + value: Option>, + take_old: bool, + ) -> Result; + + /// Returns the transient storage entry of the executing account for the given `key`. + /// + /// Returns `None` if the `key` wasn't previously set by `set_transient_storage` or + /// was deleted. + fn get_transient_storage(&self, key: &Key) -> Option>; + + /// Returns `Some(len)` (in bytes) if a transient storage item exists at `key`. + /// + /// Returns `None` if the `key` wasn't previously set by `set_transient_storage` or + /// was deleted. + fn get_transient_storage_size(&self, key: &Key) -> Option; + + /// Sets the transient storage entry for the given key to the specified value. If `value` is + /// `None` then the storage entry is deleted. + fn set_transient_storage( + &mut self, + key: &Key, + value: Option>, + take_old: bool, + ) -> Result; + + /// Returns the caller. + fn caller(&self) -> Origin; + + /// Check if a contract lives at the specified `address`. + fn is_contract(&self, address: &AccountIdOf) -> bool; + + /// Returns the code hash of the contract for the given `address`. + /// + /// Returns `None` if the `address` does not belong to a contract. + fn code_hash(&self, address: &AccountIdOf) -> Option>; + + /// Returns the code hash of the contract being executed. + fn own_code_hash(&mut self) -> &CodeHash; + + /// Check if the caller of the current contract is the origin of the whole call stack. + /// + /// This can be checked with `is_contract(self.caller())` as well. + /// However, this function does not require any storage lookup and therefore uses less weight. + fn caller_is_origin(&self) -> bool; + + /// Check if the caller is origin, and this origin is root. + fn caller_is_root(&self) -> bool; + + /// Returns a reference to the account id of the current contract. + fn address(&self) -> &AccountIdOf; + + /// Returns the balance of the current contract. + /// + /// The `value_transferred` is already added. + fn balance(&self) -> BalanceOf; + + /// Returns the value transferred along with this call. + fn value_transferred(&self) -> BalanceOf; + + /// Returns a reference to the timestamp of the current block + fn now(&self) -> &MomentOf; + + /// Returns the minimum balance that is required for creating an account. + fn minimum_balance(&self) -> BalanceOf; + + /// Returns a random number for the current block with the given subject. + fn random(&self, subject: &[u8]) -> (SeedOf, BlockNumberFor); + + /// Deposit an event with the given topics. + /// + /// There should not be any duplicates in `topics`. + fn deposit_event(&mut self, topics: Vec>, data: Vec); + + /// Returns the current block number. + fn block_number(&self) -> BlockNumberFor; + + /// Returns the maximum allowed size of a storage item. + fn max_value_size(&self) -> u32; + + /// Returns the price for the specified amount of weight. + fn get_weight_price(&self, weight: Weight) -> BalanceOf; + + /// Get a reference to the schedule used by the current call. + fn schedule(&self) -> &Schedule; + + /// Get an immutable reference to the nested gas meter. + fn gas_meter(&self) -> &GasMeter; + + /// Get a mutable reference to the nested gas meter. + fn gas_meter_mut(&mut self) -> &mut GasMeter; + + /// Charges `diff` from the meter. + fn charge_storage(&mut self, diff: &Diff); + + /// Append a string to the debug buffer. + /// + /// It is added as-is without any additional new line. + /// + /// This is a no-op if debug message recording is disabled which is always the case + /// when the code is executing on-chain. + /// + /// Returns `true` if debug message recording is enabled. Otherwise `false` is returned. + fn append_debug_buffer(&mut self, msg: &str) -> bool; + + /// Returns `true` if debug message recording is enabled. Otherwise `false` is returned. + fn debug_buffer_enabled(&self) -> bool; + + /// Call some dispatchable and return the result. + fn call_runtime(&self, call: ::RuntimeCall) -> DispatchResultWithPostInfo; + + /// Recovers ECDSA compressed public key based on signature and message hash. + fn ecdsa_recover(&self, signature: &[u8; 65], message_hash: &[u8; 32]) -> Result<[u8; 33], ()>; + + /// Verify a sr25519 signature. + fn sr25519_verify(&self, signature: &[u8; 64], message: &[u8], pub_key: &[u8; 32]) -> bool; + + /// Returns Ethereum address from the ECDSA compressed public key. + fn ecdsa_to_eth_address(&self, pk: &[u8; 33]) -> Result<[u8; 20], ()>; + + /// Tests sometimes need to modify and inspect the contract info directly. + #[cfg(any(test, feature = "runtime-benchmarks"))] + fn contract_info(&mut self) -> &mut ContractInfo; + + /// Get a mutable reference to the transient storage. + /// Useful in benchmarks when it is sometimes necessary to modify and inspect the transient + /// storage directly. + #[cfg(feature = "runtime-benchmarks")] + fn transient_storage(&mut self) -> &mut TransientStorage; + + /// Sets new code hash for existing contract. + fn set_code_hash(&mut self, hash: CodeHash) -> DispatchResult; + + /// Returns the number of times the currently executing contract exists on the call stack in + /// addition to the calling instance. A value of 0 means no reentrancy. + fn reentrance_count(&self) -> u32; + + /// Returns the number of times the specified contract exists on the call stack. Delegated calls + /// are not calculated as separate entrance. + /// A value of 0 means it does not exist on the call stack. + fn account_reentrance_count(&self, account_id: &AccountIdOf) -> u32; + + /// Returns a nonce that is incremented for every instantiated contract. + fn nonce(&mut self) -> u64; + + /// Increment the reference count of a of a stored code by one. + /// + /// # Errors + /// + /// [`Error::CodeNotFound`] is returned if no stored code found having the specified + /// `code_hash`. + fn increment_refcount(code_hash: CodeHash) -> DispatchResult; + + /// Decrement the reference count of a stored code by one. + /// + /// # Note + /// + /// A contract whose reference count dropped to zero isn't automatically removed. A + /// `remove_code` transaction must be submitted by the original uploader to do so. + fn decrement_refcount(code_hash: CodeHash); + + /// Adds a delegate dependency to [`ContractInfo`]'s `delegate_dependencies` field. + /// + /// This ensures that the delegated contract is not removed while it is still in use. It + /// increases the reference count of the code hash and charges a fraction (see + /// [`Config::CodeHashLockupDepositPercent`]) of the code deposit. + /// + /// # Errors + /// + /// - [`Error::MaxDelegateDependenciesReached`] + /// - [`Error::CannotAddSelfAsDelegateDependency`] + /// - [`Error::DelegateDependencyAlreadyExists`] + fn lock_delegate_dependency(&mut self, code_hash: CodeHash) -> DispatchResult; + + /// Removes a delegate dependency from [`ContractInfo`]'s `delegate_dependencies` field. + /// + /// This is the counterpart of [`Self::lock_delegate_dependency`]. It decreases the reference + /// count and refunds the deposit that was charged by [`Self::lock_delegate_dependency`]. + /// + /// # Errors + /// + /// - [`Error::DelegateDependencyNotFound`] + fn unlock_delegate_dependency(&mut self, code_hash: &CodeHash) -> DispatchResult; + + /// Returns the number of locked delegate dependencies. + /// + /// Note: Requires &mut self to access the contract info. + fn locked_delegate_dependencies_count(&mut self) -> usize; + + /// Check if running in read-only context. + fn is_read_only(&self) -> bool; +} + +/// Describes the different functions that can be exported by an [`Executable`]. +#[derive( + Copy, + Clone, + PartialEq, + Eq, + sp_core::RuntimeDebug, + codec::Decode, + codec::Encode, + codec::MaxEncodedLen, + scale_info::TypeInfo, +)] +pub enum ExportedFunction { + /// The constructor function which is executed on deployment of a contract. + Constructor, + /// The function which is executed when a contract is called. + Call, +} + +/// A trait that represents something that can be executed. +/// +/// In the on-chain environment this would be represented by a wasm module. This trait exists in +/// order to be able to mock the wasm logic for testing. +pub trait Executable: Sized { + /// Load the executable from storage. + /// + /// # Note + /// Charges size base load weight from the gas meter. + fn from_storage( + code_hash: CodeHash, + gas_meter: &mut GasMeter, + ) -> Result; + + /// Execute the specified exported function and return the result. + /// + /// When the specified function is `Constructor` the executable is stored and its + /// refcount incremented. + /// + /// # Note + /// + /// This functions expects to be executed in a storage transaction that rolls back + /// all of its emitted storage changes. + fn execute>( + self, + ext: &mut E, + function: &ExportedFunction, + input_data: Vec, + ) -> ExecResult; + + /// The code info of the executable. + fn code_info(&self) -> &CodeInfo; + + /// The code hash of the executable. + fn code_hash(&self) -> &CodeHash; + + /// Size of the contract code in bytes. + fn code_len(&self) -> u32; + + /// The code does not contain any instructions which could lead to indeterminism. + fn is_deterministic(&self) -> bool; +} + +/// The complete call stack of a contract execution. +/// +/// The call stack is initiated by either a signed origin or one of the contract RPC calls. +/// This type implements `Ext` and by that exposes the business logic of contract execution to +/// the runtime module which interfaces with the contract (the wasm blob) itself. +pub struct Stack<'a, T: Config, E> { + /// The origin that initiated the call stack. It could either be a Signed plain account that + /// holds an account id or Root. + /// + /// # Note + /// + /// Please note that it is possible that the id of a Signed origin belongs to a contract rather + /// than a plain account when being called through one of the contract RPCs where the + /// client can freely choose the origin. This usually makes no sense but is still possible. + origin: Origin, + /// The cost schedule used when charging from the gas meter. + schedule: &'a Schedule, + /// The gas meter where costs are charged to. + gas_meter: &'a mut GasMeter, + /// The storage meter makes sure that the storage deposit limit is obeyed. + storage_meter: &'a mut storage::meter::Meter, + /// The timestamp at the point of call stack instantiation. + timestamp: MomentOf, + /// The block number at the time of call stack instantiation. + block_number: BlockNumberFor, + /// The nonce is cached here when accessed. It is written back when the call stack + /// finishes executing. Please refer to [`Nonce`] to a description of + /// the nonce itself. + nonce: Option, + /// The actual call stack. One entry per nested contract called/instantiated. + /// This does **not** include the [`Self::first_frame`]. + frames: SmallVec, + /// Statically guarantee that each call stack has at least one frame. + first_frame: Frame, + /// A text buffer used to output human readable information. + /// + /// All the bytes added to this field should be valid UTF-8. The buffer has no defined + /// structure and is intended to be shown to users as-is for debugging purposes. + debug_message: Option<&'a mut DebugBufferVec>, + /// The determinism requirement of this call stack. + determinism: Determinism, + /// Transient storage used to store data, which is kept for the duration of a transaction. + transient_storage: TransientStorage, + /// No executable is held by the struct but influences its behaviour. + _phantom: PhantomData, +} + +/// Represents one entry in the call stack. +/// +/// For each nested contract call or instantiate one frame is created. It holds specific +/// information for the said call and caches the in-storage `ContractInfo` data structure. +/// +/// # Note +/// +/// This is an internal data structure. It is exposed to the public for the sole reason +/// of specifying [`Config::CallStack`]. +pub struct Frame { + /// The account id of the executing contract. + account_id: T::AccountId, + /// The cached in-storage data of the contract. + contract_info: CachedContract, + /// The amount of balance transferred by the caller as part of the call. + value_transferred: BalanceOf, + /// Determines whether this is a call or instantiate frame. + entry_point: ExportedFunction, + /// The gas meter capped to the supplied gas limit. + nested_gas: GasMeter, + /// The storage meter for the individual call. + nested_storage: storage::meter::NestedMeter, + /// If `false` the contract enabled its defense against reentrance attacks. + allows_reentry: bool, + /// If `true` subsequent calls cannot modify storage. + read_only: bool, + /// The caller of the currently executing frame which was spawned by `delegate_call`. + delegate_caller: Option>, +} + +/// Used in a delegate call frame arguments in order to override the executable and caller. +struct DelegatedCall { + /// The executable which is run instead of the contracts own `executable`. + executable: E, + /// The caller of the contract. + caller: Origin, +} + +/// Parameter passed in when creating a new `Frame`. +/// +/// It determines whether the new frame is for a call or an instantiate. +enum FrameArgs<'a, T: Config, E> { + Call { + /// The account id of the contract that is to be called. + dest: T::AccountId, + /// If `None` the contract info needs to be reloaded from storage. + cached_info: Option>, + /// This frame was created by `seal_delegate_call` and hence uses different code than + /// what is stored at [`Self::Call::dest`]. Its caller ([`DelegatedCall::caller`]) is the + /// account which called the caller contract + delegated_call: Option>, + }, + Instantiate { + /// The contract or signed origin which instantiates the new contract. + sender: T::AccountId, + /// The nonce that should be used to derive a new trie id for the contract. + nonce: u64, + /// The executable whose `deploy` function is run. + executable: E, + /// A salt used in the contract address derivation of the new contract. + salt: &'a [u8], + /// The input data is used in the contract address derivation of the new contract. + input_data: &'a [u8], + }, +} + +/// Describes the different states of a contract as contained in a `Frame`. +enum CachedContract { + /// The cached contract is up to date with the in-storage value. + Cached(ContractInfo), + /// A recursive call into the same contract did write to the contract info. + /// + /// In this case the cached contract is stale and needs to be reloaded from storage. + Invalidated, + /// The current contract executed `terminate` and removed the contract. + /// + /// In this case a reload is neither allowed nor possible. Please note that recursive + /// calls cannot remove a contract as this is checked and denied. + Terminated, +} + +impl CachedContract { + /// Return `Some(ContractInfo)` if the contract is in cached state. `None` otherwise. + fn into_contract(self) -> Option> { + if let CachedContract::Cached(contract) = self { + Some(contract) + } else { + None + } + } + + /// Return `Some(&mut ContractInfo)` if the contract is in cached state. `None` otherwise. + fn as_contract(&mut self) -> Option<&mut ContractInfo> { + if let CachedContract::Cached(contract) = self { + Some(contract) + } else { + None + } + } +} + +impl Frame { + /// Return the `contract_info` of the current contract. + fn contract_info(&mut self) -> &mut ContractInfo { + self.contract_info.get(&self.account_id) + } + + /// Terminate and return the `contract_info` of the current contract. + /// + /// # Note + /// + /// Under no circumstances the contract is allowed to access the `contract_info` after + /// a call to this function. This would constitute a programming error in the exec module. + fn terminate(&mut self) -> ContractInfo { + self.contract_info.terminate(&self.account_id) + } +} + +/// Extract the contract info after loading it from storage. +/// +/// This assumes that `load` was executed before calling this macro. +macro_rules! get_cached_or_panic_after_load { + ($c:expr) => {{ + if let CachedContract::Cached(contract) = $c { + contract + } else { + panic!( + "It is impossible to remove a contract that is on the call stack;\ + See implementations of terminate;\ + Therefore fetching a contract will never fail while using an account id + that is currently active on the call stack;\ + qed" + ); + } + }}; +} + +/// Same as [`Stack::top_frame`]. +/// +/// We need this access as a macro because sometimes hiding the lifetimes behind +/// a function won't work out. +macro_rules! top_frame { + ($stack:expr) => { + $stack.frames.last().unwrap_or(&$stack.first_frame) + }; +} + +/// Same as [`Stack::top_frame_mut`]. +/// +/// We need this access as a macro because sometimes hiding the lifetimes behind +/// a function won't work out. +macro_rules! top_frame_mut { + ($stack:expr) => { + $stack.frames.last_mut().unwrap_or(&mut $stack.first_frame) + }; +} + +impl CachedContract { + /// Load the `contract_info` from storage if necessary. + fn load(&mut self, account_id: &T::AccountId) { + if let CachedContract::Invalidated = self { + let contract = >::get(&account_id); + if let Some(contract) = contract { + *self = CachedContract::Cached(contract); + } + } + } + + /// Return the cached contract_info. + fn get(&mut self, account_id: &T::AccountId) -> &mut ContractInfo { + self.load(account_id); + get_cached_or_panic_after_load!(self) + } + + /// Terminate and return the contract info. + fn terminate(&mut self, account_id: &T::AccountId) -> ContractInfo { + self.load(account_id); + get_cached_or_panic_after_load!(mem::replace(self, Self::Terminated)) + } +} + +impl<'a, T, E> Stack<'a, T, E> +where + T: Config, + E: Executable, +{ + /// Create and run a new call stack by calling into `dest`. + /// + /// # Note + /// + /// `debug_message` should only ever be set to `Some` when executing as an RPC because + /// it adds allocations and could be abused to drive the runtime into an OOM panic. + /// + /// # Return Value + /// + /// Result<(ExecReturnValue, CodeSize), (ExecError, CodeSize)> + pub fn run_call( + origin: Origin, + dest: T::AccountId, + gas_meter: &'a mut GasMeter, + storage_meter: &'a mut storage::meter::Meter, + schedule: &'a Schedule, + value: BalanceOf, + input_data: Vec, + debug_message: Option<&'a mut DebugBufferVec>, + determinism: Determinism, + ) -> Result { + let (mut stack, executable) = Self::new( + FrameArgs::Call { dest, cached_info: None, delegated_call: None }, + origin, + gas_meter, + storage_meter, + schedule, + value, + debug_message, + determinism, + )?; + stack.run(executable, input_data) + } + + /// Create and run a new call stack by instantiating a new contract. + /// + /// # Note + /// + /// `debug_message` should only ever be set to `Some` when executing as an RPC because + /// it adds allocations and could be abused to drive the runtime into an OOM panic. + /// + /// # Return Value + /// + /// Result<(NewContractAccountId, ExecReturnValue), ExecError)> + pub fn run_instantiate( + origin: T::AccountId, + executable: E, + gas_meter: &'a mut GasMeter, + storage_meter: &'a mut storage::meter::Meter, + schedule: &'a Schedule, + value: BalanceOf, + input_data: Vec, + salt: &[u8], + debug_message: Option<&'a mut DebugBufferVec>, + ) -> Result<(T::AccountId, ExecReturnValue), ExecError> { + let (mut stack, executable) = Self::new( + FrameArgs::Instantiate { + sender: origin.clone(), + nonce: >::get().wrapping_add(1), + executable, + salt, + input_data: input_data.as_ref(), + }, + Origin::from_account_id(origin), + gas_meter, + storage_meter, + schedule, + value, + debug_message, + Determinism::Enforced, + )?; + let account_id = stack.top_frame().account_id.clone(); + stack.run(executable, input_data).map(|ret| (account_id, ret)) + } + + #[cfg(feature = "runtime-benchmarks")] + pub fn bench_new_call( + dest: T::AccountId, + origin: Origin, + gas_meter: &'a mut GasMeter, + storage_meter: &'a mut storage::meter::Meter, + schedule: &'a Schedule, + value: BalanceOf, + debug_message: Option<&'a mut DebugBufferVec>, + determinism: Determinism, + ) -> (Self, E) { + Self::new( + FrameArgs::Call { dest, cached_info: None, delegated_call: None }, + origin, + gas_meter, + storage_meter, + schedule, + value, + debug_message, + determinism, + ) + .unwrap() + } + + /// Create a new call stack. + fn new( + args: FrameArgs, + origin: Origin, + gas_meter: &'a mut GasMeter, + storage_meter: &'a mut storage::meter::Meter, + schedule: &'a Schedule, + value: BalanceOf, + debug_message: Option<&'a mut DebugBufferVec>, + determinism: Determinism, + ) -> Result<(Self, E), ExecError> { + let (first_frame, executable, nonce) = Self::new_frame( + args, + value, + gas_meter, + Weight::zero(), + storage_meter, + BalanceOf::::zero(), + determinism, + false, + )?; + + let stack = Self { + origin, + schedule, + gas_meter, + storage_meter, + timestamp: T::Time::now(), + block_number: >::block_number(), + nonce, + first_frame, + frames: Default::default(), + debug_message, + determinism, + transient_storage: TransientStorage::new(T::MaxTransientStorageSize::get()), + _phantom: Default::default(), + }; + + Ok((stack, executable)) + } + + /// Construct a new frame. + /// + /// This does not take `self` because when constructing the first frame `self` is + /// not initialized, yet. + fn new_frame( + frame_args: FrameArgs, + value_transferred: BalanceOf, + gas_meter: &mut GasMeter, + gas_limit: Weight, + storage_meter: &mut storage::meter::GenericMeter, + deposit_limit: BalanceOf, + determinism: Determinism, + read_only: bool, + ) -> Result<(Frame, E, Option), ExecError> { + let (account_id, contract_info, executable, delegate_caller, entry_point, nonce) = + match frame_args { + FrameArgs::Call { dest, cached_info, delegated_call } => { + let contract = if let Some(contract) = cached_info { + contract + } else { + >::get(&dest).ok_or(>::ContractNotFound)? + }; + + let (executable, delegate_caller) = + if let Some(DelegatedCall { executable, caller }) = delegated_call { + (executable, Some(caller)) + } else { + (E::from_storage(contract.code_hash, gas_meter)?, None) + }; + + (dest, contract, executable, delegate_caller, ExportedFunction::Call, None) + }, + FrameArgs::Instantiate { sender, nonce, executable, salt, input_data } => { + let account_id = Contracts::::contract_address( + &sender, + &executable.code_hash(), + input_data, + salt, + ); + let contract = ContractInfo::new(&account_id, nonce, *executable.code_hash())?; + ( + account_id, + contract, + executable, + None, + ExportedFunction::Constructor, + Some(nonce), + ) + }, + }; + + // `Relaxed` will only be ever set in case of off-chain execution. + // Instantiations are never allowed even when executing off-chain. + if !(executable.is_deterministic() || + (matches!(determinism, Determinism::Relaxed) && + matches!(entry_point, ExportedFunction::Call))) + { + return Err(Error::::Indeterministic.into()) + } + + let frame = Frame { + delegate_caller, + value_transferred, + contract_info: CachedContract::Cached(contract_info), + account_id, + entry_point, + nested_gas: gas_meter.nested(gas_limit), + nested_storage: storage_meter.nested(deposit_limit), + allows_reentry: true, + read_only, + }; + + Ok((frame, executable, nonce)) + } + + /// Create a subsequent nested frame. + fn push_frame( + &mut self, + frame_args: FrameArgs, + value_transferred: BalanceOf, + gas_limit: Weight, + deposit_limit: BalanceOf, + read_only: bool, + ) -> Result { + if self.frames.len() == T::CallStack::size() { + return Err(Error::::MaxCallDepthReached.into()) + } + + // We need to make sure that changes made to the contract info are not discarded. + // See the `in_memory_changes_not_discarded` test for more information. + // We do not store on instantiate because we do not allow to call into a contract + // from its own constructor. + let frame = self.top_frame(); + if let (CachedContract::Cached(contract), ExportedFunction::Call) = + (&frame.contract_info, frame.entry_point) + { + >::insert(frame.account_id.clone(), contract.clone()); + } + + let frame = top_frame_mut!(self); + let nested_gas = &mut frame.nested_gas; + let nested_storage = &mut frame.nested_storage; + let (frame, executable, _) = Self::new_frame( + frame_args, + value_transferred, + nested_gas, + gas_limit, + nested_storage, + deposit_limit, + self.determinism, + read_only, + )?; + self.frames.push(frame); + Ok(executable) + } + + /// Run the current (top) frame. + /// + /// This can be either a call or an instantiate. + fn run(&mut self, executable: E, input_data: Vec) -> Result { + let frame = self.top_frame(); + let entry_point = frame.entry_point; + let delegated_code_hash = + if frame.delegate_caller.is_some() { Some(*executable.code_hash()) } else { None }; + + self.transient_storage.start_transaction(); + + let do_transaction = || { + // We need to charge the storage deposit before the initial transfer so that + // it can create the account in case the initial transfer is < ed. + if entry_point == ExportedFunction::Constructor { + // Root origin can't be used to instantiate a contract, so it is safe to assume that + // if we reached this point the origin has an associated account. + let origin = &self.origin.account_id()?; + let frame = top_frame_mut!(self); + frame.nested_storage.charge_instantiate( + origin, + &frame.account_id, + frame.contract_info.get(&frame.account_id), + executable.code_info(), + )?; + } + + // Every non delegate call or instantiate also optionally transfers the balance. + self.initial_transfer()?; + + let contract_address = &top_frame!(self).account_id; + + let call_span = T::Debug::new_call_span(contract_address, entry_point, &input_data); + + let output = T::Debug::intercept_call(contract_address, &entry_point, &input_data) + .unwrap_or_else(|| { + executable + .execute(self, &entry_point, input_data) + .map_err(|e| ExecError { error: e.error, origin: ErrorOrigin::Callee }) + })?; + + call_span.after_call(&output); + + // Avoid useless work that would be reverted anyways. + if output.did_revert() { + return Ok(output) + } + + // Storage limit is normally enforced as late as possible (when the last frame returns) + // so that the ordering of storage accesses does not matter. + // (However, if a special limit was set for a sub-call, it should be enforced right + // after the sub-call returned. See below for this case of enforcement). + 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.clone(); + match (entry_point, delegated_code_hash) { + (ExportedFunction::Constructor, _) => { + // It is not allowed to terminate a contract inside its constructor. + if matches!(frame.contract_info, CachedContract::Terminated) { + return Err(Error::::TerminatedInConstructor.into()) + } + + // If a special limit was set for the sub-call, we enforce it here. + // This is needed because contract constructor might write to storage. + // The sub-call will be rolled back in case the limit is exhausted. + let frame = self.top_frame_mut(); + let contract = frame.contract_info.as_contract(); + frame.nested_storage.enforce_subcall_limit(contract)?; + + let caller = self.caller().account_id()?.clone(); + + // Deposit an instantiation event. + Contracts::::deposit_event(Event::Instantiated { + deployer: caller, + contract: account_id.clone(), + }); + }, + (ExportedFunction::Call, Some(code_hash)) => { + Contracts::::deposit_event(Event::DelegateCalled { + contract: account_id.clone(), + code_hash, + }); + }, + (ExportedFunction::Call, None) => { + // If a special limit was set for the sub-call, we enforce it here. + // The sub-call will be rolled back in case the limit is exhausted. + let frame = self.top_frame_mut(); + let contract = frame.contract_info.as_contract(); + frame.nested_storage.enforce_subcall_limit(contract)?; + + let caller = self.caller(); + Contracts::::deposit_event(Event::Called { + caller: caller.clone(), + contract: account_id.clone(), + }); + }, + } + + Ok(output) + }; + + // All changes performed by the contract are executed under a storage transaction. + // This allows for roll back on error. Changes to the cached contract_info are + // committed or rolled back when popping the frame. + // + // `with_transactional` may return an error caused by a limit in the + // transactional storage depth. + let transaction_outcome = + with_transaction(|| -> TransactionOutcome> { + let output = do_transaction(); + match &output { + Ok(result) if !result.did_revert() => + TransactionOutcome::Commit(Ok((true, output))), + _ => TransactionOutcome::Rollback(Ok((false, output))), + } + }); + + let (success, output) = match transaction_outcome { + // `with_transactional` executed successfully, and we have the expected output. + Ok((success, output)) => (success, output), + // `with_transactional` returned an error, and we propagate that error and note no state + // has changed. + Err(error) => (false, Err(error.into())), + }; + + if success { + self.transient_storage.commit_transaction(); + } else { + self.transient_storage.rollback_transaction(); + } + + self.pop_frame(success); + output + } + + /// Remove the current (top) frame from the stack. + /// + /// This is called after running the current frame. It commits cached values to storage + /// and invalidates all stale references to it that might exist further down the call stack. + fn pop_frame(&mut self, persist: bool) { + // Revert changes to the nonce in case of a failed instantiation. + if !persist && self.top_frame().entry_point == ExportedFunction::Constructor { + self.nonce.as_mut().map(|c| *c = c.wrapping_sub(1)); + } + + // Pop the current frame from the stack and return it in case it needs to interact + // with duplicates that might exist on the stack. + // A `None` means that we are returning from the `first_frame`. + let frame = self.frames.pop(); + + // Both branches do essentially the same with the exception. The difference is that + // the else branch does consume the hardcoded `first_frame`. + if let Some(mut frame) = frame { + let account_id = &frame.account_id; + let prev = top_frame_mut!(self); + + prev.nested_gas.absorb_nested(frame.nested_gas); + + // Only gas counter changes are persisted in case of a failure. + if !persist { + return + } + + // Record the storage meter changes of the nested call into the parent meter. + // If the dropped frame's contract wasn't terminated we update the deposit counter + // in its contract info. The load is necessary to pull it from storage in case + // it was invalidated. + frame.contract_info.load(account_id); + let mut contract = frame.contract_info.into_contract(); + 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 { + // optimization: Predecessor is the same contract. + // We can just copy the contract into the predecessor without a storage write. + // This is possible when there is no other contract in-between that could + // trigger a rollback. + if prev.account_id == *account_id { + prev.contract_info = CachedContract::Cached(contract); + return + } + + // Predecessor is a different contract: We persist the info and invalidate the first + // stale cache we find. This triggers a reload from storage on next use. We skip(1) + // because that case is already handled by the optimization above. Only the first + // cache needs to be invalidated because that one will invalidate the next cache + // when it is popped from the stack. + >::insert(account_id, contract); + if let Some(c) = self.frames_mut().skip(1).find(|f| f.account_id == *account_id) { + c.contract_info = CachedContract::Invalidated; + } + } + } else { + if let Some((msg, false)) = self.debug_message.as_ref().map(|m| (m, m.is_empty())) { + log::debug!( + target: LOG_TARGET, + "Execution finished with debug buffer: {}", + core::str::from_utf8(msg).unwrap_or(""), + ); + } + self.gas_meter.absorb_nested(mem::take(&mut self.first_frame.nested_gas)); + if !persist { + return + } + let mut contract = self.first_frame.contract_info.as_contract(); + self.storage_meter.absorb( + mem::take(&mut self.first_frame.nested_storage), + &self.first_frame.account_id, + contract.as_deref_mut(), + ); + if let Some(contract) = contract { + >::insert(&self.first_frame.account_id, contract); + } + if let Some(nonce) = self.nonce { + >::set(nonce); + } + } + } + + /// Transfer some funds from `from` to `to`. + fn transfer( + preservation: Preservation, + from: &T::AccountId, + to: &T::AccountId, + value: BalanceOf, + ) -> DispatchResult { + if !value.is_zero() && from != to { + T::Currency::transfer(from, to, value, preservation) + .map_err(|_| Error::::TransferFailed)?; + } + Ok(()) + } + + // The transfer as performed by a call or instantiate. + fn initial_transfer(&self) -> DispatchResult { + let frame = self.top_frame(); + + // If it is a delegate call, then we've already transferred tokens in the + // last non-delegate frame. + if frame.delegate_caller.is_some() { + return Ok(()) + } + + let value = frame.value_transferred; + + // Get the account id from the caller. + // If the caller is root there is no account to transfer from, and therefore we can't take + // any `value` other than 0. + let caller = match self.caller() { + Origin::Signed(caller) => caller, + Origin::Root if value.is_zero() => return Ok(()), + Origin::Root => return DispatchError::RootNotAllowed.into(), + }; + Self::transfer(Preservation::Preserve, &caller, &frame.account_id, value) + } + + /// Reference to the current (top) frame. + fn top_frame(&self) -> &Frame { + top_frame!(self) + } + + /// Mutable reference to the current (top) frame. + fn top_frame_mut(&mut self) -> &mut Frame { + top_frame_mut!(self) + } + + /// Iterator over all frames. + /// + /// The iterator starts with the top frame and ends with the root frame. + fn frames(&self) -> impl Iterator> { + core::iter::once(&self.first_frame).chain(&self.frames).rev() + } + + /// Same as `frames` but with a mutable reference as iterator item. + fn frames_mut(&mut self) -> impl Iterator> { + core::iter::once(&mut self.first_frame).chain(&mut self.frames).rev() + } + + /// Returns whether the current contract is on the stack multiple times. + fn is_recursive(&self) -> bool { + let account_id = &self.top_frame().account_id; + self.frames().skip(1).any(|f| &f.account_id == account_id) + } + + /// Returns whether the specified contract allows to be reentered right now. + fn allows_reentry(&self, id: &AccountIdOf) -> bool { + !self.frames().any(|f| &f.account_id == id && !f.allows_reentry) + } + + /// Increments and returns the next nonce. Pulls it from storage if it isn't in cache. + fn next_nonce(&mut self) -> u64 { + let next = self.nonce().wrapping_add(1); + self.nonce = Some(next); + next + } +} + +impl<'a, T, E> Ext for Stack<'a, T, E> +where + T: Config, + E: Executable, +{ + type T = T; + + fn call( + &mut self, + gas_limit: Weight, + deposit_limit: BalanceOf, + to: T::AccountId, + value: BalanceOf, + input_data: Vec, + allows_reentry: bool, + read_only: bool, + ) -> Result { + // Before pushing the new frame: Protect the caller contract against reentrancy attacks. + // It is important to do this before calling `allows_reentry` so that a direct recursion + // is caught by it. + self.top_frame_mut().allows_reentry = allows_reentry; + + let try_call = || { + if !self.allows_reentry(&to) { + return Err(>::ReentranceDenied.into()) + } + + // We ignore instantiate frames in our search for a cached contract. + // Otherwise it would be possible to recursively call a contract from its own + // constructor: We disallow calling not fully constructed contracts. + let cached_info = self + .frames() + .find(|f| f.entry_point == ExportedFunction::Call && f.account_id == to) + .and_then(|f| match &f.contract_info { + CachedContract::Cached(contract) => Some(contract.clone()), + _ => None, + }); + let executable = self.push_frame( + FrameArgs::Call { dest: to, cached_info, delegated_call: None }, + value, + gas_limit, + deposit_limit, + // Enable read-only access if requested; cannot disable it if already set. + read_only || self.is_read_only(), + )?; + self.run(executable, input_data) + }; + + // We need to make sure to reset `allows_reentry` even on failure. + let result = try_call(); + + // Protection is on a per call basis. + self.top_frame_mut().allows_reentry = true; + + result + } + + fn delegate_call( + &mut self, + code_hash: CodeHash, + input_data: Vec, + ) -> Result { + let executable = E::from_storage(code_hash, self.gas_meter_mut())?; + let top_frame = self.top_frame_mut(); + let contract_info = top_frame.contract_info().clone(); + let account_id = top_frame.account_id.clone(); + let value = top_frame.value_transferred; + let executable = self.push_frame( + FrameArgs::Call { + dest: account_id, + cached_info: Some(contract_info), + delegated_call: Some(DelegatedCall { executable, caller: self.caller().clone() }), + }, + value, + Weight::zero(), + BalanceOf::::zero(), + self.is_read_only(), + )?; + self.run(executable, input_data) + } + + fn instantiate( + &mut self, + gas_limit: Weight, + deposit_limit: BalanceOf, + code_hash: CodeHash, + value: BalanceOf, + input_data: Vec, + salt: &[u8], + ) -> Result<(AccountIdOf, ExecReturnValue), ExecError> { + let executable = E::from_storage(code_hash, self.gas_meter_mut())?; + let nonce = self.next_nonce(); + let executable = self.push_frame( + FrameArgs::Instantiate { + sender: self.top_frame().account_id.clone(), + nonce, + executable, + salt, + input_data: input_data.as_ref(), + }, + value, + gas_limit, + deposit_limit, + self.is_read_only(), + )?; + let account_id = self.top_frame().account_id.clone(); + self.run(executable, input_data).map(|ret| (account_id, ret)) + } + + fn terminate(&mut self, beneficiary: &AccountIdOf) -> DispatchResult { + if self.is_recursive() { + return Err(Error::::TerminatedWhileReentrant.into()) + } + let frame = self.top_frame_mut(); + let info = frame.terminate(); + frame.nested_storage.terminate(&info, beneficiary.clone()); + + info.queue_trie_for_deletion(); + ContractInfoOf::::remove(&frame.account_id); + Self::decrement_refcount(info.code_hash); + + for (code_hash, deposit) in info.delegate_dependencies() { + Self::decrement_refcount(*code_hash); + frame + .nested_storage + .charge_deposit(frame.account_id.clone(), StorageDeposit::Refund(*deposit)); + } + + Contracts::::deposit_event(Event::Terminated { + contract: frame.account_id.clone(), + beneficiary: beneficiary.clone(), + }); + Ok(()) + } + + fn transfer(&mut self, to: &T::AccountId, value: BalanceOf) -> DispatchResult { + Self::transfer(Preservation::Preserve, &self.top_frame().account_id, to, value) + } + + fn get_storage(&mut self, key: &Key) -> Option> { + self.top_frame_mut().contract_info().read(key) + } + + fn get_storage_size(&mut self, key: &Key) -> Option { + self.top_frame_mut().contract_info().size(key.into()) + } + + fn set_storage( + &mut self, + key: &Key, + value: Option>, + take_old: bool, + ) -> Result { + let frame = self.top_frame_mut(); + frame.contract_info.get(&frame.account_id).write( + key.into(), + value, + Some(&mut frame.nested_storage), + take_old, + ) + } + + fn get_transient_storage(&self, key: &Key) -> Option> { + self.transient_storage.read(self.address(), key) + } + + fn get_transient_storage_size(&self, key: &Key) -> Option { + self.transient_storage.read(self.address(), key).map(|value| value.len() as _) + } + + fn set_transient_storage( + &mut self, + key: &Key, + value: Option>, + take_old: bool, + ) -> Result { + let account_id = self.address().clone(); + self.transient_storage.write(&account_id, key, value, take_old) + } + + fn address(&self) -> &T::AccountId { + &self.top_frame().account_id + } + + fn caller(&self) -> Origin { + if let Some(caller) = &self.top_frame().delegate_caller { + caller.clone() + } else { + self.frames() + .nth(1) + .map(|f| Origin::from_account_id(f.account_id.clone())) + .unwrap_or(self.origin.clone()) + } + } + + fn is_contract(&self, address: &T::AccountId) -> bool { + ContractInfoOf::::contains_key(&address) + } + + fn code_hash(&self, address: &T::AccountId) -> Option> { + >::get(&address).map(|contract| contract.code_hash) + } + + fn own_code_hash(&mut self) -> &CodeHash { + &self.top_frame_mut().contract_info().code_hash + } + + fn caller_is_origin(&self) -> bool { + self.origin == self.caller() + } + + fn caller_is_root(&self) -> bool { + // if the caller isn't origin, then it can't be root. + self.caller_is_origin() && self.origin == Origin::Root + } + + fn balance(&self) -> BalanceOf { + T::Currency::reducible_balance( + &self.top_frame().account_id, + Preservation::Preserve, + Fortitude::Polite, + ) + } + + fn value_transferred(&self) -> BalanceOf { + self.top_frame().value_transferred + } + + fn random(&self, subject: &[u8]) -> (SeedOf, BlockNumberFor) { + T::Randomness::random(subject) + } + + fn now(&self) -> &MomentOf { + &self.timestamp + } + + fn minimum_balance(&self) -> BalanceOf { + T::Currency::minimum_balance() + } + + fn deposit_event(&mut self, topics: Vec, data: Vec) { + Contracts::::deposit_indexed_event( + topics, + Event::ContractEmitted { contract: self.top_frame().account_id.clone(), data }, + ); + } + + fn block_number(&self) -> BlockNumberFor { + self.block_number + } + + fn max_value_size(&self) -> u32 { + self.schedule.limits.payload_len + } + + fn get_weight_price(&self, weight: Weight) -> BalanceOf { + T::WeightPrice::convert(weight) + } + + fn schedule(&self) -> &Schedule { + self.schedule + } + + fn gas_meter(&self) -> &GasMeter { + &self.top_frame().nested_gas + } + + fn gas_meter_mut(&mut self) -> &mut GasMeter { + &mut self.top_frame_mut().nested_gas + } + + fn charge_storage(&mut self, diff: &Diff) { + self.top_frame_mut().nested_storage.charge(diff) + } + + fn debug_buffer_enabled(&self) -> bool { + self.debug_message.is_some() + } + + fn append_debug_buffer(&mut self, msg: &str) -> bool { + if let Some(buffer) = &mut self.debug_message { + buffer + .try_extend(&mut msg.bytes()) + .map_err(|_| { + log::debug!( + target: LOG_TARGET, + "Debug buffer (of {} bytes) exhausted!", + DebugBufferVec::::bound(), + ) + }) + .ok(); + true + } else { + false + } + } + + fn call_runtime(&self, call: ::RuntimeCall) -> DispatchResultWithPostInfo { + let mut origin: T::RuntimeOrigin = RawOrigin::Signed(self.address().clone()).into(); + origin.add_filter(T::CallFilter::contains); + call.dispatch(origin) + } + + fn ecdsa_recover(&self, signature: &[u8; 65], message_hash: &[u8; 32]) -> Result<[u8; 33], ()> { + secp256k1_ecdsa_recover_compressed(signature, message_hash).map_err(|_| ()) + } + + fn sr25519_verify(&self, signature: &[u8; 64], message: &[u8], pub_key: &[u8; 32]) -> bool { + sp_io::crypto::sr25519_verify( + &SR25519Signature::from(*signature), + message, + &SR25519Public::from(*pub_key), + ) + } + + fn ecdsa_to_eth_address(&self, pk: &[u8; 33]) -> Result<[u8; 20], ()> { + ECDSAPublic::from(*pk).to_eth_address() + } + + #[cfg(any(test, feature = "runtime-benchmarks"))] + fn contract_info(&mut self) -> &mut ContractInfo { + self.top_frame_mut().contract_info() + } + + #[cfg(feature = "runtime-benchmarks")] + fn transient_storage(&mut self) -> &mut TransientStorage { + &mut self.transient_storage + } + + fn set_code_hash(&mut self, hash: CodeHash) -> DispatchResult { + let frame = top_frame_mut!(self); + if !E::from_storage(hash, &mut frame.nested_gas)?.is_deterministic() { + return Err(>::Indeterministic.into()) + } + + let info = frame.contract_info(); + + let prev_hash = info.code_hash; + info.code_hash = hash; + + let code_info = CodeInfoOf::::get(hash).ok_or(Error::::CodeNotFound)?; + + let old_base_deposit = info.storage_base_deposit(); + let new_base_deposit = info.update_base_deposit(&code_info); + let deposit = StorageDeposit::Charge(new_base_deposit) + .saturating_sub(&StorageDeposit::Charge(old_base_deposit)); + + frame.nested_storage.charge_deposit(frame.account_id.clone(), deposit); + + Self::increment_refcount(hash)?; + Self::decrement_refcount(prev_hash); + Contracts::::deposit_event(Event::ContractCodeUpdated { + contract: frame.account_id.clone(), + new_code_hash: hash, + old_code_hash: prev_hash, + }); + Ok(()) + } + + fn reentrance_count(&self) -> u32 { + let id: &AccountIdOf = &self.top_frame().account_id; + self.account_reentrance_count(id).saturating_sub(1) + } + + fn account_reentrance_count(&self, account_id: &AccountIdOf) -> u32 { + self.frames() + .filter(|f| f.delegate_caller.is_none() && &f.account_id == account_id) + .count() as u32 + } + + fn nonce(&mut self) -> u64 { + if let Some(current) = self.nonce { + current + } else { + let current = >::get(); + self.nonce = Some(current); + current + } + } + + fn increment_refcount(code_hash: CodeHash) -> DispatchResult { + >::mutate(code_hash, |existing| -> Result<(), DispatchError> { + if let Some(info) = existing { + *info.refcount_mut() = info.refcount().saturating_add(1); + Ok(()) + } else { + Err(Error::::CodeNotFound.into()) + } + }) + } + + fn decrement_refcount(code_hash: CodeHash) { + >::mutate(code_hash, |existing| { + if let Some(info) = existing { + *info.refcount_mut() = info.refcount().saturating_sub(1); + } + }); + } + + fn lock_delegate_dependency(&mut self, code_hash: CodeHash) -> DispatchResult { + let frame = self.top_frame_mut(); + let info = frame.contract_info.get(&frame.account_id); + ensure!(code_hash != info.code_hash, Error::::CannotAddSelfAsDelegateDependency); + + let code_info = CodeInfoOf::::get(code_hash).ok_or(Error::::CodeNotFound)?; + let deposit = T::CodeHashLockupDepositPercent::get().mul_ceil(code_info.deposit()); + + info.lock_delegate_dependency(code_hash, deposit)?; + Self::increment_refcount(code_hash)?; + frame + .nested_storage + .charge_deposit(frame.account_id.clone(), StorageDeposit::Charge(deposit)); + Ok(()) + } + + fn unlock_delegate_dependency(&mut self, code_hash: &CodeHash) -> DispatchResult { + let frame = self.top_frame_mut(); + let info = frame.contract_info.get(&frame.account_id); + + let deposit = info.unlock_delegate_dependency(code_hash)?; + Self::decrement_refcount(*code_hash); + frame + .nested_storage + .charge_deposit(frame.account_id.clone(), StorageDeposit::Refund(deposit)); + Ok(()) + } + + fn locked_delegate_dependencies_count(&mut self) -> usize { + self.top_frame_mut().contract_info().delegate_dependencies_count() + } + + fn is_read_only(&self) -> bool { + self.top_frame().read_only + } +} + +mod sealing { + use super::*; + + pub trait Sealed {} + + impl<'a, T: Config, E> Sealed for Stack<'a, T, E> {} + + #[cfg(test)] + impl Sealed for crate::wasm::MockExt {} + + #[cfg(test)] + impl Sealed for &mut crate::wasm::MockExt {} +} + +/// These tests exercise the executive layer. +/// +/// In these tests the VM/loader are mocked. Instead of dealing with wasm bytecode they use simple +/// closures. This allows you to tackle executive logic more thoroughly without writing a +/// wasm VM code. +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + exec::ExportedFunction::*, + gas::GasMeter, + tests::{ + test_utils::{get_balance, place_contract, set_balance}, + ExtBuilder, RuntimeCall, RuntimeEvent as MetaEvent, Test, TestFilter, ALICE, BOB, + CHARLIE, GAS_LIMIT, + }, + Error, + }; + use assert_matches::assert_matches; + use codec::{Decode, Encode}; + use frame_support::{assert_err, assert_ok, parameter_types}; + use frame_system::{EventRecord, Phase}; + use pallet_contracts_uapi::ReturnFlags; + use pretty_assertions::assert_eq; + use sp_runtime::{traits::Hash, DispatchError}; + use std::{cell::RefCell, collections::hash_map::HashMap, rc::Rc}; + + type System = frame_system::Pallet; + + type MockStack<'a> = Stack<'a, Test, MockExecutable>; + + parameter_types! { + static Loader: MockLoader = MockLoader::default(); + } + + fn events() -> Vec> { + System::events() + .into_iter() + .filter_map(|meta| match meta.event { + MetaEvent::Contracts(contract_event) => Some(contract_event), + _ => None, + }) + .collect() + } + + struct MockCtx<'a> { + ext: &'a mut MockStack<'a>, + input_data: Vec, + } + + #[derive(Clone)] + struct MockExecutable { + func: Rc Fn(MockCtx<'a>, &Self) -> ExecResult + 'static>, + func_type: ExportedFunction, + code_hash: CodeHash, + code_info: CodeInfo, + } + + #[derive(Default, Clone)] + pub struct MockLoader { + map: HashMap, MockExecutable>, + counter: u64, + } + + impl MockLoader { + fn code_hashes() -> Vec> { + Loader::get().map.keys().copied().collect() + } + + fn insert( + func_type: ExportedFunction, + f: impl Fn(MockCtx, &MockExecutable) -> ExecResult + 'static, + ) -> CodeHash { + Loader::mutate(|loader| { + // Generate code hashes as monotonically increasing values. + let hash = ::Hash::from_low_u64_be(loader.counter); + loader.counter += 1; + loader.map.insert( + hash, + MockExecutable { + func: Rc::new(f), + func_type, + code_hash: hash, + code_info: CodeInfo::::new(ALICE), + }, + ); + hash + }) + } + } + + impl Executable for MockExecutable { + fn from_storage( + code_hash: CodeHash, + _gas_meter: &mut GasMeter, + ) -> Result { + Loader::mutate(|loader| { + loader.map.get(&code_hash).cloned().ok_or(Error::::CodeNotFound.into()) + }) + } + + fn execute>( + self, + ext: &mut E, + function: &ExportedFunction, + input_data: Vec, + ) -> ExecResult { + if let &Constructor = function { + E::increment_refcount(self.code_hash).unwrap(); + } + // # Safety + // + // We know that we **always** call execute with a `MockStack` in this test. + // + // # Note + // + // The transmute is necessary because `execute` has to be generic over all + // `E: Ext`. However, `MockExecutable` can't be generic over `E` as it would + // constitute a cycle. + let ext = unsafe { mem::transmute(ext) }; + if function == &self.func_type { + (self.func)(MockCtx { ext, input_data }, &self) + } else { + exec_success() + } + } + + fn code_hash(&self) -> &CodeHash { + &self.code_hash + } + + fn code_info(&self) -> &CodeInfo { + &self.code_info + } + + fn code_len(&self) -> u32 { + 0 + } + + fn is_deterministic(&self) -> bool { + true + } + } + + fn exec_success() -> ExecResult { + Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() }) + } + + fn exec_trapped() -> ExecResult { + Err(ExecError { error: >::ContractTrapped.into(), origin: ErrorOrigin::Callee }) + } + + #[test] + fn it_works() { + parameter_types! { + static TestData: Vec = vec![0]; + } + + let value = Default::default(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + let exec_ch = MockLoader::insert(Call, |_ctx, _executable| { + TestData::mutate(|data| data.push(1)); + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, exec_ch); + let mut storage_meter = + storage::meter::Meter::new(&Origin::from_account_id(ALICE), Some(0), value) + .unwrap(); + + assert_matches!( + MockStack::run_call( + Origin::from_account_id(ALICE), + BOB, + &mut gas_meter, + &mut storage_meter, + &schedule, + value, + vec![], + None, + Determinism::Enforced, + ), + Ok(_) + ); + }); + + assert_eq!(TestData::get(), vec![0, 1]); + } + + #[test] + fn transfer_works() { + // This test verifies that a contract is able to transfer + // some funds to another account. + let origin = ALICE; + let dest = BOB; + + ExtBuilder::default().build().execute_with(|| { + set_balance(&origin, 100); + set_balance(&dest, 0); + + MockStack::transfer(Preservation::Preserve, &origin, &dest, 55).unwrap(); + + assert_eq!(get_balance(&origin), 45); + assert_eq!(get_balance(&dest), 55); + }); + } + + #[test] + fn correct_transfer_on_call() { + let origin = ALICE; + let dest = BOB; + let value = 55; + + let success_ch = MockLoader::insert(Call, move |ctx, _| { + assert_eq!(ctx.ext.value_transferred(), value); + Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() }) + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&dest, success_ch); + set_balance(&origin, 100); + let balance = get_balance(&dest); + let contract_origin = Origin::from_account_id(origin.clone()); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), value).unwrap(); + + let _ = MockStack::run_call( + contract_origin.clone(), + dest.clone(), + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + value, + vec![], + None, + Determinism::Enforced, + ) + .unwrap(); + + assert_eq!(get_balance(&origin), 100 - value); + assert_eq!(get_balance(&dest), balance + value); + }); + } + + #[test] + fn correct_transfer_on_delegate_call() { + let origin = ALICE; + let dest = BOB; + let value = 35; + + let success_ch = MockLoader::insert(Call, move |ctx, _| { + assert_eq!(ctx.ext.value_transferred(), value); + Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() }) + }); + + let delegate_ch = MockLoader::insert(Call, move |ctx, _| { + assert_eq!(ctx.ext.value_transferred(), value); + let _ = ctx.ext.delegate_call(success_ch, Vec::new())?; + Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() }) + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&dest, delegate_ch); + set_balance(&origin, 100); + let balance = get_balance(&dest); + let contract_origin = Origin::from_account_id(origin.clone()); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 55).unwrap(); + + let _ = MockStack::run_call( + contract_origin.clone(), + dest.clone(), + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + value, + vec![], + None, + Determinism::Enforced, + ) + .unwrap(); + + assert_eq!(get_balance(&origin), 100 - value); + assert_eq!(get_balance(&dest), balance + value); + }); + } + + #[test] + fn changes_are_reverted_on_failing_call() { + // This test verifies that changes are reverted on a call which fails (or equally, returns + // a non-zero status code). + let origin = ALICE; + let dest = BOB; + + let return_ch = MockLoader::insert(Call, |_, _| { + Ok(ExecReturnValue { flags: ReturnFlags::REVERT, data: Vec::new() }) + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&dest, return_ch); + set_balance(&origin, 100); + let balance = get_balance(&dest); + let contract_origin = Origin::from_account_id(origin.clone()); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 55).unwrap(); + + let output = MockStack::run_call( + contract_origin.clone(), + dest.clone(), + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 55, + vec![], + None, + Determinism::Enforced, + ) + .unwrap(); + + assert!(output.did_revert()); + assert_eq!(get_balance(&origin), 100); + assert_eq!(get_balance(&dest), balance); + }); + } + + #[test] + fn balance_too_low() { + // This test verifies that a contract can't send value if it's + // balance is too low. + let origin = ALICE; + let dest = BOB; + + ExtBuilder::default().build().execute_with(|| { + set_balance(&origin, 0); + + let result = MockStack::transfer(Preservation::Preserve, &origin, &dest, 100); + + assert_eq!(result, Err(Error::::TransferFailed.into())); + assert_eq!(get_balance(&origin), 0); + assert_eq!(get_balance(&dest), 0); + }); + } + + #[test] + fn output_is_returned_on_success() { + // Verifies that if a contract returns data with a successful exit status, this data + // is returned from the execution context. + let origin = ALICE; + let dest = BOB; + let return_ch = MockLoader::insert(Call, |_, _| { + Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: vec![1, 2, 3, 4] }) + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + let contract_origin = Origin::from_account_id(origin); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + place_contract(&BOB, return_ch); + + let result = MockStack::run_call( + contract_origin, + dest, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced, + ); + + let output = result.unwrap(); + assert!(!output.did_revert()); + assert_eq!(output.data, vec![1, 2, 3, 4]); + }); + } + + #[test] + fn output_is_returned_on_failure() { + // Verifies that if a contract returns data with a failing exit status, this data + // is returned from the execution context. + let origin = ALICE; + let dest = BOB; + let return_ch = MockLoader::insert(Call, |_, _| { + Ok(ExecReturnValue { flags: ReturnFlags::REVERT, data: vec![1, 2, 3, 4] }) + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, return_ch); + let contract_origin = Origin::from_account_id(origin); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + + let result = MockStack::run_call( + contract_origin, + dest, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced, + ); + + let output = result.unwrap(); + assert!(output.did_revert()); + assert_eq!(output.data, vec![1, 2, 3, 4]); + }); + } + + #[test] + fn input_data_to_call() { + let input_data_ch = MockLoader::insert(Call, |ctx, _| { + assert_eq!(ctx.input_data, &[1, 2, 3, 4]); + exec_success() + }); + + // This one tests passing the input data into a contract via call. + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, input_data_ch); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![1, 2, 3, 4], + None, + Determinism::Enforced, + ); + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn input_data_to_instantiate() { + let input_data_ch = MockLoader::insert(Constructor, |ctx, _| { + assert_eq!(ctx.input_data, &[1, 2, 3, 4]); + exec_success() + }); + + // This one tests passing the input data into a contract via instantiate. + ExtBuilder::default() + .with_code_hashes(MockLoader::code_hashes()) + .build() + .execute_with(|| { + let schedule = ::Schedule::get(); + let min_balance = ::Currency::minimum_balance(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + let executable = + MockExecutable::from_storage(input_data_ch, &mut gas_meter).unwrap(); + set_balance(&ALICE, min_balance * 10_000); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, None, min_balance).unwrap(); + + let result = MockStack::run_instantiate( + ALICE, + executable, + &mut gas_meter, + &mut storage_meter, + &schedule, + min_balance, + vec![1, 2, 3, 4], + &[], + None, + ); + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn max_depth() { + // This test verifies that when we reach the maximal depth creation of an + // yet another context fails. + parameter_types! { + static ReachedBottom: bool = false; + } + let value = Default::default(); + let recurse_ch = MockLoader::insert(Call, |ctx, _| { + // Try to call into yourself. + let r = ctx.ext.call( + Weight::zero(), + BalanceOf::::zero(), + BOB, + 0, + vec![], + true, + false, + ); + + ReachedBottom::mutate(|reached_bottom| { + if !*reached_bottom { + // We are first time here, it means we just reached bottom. + // Verify that we've got proper error and set `reached_bottom`. + assert_eq!(r, Err(Error::::MaxCallDepthReached.into())); + *reached_bottom = true; + } else { + // We just unwinding stack here. + assert_matches!(r, Ok(_)); + } + }); + + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + set_balance(&BOB, 1); + place_contract(&BOB, recurse_ch); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), value).unwrap(); + + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + value, + vec![], + None, + Determinism::Enforced, + ); + + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn caller_returns_proper_values() { + let origin = ALICE; + let dest = BOB; + + parameter_types! { + static WitnessedCallerBob: Option> = None; + static WitnessedCallerCharlie: Option> = None; + } + + let bob_ch = MockLoader::insert(Call, |ctx, _| { + // Record the caller for bob. + WitnessedCallerBob::mutate(|caller| { + *caller = Some(ctx.ext.caller().account_id().unwrap().clone()) + }); + + // Call into CHARLIE contract. + assert_matches!( + ctx.ext.call( + Weight::zero(), + BalanceOf::::zero(), + CHARLIE, + 0, + vec![], + true, + false + ), + Ok(_) + ); + exec_success() + }); + let charlie_ch = MockLoader::insert(Call, |ctx, _| { + // Record the caller for charlie. + WitnessedCallerCharlie::mutate(|caller| { + *caller = Some(ctx.ext.caller().account_id().unwrap().clone()) + }); + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&dest, bob_ch); + place_contract(&CHARLIE, charlie_ch); + let contract_origin = Origin::from_account_id(origin.clone()); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + + let result = MockStack::run_call( + contract_origin.clone(), + dest.clone(), + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced, + ); + + assert_matches!(result, Ok(_)); + }); + + assert_eq!(WitnessedCallerBob::get(), Some(origin)); + assert_eq!(WitnessedCallerCharlie::get(), Some(dest)); + } + + #[test] + fn is_contract_returns_proper_values() { + let bob_ch = MockLoader::insert(Call, |ctx, _| { + // Verify that BOB is a contract + assert!(ctx.ext.is_contract(&BOB)); + // Verify that ALICE is not a contract + assert!(!ctx.ext.is_contract(&ALICE)); + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, bob_ch); + + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced, + ); + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn code_hash_returns_proper_values() { + let code_bob = MockLoader::insert(Call, |ctx, _| { + // ALICE is not a contract and hence they do not have a code_hash + assert!(ctx.ext.code_hash(&ALICE).is_none()); + // BOB is a contract and hence it has a code_hash + assert!(ctx.ext.code_hash(&BOB).is_some()); + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_bob); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + // ALICE (not contract) -> BOB (contract) + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![0], + None, + Determinism::Enforced, + ); + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn own_code_hash_returns_proper_values() { + let bob_ch = MockLoader::insert(Call, |ctx, _| { + let code_hash = ctx.ext.code_hash(&BOB).unwrap(); + assert_eq!(*ctx.ext.own_code_hash(), code_hash); + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, bob_ch); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + // ALICE (not contract) -> BOB (contract) + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![0], + None, + Determinism::Enforced, + ); + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn caller_is_origin_returns_proper_values() { + let code_charlie = MockLoader::insert(Call, |ctx, _| { + // BOB is not the origin of the stack call + assert!(!ctx.ext.caller_is_origin()); + exec_success() + }); + + let code_bob = MockLoader::insert(Call, |ctx, _| { + // ALICE is the origin of the call stack + assert!(ctx.ext.caller_is_origin()); + // BOB calls CHARLIE + ctx.ext + .call(Weight::zero(), BalanceOf::::zero(), CHARLIE, 0, vec![], true, false) + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_bob); + place_contract(&CHARLIE, code_charlie); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + // ALICE -> BOB (caller is origin) -> CHARLIE (caller is not origin) + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![0], + None, + Determinism::Enforced, + ); + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn root_caller_succeeds() { + let code_bob = MockLoader::insert(Call, |ctx, _| { + // root is the origin of the call stack. + assert!(ctx.ext.caller_is_root()); + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_bob); + let contract_origin = Origin::Root; + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + // root -> BOB (caller is root) + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![0], + None, + Determinism::Enforced, + ); + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn root_caller_does_not_succeed_when_value_not_zero() { + let code_bob = MockLoader::insert(Call, |ctx, _| { + // root is the origin of the call stack. + assert!(ctx.ext.caller_is_root()); + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_bob); + let contract_origin = Origin::Root; + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + // root -> BOB (caller is root) + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 1, + vec![0], + None, + Determinism::Enforced, + ); + assert_matches!(result, Err(_)); + }); + } + + #[test] + fn root_caller_succeeds_with_consecutive_calls() { + let code_charlie = MockLoader::insert(Call, |ctx, _| { + // BOB is not root, even though the origin is root. + assert!(!ctx.ext.caller_is_root()); + exec_success() + }); + + let code_bob = MockLoader::insert(Call, |ctx, _| { + // root is the origin of the call stack. + assert!(ctx.ext.caller_is_root()); + // BOB calls CHARLIE. + ctx.ext + .call(Weight::zero(), BalanceOf::::zero(), CHARLIE, 0, vec![], true, false) + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_bob); + place_contract(&CHARLIE, code_charlie); + let contract_origin = Origin::Root; + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + // root -> BOB (caller is root) -> CHARLIE (caller is not root) + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![0], + None, + Determinism::Enforced, + ); + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn address_returns_proper_values() { + let bob_ch = MockLoader::insert(Call, |ctx, _| { + // Verify that address matches BOB. + assert_eq!(*ctx.ext.address(), BOB); + + // Call into charlie contract. + assert_matches!( + ctx.ext.call( + Weight::zero(), + BalanceOf::::zero(), + CHARLIE, + 0, + vec![], + true, + false + ), + Ok(_) + ); + exec_success() + }); + let charlie_ch = MockLoader::insert(Call, |ctx, _| { + assert_eq!(*ctx.ext.address(), CHARLIE); + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, bob_ch); + place_contract(&CHARLIE, charlie_ch); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced, + ); + + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn refuse_instantiate_with_value_below_existential_deposit() { + let dummy_ch = MockLoader::insert(Constructor, |_, _| exec_success()); + + ExtBuilder::default().existential_deposit(15).build().execute_with(|| { + let schedule = ::Schedule::get(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + let executable = MockExecutable::from_storage(dummy_ch, &mut gas_meter).unwrap(); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + + assert_matches!( + MockStack::run_instantiate( + ALICE, + executable, + &mut gas_meter, + &mut storage_meter, + &schedule, + 0, // <- zero value + vec![], + &[], + None, + ), + Err(_) + ); + }); + } + + #[test] + fn instantiation_work_with_success_output() { + let dummy_ch = MockLoader::insert(Constructor, |_, _| { + Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: vec![80, 65, 83, 83] }) + }); + + ExtBuilder::default() + .with_code_hashes(MockLoader::code_hashes()) + .existential_deposit(15) + .build() + .execute_with(|| { + let schedule = ::Schedule::get(); + let min_balance = ::Currency::minimum_balance(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + let executable = MockExecutable::from_storage(dummy_ch, &mut gas_meter).unwrap(); + set_balance(&ALICE, min_balance * 1000); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = storage::meter::Meter::new( + &contract_origin, + Some(min_balance * 100), + min_balance, + ) + .unwrap(); + + let instantiated_contract_address = assert_matches!( + MockStack::run_instantiate( + ALICE, + executable, + &mut gas_meter, + &mut storage_meter, + &schedule, + min_balance, + vec![], + &[], + None, + ), + Ok((address, ref output)) if output.data == vec![80, 65, 83, 83] => address + ); + + // Check that the newly created account has the expected code hash and + // there are instantiation event. + assert_eq!( + ContractInfo::::load_code_hash(&instantiated_contract_address).unwrap(), + dummy_ch + ); + assert_eq!( + &events(), + &[Event::Instantiated { + deployer: ALICE, + contract: instantiated_contract_address + }] + ); + }); + } + + #[test] + fn instantiation_fails_with_failing_output() { + let dummy_ch = MockLoader::insert(Constructor, |_, _| { + Ok(ExecReturnValue { flags: ReturnFlags::REVERT, data: vec![70, 65, 73, 76] }) + }); + + ExtBuilder::default() + .with_code_hashes(MockLoader::code_hashes()) + .existential_deposit(15) + .build() + .execute_with(|| { + let schedule = ::Schedule::get(); + let min_balance = ::Currency::minimum_balance(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + let executable = MockExecutable::from_storage(dummy_ch, &mut gas_meter).unwrap(); + set_balance(&ALICE, min_balance * 1000); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = storage::meter::Meter::new( + &contract_origin, + Some(min_balance * 100), + min_balance, + ) + .unwrap(); + + let instantiated_contract_address = assert_matches!( + MockStack::run_instantiate( + ALICE, + executable, + &mut gas_meter, + &mut storage_meter, + &schedule, + min_balance, + vec![], + &[], + None, + ), + Ok((address, ref output)) if output.data == vec![70, 65, 73, 76] => address + ); + + // Check that the account has not been created. + assert!( + ContractInfo::::load_code_hash(&instantiated_contract_address).is_none() + ); + assert!(events().is_empty()); + }); + } + + #[test] + fn instantiation_from_contract() { + let dummy_ch = MockLoader::insert(Call, |_, _| exec_success()); + let instantiated_contract_address = Rc::new(RefCell::new(None::>)); + let instantiator_ch = MockLoader::insert(Call, { + let instantiated_contract_address = Rc::clone(&instantiated_contract_address); + move |ctx, _| { + // Instantiate a contract and save it's address in `instantiated_contract_address`. + let (address, output) = ctx + .ext + .instantiate( + Weight::zero(), + BalanceOf::::zero(), + dummy_ch, + ::Currency::minimum_balance(), + vec![], + &[48, 49, 50], + ) + .unwrap(); + + *instantiated_contract_address.borrow_mut() = address.into(); + Ok(output) + } + }); + + ExtBuilder::default() + .with_code_hashes(MockLoader::code_hashes()) + .existential_deposit(15) + .build() + .execute_with(|| { + let schedule = ::Schedule::get(); + let min_balance = ::Currency::minimum_balance(); + set_balance(&ALICE, min_balance * 100); + place_contract(&BOB, instantiator_ch); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = storage::meter::Meter::new( + &contract_origin, + Some(min_balance * 10), + min_balance * 10, + ) + .unwrap(); + + assert_matches!( + MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + min_balance * 10, + vec![], + None, + Determinism::Enforced, + ), + Ok(_) + ); + + let instantiated_contract_address = + instantiated_contract_address.borrow().as_ref().unwrap().clone(); + + // Check that the newly created account has the expected code hash and + // there are instantiation event. + assert_eq!( + ContractInfo::::load_code_hash(&instantiated_contract_address).unwrap(), + dummy_ch + ); + assert_eq!( + &events(), + &[ + Event::Instantiated { + deployer: BOB, + contract: instantiated_contract_address + }, + Event::Called { caller: Origin::from_account_id(ALICE), contract: BOB }, + ] + ); + }); + } + + #[test] + fn instantiation_traps() { + let dummy_ch = MockLoader::insert(Constructor, |_, _| Err("It's a trap!".into())); + let instantiator_ch = MockLoader::insert(Call, { + move |ctx, _| { + // Instantiate a contract and save it's address in `instantiated_contract_address`. + assert_matches!( + ctx.ext.instantiate( + Weight::zero(), + BalanceOf::::zero(), + dummy_ch, + ::Currency::minimum_balance(), + vec![], + &[], + ), + Err(ExecError { + error: DispatchError::Other("It's a trap!"), + origin: ErrorOrigin::Callee, + }) + ); + + exec_success() + } + }); + + ExtBuilder::default() + .with_code_hashes(MockLoader::code_hashes()) + .existential_deposit(15) + .build() + .execute_with(|| { + let schedule = ::Schedule::get(); + set_balance(&ALICE, 1000); + set_balance(&BOB, 100); + place_contract(&BOB, instantiator_ch); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(200), 0).unwrap(); + + assert_matches!( + MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced, + ), + Ok(_) + ); + + // The contract wasn't instantiated so we don't expect to see an instantiation + // event here. + assert_eq!( + &events(), + &[Event::Called { caller: Origin::from_account_id(ALICE), contract: BOB },] + ); + }); + } + + #[test] + fn termination_from_instantiate_fails() { + let terminate_ch = MockLoader::insert(Constructor, |ctx, _| { + ctx.ext.terminate(&ALICE).unwrap(); + exec_success() + }); + + ExtBuilder::default() + .with_code_hashes(MockLoader::code_hashes()) + .existential_deposit(15) + .build() + .execute_with(|| { + let schedule = ::Schedule::get(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + let executable = + MockExecutable::from_storage(terminate_ch, &mut gas_meter).unwrap(); + set_balance(&ALICE, 10_000); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, None, 100).unwrap(); + + assert_eq!( + MockStack::run_instantiate( + ALICE, + executable, + &mut gas_meter, + &mut storage_meter, + &schedule, + 100, + vec![], + &[], + None, + ), + Err(Error::::TerminatedInConstructor.into()) + ); + + assert_eq!(&events(), &[]); + }); + } + + #[test] + fn in_memory_changes_not_discarded() { + // Call stack: BOB -> CHARLIE (trap) -> BOB' (success) + // This tests verifies some edge case of the contract info cache: + // We change some value in our contract info before calling into a contract + // that calls into ourself. This triggers a case where BOBs contract info + // is written to storage and invalidated by the successful execution of BOB'. + // The trap of CHARLIE reverts the storage changes to BOB. When the root BOB regains + // control it reloads its contract info from storage. We check that changes that + // are made before calling into CHARLIE are not discarded. + let code_bob = MockLoader::insert(Call, |ctx, _| { + if ctx.input_data[0] == 0 { + let info = ctx.ext.contract_info(); + assert_eq!(info.storage_byte_deposit, 0); + info.storage_byte_deposit = 42; + assert_eq!( + ctx.ext.call( + Weight::zero(), + BalanceOf::::zero(), + CHARLIE, + 0, + vec![], + true, + false + ), + exec_trapped() + ); + assert_eq!(ctx.ext.contract_info().storage_byte_deposit, 42); + } + exec_success() + }); + let code_charlie = MockLoader::insert(Call, |ctx, _| { + assert!(ctx + .ext + .call(Weight::zero(), BalanceOf::::zero(), BOB, 0, vec![99], true, false) + .is_ok()); + exec_trapped() + }); + + // This one tests passing the input data into a contract via call. + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_bob); + place_contract(&CHARLIE, code_charlie); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![0], + None, + Determinism::Enforced, + ); + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn recursive_call_during_constructor_fails() { + let code = MockLoader::insert(Constructor, |ctx, _| { + assert_matches!( + ctx.ext.call(Weight::zero(), BalanceOf::::zero(), ctx.ext.address().clone(), 0, vec![], true, false), + Err(ExecError{error, ..}) if error == >::ContractNotFound.into() + ); + exec_success() + }); + + // This one tests passing the input data into a contract via instantiate. + ExtBuilder::default() + .with_code_hashes(MockLoader::code_hashes()) + .build() + .execute_with(|| { + let schedule = ::Schedule::get(); + let min_balance = ::Currency::minimum_balance(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + let executable = MockExecutable::from_storage(code, &mut gas_meter).unwrap(); + set_balance(&ALICE, min_balance * 10_000); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, None, min_balance).unwrap(); + + let result = MockStack::run_instantiate( + ALICE, + executable, + &mut gas_meter, + &mut storage_meter, + &schedule, + min_balance, + vec![], + &[], + None, + ); + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn printing_works() { + let code_hash = MockLoader::insert(Call, |ctx, _| { + ctx.ext.append_debug_buffer("This is a test"); + ctx.ext.append_debug_buffer("More text"); + exec_success() + }); + + let mut debug_buffer = DebugBufferVec::::try_from(Vec::new()).unwrap(); + + ExtBuilder::default().build().execute_with(|| { + let min_balance = ::Currency::minimum_balance(); + let schedule = ::Schedule::get(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + set_balance(&ALICE, min_balance * 10); + place_contract(&BOB, code_hash); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + MockStack::run_call( + contract_origin, + BOB, + &mut gas_meter, + &mut storage_meter, + &schedule, + 0, + vec![], + Some(&mut debug_buffer), + Determinism::Enforced, + ) + .unwrap(); + }); + + assert_eq!(&String::from_utf8(debug_buffer.to_vec()).unwrap(), "This is a testMore text"); + } + + #[test] + fn printing_works_on_fail() { + let code_hash = MockLoader::insert(Call, |ctx, _| { + ctx.ext.append_debug_buffer("This is a test"); + ctx.ext.append_debug_buffer("More text"); + exec_trapped() + }); + + let mut debug_buffer = DebugBufferVec::::try_from(Vec::new()).unwrap(); + + ExtBuilder::default().build().execute_with(|| { + let min_balance = ::Currency::minimum_balance(); + let schedule = ::Schedule::get(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + set_balance(&ALICE, min_balance * 10); + place_contract(&BOB, code_hash); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + let result = MockStack::run_call( + contract_origin, + BOB, + &mut gas_meter, + &mut storage_meter, + &schedule, + 0, + vec![], + Some(&mut debug_buffer), + Determinism::Enforced, + ); + assert!(result.is_err()); + }); + + assert_eq!(&String::from_utf8(debug_buffer.to_vec()).unwrap(), "This is a testMore text"); + } + + #[test] + fn debug_buffer_is_limited() { + let code_hash = MockLoader::insert(Call, move |ctx, _| { + ctx.ext.append_debug_buffer("overflowing bytes"); + exec_success() + }); + + // Pre-fill the buffer almost up to its limit, leaving not enough space to the message + let debug_buf_before = + DebugBufferVec::::try_from(vec![0u8; DebugBufferVec::::bound() - 5]) + .unwrap(); + let mut debug_buf_after = debug_buf_before.clone(); + + ExtBuilder::default().build().execute_with(|| { + let schedule: Schedule = ::Schedule::get(); + let min_balance = ::Currency::minimum_balance(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + set_balance(&ALICE, min_balance * 10); + place_contract(&BOB, code_hash); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + MockStack::run_call( + contract_origin, + BOB, + &mut gas_meter, + &mut storage_meter, + &schedule, + 0, + vec![], + Some(&mut debug_buf_after), + Determinism::Enforced, + ) + .unwrap(); + assert_eq!(debug_buf_before, debug_buf_after); + }); + } + + #[test] + fn call_reentry_direct_recursion() { + // call the contract passed as input with disabled reentry + let code_bob = MockLoader::insert(Call, |ctx, _| { + let dest = Decode::decode(&mut ctx.input_data.as_ref()).unwrap(); + ctx.ext + .call(Weight::zero(), BalanceOf::::zero(), dest, 0, vec![], false, false) + }); + + let code_charlie = MockLoader::insert(Call, |_, _| exec_success()); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_bob); + place_contract(&CHARLIE, code_charlie); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + + // Calling another contract should succeed + assert_ok!(MockStack::run_call( + contract_origin.clone(), + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + CHARLIE.encode(), + None, + Determinism::Enforced + )); + + // Calling into oneself fails + assert_err!( + MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + BOB.encode(), + None, + Determinism::Enforced + ) + .map_err(|e| e.error), + >::ReentranceDenied, + ); + }); + } + + #[test] + fn call_deny_reentry() { + let code_bob = MockLoader::insert(Call, |ctx, _| { + if ctx.input_data[0] == 0 { + ctx.ext.call( + Weight::zero(), + BalanceOf::::zero(), + CHARLIE, + 0, + vec![], + false, + false, + ) + } else { + exec_success() + } + }); + + // call BOB with input set to '1' + let code_charlie = MockLoader::insert(Call, |ctx, _| { + ctx.ext + .call(Weight::zero(), BalanceOf::::zero(), BOB, 0, vec![1], true, false) + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_bob); + place_contract(&CHARLIE, code_charlie); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + + // BOB -> CHARLIE -> BOB fails as BOB denies reentry. + assert_err!( + MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![0], + None, + Determinism::Enforced + ) + .map_err(|e| e.error), + >::ReentranceDenied, + ); + }); + } + + #[test] + fn call_runtime_works() { + let code_hash = MockLoader::insert(Call, |ctx, _| { + let call = RuntimeCall::System(frame_system::Call::remark_with_event { + remark: b"Hello World".to_vec(), + }); + ctx.ext.call_runtime(call).unwrap(); + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let min_balance = ::Currency::minimum_balance(); + let schedule = ::Schedule::get(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + set_balance(&ALICE, min_balance * 10); + place_contract(&BOB, code_hash); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + System::reset_events(); + MockStack::run_call( + contract_origin, + BOB, + &mut gas_meter, + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced, + ) + .unwrap(); + + let remark_hash = ::Hashing::hash(b"Hello World"); + assert_eq!( + System::events(), + vec![ + EventRecord { + phase: Phase::Initialization, + event: MetaEvent::System(frame_system::Event::Remarked { + sender: BOB, + hash: remark_hash + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: MetaEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(ALICE), + contract: BOB, + }), + topics: vec![], + }, + ] + ); + }); + } + + #[test] + fn call_runtime_filter() { + let code_hash = MockLoader::insert(Call, |ctx, _| { + use frame_system::Call as SysCall; + use pallet_balances::Call as BalanceCall; + use pallet_utility::Call as UtilCall; + + // remark should still be allowed + let allowed_call = + RuntimeCall::System(SysCall::remark_with_event { remark: b"Hello".to_vec() }); + + // transfers are disallowed by the `TestFiler` (see below) + let forbidden_call = RuntimeCall::Balances(BalanceCall::transfer_allow_death { + dest: CHARLIE, + value: 22, + }); + + // simple cases: direct call + assert_err!( + ctx.ext.call_runtime(forbidden_call.clone()), + frame_system::Error::::CallFiltered + ); + + // as part of a patch: return is OK (but it interrupted the batch) + assert_ok!(ctx.ext.call_runtime(RuntimeCall::Utility(UtilCall::batch { + calls: vec![allowed_call.clone(), forbidden_call, allowed_call] + })),); + + // the transfer wasn't performed + assert_eq!(get_balance(&CHARLIE), 0); + + exec_success() + }); + + TestFilter::set_filter(|call| match call { + RuntimeCall::Balances(pallet_balances::Call::transfer_allow_death { .. }) => false, + _ => true, + }); + + ExtBuilder::default().build().execute_with(|| { + let min_balance = ::Currency::minimum_balance(); + let schedule = ::Schedule::get(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + set_balance(&ALICE, min_balance * 10); + place_contract(&BOB, code_hash); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + System::reset_events(); + MockStack::run_call( + contract_origin, + BOB, + &mut gas_meter, + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced, + ) + .unwrap(); + + let remark_hash = ::Hashing::hash(b"Hello"); + assert_eq!( + System::events(), + vec![ + EventRecord { + phase: Phase::Initialization, + event: MetaEvent::System(frame_system::Event::Remarked { + sender: BOB, + hash: remark_hash + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: MetaEvent::Utility(pallet_utility::Event::ItemCompleted), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: MetaEvent::Utility(pallet_utility::Event::BatchInterrupted { + index: 1, + error: frame_system::Error::::CallFiltered.into() + },), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: MetaEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(ALICE), + contract: BOB, + }), + topics: vec![], + }, + ] + ); + }); + } + + #[test] + fn nonce() { + let fail_code = MockLoader::insert(Constructor, |_, _| exec_trapped()); + let success_code = MockLoader::insert(Constructor, |_, _| exec_success()); + let succ_fail_code = MockLoader::insert(Constructor, move |ctx, _| { + ctx.ext + .instantiate( + Weight::zero(), + BalanceOf::::zero(), + fail_code, + ctx.ext.minimum_balance() * 100, + vec![], + &[], + ) + .ok(); + exec_success() + }); + let succ_succ_code = MockLoader::insert(Constructor, move |ctx, _| { + let (account_id, _) = ctx + .ext + .instantiate( + Weight::zero(), + BalanceOf::::zero(), + success_code, + ctx.ext.minimum_balance() * 100, + vec![], + &[], + ) + .unwrap(); + + // a plain call should not influence the account counter + ctx.ext + .call( + Weight::zero(), + BalanceOf::::zero(), + account_id, + 0, + vec![], + false, + false, + ) + .unwrap(); + + exec_success() + }); + + ExtBuilder::default() + .with_code_hashes(MockLoader::code_hashes()) + .build() + .execute_with(|| { + let schedule = ::Schedule::get(); + let min_balance = ::Currency::minimum_balance(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + let fail_executable = + MockExecutable::from_storage(fail_code, &mut gas_meter).unwrap(); + let success_executable = + MockExecutable::from_storage(success_code, &mut gas_meter).unwrap(); + let succ_fail_executable = + MockExecutable::from_storage(succ_fail_code, &mut gas_meter).unwrap(); + let succ_succ_executable = + MockExecutable::from_storage(succ_succ_code, &mut gas_meter).unwrap(); + set_balance(&ALICE, min_balance * 10_000); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, None, min_balance * 100).unwrap(); + + MockStack::run_instantiate( + ALICE, + fail_executable, + &mut gas_meter, + &mut storage_meter, + &schedule, + min_balance * 100, + vec![], + &[], + None, + ) + .ok(); + assert_eq!(>::get(), 0); + + assert_ok!(MockStack::run_instantiate( + ALICE, + success_executable, + &mut gas_meter, + &mut storage_meter, + &schedule, + min_balance * 100, + vec![], + &[], + None, + )); + assert_eq!(>::get(), 1); + + assert_ok!(MockStack::run_instantiate( + ALICE, + succ_fail_executable, + &mut gas_meter, + &mut storage_meter, + &schedule, + min_balance * 200, + vec![], + &[], + None, + )); + assert_eq!(>::get(), 2); + + assert_ok!(MockStack::run_instantiate( + ALICE, + succ_succ_executable, + &mut gas_meter, + &mut storage_meter, + &schedule, + min_balance * 200, + vec![], + &[], + None, + )); + assert_eq!(>::get(), 4); + }); + } + + #[test] + fn set_storage_works() { + let code_hash = MockLoader::insert(Call, |ctx, _| { + // Write + assert_eq!( + ctx.ext.set_storage(&Key::Fix([1; 32]), Some(vec![1, 2, 3]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_storage(&Key::Fix([2; 32]), Some(vec![4, 5, 6]), true), + Ok(WriteOutcome::New) + ); + assert_eq!(ctx.ext.set_storage(&Key::Fix([3; 32]), None, false), Ok(WriteOutcome::New)); + assert_eq!(ctx.ext.set_storage(&Key::Fix([4; 32]), None, true), Ok(WriteOutcome::New)); + assert_eq!( + ctx.ext.set_storage(&Key::Fix([5; 32]), Some(vec![]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_storage(&Key::Fix([6; 32]), Some(vec![]), true), + Ok(WriteOutcome::New) + ); + + // Overwrite + assert_eq!( + ctx.ext.set_storage(&Key::Fix([1; 32]), Some(vec![42]), false), + Ok(WriteOutcome::Overwritten(3)) + ); + assert_eq!( + ctx.ext.set_storage(&Key::Fix([2; 32]), Some(vec![48]), true), + Ok(WriteOutcome::Taken(vec![4, 5, 6])) + ); + assert_eq!(ctx.ext.set_storage(&Key::Fix([3; 32]), None, false), Ok(WriteOutcome::New)); + assert_eq!(ctx.ext.set_storage(&Key::Fix([4; 32]), None, true), Ok(WriteOutcome::New)); + assert_eq!( + ctx.ext.set_storage(&Key::Fix([5; 32]), Some(vec![]), false), + Ok(WriteOutcome::Overwritten(0)) + ); + assert_eq!( + ctx.ext.set_storage(&Key::Fix([6; 32]), Some(vec![]), true), + Ok(WriteOutcome::Taken(vec![])) + ); + + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let min_balance = ::Currency::minimum_balance(); + let schedule = ::Schedule::get(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + set_balance(&ALICE, min_balance * 1000); + place_contract(&BOB, code_hash); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = storage::meter::Meter::new(&contract_origin, None, 0).unwrap(); + assert_ok!(MockStack::run_call( + contract_origin, + BOB, + &mut gas_meter, + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced + )); + }); + } + + #[test] + fn set_storage_varsized_key_works() { + let code_hash = MockLoader::insert(Call, |ctx, _| { + // Write + assert_eq!( + ctx.ext.set_storage( + &Key::::try_from_var([1; 64].to_vec()).unwrap(), + Some(vec![1, 2, 3]), + false + ), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_storage( + &Key::::try_from_var([2; 19].to_vec()).unwrap(), + Some(vec![4, 5, 6]), + true + ), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_storage( + &Key::::try_from_var([3; 19].to_vec()).unwrap(), + None, + false + ), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_storage( + &Key::::try_from_var([4; 64].to_vec()).unwrap(), + None, + true + ), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_storage( + &Key::::try_from_var([5; 30].to_vec()).unwrap(), + Some(vec![]), + false + ), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_storage( + &Key::::try_from_var([6; 128].to_vec()).unwrap(), + Some(vec![]), + true + ), + Ok(WriteOutcome::New) + ); + + // Overwrite + assert_eq!( + ctx.ext.set_storage( + &Key::::try_from_var([1; 64].to_vec()).unwrap(), + Some(vec![42, 43, 44]), + false + ), + Ok(WriteOutcome::Overwritten(3)) + ); + assert_eq!( + ctx.ext.set_storage( + &Key::::try_from_var([2; 19].to_vec()).unwrap(), + Some(vec![48]), + true + ), + Ok(WriteOutcome::Taken(vec![4, 5, 6])) + ); + assert_eq!( + ctx.ext.set_storage( + &Key::::try_from_var([3; 19].to_vec()).unwrap(), + None, + false + ), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_storage( + &Key::::try_from_var([4; 64].to_vec()).unwrap(), + None, + true + ), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_storage( + &Key::::try_from_var([5; 30].to_vec()).unwrap(), + Some(vec![]), + false + ), + Ok(WriteOutcome::Overwritten(0)) + ); + assert_eq!( + ctx.ext.set_storage( + &Key::::try_from_var([6; 128].to_vec()).unwrap(), + Some(vec![]), + true + ), + Ok(WriteOutcome::Taken(vec![])) + ); + + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let min_balance = ::Currency::minimum_balance(); + let schedule = ::Schedule::get(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + set_balance(&ALICE, min_balance * 1000); + place_contract(&BOB, code_hash); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = storage::meter::Meter::new(&contract_origin, None, 0).unwrap(); + assert_ok!(MockStack::run_call( + contract_origin, + BOB, + &mut gas_meter, + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced + )); + }); + } + + #[test] + fn get_storage_works() { + let code_hash = MockLoader::insert(Call, |ctx, _| { + assert_eq!( + ctx.ext.set_storage(&Key::Fix([1; 32]), Some(vec![1, 2, 3]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_storage(&Key::Fix([2; 32]), Some(vec![]), false), + Ok(WriteOutcome::New) + ); + assert_eq!(ctx.ext.get_storage(&Key::Fix([1; 32])), Some(vec![1, 2, 3])); + assert_eq!(ctx.ext.get_storage(&Key::Fix([2; 32])), Some(vec![])); + assert_eq!(ctx.ext.get_storage(&Key::Fix([3; 32])), None); + + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let min_balance = ::Currency::minimum_balance(); + let schedule = ::Schedule::get(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + set_balance(&ALICE, min_balance * 1000); + place_contract(&BOB, code_hash); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = storage::meter::Meter::new(&contract_origin, None, 0).unwrap(); + assert_ok!(MockStack::run_call( + contract_origin, + BOB, + &mut gas_meter, + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced + )); + }); + } + + #[test] + fn get_storage_size_works() { + let code_hash = MockLoader::insert(Call, |ctx, _| { + assert_eq!( + ctx.ext.set_storage(&Key::Fix([1; 32]), Some(vec![1, 2, 3]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_storage(&Key::Fix([2; 32]), Some(vec![]), false), + Ok(WriteOutcome::New) + ); + assert_eq!(ctx.ext.get_storage_size(&Key::Fix([1; 32])), Some(3)); + assert_eq!(ctx.ext.get_storage_size(&Key::Fix([2; 32])), Some(0)); + assert_eq!(ctx.ext.get_storage_size(&Key::Fix([3; 32])), None); + + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let min_balance = ::Currency::minimum_balance(); + let schedule = ::Schedule::get(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + set_balance(&ALICE, min_balance * 1000); + place_contract(&BOB, code_hash); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = storage::meter::Meter::new(&contract_origin, None, 0).unwrap(); + assert_ok!(MockStack::run_call( + contract_origin, + BOB, + &mut gas_meter, + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced + )); + }); + } + + #[test] + fn get_storage_varsized_key_works() { + let code_hash = MockLoader::insert(Call, |ctx, _| { + assert_eq!( + ctx.ext.set_storage( + &Key::::try_from_var([1; 19].to_vec()).unwrap(), + Some(vec![1, 2, 3]), + false + ), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_storage( + &Key::::try_from_var([2; 16].to_vec()).unwrap(), + Some(vec![]), + false + ), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.get_storage(&Key::::try_from_var([1; 19].to_vec()).unwrap()), + Some(vec![1, 2, 3]) + ); + assert_eq!( + ctx.ext.get_storage(&Key::::try_from_var([2; 16].to_vec()).unwrap()), + Some(vec![]) + ); + assert_eq!( + ctx.ext.get_storage(&Key::::try_from_var([3; 8].to_vec()).unwrap()), + None + ); + + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let min_balance = ::Currency::minimum_balance(); + let schedule = ::Schedule::get(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + set_balance(&ALICE, min_balance * 1000); + place_contract(&BOB, code_hash); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = storage::meter::Meter::new(&contract_origin, None, 0).unwrap(); + assert_ok!(MockStack::run_call( + contract_origin, + BOB, + &mut gas_meter, + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced + )); + }); + } + + #[test] + fn get_storage_size_varsized_key_works() { + let code_hash = MockLoader::insert(Call, |ctx, _| { + assert_eq!( + ctx.ext.set_storage( + &Key::::try_from_var([1; 19].to_vec()).unwrap(), + Some(vec![1, 2, 3]), + false + ), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_storage( + &Key::::try_from_var([2; 16].to_vec()).unwrap(), + Some(vec![]), + false + ), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.get_storage_size(&Key::::try_from_var([1; 19].to_vec()).unwrap()), + Some(3) + ); + assert_eq!( + ctx.ext.get_storage_size(&Key::::try_from_var([2; 16].to_vec()).unwrap()), + Some(0) + ); + assert_eq!( + ctx.ext.get_storage_size(&Key::::try_from_var([3; 8].to_vec()).unwrap()), + None + ); + + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let min_balance = ::Currency::minimum_balance(); + let schedule = ::Schedule::get(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + set_balance(&ALICE, min_balance * 1000); + place_contract(&BOB, code_hash); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = storage::meter::Meter::new(&contract_origin, None, 0).unwrap(); + assert_ok!(MockStack::run_call( + contract_origin, + BOB, + &mut gas_meter, + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced + )); + }); + } + + #[test] + fn set_transient_storage_works() { + let code_hash = MockLoader::insert(Call, |ctx, _| { + // Write + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([1; 32]), Some(vec![1, 2, 3]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([2; 32]), Some(vec![4, 5, 6]), true), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([3; 32]), None, false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([4; 32]), None, true), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([5; 32]), Some(vec![]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([6; 32]), Some(vec![]), true), + Ok(WriteOutcome::New) + ); + + // Overwrite + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([1; 32]), Some(vec![42]), false), + Ok(WriteOutcome::Overwritten(3)) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([2; 32]), Some(vec![48]), true), + Ok(WriteOutcome::Taken(vec![4, 5, 6])) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([3; 32]), None, false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([4; 32]), None, true), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([5; 32]), Some(vec![]), false), + Ok(WriteOutcome::Overwritten(0)) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([6; 32]), Some(vec![]), true), + Ok(WriteOutcome::Taken(vec![])) + ); + + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_hash); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = storage::meter::Meter::new(&contract_origin, None, 0).unwrap(); + assert_ok!(MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced + )); + }); + } + + #[test] + fn get_transient_storage_works() { + // Call stack: BOB -> CHARLIE(success) -> BOB' (success) + let storage_key_1 = &Key::Fix([1; 32]); + let storage_key_2 = &Key::Fix([2; 32]); + let storage_key_3 = &Key::Fix([3; 32]); + let code_bob = MockLoader::insert(Call, |ctx, _| { + if ctx.input_data[0] == 0 { + assert_eq!( + ctx.ext.set_transient_storage(storage_key_1, Some(vec![1, 2]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.call( + Weight::zero(), + BalanceOf::::zero(), + CHARLIE, + 0, + vec![], + true, + false, + ), + exec_success() + ); + assert_eq!(ctx.ext.get_transient_storage(storage_key_1), Some(vec![3])); + assert_eq!(ctx.ext.get_transient_storage(storage_key_2), Some(vec![])); + assert_eq!(ctx.ext.get_transient_storage(storage_key_3), None); + } else { + assert_eq!( + ctx.ext.set_transient_storage(storage_key_1, Some(vec![3]), true), + Ok(WriteOutcome::Taken(vec![1, 2])) + ); + assert_eq!( + ctx.ext.set_transient_storage(storage_key_2, Some(vec![]), false), + Ok(WriteOutcome::New) + ); + } + exec_success() + }); + let code_charlie = MockLoader::insert(Call, |ctx, _| { + assert!(ctx + .ext + .call(Weight::zero(), BalanceOf::::zero(), BOB, 0, vec![99], true, false) + .is_ok()); + // CHARLIE can not read BOB`s storage. + assert_eq!(ctx.ext.get_transient_storage(storage_key_1), None); + exec_success() + }); + + // This one tests passing the input data into a contract via call. + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_bob); + place_contract(&CHARLIE, code_charlie); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![0], + None, + Determinism::Enforced, + ); + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn get_transient_storage_size_works() { + let storage_key_1 = &Key::Fix([1; 32]); + let storage_key_2 = &Key::Fix([2; 32]); + let storage_key_3 = &Key::Fix([3; 32]); + let code_hash = MockLoader::insert(Call, |ctx, _| { + assert_eq!( + ctx.ext.set_transient_storage(storage_key_1, Some(vec![1, 2, 3]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_transient_storage(storage_key_2, Some(vec![]), false), + Ok(WriteOutcome::New) + ); + assert_eq!(ctx.ext.get_transient_storage_size(storage_key_1), Some(3)); + assert_eq!(ctx.ext.get_transient_storage_size(storage_key_2), Some(0)); + assert_eq!(ctx.ext.get_transient_storage_size(storage_key_3), None); + + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_hash); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + assert_ok!(MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced + )); + }); + } + + #[test] + fn rollback_transient_storage_works() { + // Call stack: BOB -> CHARLIE (trap) -> BOB' (success) + let storage_key = &Key::Fix([1; 32]); + let code_bob = MockLoader::insert(Call, |ctx, _| { + if ctx.input_data[0] == 0 { + assert_eq!( + ctx.ext.set_transient_storage(storage_key, Some(vec![1, 2]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.call( + Weight::zero(), + BalanceOf::::zero(), + CHARLIE, + 0, + vec![], + true, + false + ), + exec_trapped() + ); + assert_eq!(ctx.ext.get_transient_storage(storage_key), Some(vec![1, 2])); + } else { + let overwritten_length = ctx.ext.get_transient_storage_size(storage_key).unwrap(); + assert_eq!( + ctx.ext.set_transient_storage(storage_key, Some(vec![3]), false), + Ok(WriteOutcome::Overwritten(overwritten_length)) + ); + assert_eq!(ctx.ext.get_transient_storage(storage_key), Some(vec![3])); + } + exec_success() + }); + let code_charlie = MockLoader::insert(Call, |ctx, _| { + assert!(ctx + .ext + .call(Weight::zero(), BalanceOf::::zero(), BOB, 0, vec![99], true, false) + .is_ok()); + exec_trapped() + }); + + // This one tests passing the input data into a contract via call. + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_bob); + place_contract(&CHARLIE, code_charlie); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![0], + None, + Determinism::Enforced, + ); + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn ecdsa_to_eth_address_returns_proper_value() { + let bob_ch = MockLoader::insert(Call, |ctx, _| { + let pubkey_compressed = array_bytes::hex2array_unchecked( + "028db55b05db86c0b1786ca49f095d76344c9e6056b2f02701a7e7f3c20aabfd91", + ); + assert_eq!( + ctx.ext.ecdsa_to_eth_address(&pubkey_compressed).unwrap(), + array_bytes::hex2array_unchecked::<_, 20>( + "09231da7b19A016f9e576d23B16277062F4d46A8" + ) + ); + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, bob_ch); + + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced, + ); + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn nonce_api_works() { + let fail_code = MockLoader::insert(Constructor, |_, _| exec_trapped()); + let success_code = MockLoader::insert(Constructor, |_, _| exec_success()); + let code_hash = MockLoader::insert(Call, move |ctx, _| { + // It is set to one when this contract was instantiated by `place_contract` + assert_eq!(ctx.ext.nonce(), 1); + // Should not change without any instantiation in-between + assert_eq!(ctx.ext.nonce(), 1); + // Should not change with a failed instantiation + assert_err!( + ctx.ext.instantiate( + Weight::zero(), + BalanceOf::::zero(), + fail_code, + 0, + vec![], + &[], + ), + ExecError { + error: >::ContractTrapped.into(), + origin: ErrorOrigin::Callee + } + ); + assert_eq!(ctx.ext.nonce(), 1); + // Successful instantiation increments + ctx.ext + .instantiate( + Weight::zero(), + BalanceOf::::zero(), + success_code, + 0, + vec![], + &[], + ) + .unwrap(); + assert_eq!(ctx.ext.nonce(), 2); + exec_success() + }); + + ExtBuilder::default() + .with_code_hashes(MockLoader::code_hashes()) + .build() + .execute_with(|| { + let min_balance = ::Currency::minimum_balance(); + let schedule = ::Schedule::get(); + let mut gas_meter = GasMeter::::new(GAS_LIMIT); + set_balance(&ALICE, min_balance * 1000); + place_contract(&BOB, code_hash); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, None, 0).unwrap(); + assert_ok!(MockStack::run_call( + contract_origin, + BOB, + &mut gas_meter, + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced + )); + }); + } + + /// This works even though random interface is deprecated, as the check to ban deprecated + /// functions happens in the wasm stack which is mocked for exec tests. + #[test] + fn randomness_works() { + let subject = b"nice subject".as_ref(); + let code_hash = MockLoader::insert(Call, move |ctx, _| { + let rand = ::Randomness::random(subject); + assert_eq!(rand, ctx.ext.random(subject)); + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_hash); + + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced, + ); + assert_matches!(result, Ok(_)); + }); + } +} diff --git a/pallets/contracts/src/gas.rs b/pallets/contracts/src/gas.rs new file mode 100644 index 00000000..f8c97e25 --- /dev/null +++ b/pallets/contracts/src/gas.rs @@ -0,0 +1,399 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::{exec::ExecError, Config, Error}; +use core::marker::PhantomData; +use frame_support::{ + dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, PostDispatchInfo}, + weights::Weight, + DefaultNoBound, +}; +use sp_core::Get; +use sp_runtime::{traits::Zero, DispatchError}; + +#[cfg(test)] +use std::{any::Any, fmt::Debug}; + +#[derive(Debug, PartialEq, Eq)] +pub struct ChargedAmount(Weight); + +impl ChargedAmount { + pub fn amount(&self) -> Weight { + self.0 + } +} + +/// Meter for syncing the gas between the executor and the gas meter. +#[derive(DefaultNoBound)] +struct EngineMeter { + fuel: u64, + _phantom: PhantomData, +} + +impl EngineMeter { + /// Create a meter with the given fuel limit. + fn new(limit: Weight) -> Self { + Self { + fuel: limit.ref_time().saturating_div(T::Schedule::get().ref_time_by_fuel()), + _phantom: PhantomData, + } + } + + /// Set the fuel left to the given value. + /// Returns the amount of Weight consumed since the last update. + fn set_fuel(&mut self, fuel: u64) -> Weight { + let consumed = self + .fuel + .saturating_sub(fuel) + .saturating_mul(T::Schedule::get().ref_time_by_fuel()); + self.fuel = fuel; + Weight::from_parts(consumed, 0) + } + + /// Charge the given amount of gas. + /// Returns the amount of fuel left. + fn charge_ref_time(&mut self, ref_time: u64) -> Result { + let amount = ref_time + .checked_div(T::Schedule::get().ref_time_by_fuel()) + .ok_or(Error::::InvalidSchedule)?; + + self.fuel.checked_sub(amount).ok_or_else(|| Error::::OutOfGas)?; + Ok(Syncable(self.fuel)) + } +} + +/// Used to capture the gas left before entering a host function. +/// +/// Has to be consumed in order to sync back the gas after leaving the host function. +#[must_use] +pub struct RefTimeLeft(u64); + +/// Resource that needs to be synced to the executor. +/// +/// Wrapped to make sure that the resource will be synced back the the executor. +#[must_use] +pub struct Syncable(u64); + +impl From for u64 { + fn from(from: Syncable) -> u64 { + from.0 + } +} + +#[cfg(not(test))] +pub trait TestAuxiliaries {} +#[cfg(not(test))] +impl TestAuxiliaries for T {} + +#[cfg(test)] +pub trait TestAuxiliaries: Any + Debug + PartialEq + Eq {} +#[cfg(test)] +impl TestAuxiliaries for T {} + +/// This trait represents a token that can be used for charging `GasMeter`. +/// There is no other way of charging it. +/// +/// Implementing type is expected to be super lightweight hence `Copy` (`Clone` is added +/// for consistency). If inlined there should be no observable difference compared +/// to a hand-written code. +pub trait Token: Copy + Clone + TestAuxiliaries { + /// Return the amount of gas that should be taken by this token. + /// + /// This function should be really lightweight and must not fail. It is not + /// expected that implementors will query the storage or do any kinds of heavy operations. + /// + /// That said, implementors of this function still can run into overflows + /// while calculating the amount. In this case it is ok to use saturating operations + /// since on overflow they will return `max_value` which should consume all gas. + fn weight(&self) -> Weight; + + /// Returns true if this token is expected to influence the lowest gas limit. + fn influence_lowest_gas_limit(&self) -> bool { + true + } +} + +/// A wrapper around a type-erased trait object of what used to be a `Token`. +#[cfg(test)] +pub struct ErasedToken { + pub description: String, + pub token: Box, +} + +#[derive(DefaultNoBound)] +pub struct GasMeter { + gas_limit: Weight, + /// Amount of gas left from initial gas limit. Can reach zero. + gas_left: Weight, + /// Due to `adjust_gas` and `nested` the `gas_left` can temporarily dip below its final value. + gas_left_lowest: Weight, + /// The amount of resources that was consumed by the execution engine. + /// We have to track it separately in order to avoid the loss of precision that happens when + /// converting from ref_time to the execution engine unit. + engine_meter: EngineMeter, + _phantom: PhantomData, + #[cfg(test)] + tokens: Vec, +} + +impl GasMeter { + pub fn new(gas_limit: Weight) -> Self { + GasMeter { + gas_limit, + gas_left: gas_limit, + gas_left_lowest: gas_limit, + engine_meter: EngineMeter::new(gas_limit), + _phantom: PhantomData, + #[cfg(test)] + tokens: Vec::new(), + } + } + + /// Create a new gas meter by removing gas from the current meter. + /// + /// # Note + /// + /// Passing `0` as amount is interpreted as "all remaining gas". + pub fn nested(&mut self, amount: Weight) -> Self { + let amount = Weight::from_parts( + if amount.ref_time().is_zero() { + self.gas_left().ref_time() + } else { + amount.ref_time() + }, + if amount.proof_size().is_zero() { + self.gas_left().proof_size() + } else { + amount.proof_size() + }, + ) + .min(self.gas_left); + self.gas_left -= amount; + GasMeter::new(amount) + } + + /// Absorb the remaining gas of a nested meter after we are done using it. + pub fn absorb_nested(&mut self, nested: Self) { + self.gas_left_lowest = (self.gas_left + nested.gas_limit) + .saturating_sub(nested.gas_required()) + .min(self.gas_left_lowest); + self.gas_left += nested.gas_left; + } + + /// Account for used gas. + /// + /// Amount is calculated by the given `token`. + /// + /// Returns `OutOfGas` if there is not enough gas or addition of the specified + /// amount of gas has lead to overflow. + /// + /// NOTE that amount isn't consumed if there is not enough gas. This is considered + /// safe because we always charge gas before performing any resource-spending action. + #[inline] + pub fn charge>(&mut self, token: Tok) -> Result { + #[cfg(test)] + { + // Unconditionally add the token to the storage. + let erased_tok = + ErasedToken { description: format!("{:?}", token), token: Box::new(token) }; + self.tokens.push(erased_tok); + } + let amount = token.weight(); + // It is OK to not charge anything on failure because we always charge _before_ we perform + // any action + self.gas_left = self.gas_left.checked_sub(&amount).ok_or_else(|| Error::::OutOfGas)?; + Ok(ChargedAmount(amount)) + } + + /// Adjust a previously charged amount down to its actual amount. + /// + /// This is when a maximum a priori amount was charged and then should be partially + /// refunded to match the actual amount. + pub fn adjust_gas>(&mut self, charged_amount: ChargedAmount, token: Tok) { + if token.influence_lowest_gas_limit() { + self.gas_left_lowest = self.gas_left_lowest(); + } + let adjustment = charged_amount.0.saturating_sub(token.weight()); + self.gas_left = self.gas_left.saturating_add(adjustment).min(self.gas_limit); + } + + /// Hand over the gas metering responsibility from the executor to this meter. + /// + /// Needs to be called when entering a host function to update this meter with the + /// gas that was tracked by the executor. It tracks the latest seen total value + /// in order to compute the delta that needs to be charged. + pub fn sync_from_executor(&mut self, engine_fuel: u64) -> Result { + let weight_consumed = self.engine_meter.set_fuel(engine_fuel); + self.gas_left + .checked_reduce(weight_consumed) + .ok_or_else(|| Error::::OutOfGas)?; + Ok(RefTimeLeft(self.gas_left.ref_time())) + } + + /// Hand over the gas metering responsibility from this meter to the executor. + /// + /// Needs to be called when leaving a host function in order to calculate how much + /// gas needs to be charged from the **executor**. It updates the last seen executor + /// total value so that it is correct when `sync_from_executor` is called the next time. + /// + /// It is important that this does **not** actually sync with the executor. That has + /// to be done by the caller. + pub fn sync_to_executor(&mut self, before: RefTimeLeft) -> Result { + let ref_time_consumed = before.0.saturating_sub(self.gas_left().ref_time()); + self.engine_meter.charge_ref_time(ref_time_consumed) + } + + /// Returns the amount of gas that is required to run the same call. + /// + /// This can be different from `gas_spent` because due to `adjust_gas` the amount of + /// spent gas can temporarily drop and be refunded later. + pub fn gas_required(&self) -> Weight { + self.gas_limit.saturating_sub(self.gas_left_lowest()) + } + + /// Returns how much gas was spent + pub fn gas_consumed(&self) -> Weight { + self.gas_limit.saturating_sub(self.gas_left) + } + + /// Returns how much gas left from the initial budget. + pub fn gas_left(&self) -> Weight { + self.gas_left + } + + /// Turn this GasMeter into a DispatchResult that contains the actually used gas. + pub fn into_dispatch_result( + self, + result: Result, + base_weight: Weight, + ) -> DispatchResultWithPostInfo + where + E: Into, + { + let post_info = PostDispatchInfo { + actual_weight: Some(self.gas_consumed().saturating_add(base_weight)), + pays_fee: Default::default(), + }; + + result + .map(|_| post_info) + .map_err(|e| DispatchErrorWithPostInfo { post_info, error: e.into().error }) + } + + fn gas_left_lowest(&self) -> Weight { + self.gas_left_lowest.min(self.gas_left) + } + + #[cfg(test)] + pub fn tokens(&self) -> &[ErasedToken] { + &self.tokens + } +} + +#[cfg(test)] +mod tests { + use super::{GasMeter, Token, Weight}; + use crate::tests::Test; + + /// A simple utility macro that helps to match against a + /// list of tokens. + macro_rules! match_tokens { + ($tokens_iter:ident,) => { + }; + ($tokens_iter:ident, $x:expr, $($rest:tt)*) => { + { + let next = ($tokens_iter).next().unwrap(); + let pattern = $x; + + // Note that we don't specify the type name directly in this macro, + // we only have some expression $x of some type. At the same time, we + // have an iterator of Box and to downcast we need to specify + // the type which we want downcast to. + // + // So what we do is we assign `_pattern_typed_next_ref` to a variable which has + // the required type. + // + // Then we make `_pattern_typed_next_ref = token.downcast_ref()`. This makes + // rustc infer the type `T` (in `downcast_ref`) to be the same as in $x. + + let mut _pattern_typed_next_ref = &pattern; + _pattern_typed_next_ref = match next.token.downcast_ref() { + Some(p) => { + assert_eq!(p, &pattern); + p + } + None => { + panic!("expected type {} got {}", stringify!($x), next.description); + } + }; + } + + match_tokens!($tokens_iter, $($rest)*); + }; + } + + /// A trivial token that charges the specified number of gas units. + #[derive(Copy, Clone, PartialEq, Eq, Debug)] + struct SimpleToken(u64); + impl Token for SimpleToken { + fn weight(&self) -> Weight { + Weight::from_parts(self.0, 0) + } + } + + #[test] + fn it_works() { + let gas_meter = GasMeter::::new(Weight::from_parts(50000, 0)); + assert_eq!(gas_meter.gas_left(), Weight::from_parts(50000, 0)); + } + + #[test] + fn tracing() { + let mut gas_meter = GasMeter::::new(Weight::from_parts(50000, 0)); + assert!(!gas_meter.charge(SimpleToken(1)).is_err()); + + let mut tokens = gas_meter.tokens().iter(); + match_tokens!(tokens, SimpleToken(1),); + } + + // This test makes sure that nothing can be executed if there is no gas. + #[test] + fn refuse_to_execute_anything_if_zero() { + let mut gas_meter = GasMeter::::new(Weight::zero()); + assert!(gas_meter.charge(SimpleToken(1)).is_err()); + } + + // Make sure that the gas meter does not charge in case of overcharge + #[test] + fn overcharge_does_not_charge() { + let mut gas_meter = GasMeter::::new(Weight::from_parts(200, 0)); + + // The first charge is should lead to OOG. + assert!(gas_meter.charge(SimpleToken(300)).is_err()); + + // The gas meter should still contain the full 200. + assert!(gas_meter.charge(SimpleToken(200)).is_ok()); + } + + // Charging the exact amount that the user paid for should be + // possible. + #[test] + fn charge_exact_amount() { + let mut gas_meter = GasMeter::::new(Weight::from_parts(25, 0)); + assert!(!gas_meter.charge(SimpleToken(25)).is_err()); + } +} diff --git a/pallets/contracts/src/lib.rs b/pallets/contracts/src/lib.rs new file mode 100644 index 00000000..7bb5b46c --- /dev/null +++ b/pallets/contracts/src/lib.rs @@ -0,0 +1,1986 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! # Contracts Pallet +//! +//! The Contracts module provides functionality for the runtime to deploy and execute WebAssembly +//! smart-contracts. +//! +//! - [`Config`] +//! - [`Call`] +//! +//! ## Overview +//! +//! This module extends accounts based on the [`frame_support::traits::fungible`] traits to have +//! smart-contract functionality. It can be used with other modules that implement accounts based on +//! the [`frame_support::traits::fungible`] traits. These "smart-contract accounts" have the ability +//! to instantiate smart-contracts and make calls to other contract and non-contract accounts. +//! +//! The smart-contract code is stored once, and later retrievable via its hash. +//! This means that multiple smart-contracts can be instantiated from the same hash, without +//! replicating the code each time. +//! +//! When a smart-contract is called, its associated code is retrieved via the code hash and gets +//! executed. This call can alter the storage entries of the smart-contract account, instantiate new +//! smart-contracts, or call other smart-contracts. +//! +//! Finally, when an account is reaped, its associated code and storage of the smart-contract +//! account will also be deleted. +//! +//! ### Weight +//! +//! Senders must specify a [`Weight`] limit with every call, as all instructions invoked by the +//! smart-contract require weight. Unused weight is refunded after the call, regardless of the +//! execution outcome. +//! +//! If the weight limit is reached, then all calls and state changes (including balance transfers) +//! are only reverted at the current call's contract level. For example, if contract A calls B and B +//! runs out of gas mid-call, then all of B's calls are reverted. Assuming correct error handling by +//! contract A, A's other calls and state changes still persist. +//! +//! ### Notable Scenarios +//! +//! Contract call failures are not always cascading. When failures occur in a sub-call, they do not +//! "bubble up", and the call will only revert at the specific contract level. For example, if +//! contract A calls contract B, and B fails, A can decide how to handle that failure, either +//! proceeding or reverting A's changes. +//! +//! ## Interface +//! +//! ### Dispatchable functions +//! +//! * [`Pallet::instantiate_with_code`] - Deploys a new contract from the supplied Wasm binary, +//! optionally transferring +//! some balance. This instantiates a new smart contract account with the supplied code and +//! calls its constructor to initialize the contract. +//! * [`Pallet::instantiate`] - The same as `instantiate_with_code` but instead of uploading new +//! code an existing `code_hash` is supplied. +//! * [`Pallet::call`] - Makes a call to an account, optionally transferring some balance. +//! * [`Pallet::upload_code`] - Uploads new code without instantiating a contract from it. +//! * [`Pallet::remove_code`] - Removes the stored code and refunds the deposit to its owner. Only +//! allowed to code owner. +//! * [`Pallet::set_code`] - Changes the code of an existing contract. Only allowed to `Root` +//! origin. +//! * [`Pallet::migrate`] - Runs migration steps of current multi-block migration in priority, +//! before [`Hooks::on_idle`][frame_support::traits::Hooks::on_idle] activates. +//! +//! ## Usage +//! +//! * [`ink!`](https://use.ink) is language that enables writing Wasm-based smart contracts in plain +//! Rust. + +#![allow(rustdoc::private_intra_doc_links)] +#![cfg_attr(not(feature = "std"), no_std)] +#![cfg_attr(feature = "runtime-benchmarks", recursion_limit = "1024")] + +extern crate alloc; +mod address; +mod benchmarking; +mod exec; +mod gas; +mod primitives; +pub use primitives::*; + +mod schedule; +mod storage; +mod transient_storage; +mod wasm; + +pub mod chain_extension; +pub mod debug; +pub mod migration; +pub mod test_utils; +pub mod weights; + +#[cfg(test)] +mod tests; +use crate::{ + exec::{ + AccountIdOf, ErrorOrigin, ExecError, Executable, Ext, Key, MomentOf, Stack as ExecStack, + }, + gas::GasMeter, + storage::{meter::Meter as StorageMeter, ContractInfo, DeletionQueueManager}, + wasm::{CodeInfo, RuntimeCosts, WasmBlob}, +}; +use codec::{Codec, Decode, Encode, HasCompact, MaxEncodedLen}; +use core::fmt::Debug; +use environmental::*; +use frame_support::{ + dispatch::{GetDispatchInfo, Pays, PostDispatchInfo, RawOrigin, WithPostDispatchInfo}, + ensure, + traits::{ + fungible::{Inspect, Mutate, MutateHold}, + ConstU32, Contains, Get, Randomness, Time, + }, + weights::{Weight, WeightMeter}, + BoundedVec, DefaultNoBound, RuntimeDebugNoBound, +}; +use frame_system::{ + ensure_signed, + pallet_prelude::{BlockNumberFor, OriginFor}, + EventRecord, Pallet as System, +}; +use scale_info::TypeInfo; +use smallvec::Array; +use sp_runtime::{ + traits::{BadOrigin, Convert, Dispatchable, Saturating, StaticLookup, Zero}, + DispatchError, RuntimeDebug, +}; + +pub use crate::{ + address::{AddressGenerator, DefaultAddressGenerator}, + debug::Tracing, + exec::Frame, + migration::{MigrateSequence, Migration, NoopMigration}, + pallet::*, + schedule::{InstructionWeights, Limits, Schedule}, + wasm::Determinism, +}; +pub use weights::WeightInfo; + +#[cfg(doc)] +pub use crate::wasm::api_doc; + +type CodeHash = ::Hash; +type TrieId = BoundedVec>; +type BalanceOf = + <::Currency as Inspect<::AccountId>>::Balance; +type CodeVec = BoundedVec::MaxCodeLen>; +type AccountIdLookupOf = <::Lookup as StaticLookup>::Source; +type DebugBufferVec = BoundedVec::MaxDebugBufferLen>; +type EventRecordOf = + EventRecord<::RuntimeEvent, ::Hash>; + +/// The old weight type. +/// +/// This is a copy of the [`frame_support::weights::OldWeight`] type since the contracts pallet +/// needs to support it indefinitely. +type OldWeight = u64; + +/// Used as a sentinel value when reading and writing contract memory. +/// +/// It is usually used to signal `None` to a contract when only a primitive is allowed +/// and we don't want to go through encoding a full Rust type. Using `u32::Max` is a safe +/// sentinel because contracts are never allowed to use such a large amount of resources +/// that this value makes sense for a memory location or length. +const SENTINEL: u32 = u32::MAX; + +/// The target that is used for the log output emitted by this crate. +/// +/// Hence you can use this target to selectively increase the log level for this crate. +/// +/// Example: `RUST_LOG=runtime::contracts=debug my_code --dev` +const LOG_TARGET: &str = "runtime::contracts"; + +/// Wrapper around `PhantomData` to prevent it being filtered by `scale-info`. +/// +/// `scale-info` filters out `PhantomData` fields because usually we are only interested +/// in sized types. However, when trying to communicate **types** as opposed to **values** +/// we want to have those zero sized types be included. +#[derive(Encode, Decode, DefaultNoBound, TypeInfo)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +pub struct EnvironmentType(PhantomData); + +/// List of all runtime configurable types that are used in the communication between +/// `pallet-contracts` and any given contract. +/// +/// Since those types are configurable they can vary between +/// chains all using `pallet-contracts`. Hence we need a mechanism to communicate those types +/// in a way that can be consumed by offchain tooling. +/// +/// This type only exists in order to appear in the metadata where it can be read by +/// offchain tooling. +#[derive(Encode, Decode, DefaultNoBound, TypeInfo)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +#[scale_info(skip_type_params(T))] +pub struct Environment { + account_id: EnvironmentType>, + balance: EnvironmentType>, + hash: EnvironmentType<::Hash>, + hasher: EnvironmentType<::Hashing>, + timestamp: EnvironmentType>, + block_number: EnvironmentType>, +} + +/// Defines the current version of the HostFn APIs. +/// This is used to communicate the available APIs in pallet-contracts. +/// +/// The version is bumped any time a new HostFn is added or stabilized. +#[derive(Encode, Decode, TypeInfo)] +pub struct ApiVersion(u16); +impl Default for ApiVersion { + fn default() -> Self { + Self(4) + } +} + +#[test] +fn api_version_is_up_to_date() { + assert_eq!( + 111, + crate::wasm::STABLE_API_COUNT, + "Stable API count has changed. Bump the returned value of ApiVersion::default() and update the test." + ); +} + +#[frame_support::pallet] +pub mod pallet { + use super::*; + use crate::debug::Debugger; + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; + use sp_runtime::Perbill; + + /// The in-code storage version. + pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(16); + + #[pallet::pallet] + #[pallet::storage_version(STORAGE_VERSION)] + pub struct Pallet(_); + + #[pallet::config(with_default)] + pub trait Config: frame_system::Config { + /// 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`. + /// + /// # Deprecated + /// + /// Codes using the randomness functionality cannot be uploaded. Neither can contracts + /// be instantiated from existing codes that use this deprecated functionality. It will + /// be removed eventually. Hence for new `pallet-contracts` deployments it is okay + /// to supply a dummy implementation for this type (because it is never used). + #[pallet::no_default_bounds] + type Randomness: Randomness>; + + /// The fungible in which fees are paid and contract balances are held. + #[pallet::no_default] + type Currency: Inspect + + Mutate + + MutateHold; + + /// The overarching event type. + #[pallet::no_default_bounds] + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + + /// The overarching call type. + #[pallet::no_default_bounds] + type RuntimeCall: Dispatchable + + GetDispatchInfo + + codec::Decode + + IsType<::RuntimeCall>; + + /// Overarching hold reason. + #[pallet::no_default_bounds] + type RuntimeHoldReason: From; + + /// Filter that is applied to calls dispatched by contracts. + /// + /// Use this filter to control which dispatchables are callable by contracts. + /// This is applied in **addition** to [`frame_system::Config::BaseCallFilter`]. + /// It is recommended to treat this as a whitelist. + /// + /// # Stability + /// + /// The runtime **must** make sure that all dispatchables that are callable by + /// contracts remain stable. In addition [`Self::RuntimeCall`] itself must remain stable. + /// This means that no existing variants are allowed to switch their positions. + /// + /// # Note + /// + /// Note that dispatchables that are called via contracts do not spawn their + /// own wasm instance for each call (as opposed to when called via a transaction). + /// Therefore please make sure to be restrictive about which dispatchables are allowed + /// in order to not introduce a new DoS vector like memory allocation patterns that can + /// be exploited to drive the runtime into a panic. + /// + /// This filter does not apply to XCM transact calls. To impose restrictions on XCM transact + /// calls, you must configure them separately within the XCM pallet itself. + #[pallet::no_default_bounds] + type CallFilter: Contains<::RuntimeCall>; + + /// Used to answer contracts' queries regarding the current weight price. This is **not** + /// used to calculate the actual fee and is only for informational purposes. + #[pallet::no_default_bounds] + type WeightPrice: Convert>; + + /// Describes the weights of the dispatchables of this module and is also used to + /// construct a default cost schedule. + type WeightInfo: WeightInfo; + + /// Type that allows the runtime authors to add new host functions for a contract to call. + #[pallet::no_default_bounds] + type ChainExtension: chain_extension::ChainExtension + Default; + + /// Cost schedule and limits. + #[pallet::constant] + #[pallet::no_default] + type Schedule: Get>; + + /// The type of the call stack determines the maximum nesting depth of contract calls. + /// + /// The allowed depth is `CallStack::size() + 1`. + /// Therefore a size of `0` means that a contract cannot use call or instantiate. + /// In other words only the origin called "root contract" is allowed to execute then. + /// + /// This setting along with [`MaxCodeLen`](#associatedtype.MaxCodeLen) directly affects + /// memory usage of your runtime. + #[pallet::no_default] + type CallStack: Array>; + + /// The amount of balance a caller has to pay for each byte of storage. + /// + /// # Note + /// + /// Changing this value for an existing chain might need a storage migration. + #[pallet::constant] + #[pallet::no_default_bounds] + type DepositPerByte: Get>; + + /// Fallback value to limit the storage deposit if it's not being set by the caller. + #[pallet::constant] + #[pallet::no_default_bounds] + type DefaultDepositLimit: Get>; + + /// The amount of balance a caller has to pay for each storage item. + /// + /// # Note + /// + /// Changing this value for an existing chain might need a storage migration. + #[pallet::constant] + #[pallet::no_default_bounds] + type DepositPerItem: Get>; + + /// The percentage of the storage deposit that should be held for using a code hash. + /// Instantiating a contract, or calling [`chain_extension::Ext::lock_delegate_dependency`] + /// protects the code from being removed. In order to prevent abuse these actions are + /// protected with a percentage of the code deposit. + #[pallet::constant] + type CodeHashLockupDepositPercent: Get; + + /// The address generator used to generate the addresses of contracts. + #[pallet::no_default_bounds] + type AddressGenerator: AddressGenerator; + + /// The maximum length of a contract code in bytes. + /// + /// The value should be chosen carefully taking into the account the overall memory limit + /// your runtime has, as well as the [maximum allowed callstack + /// depth](#associatedtype.CallStack). Look into the `integrity_test()` for some insights. + #[pallet::constant] + type MaxCodeLen: Get; + + /// The maximum allowable length in bytes for storage keys. + #[pallet::constant] + type MaxStorageKeyLen: Get; + + /// The maximum size of the transient storage in bytes. + /// This includes keys, values, and previous entries used for storage rollback. + #[pallet::constant] + type MaxTransientStorageSize: Get; + + /// The maximum number of delegate_dependencies that a contract can lock with + /// [`chain_extension::Ext::lock_delegate_dependency`]. + #[pallet::constant] + type MaxDelegateDependencies: Get; + + /// Make contract callable functions marked as `#[unstable]` available. + /// + /// Contracts that use `#[unstable]` functions won't be able to be uploaded unless + /// this is set to `true`. This is only meant for testnets and dev nodes in order to + /// experiment with new features. + /// + /// # Warning + /// + /// Do **not** set to `true` on productions chains. + #[pallet::constant] + type UnsafeUnstableInterface: Get; + + /// The maximum length of the debug buffer in bytes. + #[pallet::constant] + type MaxDebugBufferLen: Get; + + /// Origin allowed to upload code. + /// + /// By default, it is safe to set this to `EnsureSigned`, allowing anyone to upload contract + /// code. + #[pallet::no_default_bounds] + type UploadOrigin: EnsureOrigin; + + /// Origin allowed to instantiate code. + /// + /// # Note + /// + /// This is not enforced when a contract instantiates another contract. The + /// [`Self::UploadOrigin`] should make sure that no code is deployed that does unwanted + /// instantiations. + /// + /// By default, it is safe to set this to `EnsureSigned`, allowing anyone to instantiate + /// contract code. + #[pallet::no_default_bounds] + type InstantiateOrigin: EnsureOrigin; + + /// The sequence of migration steps that will be applied during a migration. + /// + /// # Examples + /// ``` + /// use pallet_contracts::migration::{v10, v11}; + /// # struct Runtime {}; + /// # struct Currency {}; + /// type Migrations = (v10::Migration, v11::Migration); + /// ``` + /// + /// If you have a single migration step, you can use a tuple with a single element: + /// ``` + /// use pallet_contracts::migration::v10; + /// # struct Runtime {}; + /// # struct Currency {}; + /// type Migrations = (v10::Migration,); + /// ``` + type Migrations: MigrateSequence; + + /// # Note + /// For most production chains, it's recommended to use the `()` implementation of this + /// trait. This implementation offers additional logging when the log target + /// "runtime::contracts" is set to trace. + #[pallet::no_default_bounds] + type Debug: Debugger; + + /// Type that bundles together all the runtime configurable interface types. + /// + /// This is not a real config. We just mention the type here as constant so that + /// its type appears in the metadata. Only valid value is `()`. + #[pallet::constant] + #[pallet::no_default_bounds] + type Environment: Get>; + + /// The version of the HostFn APIs that are available in the runtime. + /// + /// Only valid value is `()`. + #[pallet::constant] + #[pallet::no_default_bounds] + type ApiVersion: Get; + + /// A type that exposes XCM APIs, allowing contracts to interact with other parachains, and + /// execute XCM programs. + #[pallet::no_default_bounds] + type Xcm: xcm_builder::Controller< + OriginFor, + ::RuntimeCall, + BlockNumberFor, + >; + } + + /// Container for different types that implement [`DefaultConfig`]` of this pallet. + pub mod config_preludes { + use super::*; + use frame_support::{ + derive_impl, + traits::{ConstBool, ConstU32}, + }; + use frame_system::EnsureSigned; + use sp_core::parameter_types; + + type AccountId = sp_runtime::AccountId32; + type Balance = u64; + const UNITS: Balance = 10_000_000_000; + const CENTS: Balance = UNITS / 100; + + const fn deposit(items: u32, bytes: u32) -> Balance { + items as Balance * 1 * CENTS + (bytes as Balance) * 1 * CENTS + } + + parameter_types! { + pub const DepositPerItem: Balance = deposit(1, 0); + pub const DepositPerByte: Balance = deposit(0, 1); + pub const DefaultDepositLimit: Balance = deposit(1024, 1024 * 1024); + pub const CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0); + pub const MaxDelegateDependencies: u32 = 32; + } + + /// A type providing default configurations for this pallet in testing environment. + pub struct TestDefaultConfig; + + impl Randomness for TestDefaultConfig { + fn random(_subject: &[u8]) -> (Output, BlockNumber) { + unimplemented!("No default `random` implementation in `TestDefaultConfig`, provide a custom `T::Randomness` type.") + } + } + + impl Time for TestDefaultConfig { + type Moment = u64; + fn now() -> Self::Moment { + unimplemented!("No default `now` implementation in `TestDefaultConfig` provide a custom `T::Time` type.") + } + } + + impl> Convert for TestDefaultConfig { + fn convert(w: Weight) -> T { + w.ref_time().into() + } + } + + #[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)] + impl frame_system::DefaultConfig for TestDefaultConfig {} + + #[frame_support::register_default_impl(TestDefaultConfig)] + impl DefaultConfig for TestDefaultConfig { + #[inject_runtime_type] + type RuntimeEvent = (); + + #[inject_runtime_type] + type RuntimeHoldReason = (); + + #[inject_runtime_type] + type RuntimeCall = (); + + type AddressGenerator = DefaultAddressGenerator; + type CallFilter = (); + type ChainExtension = (); + type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; + type DefaultDepositLimit = DefaultDepositLimit; + type DepositPerByte = DepositPerByte; + type DepositPerItem = DepositPerItem; + type MaxCodeLen = ConstU32<{ 123 * 1024 }>; + type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>; + type MaxDelegateDependencies = MaxDelegateDependencies; + type MaxStorageKeyLen = ConstU32<128>; + type MaxTransientStorageSize = ConstU32<{ 1 * 1024 * 1024 }>; + type Migrations = (); + type Time = Self; + type Randomness = Self; + type UnsafeUnstableInterface = ConstBool; + type UploadOrigin = EnsureSigned; + type InstantiateOrigin = EnsureSigned; + type WeightInfo = (); + type WeightPrice = Self; + type Debug = (); + type Environment = (); + type ApiVersion = (); + type Xcm = (); + } + } + + #[pallet::hooks] + impl Hooks> for Pallet { + fn on_idle(_block: BlockNumberFor, limit: Weight) -> Weight { + use migration::MigrateResult::*; + let mut meter = WeightMeter::with_limit(limit); + + loop { + match Migration::::migrate(&mut meter) { + // There is not enough weight to perform a migration. + // We can't do anything more, so we return the used weight. + NoMigrationPerformed | InProgress { steps_done: 0 } => return meter.consumed(), + // Migration is still in progress, we can start the next step. + InProgress { .. } => continue, + // Either no migration is in progress, or we are done with all migrations, we + // can do some more other work with the remaining weight. + Completed | NoMigrationInProgress => break, + } + } + + ContractInfo::::process_deletion_queue_batch(&mut meter); + meter.consumed() + } + + fn integrity_test() { + Migration::::integrity_test(); + + // Total runtime memory limit + let max_runtime_mem: u32 = T::Schedule::get().limits.runtime_memory; + // Memory limits for a single contract: + // Value stack size: 1Mb per contract, default defined in wasmi + const MAX_STACK_SIZE: u32 = 1024 * 1024; + // Heap limit is normally 16 mempages of 64kb each = 1Mb per contract + let max_heap_size = T::Schedule::get().limits.max_memory_size(); + // Max call depth is CallStack::size() + 1 + let max_call_depth = u32::try_from(T::CallStack::size().saturating_add(1)) + .expect("CallStack size is too big"); + // Transient storage uses a BTreeMap, which has overhead compared to the raw size of + // key-value data. To ensure safety, a margin of 2x the raw key-value size is used. + let max_transient_storage_size = T::MaxTransientStorageSize::get() + .checked_mul(2) + .expect("MaxTransientStorageSize is too large"); + // Check that given configured `MaxCodeLen`, runtime heap memory limit can't be broken. + // + // In worst case, the decoded Wasm contract code would be `x16` times larger than the + // encoded one. This is because even a single-byte wasm instruction has 16-byte size in + // wasmi. This gives us `MaxCodeLen*16` safety margin. + // + // Next, the pallet keeps the Wasm blob for each + // contract, hence we add up `MaxCodeLen` to the safety margin. + // + // The inefficiencies of the freeing-bump allocator + // being used in the client for the runtime memory allocations, could lead to possible + // memory allocations for contract code grow up to `x4` times in some extreme cases, + // which gives us total multiplier of `17*4` for `MaxCodeLen`. + // + // That being said, for every contract executed in runtime, at least `MaxCodeLen*17*4` + // memory should be available. Note that maximum allowed heap memory and stack size per + // each contract (stack frame) should also be counted. + // + // The pallet holds transient storage with a size up to `max_transient_storage_size`. + // + // Finally, we allow 50% of the runtime memory to be utilized by the contracts call + // stack, keeping the rest for other facilities, such as PoV, etc. + // + // This gives us the following formula: + // + // `(MaxCodeLen * 17 * 4 + MAX_STACK_SIZE + max_heap_size) * max_call_depth + + // max_transient_storage_size < max_runtime_mem/2` + // + // Hence the upper limit for the `MaxCodeLen` can be defined as follows: + let code_len_limit = max_runtime_mem + .saturating_div(2) + .saturating_sub(max_transient_storage_size) + .saturating_div(max_call_depth) + .saturating_sub(max_heap_size) + .saturating_sub(MAX_STACK_SIZE) + .saturating_div(17 * 4); + + assert!( + T::MaxCodeLen::get() < code_len_limit, + "Given `CallStack` height {:?}, `MaxCodeLen` should be set less than {:?} \ + (current value is {:?}), to avoid possible runtime oom issues.", + max_call_depth, + code_len_limit, + T::MaxCodeLen::get(), + ); + + // Debug buffer should at least be large enough to accommodate a simple error message + const MIN_DEBUG_BUF_SIZE: u32 = 256; + assert!( + T::MaxDebugBufferLen::get() > MIN_DEBUG_BUF_SIZE, + "Debug buffer should have minimum size of {} (current setting is {})", + MIN_DEBUG_BUF_SIZE, + T::MaxDebugBufferLen::get(), + ); + + // Validators are configured to be able to use more memory than block builders. This is + // because in addition to `max_runtime_mem` they need to hold additional data in + // memory: PoV in multiple copies (1x encoded + 2x decoded) and all storage which + // includes emitted events. The assumption is that storage/events size + // can be a maximum of half of the validator runtime memory - max_runtime_mem. + let max_block_ref_time = T::BlockWeights::get() + .get(DispatchClass::Normal) + .max_total + .unwrap_or_else(|| T::BlockWeights::get().max_block) + .ref_time(); + let max_payload_size = T::Schedule::get().limits.payload_len; + let max_key_size = + Key::::try_from_var(alloc::vec![0u8; T::MaxStorageKeyLen::get() as usize]) + .expect("Key of maximal size shall be created") + .hash() + .len() as u32; + + // We can use storage to store items using the available block ref_time with the + // `set_storage` host function. + let max_storage_size: u32 = ((max_block_ref_time / + (>::weight(&RuntimeCosts::SetStorage { + new_bytes: max_payload_size, + old_bytes: 0, + }) + .ref_time())) + .saturating_mul(max_payload_size.saturating_add(max_key_size) as u64)) + .try_into() + .expect("Storage size too big"); + + let max_validator_runtime_mem: u32 = T::Schedule::get().limits.validator_runtime_memory; + let storage_size_limit = max_validator_runtime_mem.saturating_sub(max_runtime_mem) / 2; + + assert!( + max_storage_size < storage_size_limit, + "Maximal storage size {} exceeds the storage limit {}", + max_storage_size, + storage_size_limit + ); + + // We can use storage to store events using the available block ref_time with the + // `deposit_event` host function. The overhead of stored events, which is around 100B, + // is not taken into account to simplify calculations, as it does not change much. + let max_events_size: u32 = ((max_block_ref_time / + (>::weight(&RuntimeCosts::DepositEvent { + num_topic: 0, + len: max_payload_size, + }) + .ref_time())) + .saturating_mul(max_payload_size as u64)) + .try_into() + .expect("Events size too big"); + + assert!( + max_events_size < storage_size_limit, + "Maximal events size {} exceeds the events limit {}", + max_events_size, + storage_size_limit + ); + } + } + + #[pallet::call] + impl Pallet + where + as HasCompact>::Type: Clone + Eq + PartialEq + Debug + TypeInfo + Encode, + { + /// Deprecated version if [`Self::call`] for use in an in-storage `Call`. + #[pallet::call_index(0)] + #[pallet::weight(T::WeightInfo::call().saturating_add(>::compat_weight_limit(*gas_limit)))] + #[allow(deprecated)] + #[deprecated(note = "1D weight is used in this extrinsic, please migrate to `call`")] + pub fn call_old_weight( + origin: OriginFor, + dest: AccountIdLookupOf, + #[pallet::compact] value: BalanceOf, + #[pallet::compact] gas_limit: OldWeight, + storage_deposit_limit: Option< as codec::HasCompact>::Type>, + data: Vec, + ) -> DispatchResultWithPostInfo { + Self::call( + origin, + dest, + value, + >::compat_weight_limit(gas_limit), + storage_deposit_limit, + data, + ) + } + + /// Deprecated version if [`Self::instantiate_with_code`] for use in an in-storage `Call`. + #[pallet::call_index(1)] + #[pallet::weight( + T::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32, salt.len() as u32) + .saturating_add(>::compat_weight_limit(*gas_limit)) + )] + #[allow(deprecated)] + #[deprecated( + note = "1D weight is used in this extrinsic, please migrate to `instantiate_with_code`" + )] + pub fn instantiate_with_code_old_weight( + origin: OriginFor, + #[pallet::compact] value: BalanceOf, + #[pallet::compact] gas_limit: OldWeight, + storage_deposit_limit: Option< as codec::HasCompact>::Type>, + code: Vec, + data: Vec, + salt: Vec, + ) -> DispatchResultWithPostInfo { + Self::instantiate_with_code( + origin, + value, + >::compat_weight_limit(gas_limit), + storage_deposit_limit, + code, + data, + salt, + ) + } + + /// Deprecated version if [`Self::instantiate`] for use in an in-storage `Call`. + #[pallet::call_index(2)] + #[pallet::weight( + T::WeightInfo::instantiate(data.len() as u32, salt.len() as u32).saturating_add(>::compat_weight_limit(*gas_limit)) + )] + #[allow(deprecated)] + #[deprecated(note = "1D weight is used in this extrinsic, please migrate to `instantiate`")] + pub fn instantiate_old_weight( + origin: OriginFor, + #[pallet::compact] value: BalanceOf, + #[pallet::compact] gas_limit: OldWeight, + storage_deposit_limit: Option< as codec::HasCompact>::Type>, + code_hash: CodeHash, + data: Vec, + salt: Vec, + ) -> DispatchResultWithPostInfo { + Self::instantiate( + origin, + value, + >::compat_weight_limit(gas_limit), + storage_deposit_limit, + code_hash, + data, + salt, + ) + } + + /// Upload new `code` without instantiating a contract from it. + /// + /// If the code does not already exist a deposit is reserved from the caller + /// and unreserved only when [`Self::remove_code`] is called. The size of the reserve + /// depends on the size of the supplied `code`. + /// + /// If the code already exists in storage it will still return `Ok` and upgrades + /// the in storage version to the current + /// [`InstructionWeights::version`](InstructionWeights). + /// + /// - `determinism`: If this is set to any other value but [`Determinism::Enforced`] then + /// the only way to use this code is to delegate call into it from an offchain execution. + /// Set to [`Determinism::Enforced`] if in doubt. + /// + /// # Note + /// + /// Anyone can instantiate a contract from any uploaded code and thus prevent its removal. + /// To avoid this situation a constructor could employ access control so that it can + /// only be instantiated by permissioned entities. The same is true when uploading + /// through [`Self::instantiate_with_code`]. + /// + /// Use [`Determinism::Relaxed`] exclusively for non-deterministic code. If the uploaded + /// code is deterministic, specifying [`Determinism::Relaxed`] will be disregarded and + /// result in higher gas costs. + #[pallet::call_index(3)] + #[pallet::weight( + match determinism { + Determinism::Enforced => T::WeightInfo::upload_code_determinism_enforced(code.len() as u32), + Determinism::Relaxed => T::WeightInfo::upload_code_determinism_relaxed(code.len() as u32), + } + )] + pub fn upload_code( + origin: OriginFor, + code: Vec, + storage_deposit_limit: Option< as codec::HasCompact>::Type>, + determinism: Determinism, + ) -> DispatchResult { + Migration::::ensure_migrated()?; + let origin = T::UploadOrigin::ensure_origin(origin)?; + Self::bare_upload_code(origin, code, storage_deposit_limit.map(Into::into), determinism) + .map(|_| ()) + } + + /// Remove the code stored under `code_hash` and refund the deposit to its owner. + /// + /// A code can only be removed by its original uploader (its owner) and only if it is + /// not used by any contract. + #[pallet::call_index(4)] + #[pallet::weight(T::WeightInfo::remove_code())] + pub fn remove_code( + origin: OriginFor, + code_hash: CodeHash, + ) -> DispatchResultWithPostInfo { + Migration::::ensure_migrated()?; + let origin = ensure_signed(origin)?; + >::remove(&origin, code_hash)?; + // we waive the fee because removing unused code is beneficial + Ok(Pays::No.into()) + } + + /// Privileged function that changes the code of an existing contract. + /// + /// This takes care of updating refcounts and all other necessary operations. Returns + /// an error if either the `code_hash` or `dest` do not exist. + /// + /// # Note + /// + /// This does **not** change the address of the contract in question. This means + /// that the contract address is no longer derived from its code hash after calling + /// this dispatchable. + #[pallet::call_index(5)] + #[pallet::weight(T::WeightInfo::set_code())] + pub fn set_code( + origin: OriginFor, + dest: AccountIdLookupOf, + code_hash: CodeHash, + ) -> DispatchResult { + Migration::::ensure_migrated()?; + ensure_root(origin)?; + let dest = T::Lookup::lookup(dest)?; + >::try_mutate(&dest, |contract| { + let contract = if let Some(contract) = contract { + contract + } else { + return Err(>::ContractNotFound.into()) + }; + >>::increment_refcount(code_hash)?; + >>::decrement_refcount(contract.code_hash); + Self::deposit_event(Event::ContractCodeUpdated { + contract: dest.clone(), + new_code_hash: code_hash, + old_code_hash: contract.code_hash, + }); + contract.code_hash = code_hash; + Ok(()) + }) + } + + /// Makes a call to an account, optionally transferring some balance. + /// + /// # Parameters + /// + /// * `dest`: Address of the contract to call. + /// * `value`: The balance to transfer from the `origin` to `dest`. + /// * `gas_limit`: The gas limit enforced when executing the constructor. + /// * `storage_deposit_limit`: The maximum amount of balance that can be charged from the + /// caller to pay for the storage consumed. + /// * `data`: The input data to pass to the contract. + /// + /// * If the account is a smart-contract account, the associated code will be + /// executed and any value will be transferred. + /// * If the account is a regular account, any value will be transferred. + /// * If no account exists and the call value is not less than `existential_deposit`, + /// a regular account will be created and any value will be transferred. + #[pallet::call_index(6)] + #[pallet::weight(T::WeightInfo::call().saturating_add(*gas_limit))] + pub fn call( + origin: OriginFor, + dest: AccountIdLookupOf, + #[pallet::compact] value: BalanceOf, + gas_limit: Weight, + storage_deposit_limit: Option< as codec::HasCompact>::Type>, + data: Vec, + ) -> DispatchResultWithPostInfo { + Migration::::ensure_migrated()?; + let common = CommonInput { + origin: Origin::from_runtime_origin(origin)?, + value, + data, + gas_limit: gas_limit.into(), + storage_deposit_limit: storage_deposit_limit.map(Into::into), + debug_message: None, + }; + let dest = T::Lookup::lookup(dest)?; + let mut output = + CallInput:: { dest, determinism: Determinism::Enforced }.run_guarded(common); + if let Ok(retval) = &output.result { + if retval.did_revert() { + output.result = Err(>::ContractReverted.into()); + } + } + output.gas_meter.into_dispatch_result(output.result, T::WeightInfo::call()) + } + + /// Instantiates a new contract from the supplied `code` optionally transferring + /// some balance. + /// + /// This dispatchable has the same effect as calling [`Self::upload_code`] + + /// [`Self::instantiate`]. Bundling them together provides efficiency gains. Please + /// also check the documentation of [`Self::upload_code`]. + /// + /// # Parameters + /// + /// * `value`: The balance to transfer from the `origin` to the newly created contract. + /// * `gas_limit`: The gas limit enforced when executing the constructor. + /// * `storage_deposit_limit`: The maximum amount of balance that can be charged/reserved + /// from the caller to pay for the storage consumed. + /// * `code`: The contract code to deploy in raw bytes. + /// * `data`: The input data to pass to the contract constructor. + /// * `salt`: Used for the address derivation. See [`Pallet::contract_address`]. + /// + /// Instantiation is executed as follows: + /// + /// - The supplied `code` is deployed, and a `code_hash` is created for that code. + /// - If the `code_hash` already exists on the chain the underlying `code` will be shared. + /// - The destination address is computed based on the sender, code_hash and the salt. + /// - The smart-contract account is created at the computed address. + /// - The `value` is transferred to the new account. + /// - The `deploy` function is executed in the context of the newly-created account. + #[pallet::call_index(7)] + #[pallet::weight( + T::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32, salt.len() as u32) + .saturating_add(*gas_limit) + )] + pub fn instantiate_with_code( + origin: OriginFor, + #[pallet::compact] value: BalanceOf, + gas_limit: Weight, + storage_deposit_limit: Option< as codec::HasCompact>::Type>, + code: Vec, + data: Vec, + salt: Vec, + ) -> DispatchResultWithPostInfo { + Migration::::ensure_migrated()?; + + // These two origins will usually be the same; however, we treat them as separate since + // it is possible for the `Success` value of `UploadOrigin` and `InstantiateOrigin` to + // differ. + let upload_origin = T::UploadOrigin::ensure_origin(origin.clone())?; + let instantiate_origin = T::InstantiateOrigin::ensure_origin(origin)?; + + let code_len = code.len() as u32; + + let (module, upload_deposit) = Self::try_upload_code( + upload_origin, + code, + storage_deposit_limit.clone().map(Into::into), + Determinism::Enforced, + None, + )?; + + // Reduces the storage deposit limit by the amount that was reserved for the upload. + let storage_deposit_limit = + storage_deposit_limit.map(|limit| limit.into().saturating_sub(upload_deposit)); + + let data_len = data.len() as u32; + let salt_len = salt.len() as u32; + let common = CommonInput { + origin: Origin::from_account_id(instantiate_origin), + value, + data, + gas_limit, + storage_deposit_limit, + debug_message: None, + }; + + let mut output = + InstantiateInput:: { code: WasmCode::Wasm(module), salt }.run_guarded(common); + if let Ok(retval) = &output.result { + if retval.1.did_revert() { + output.result = Err(>::ContractReverted.into()); + } + } + + output.gas_meter.into_dispatch_result( + output.result.map(|(_address, output)| output), + T::WeightInfo::instantiate_with_code(code_len, data_len, salt_len), + ) + } + + /// Instantiates a contract from a previously deployed wasm binary. + /// + /// This function is identical to [`Self::instantiate_with_code`] but without the + /// code deployment step. Instead, the `code_hash` of an on-chain deployed wasm binary + /// must be supplied. + #[pallet::call_index(8)] + #[pallet::weight( + T::WeightInfo::instantiate(data.len() as u32, salt.len() as u32).saturating_add(*gas_limit) + )] + pub fn instantiate( + origin: OriginFor, + #[pallet::compact] value: BalanceOf, + gas_limit: Weight, + storage_deposit_limit: Option< as codec::HasCompact>::Type>, + code_hash: CodeHash, + data: Vec, + salt: Vec, + ) -> DispatchResultWithPostInfo { + Migration::::ensure_migrated()?; + let origin = T::InstantiateOrigin::ensure_origin(origin)?; + let data_len = data.len() as u32; + let salt_len = salt.len() as u32; + let common = CommonInput { + origin: Origin::from_account_id(origin), + value, + data, + gas_limit, + storage_deposit_limit: storage_deposit_limit.map(Into::into), + debug_message: None, + }; + let mut output = InstantiateInput:: { code: WasmCode::CodeHash(code_hash), salt } + .run_guarded(common); + if let Ok(retval) = &output.result { + if retval.1.did_revert() { + output.result = Err(>::ContractReverted.into()); + } + } + output.gas_meter.into_dispatch_result( + output.result.map(|(_address, output)| output), + T::WeightInfo::instantiate(data_len, salt_len), + ) + } + + /// When a migration is in progress, this dispatchable can be used to run migration steps. + /// Calls that contribute to advancing the migration have their fees waived, as it's helpful + /// for the chain. Note that while the migration is in progress, the pallet will also + /// leverage the `on_idle` hooks to run migration steps. + #[pallet::call_index(9)] + #[pallet::weight(T::WeightInfo::migrate().saturating_add(*weight_limit))] + pub fn migrate(origin: OriginFor, weight_limit: Weight) -> DispatchResultWithPostInfo { + use migration::MigrateResult::*; + ensure_signed(origin)?; + + let weight_limit = weight_limit.saturating_add(T::WeightInfo::migrate()); + let mut meter = WeightMeter::with_limit(weight_limit); + let result = Migration::::migrate(&mut meter); + + match result { + Completed => Ok(PostDispatchInfo { + actual_weight: Some(meter.consumed()), + pays_fee: Pays::No, + }), + InProgress { steps_done, .. } if steps_done > 0 => Ok(PostDispatchInfo { + actual_weight: Some(meter.consumed()), + pays_fee: Pays::No, + }), + InProgress { .. } => Ok(PostDispatchInfo { + actual_weight: Some(meter.consumed()), + pays_fee: Pays::Yes, + }), + NoMigrationInProgress | NoMigrationPerformed => { + let err: DispatchError = >::NoMigrationPerformed.into(); + Err(err.with_weight(meter.consumed())) + }, + } + } + } + + #[pallet::event] + pub enum Event { + /// Contract deployed by address at the specified address. + Instantiated { deployer: T::AccountId, contract: T::AccountId }, + + /// Contract has been removed. + /// + /// # Note + /// + /// The only way for a contract to be removed and emitting this event is by calling + /// `seal_terminate`. + Terminated { + /// The contract that was terminated. + contract: T::AccountId, + /// The account that received the contracts remaining balance + beneficiary: T::AccountId, + }, + + /// Code with the specified hash has been stored. + CodeStored { code_hash: T::Hash, deposit_held: BalanceOf, uploader: T::AccountId }, + + /// A custom event emitted by the contract. + ContractEmitted { + /// The contract that emitted the event. + contract: T::AccountId, + /// Data supplied by the contract. Metadata generated during contract compilation + /// is needed to decode it. + data: Vec, + }, + + /// A code with the specified hash was removed. + CodeRemoved { code_hash: T::Hash, deposit_released: BalanceOf, remover: T::AccountId }, + + /// A contract's code was updated. + ContractCodeUpdated { + /// The contract that has been updated. + contract: T::AccountId, + /// New code hash that was set for the contract. + new_code_hash: T::Hash, + /// Previous code hash of the contract. + old_code_hash: T::Hash, + }, + + /// A contract was called either by a plain account or another contract. + /// + /// # Note + /// + /// Please keep in mind that like all events this is only emitted for successful + /// calls. This is because on failure all storage changes including events are + /// rolled back. + Called { + /// The caller of the `contract`. + caller: Origin, + /// The contract that was called. + contract: T::AccountId, + }, + + /// A contract delegate called a code hash. + /// + /// # Note + /// + /// Please keep in mind that like all events this is only emitted for successful + /// calls. This is because on failure all storage changes including events are + /// rolled back. + DelegateCalled { + /// The contract that performed the delegate call and hence in whose context + /// the `code_hash` is executed. + contract: T::AccountId, + /// The code hash that was delegate called. + code_hash: CodeHash, + }, + + /// Some funds have been transferred and held as storage deposit. + StorageDepositTransferredAndHeld { + from: T::AccountId, + to: T::AccountId, + amount: BalanceOf, + }, + + /// Some storage deposit funds have been transferred and released. + StorageDepositTransferredAndReleased { + from: T::AccountId, + to: T::AccountId, + amount: BalanceOf, + }, + } + + #[pallet::error] + pub enum Error { + /// Invalid schedule supplied, e.g. with zero weight of a basic operation. + InvalidSchedule, + /// Invalid combination of flags supplied to `seal_call` or `seal_delegate_call`. + InvalidCallFlags, + /// The executed contract exhausted its gas limit. + OutOfGas, + /// The output buffer supplied to a contract API call was too small. + OutputBufferTooSmall, + /// Performing the requested transfer failed. Probably because there isn't enough + /// free balance in the sender's account. + TransferFailed, + /// Performing a call was denied because the calling depth reached the limit + /// of what is specified in the schedule. + MaxCallDepthReached, + /// No contract was found at the specified address. + ContractNotFound, + /// The code supplied to `instantiate_with_code` exceeds the limit specified in the + /// current schedule. + CodeTooLarge, + /// No code could be found at the supplied code hash. + CodeNotFound, + /// No code info could be found at the supplied code hash. + CodeInfoNotFound, + /// A buffer outside of sandbox memory was passed to a contract API function. + OutOfBounds, + /// Input passed to a contract API function failed to decode as expected type. + DecodingFailed, + /// Contract trapped during execution. + ContractTrapped, + /// The size defined in `T::MaxValueSize` was exceeded. + ValueTooLarge, + /// Termination of a contract is not allowed while the contract is already + /// on the call stack. Can be triggered by `seal_terminate`. + TerminatedWhileReentrant, + /// `seal_call` forwarded this contracts input. It therefore is no longer available. + InputForwarded, + /// The subject passed to `seal_random` exceeds the limit. + RandomSubjectTooLong, + /// The amount of topics passed to `seal_deposit_events` exceeds the limit. + TooManyTopics, + /// The chain does not provide a chain extension. Calling the chain extension results + /// in this error. Note that this usually shouldn't happen as deploying such contracts + /// is rejected. + NoChainExtension, + /// Failed to decode the XCM program. + XCMDecodeFailed, + /// A contract with the same AccountId already exists. + DuplicateContract, + /// A contract self destructed in its constructor. + /// + /// This can be triggered by a call to `seal_terminate`. + TerminatedInConstructor, + /// A call tried to invoke a contract that is flagged as non-reentrant. + /// The only other cause is that a call from a contract into the runtime tried to call back + /// into `pallet-contracts`. This would make the whole pallet reentrant with regard to + /// contract code execution which is not supported. + ReentranceDenied, + /// A contract attempted to invoke a state modifying API while being in read-only mode. + StateChangeDenied, + /// Origin doesn't have enough balance to pay the required storage deposits. + StorageDepositNotEnoughFunds, + /// More storage was created than allowed by the storage deposit limit. + StorageDepositLimitExhausted, + /// Code removal was denied because the code is still in use by at least one contract. + CodeInUse, + /// The contract ran to completion but decided to revert its storage changes. + /// Please note that this error is only returned from extrinsics. When called directly + /// or via RPC an `Ok` will be returned. In this case the caller needs to inspect the flags + /// to determine whether a reversion has taken place. + ContractReverted, + /// The contract's code was found to be invalid during validation. + /// + /// The most likely cause of this is that an API was used which is not supported by the + /// node. This happens if an older node is used with a new version of ink!. Try updating + /// your node to the newest available version. + /// + /// A more detailed error can be found on the node console if debug messages are enabled + /// by supplying `-lruntime::contracts=debug`. + CodeRejected, + /// An indeterministic code was used in a context where this is not permitted. + Indeterministic, + /// A pending migration needs to complete before the extrinsic can be called. + MigrationInProgress, + /// Migrate dispatch call was attempted but no migration was performed. + NoMigrationPerformed, + /// The contract has reached its maximum number of delegate dependencies. + MaxDelegateDependenciesReached, + /// The dependency was not found in the contract's delegate dependencies. + DelegateDependencyNotFound, + /// The contract already depends on the given delegate dependency. + DelegateDependencyAlreadyExists, + /// Can not add a delegate dependency to the code hash of the contract itself. + CannotAddSelfAsDelegateDependency, + /// Can not add more data to transient storage. + OutOfTransientStorage, + } + + /// A reason for the pallet contracts placing a hold on funds. + #[pallet::composite_enum] + pub enum HoldReason { + /// The Pallet has reserved it for storing code on-chain. + CodeUploadDepositReserve, + /// The Pallet has reserved it for storage deposit. + StorageDepositReserve, + } + + /// A mapping from a contract's code hash to its code. + #[pallet::storage] + pub(crate) type PristineCode = StorageMap<_, Identity, CodeHash, CodeVec>; + + /// A mapping from a contract's code hash to its code info. + #[pallet::storage] + pub(crate) type CodeInfoOf = StorageMap<_, Identity, CodeHash, CodeInfo>; + + /// This is a **monotonic** counter incremented on contract instantiation. + /// + /// This is used in order to generate unique trie ids for contracts. + /// The trie id of a new contract is calculated from hash(account_id, nonce). + /// The nonce is required because otherwise the following sequence would lead to + /// a possible collision of storage: + /// + /// 1. Create a new contract. + /// 2. Terminate the contract. + /// 3. Immediately recreate the contract with the same account_id. + /// + /// This is bad because the contents of a trie are deleted lazily and there might be + /// storage of the old instantiation still in it when the new contract is created. Please + /// note that we can't replace the counter by the block number because the sequence above + /// can happen in the same block. We also can't keep the account counter in memory only + /// because storage is the only way to communicate across different extrinsics in the + /// same block. + /// + /// # Note + /// + /// Do not use it to determine the number of contracts. It won't be decremented if + /// a contract is destroyed. + #[pallet::storage] + pub(crate) type Nonce = StorageValue<_, u64, ValueQuery>; + + /// The code associated with a given account. + /// + /// TWOX-NOTE: SAFE since `AccountId` is a secure hash. + #[pallet::storage] + pub(crate) type ContractInfoOf = + StorageMap<_, Twox64Concat, T::AccountId, ContractInfo>; + + /// Evicted contracts that await child trie deletion. + /// + /// Child trie deletion is a heavy operation depending on the amount of storage items + /// stored in said trie. Therefore this operation is performed lazily in `on_idle`. + #[pallet::storage] + pub(crate) type DeletionQueue = StorageMap<_, Twox64Concat, u32, TrieId>; + + /// A pair of monotonic counters used to track the latest contract marked for deletion + /// and the latest deleted contract in queue. + #[pallet::storage] + pub(crate) type DeletionQueueCounter = + StorageValue<_, DeletionQueueManager, ValueQuery>; + + /// A migration can span across multiple blocks. This storage defines a cursor to track the + /// progress of the migration, enabling us to resume from the last completed position. + #[pallet::storage] + pub(crate) type MigrationInProgress = + StorageValue<_, migration::Cursor, OptionQuery>; +} + +/// The type of origins supported by the contracts pallet. +#[derive(Clone, Encode, Decode, PartialEq, TypeInfo, RuntimeDebugNoBound)] +pub enum Origin { + Root, + Signed(T::AccountId), +} + +impl Origin { + /// Creates a new Signed Caller from an AccountId. + pub fn from_account_id(account_id: T::AccountId) -> Self { + Origin::Signed(account_id) + } + /// Creates a new Origin from a `RuntimeOrigin`. + pub fn from_runtime_origin(o: OriginFor) -> Result { + match o.into() { + Ok(RawOrigin::Root) => Ok(Self::Root), + Ok(RawOrigin::Signed(t)) => Ok(Self::Signed(t)), + _ => Err(BadOrigin.into()), + } + } + /// Returns the AccountId of a Signed Origin or an error if the origin is Root. + pub fn account_id(&self) -> Result<&T::AccountId, DispatchError> { + match self { + Origin::Signed(id) => Ok(id), + Origin::Root => Err(DispatchError::RootNotAllowed), + } + } +} + +/// Context of a contract invocation. +struct CommonInput<'a, T: Config> { + origin: Origin, + value: BalanceOf, + data: Vec, + gas_limit: Weight, + storage_deposit_limit: Option>, + debug_message: Option<&'a mut DebugBufferVec>, +} + +/// Input specific to a call into contract. +struct CallInput { + dest: T::AccountId, + determinism: Determinism, +} + +/// Reference to an existing code hash or a new wasm module. +enum WasmCode { + Wasm(WasmBlob), + CodeHash(CodeHash), +} + +/// Input specific to a contract instantiation invocation. +struct InstantiateInput { + code: WasmCode, + salt: Vec, +} + +/// Determines whether events should be collected during execution. +#[derive( + Copy, Clone, PartialEq, Eq, RuntimeDebug, Decode, Encode, MaxEncodedLen, scale_info::TypeInfo, +)] +pub enum CollectEvents { + /// Collect events. + /// + /// # Note + /// + /// Events should only be collected when called off-chain, as this would otherwise + /// collect all the Events emitted in the block so far and put them into the PoV. + /// + /// **Never** use this mode for on-chain execution. + UnsafeCollect, + /// Skip event collection. + Skip, +} + +/// Determines whether debug messages will be collected. +#[derive( + Copy, Clone, PartialEq, Eq, RuntimeDebug, Decode, Encode, MaxEncodedLen, scale_info::TypeInfo, +)] +pub enum DebugInfo { + /// Collect debug messages. + /// # Note + /// + /// This should only ever be set to `UnsafeDebug` when executing as an RPC because + /// it adds allocations and could be abused to drive the runtime into an OOM panic. + UnsafeDebug, + /// Skip collection of debug messages. + Skip, +} + +/// Return type of private helper functions. +struct InternalOutput { + /// The gas meter that was used to execute the call. + gas_meter: GasMeter, + /// The storage deposit used by the call. + storage_deposit: StorageDeposit>, + /// The result of the call. + result: Result, +} + +// Set up a global reference to the boolean flag used for the re-entrancy guard. +environmental!(executing_contract: bool); + +/// Helper trait to wrap contract execution entry points into a single function +/// [`Invokable::run_guarded`]. +trait Invokable: Sized { + /// What is returned as a result of a successful invocation. + type Output; + + /// Single entry point to contract execution. + /// Downstream execution flow is branched by implementations of [`Invokable`] trait: + /// + /// - [`InstantiateInput::run`] runs contract instantiation, + /// - [`CallInput::run`] runs contract call. + /// + /// We enforce a re-entrancy guard here by initializing and checking a boolean flag through a + /// global reference. + fn run_guarded(self, common: CommonInput) -> InternalOutput { + let gas_limit = common.gas_limit; + + // Check whether the origin is allowed here. The logic of the access rules + // is in the `ensure_origin`, this could vary for different implementations of this + // trait. For example, some actions might not allow Root origin as they could require an + // AccountId associated with the origin. + if let Err(e) = self.ensure_origin(common.origin.clone()) { + return InternalOutput { + gas_meter: GasMeter::new(gas_limit), + storage_deposit: Default::default(), + result: Err(ExecError { error: e.into(), origin: ErrorOrigin::Caller }), + } + } + + executing_contract::using_once(&mut false, || { + executing_contract::with(|f| { + // Fail if already entered contract execution + if *f { + return Err(()) + } + // We are entering contract execution + *f = true; + Ok(()) + }) + .expect("Returns `Ok` if called within `using_once`. It is syntactically obvious that this is the case; qed") + .map_or_else( + |_| InternalOutput { + gas_meter: GasMeter::new(gas_limit), + storage_deposit: Default::default(), + result: Err(ExecError { + error: >::ReentranceDenied.into(), + origin: ErrorOrigin::Caller, + }), + }, + // Enter contract call. + |_| self.run(common, GasMeter::new(gas_limit)), + ) + }) + } + + /// Method that does the actual call to a contract. It can be either a call to a deployed + /// contract or a instantiation of a new one. + /// + /// Called by dispatchables and public functions through the [`Invokable::run_guarded`]. + fn run(self, common: CommonInput, gas_meter: GasMeter) + -> InternalOutput; + + /// This method ensures that the given `origin` is allowed to invoke the current `Invokable`. + /// + /// Called by dispatchables and public functions through the [`Invokable::run_guarded`]. + fn ensure_origin(&self, origin: Origin) -> Result<(), DispatchError>; +} + +impl Invokable for CallInput { + type Output = ExecReturnValue; + + fn run( + self, + common: CommonInput, + mut gas_meter: GasMeter, + ) -> InternalOutput { + let CallInput { dest, determinism } = self; + let CommonInput { origin, value, data, debug_message, .. } = common; + let mut storage_meter = + match StorageMeter::new(&origin, common.storage_deposit_limit, common.value) { + Ok(meter) => meter, + Err(err) => + return InternalOutput { + result: Err(err.into()), + gas_meter, + storage_deposit: Default::default(), + }, + }; + let schedule = T::Schedule::get(); + let result = ExecStack::>::run_call( + origin.clone(), + dest.clone(), + &mut gas_meter, + &mut storage_meter, + &schedule, + value, + data.clone(), + debug_message, + determinism, + ); + + match storage_meter.try_into_deposit(&origin) { + Ok(storage_deposit) => InternalOutput { gas_meter, storage_deposit, result }, + Err(err) => InternalOutput { + gas_meter, + storage_deposit: Default::default(), + result: Err(err.into()), + }, + } + } + + fn ensure_origin(&self, _origin: Origin) -> Result<(), DispatchError> { + Ok(()) + } +} + +impl Invokable for InstantiateInput { + type Output = (AccountIdOf, ExecReturnValue); + + fn run( + self, + common: CommonInput, + mut gas_meter: GasMeter, + ) -> InternalOutput { + let mut storage_deposit = Default::default(); + let try_exec = || { + let schedule = T::Schedule::get(); + let InstantiateInput { salt, .. } = self; + let CommonInput { origin: contract_origin, .. } = common; + let origin = contract_origin.account_id()?; + + let executable = match self.code { + WasmCode::Wasm(module) => module, + WasmCode::CodeHash(code_hash) => WasmBlob::from_storage(code_hash, &mut gas_meter)?, + }; + + let contract_origin = Origin::from_account_id(origin.clone()); + let mut storage_meter = + StorageMeter::new(&contract_origin, common.storage_deposit_limit, common.value)?; + let CommonInput { value, data, debug_message, .. } = common; + let result = ExecStack::>::run_instantiate( + origin.clone(), + executable, + &mut gas_meter, + &mut storage_meter, + &schedule, + value, + data.clone(), + &salt, + debug_message, + ); + + storage_deposit = storage_meter.try_into_deposit(&contract_origin)?; + result + }; + InternalOutput { result: try_exec(), gas_meter, storage_deposit } + } + + fn ensure_origin(&self, origin: Origin) -> Result<(), DispatchError> { + match origin { + Origin::Signed(_) => Ok(()), + Origin::Root => Err(DispatchError::RootNotAllowed), + } + } +} + +macro_rules! ensure_no_migration_in_progress { + () => { + if Migration::::in_progress() { + return ContractResult { + gas_consumed: Zero::zero(), + gas_required: Zero::zero(), + storage_deposit: Default::default(), + debug_message: Vec::new(), + result: Err(Error::::MigrationInProgress.into()), + events: None, + } + } + }; +} + +impl Pallet { + /// Perform a call to a specified contract. + /// + /// This function is similar to [`Self::call`], but doesn't perform any address lookups + /// and better suitable for calling directly from Rust. + /// + /// # Note + /// + /// If `debug` is set to `DebugInfo::UnsafeDebug` it returns additional human readable debugging + /// information. + /// + /// If `collect_events` is set to `CollectEvents::UnsafeCollect` it collects all the Events + /// emitted in the block so far and the ones emitted during the execution of this contract. + pub fn bare_call( + origin: T::AccountId, + dest: T::AccountId, + value: BalanceOf, + gas_limit: Weight, + storage_deposit_limit: Option>, + data: Vec, + debug: DebugInfo, + collect_events: CollectEvents, + determinism: Determinism, + ) -> ContractExecResult, EventRecordOf> { + ensure_no_migration_in_progress!(); + + let mut debug_message = if matches!(debug, DebugInfo::UnsafeDebug) { + Some(DebugBufferVec::::default()) + } else { + None + }; + let origin = Origin::from_account_id(origin); + let common = CommonInput { + origin, + value, + data, + gas_limit, + storage_deposit_limit, + debug_message: debug_message.as_mut(), + }; + let output = CallInput:: { dest, determinism }.run_guarded(common); + let events = if matches!(collect_events, CollectEvents::UnsafeCollect) { + Some(System::::read_events_no_consensus().map(|e| *e).collect()) + } else { + None + }; + + ContractExecResult { + result: output.result.map_err(|r| r.error), + gas_consumed: output.gas_meter.gas_consumed(), + gas_required: output.gas_meter.gas_required(), + storage_deposit: output.storage_deposit, + debug_message: debug_message.unwrap_or_default().to_vec(), + events, + } + } + + /// Instantiate a new contract. + /// + /// This function is similar to [`Self::instantiate`], but doesn't perform any address lookups + /// and better suitable for calling directly from Rust. + /// + /// It returns the execution result, account id and the amount of used weight. + /// + /// # Note + /// + /// If `debug` is set to `DebugInfo::UnsafeDebug` it returns additional human readable debugging + /// information. + /// + /// If `collect_events` is set to `CollectEvents::UnsafeCollect` it collects all the Events + /// emitted in the block so far. + pub fn bare_instantiate( + origin: T::AccountId, + value: BalanceOf, + gas_limit: Weight, + mut storage_deposit_limit: Option>, + code: Code>, + data: Vec, + salt: Vec, + debug: DebugInfo, + collect_events: CollectEvents, + ) -> ContractInstantiateResult, EventRecordOf> { + ensure_no_migration_in_progress!(); + + let mut debug_message = if debug == DebugInfo::UnsafeDebug { + Some(DebugBufferVec::::default()) + } else { + None + }; + // collect events if CollectEvents is UnsafeCollect + let events = || { + if collect_events == CollectEvents::UnsafeCollect { + Some(System::::read_events_no_consensus().map(|e| *e).collect()) + } else { + None + } + }; + + let (code, upload_deposit): (WasmCode, BalanceOf) = match code { + Code::Upload(code) => { + let result = Self::try_upload_code( + origin.clone(), + code, + storage_deposit_limit.map(Into::into), + Determinism::Enforced, + debug_message.as_mut(), + ); + + let (module, deposit) = match result { + Ok(result) => result, + Err(error) => + return ContractResult { + gas_consumed: Zero::zero(), + gas_required: Zero::zero(), + storage_deposit: Default::default(), + debug_message: debug_message.unwrap_or(Default::default()).into(), + result: Err(error), + events: events(), + }, + }; + + storage_deposit_limit = + storage_deposit_limit.map(|l| l.saturating_sub(deposit.into())); + (WasmCode::Wasm(module), deposit) + }, + Code::Existing(hash) => (WasmCode::CodeHash(hash), Default::default()), + }; + + let common = CommonInput { + origin: Origin::from_account_id(origin), + value, + data, + gas_limit, + storage_deposit_limit, + debug_message: debug_message.as_mut(), + }; + + let output = InstantiateInput:: { code, salt }.run_guarded(common); + ContractInstantiateResult { + result: output + .result + .map(|(account_id, result)| InstantiateReturnValue { result, account_id }) + .map_err(|e| e.error), + gas_consumed: output.gas_meter.gas_consumed(), + gas_required: output.gas_meter.gas_required(), + storage_deposit: output + .storage_deposit + .saturating_add(&StorageDeposit::Charge(upload_deposit)), + debug_message: debug_message.unwrap_or_default().to_vec(), + events: events(), + } + } + + /// Upload new code without instantiating a contract from it. + /// + /// This function is similar to [`Self::upload_code`], but doesn't perform any address lookups + /// and better suitable for calling directly from Rust. + pub fn bare_upload_code( + origin: T::AccountId, + code: Vec, + storage_deposit_limit: Option>, + determinism: Determinism, + ) -> CodeUploadResult, BalanceOf> { + Migration::::ensure_migrated()?; + let (module, deposit) = + Self::try_upload_code(origin, code, storage_deposit_limit, determinism, None)?; + Ok(CodeUploadReturnValue { code_hash: *module.code_hash(), deposit }) + } + + /// Uploads new code and returns the Wasm blob and deposit amount collected. + fn try_upload_code( + origin: T::AccountId, + code: Vec, + storage_deposit_limit: Option>, + determinism: Determinism, + mut debug_message: Option<&mut DebugBufferVec>, + ) -> Result<(WasmBlob, BalanceOf), DispatchError> { + let schedule = T::Schedule::get(); + let mut module = + WasmBlob::from_code(code, &schedule, origin, determinism).map_err(|(err, msg)| { + debug_message.as_mut().map(|d| d.try_extend(msg.bytes())); + err + })?; + let deposit = module.store_code()?; + if let Some(storage_deposit_limit) = storage_deposit_limit { + ensure!(storage_deposit_limit >= deposit, >::StorageDepositLimitExhausted); + } + + Ok((module, deposit)) + } + + /// Query storage of a specified contract under a specified key. + pub fn get_storage(address: T::AccountId, key: Vec) -> GetStorageResult { + if Migration::::in_progress() { + return Err(ContractAccessError::MigrationInProgress) + } + let contract_info = + ContractInfoOf::::get(&address).ok_or(ContractAccessError::DoesntExist)?; + + let maybe_value = contract_info.read( + &Key::::try_from_var(key) + .map_err(|_| ContractAccessError::KeyDecodingFailed)? + .into(), + ); + Ok(maybe_value) + } + + /// Determine the address of a contract. + /// + /// This is the address generation function used by contract instantiation. See + /// [`DefaultAddressGenerator`] for the default implementation. + pub fn contract_address( + deploying_address: &T::AccountId, + code_hash: &CodeHash, + input_data: &[u8], + salt: &[u8], + ) -> T::AccountId { + T::AddressGenerator::contract_address(deploying_address, code_hash, input_data, salt) + } + + /// Returns the code hash of the contract specified by `account` ID. + pub fn code_hash(account: &AccountIdOf) -> Option> { + ContractInfo::::load_code_hash(account) + } + + /// Store code for benchmarks which does not validate the code. + #[cfg(feature = "runtime-benchmarks")] + fn store_code_raw( + code: Vec, + owner: T::AccountId, + ) -> frame_support::dispatch::DispatchResult { + let schedule = T::Schedule::get(); + WasmBlob::::from_code_unchecked(code, &schedule, owner)?.store_code()?; + Ok(()) + } + + /// Deposit a pallet contracts event. + fn deposit_event(event: Event) { + >::deposit_event(::RuntimeEvent::from(event)) + } + + /// Deposit a pallet contracts indexed event. + fn deposit_indexed_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() + } + + /// Convert gas_limit from 1D Weight to a 2D Weight. + /// + /// Used by backwards compatible extrinsics. We cannot just set the proof_size weight limit to + /// zero or an old `Call` will just fail with OutOfGas. + fn compat_weight_limit(gas_limit: OldWeight) -> Weight { + Weight::from_parts(gas_limit, u64::from(T::MaxCodeLen::get()) * 2) + } +} + +sp_api::decl_runtime_apis! { + /// The API used to dry-run contract interactions. + #[api_version(2)] + pub trait ContractsApi where + AccountId: Codec, + Balance: Codec, + BlockNumber: Codec, + Hash: Codec, + EventRecord: Codec, + { + /// Perform a call from a specified account to a given contract. + /// + /// See [`crate::Pallet::bare_call`]. + fn call( + origin: AccountId, + dest: AccountId, + value: Balance, + gas_limit: Option, + storage_deposit_limit: Option, + input_data: Vec, + ) -> ContractExecResult; + + /// Instantiate a new contract. + /// + /// See `[crate::Pallet::bare_instantiate]`. + fn instantiate( + origin: AccountId, + value: Balance, + gas_limit: Option, + storage_deposit_limit: Option, + code: Code, + data: Vec, + salt: Vec, + ) -> ContractInstantiateResult; + + /// Upload new code without instantiating a contract from it. + /// + /// See [`crate::Pallet::bare_upload_code`]. + fn upload_code( + origin: AccountId, + code: Vec, + storage_deposit_limit: Option, + determinism: Determinism, + ) -> CodeUploadResult; + + /// Query a given storage key in a given contract. + /// + /// Returns `Ok(Some(Vec))` if the storage value exists under the given key in the + /// specified account and `Ok(None)` if it doesn't. If the account specified by the address + /// doesn't exist, or doesn't have a contract then `Err` is returned. + fn get_storage( + address: AccountId, + key: Vec, + ) -> GetStorageResult; + } +} diff --git a/pallets/contracts/src/migration.rs b/pallets/contracts/src/migration.rs new file mode 100644 index 00000000..29ac74d0 --- /dev/null +++ b/pallets/contracts/src/migration.rs @@ -0,0 +1,658 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Multi-block Migration framework for pallet-contracts. +//! +//! This module allows us to define a migration as a sequence of [`MigrationStep`]s that can be +//! executed across multiple blocks. +//! +//! # Usage +//! +//! A migration step is defined under `src/migration/vX.rs`, where `X` is the version number. +//! For example, `vX.rs` defines a migration from version `X - 1` to version `X`. +//! +//! ## Example: +//! +//! To configure a migration to `v11` for a runtime using `v10` of pallet-contracts on the chain, +//! you would set the `Migrations` type as follows: +//! +//! ``` +//! use pallet_contracts::migration::{v10, v11}; +//! # pub enum Runtime {}; +//! # struct Currency; +//! type Migrations = (v10::Migration, v11::Migration); +//! ``` +//! +//! ## Notes: +//! +//! - Migrations should always be tested with `try-runtime` before being deployed. +//! - By testing with `try-runtime` against a live network, you ensure that all migration steps work +//! and that you have included the required steps. +//! +//! ## Low Level / Implementation Details +//! +//! When a migration starts and [`OnRuntimeUpgrade::on_runtime_upgrade`] is called, instead of +//! performing the actual migration, we set a custom storage item [`MigrationInProgress`]. +//! This storage item defines a [`Cursor`] for the current migration. +//! +//! If the [`MigrationInProgress`] storage item exists, it means a migration is in progress, and its +//! value holds a cursor for the current migration step. These migration steps are executed during +//! [`Hooks::on_idle`] or when the [`Pallet::migrate`] dispatchable is +//! called. +//! +//! While the migration is in progress, all dispatchables except `migrate`, are blocked, and returns +//! a `MigrationInProgress` error. + +pub mod v09; +pub mod v10; +pub mod v11; +pub mod v12; +pub mod v13; +pub mod v14; +pub mod v15; +pub mod v16; +include!(concat!(env!("OUT_DIR"), "/migration_codegen.rs")); + +use crate::{weights::WeightInfo, Config, Error, MigrationInProgress, Pallet, Weight, LOG_TARGET}; +use codec::{Codec, Decode}; +use core::marker::PhantomData; +use frame_support::{ + pallet_prelude::*, + traits::{ConstU32, OnRuntimeUpgrade}, + weights::WeightMeter, +}; +use sp_runtime::Saturating; + +#[cfg(feature = "try-runtime")] +use alloc::vec::Vec; +#[cfg(feature = "try-runtime")] +use sp_runtime::TryRuntimeError; + +const PROOF_ENCODE: &str = "Tuple::max_encoded_len() < Cursor::max_encoded_len()` is verified in `Self::integrity_test()`; qed"; +const PROOF_DECODE: &str = + "We encode to the same type in this trait only. No other code touches this item; qed"; + +fn invalid_version(version: StorageVersion) -> ! { + panic!("Required migration {version:?} not supported by this runtime. This is a bug."); +} + +/// The cursor used to encode the position (usually the last iterated key) of the current migration +/// step. +pub type Cursor = BoundedVec>; + +/// IsFinished describes whether a migration is finished or not. +pub enum IsFinished { + Yes, + No, +} + +/// A trait that allows to migrate storage from one version to another. +/// +/// The migration is done in steps. The migration is finished when +/// `step()` returns `IsFinished::Yes`. +pub trait MigrationStep: Codec + MaxEncodedLen + Default { + /// Returns the version of the migration. + const VERSION: u16; + + /// Returns the maximum weight that can be consumed in a single step. + fn max_step_weight() -> Weight; + + /// Process one step of the migration. + /// + /// Returns whether the migration is finished. + fn step(&mut self, meter: &mut WeightMeter) -> IsFinished; + + /// Verify that the migration step fits into `Cursor`, and that `max_step_weight` is not greater + /// than `max_block_weight`. + fn integrity_test(max_block_weight: Weight) { + if Self::max_step_weight().any_gt(max_block_weight) { + panic!( + "Invalid max_step_weight for Migration {}. Value should be lower than {}", + Self::VERSION, + max_block_weight + ); + } + + let len = ::max_encoded_len(); + let max = Cursor::bound(); + if len > max { + panic!( + "Migration {} has size {} which is bigger than the maximum of {}", + Self::VERSION, + len, + max, + ); + } + } + + /// Execute some pre-checks prior to running the first step of this migration. + #[cfg(feature = "try-runtime")] + fn pre_upgrade_step() -> Result, TryRuntimeError> { + Ok(Vec::new()) + } + + /// Execute some post-checks after running the last step of this migration. + #[cfg(feature = "try-runtime")] + fn post_upgrade_step(_state: Vec) -> Result<(), TryRuntimeError> { + Ok(()) + } +} + +/// A noop migration that can be used when there is no migration to be done for a given version. +#[doc(hidden)] +#[derive(frame_support::DefaultNoBound, Encode, Decode, MaxEncodedLen)] +pub struct NoopMigration; + +impl MigrationStep for NoopMigration { + const VERSION: u16 = N; + fn max_step_weight() -> Weight { + Weight::zero() + } + fn step(&mut self, _meter: &mut WeightMeter) -> IsFinished { + log::debug!(target: LOG_TARGET, "Noop migration for version {}", N); + IsFinished::Yes + } +} + +mod private { + use crate::migration::MigrationStep; + pub trait Sealed {} + #[impl_trait_for_tuples::impl_for_tuples(10)] + #[tuple_types_custom_trait_bound(MigrationStep)] + impl Sealed for Tuple {} +} + +/// Defines a sequence of migrations. +/// +/// The sequence must be defined by a tuple of migrations, each of which must implement the +/// `MigrationStep` trait. Migrations must be ordered by their versions with no gaps. +pub trait MigrateSequence: private::Sealed { + /// Returns the range of versions that this migrations sequence can handle. + /// Migrations must be ordered by their versions with no gaps. + /// + /// The following code will fail to compile: + /// + /// ```compile_fail + /// # use pallet_contracts::{NoopMigration, MigrateSequence}; + /// let _ = <(NoopMigration<1>, NoopMigration<3>)>::VERSION_RANGE; + /// ``` + /// The following code will compile: + /// ``` + /// # use pallet_contracts::{NoopMigration, MigrateSequence}; + /// let _ = <(NoopMigration<1>, NoopMigration<2>)>::VERSION_RANGE; + /// ``` + const VERSION_RANGE: (u16, u16); + + /// Returns the default cursor for the given version. + fn new(version: StorageVersion) -> Cursor; + + #[cfg(feature = "try-runtime")] + fn pre_upgrade_step(_version: StorageVersion) -> Result, TryRuntimeError> { + Ok(Vec::new()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade_step(_version: StorageVersion, _state: Vec) -> Result<(), TryRuntimeError> { + Ok(()) + } + + /// Execute the migration step until the available weight is consumed. + fn steps(version: StorageVersion, cursor: &[u8], meter: &mut WeightMeter) -> StepResult; + + /// Verify that the migration step fits into `Cursor`, and that `max_step_weight` is not greater + /// than `max_block_weight`. + fn integrity_test(max_block_weight: Weight); + + /// Returns whether migrating from `in_storage` to `target` is supported. + /// + /// A migration is supported if `VERSION_RANGE` is (in_storage + 1, target). + fn is_upgrade_supported(in_storage: StorageVersion, target: StorageVersion) -> bool { + let (low, high) = Self::VERSION_RANGE; + target == high && in_storage + 1 == low + } +} + +/// Performs all necessary migrations based on `StorageVersion`. +/// +/// If `TEST_ALL_STEPS == true` and `try-runtime` is enabled, this will run all the migrations +/// inside `on_runtime_upgrade`. This should be set to false in tests that want to ensure the step +/// by step migration works. +pub struct Migration(PhantomData); + +#[cfg(feature = "try-runtime")] +impl Migration { + fn run_all_steps() -> Result<(), TryRuntimeError> { + let mut meter = &mut WeightMeter::new(); + let name = >::name(); + loop { + let in_progress_version = >::on_chain_storage_version() + 1; + let state = T::Migrations::pre_upgrade_step(in_progress_version)?; + let before = meter.consumed(); + let status = Self::migrate(&mut meter); + log::info!( + target: LOG_TARGET, + "{name}: Migration step {:?} weight = {}", + in_progress_version, + meter.consumed() - before + ); + T::Migrations::post_upgrade_step(in_progress_version, state)?; + if matches!(status, MigrateResult::Completed) { + break + } + } + + let name = >::name(); + log::info!(target: LOG_TARGET, "{name}: Migration steps weight = {}", meter.consumed()); + Ok(()) + } +} + +impl OnRuntimeUpgrade for Migration { + fn on_runtime_upgrade() -> Weight { + let name = >::name(); + let in_code_version = >::in_code_storage_version(); + let on_chain_version = >::on_chain_storage_version(); + + if on_chain_version == in_code_version { + log::warn!( + target: LOG_TARGET, + "{name}: No Migration performed storage_version = latest_version = {:?}", + &on_chain_version + ); + return T::WeightInfo::on_runtime_upgrade_noop() + } + + // In case a migration is already in progress we create the next migration + // (if any) right when the current one finishes. + if Self::in_progress() { + log::warn!( + target: LOG_TARGET, + "{name}: Migration already in progress {:?}", + &on_chain_version + ); + + return T::WeightInfo::on_runtime_upgrade_in_progress() + } + + log::info!( + target: LOG_TARGET, + "{name}: Upgrading storage from {on_chain_version:?} to {in_code_version:?}.", + ); + + let cursor = T::Migrations::new(on_chain_version + 1); + MigrationInProgress::::set(Some(cursor)); + + #[cfg(feature = "try-runtime")] + if TEST_ALL_STEPS { + Self::run_all_steps().unwrap(); + } + + T::WeightInfo::on_runtime_upgrade() + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, TryRuntimeError> { + // We can't really do much here as our migrations do not happen during the runtime upgrade. + // Instead, we call the migrations `pre_upgrade` and `post_upgrade` hooks when we iterate + // over our migrations. + let on_chain_version = >::on_chain_storage_version(); + let in_code_version = >::in_code_storage_version(); + + if on_chain_version == in_code_version { + return Ok(Default::default()) + } + + log::debug!( + target: LOG_TARGET, + "Requested migration of {} from {:?}(on-chain storage version) to {:?}(in-code storage version)", + >::name(), on_chain_version, in_code_version + ); + + ensure!( + T::Migrations::is_upgrade_supported(on_chain_version, in_code_version), + "Unsupported upgrade: VERSION_RANGE should be (on-chain storage version + 1, in-code storage version)" + ); + + Ok(Default::default()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(_state: Vec) -> Result<(), TryRuntimeError> { + if !TEST_ALL_STEPS { + return Ok(()) + } + + log::info!(target: LOG_TARGET, "=== POST UPGRADE CHECKS ==="); + + // Ensure that the hashing algorithm is correct for each storage map. + if let Some(hash) = crate::CodeInfoOf::::iter_keys().next() { + crate::CodeInfoOf::::get(hash).expect("CodeInfo exists for hash; qed"); + } + if let Some(hash) = crate::PristineCode::::iter_keys().next() { + crate::PristineCode::::get(hash).expect("PristineCode exists for hash; qed"); + } + if let Some(account_id) = crate::ContractInfoOf::::iter_keys().next() { + crate::ContractInfoOf::::get(account_id) + .expect("ContractInfo exists for account_id; qed"); + } + if let Some(nonce) = crate::DeletionQueue::::iter_keys().next() { + crate::DeletionQueue::::get(nonce).expect("DeletionQueue exists for nonce; qed"); + } + + Ok(()) + } +} + +/// The result of running the migration. +#[derive(Debug, PartialEq)] +pub enum MigrateResult { + /// No migration was performed + NoMigrationPerformed, + /// No migration currently in progress + NoMigrationInProgress, + /// A migration is in progress + InProgress { steps_done: u32 }, + /// All migrations are completed + Completed, +} + +/// The result of running a migration step. +#[derive(Debug, PartialEq)] +pub enum StepResult { + InProgress { cursor: Cursor, steps_done: u32 }, + Completed { steps_done: u32 }, +} + +impl Migration { + /// Verify that each migration's step of the [`Config::Migrations`] sequence fits into + /// `Cursor`. + pub(crate) fn integrity_test() { + let max_weight = ::BlockWeights::get().max_block; + T::Migrations::integrity_test(max_weight) + } + + /// Execute the multi-step migration. + /// Returns whether or not a migration is in progress + pub(crate) fn migrate(mut meter: &mut WeightMeter) -> MigrateResult { + let name = >::name(); + + if meter.try_consume(T::WeightInfo::migrate()).is_err() { + return MigrateResult::NoMigrationPerformed + } + + MigrationInProgress::::mutate_exists(|progress| { + let Some(cursor_before) = progress.as_mut() else { + meter.consume(T::WeightInfo::migration_noop()); + return MigrateResult::NoMigrationInProgress + }; + + // if a migration is running it is always upgrading to the next version + let storage_version = >::on_chain_storage_version(); + let in_progress_version = storage_version + 1; + + log::info!( + target: LOG_TARGET, + "{name}: Migrating from {:?} to {:?},", + storage_version, + in_progress_version, + ); + + let result = + match T::Migrations::steps(in_progress_version, cursor_before.as_ref(), &mut meter) + { + StepResult::InProgress { cursor, steps_done } => { + *progress = Some(cursor); + MigrateResult::InProgress { steps_done } + }, + StepResult::Completed { steps_done } => { + in_progress_version.put::>(); + if >::in_code_storage_version() != in_progress_version { + log::info!( + target: LOG_TARGET, + "{name}: Next migration is {:?},", + in_progress_version + 1 + ); + *progress = Some(T::Migrations::new(in_progress_version + 1)); + MigrateResult::InProgress { steps_done } + } else { + log::info!( + target: LOG_TARGET, + "{name}: All migrations done. At version {:?},", + in_progress_version + ); + *progress = None; + MigrateResult::Completed + } + }, + }; + + result + }) + } + + pub(crate) fn ensure_migrated() -> DispatchResult { + if Self::in_progress() { + Err(Error::::MigrationInProgress.into()) + } else { + Ok(()) + } + } + + pub(crate) fn in_progress() -> bool { + MigrationInProgress::::exists() + } +} + +#[impl_trait_for_tuples::impl_for_tuples(10)] +#[tuple_types_custom_trait_bound(MigrationStep)] +impl MigrateSequence for Tuple { + const VERSION_RANGE: (u16, u16) = { + let mut versions: (u16, u16) = (0, 0); + for_tuples!( + #( + match versions { + (0, 0) => { + versions = (Tuple::VERSION, Tuple::VERSION); + }, + (min_version, last_version) if Tuple::VERSION == last_version + 1 => { + versions = (min_version, Tuple::VERSION); + }, + _ => panic!("Migrations must be ordered by their versions with no gaps.") + } + )* + ); + versions + }; + + fn new(version: StorageVersion) -> Cursor { + for_tuples!( + #( + if version == Tuple::VERSION { + return Tuple::default().encode().try_into().expect(PROOF_ENCODE) + } + )* + ); + invalid_version(version) + } + + #[cfg(feature = "try-runtime")] + /// Execute the pre-checks of the step associated with this version. + fn pre_upgrade_step(version: StorageVersion) -> Result, TryRuntimeError> { + for_tuples!( + #( + if version == Tuple::VERSION { + return Tuple::pre_upgrade_step() + } + )* + ); + invalid_version(version) + } + + #[cfg(feature = "try-runtime")] + /// Execute the post-checks of the step associated with this version. + fn post_upgrade_step(version: StorageVersion, state: Vec) -> Result<(), TryRuntimeError> { + for_tuples!( + #( + if version == Tuple::VERSION { + return Tuple::post_upgrade_step(state) + } + )* + ); + invalid_version(version) + } + + fn steps(version: StorageVersion, mut cursor: &[u8], meter: &mut WeightMeter) -> StepResult { + for_tuples!( + #( + if version == Tuple::VERSION { + let mut migration = ::decode(&mut cursor) + .expect(PROOF_DECODE); + let max_weight = Tuple::max_step_weight(); + let mut steps_done = 0; + while meter.can_consume(max_weight) { + steps_done.saturating_accrue(1); + if matches!(migration.step(meter), IsFinished::Yes) { + return StepResult::Completed{ steps_done } + } + } + return StepResult::InProgress{cursor: migration.encode().try_into().expect(PROOF_ENCODE), steps_done } + } + )* + ); + invalid_version(version) + } + + fn integrity_test(max_block_weight: Weight) { + for_tuples!( + #( + Tuple::integrity_test(max_block_weight); + )* + ); + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::{ + migration::codegen::LATEST_MIGRATION_VERSION, + tests::{ExtBuilder, Test}, + }; + + #[derive(Default, Encode, Decode, MaxEncodedLen)] + struct MockMigration { + // MockMigration needs `N` steps to finish + count: u16, + } + + impl MigrationStep for MockMigration { + const VERSION: u16 = N; + fn max_step_weight() -> Weight { + Weight::from_all(1) + } + fn step(&mut self, meter: &mut WeightMeter) -> IsFinished { + assert!(self.count != N); + self.count += 1; + meter.consume(Weight::from_all(1)); + if self.count == N { + IsFinished::Yes + } else { + IsFinished::No + } + } + } + + #[test] + fn test_storage_version_matches_last_migration_file() { + assert_eq!(StorageVersion::new(LATEST_MIGRATION_VERSION), crate::pallet::STORAGE_VERSION); + } + + #[test] + fn version_range_works() { + let range = <(MockMigration<1>, MockMigration<2>)>::VERSION_RANGE; + assert_eq!(range, (1, 2)); + } + + #[test] + fn is_upgrade_supported_works() { + type Migrations = (MockMigration<9>, MockMigration<10>, MockMigration<11>); + assert!(Migrations::is_upgrade_supported(StorageVersion::new(8), StorageVersion::new(11))); + assert!(!Migrations::is_upgrade_supported(StorageVersion::new(9), StorageVersion::new(11))); + assert!(!Migrations::is_upgrade_supported(StorageVersion::new(8), StorageVersion::new(12))); + } + + #[test] + fn steps_works() { + type Migrations = (MockMigration<2>, MockMigration<3>); + let version = StorageVersion::new(2); + let mut cursor = Migrations::new(version); + + let mut meter = WeightMeter::with_limit(Weight::from_all(1)); + let result = Migrations::steps(version, &cursor, &mut meter); + cursor = alloc::vec![1u8, 0].try_into().unwrap(); + assert_eq!(result, StepResult::InProgress { cursor: cursor.clone(), steps_done: 1 }); + assert_eq!(meter.consumed(), Weight::from_all(1)); + + let mut meter = WeightMeter::with_limit(Weight::from_all(1)); + assert_eq!( + Migrations::steps(version, &cursor, &mut meter), + StepResult::Completed { steps_done: 1 } + ); + } + + #[test] + fn no_migration_in_progress_works() { + type TestMigration = Migration; + + ExtBuilder::default().build().execute_with(|| { + assert_eq!(StorageVersion::get::>(), LATEST_MIGRATION_VERSION); + assert_eq!( + TestMigration::migrate(&mut WeightMeter::new()), + MigrateResult::NoMigrationInProgress + ) + }); + } + + #[test] + fn migration_works() { + type TestMigration = Migration; + + ExtBuilder::default() + .set_storage_version(LATEST_MIGRATION_VERSION - 2) + .build() + .execute_with(|| { + assert_eq!(StorageVersion::get::>(), LATEST_MIGRATION_VERSION - 2); + TestMigration::on_runtime_upgrade(); + for (version, status) in [ + (LATEST_MIGRATION_VERSION - 1, MigrateResult::InProgress { steps_done: 1 }), + (LATEST_MIGRATION_VERSION, MigrateResult::Completed), + ] { + assert_eq!(TestMigration::migrate(&mut WeightMeter::new()), status); + assert_eq!( + >::on_chain_storage_version(), + StorageVersion::new(version) + ); + } + + assert_eq!( + TestMigration::migrate(&mut WeightMeter::new()), + MigrateResult::NoMigrationInProgress + ); + assert_eq!(StorageVersion::get::>(), LATEST_MIGRATION_VERSION); + }); + } +} diff --git a/pallets/contracts/src/migration/v09.rs b/pallets/contracts/src/migration/v09.rs new file mode 100644 index 00000000..6a673951 --- /dev/null +++ b/pallets/contracts/src/migration/v09.rs @@ -0,0 +1,148 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Update `CodeStorage` with the new `determinism` field. + +use crate::{ + migration::{IsFinished, MigrationStep}, + weights::WeightInfo, + CodeHash, Config, Determinism, Pallet, Weight, LOG_TARGET, +}; +use alloc::vec::Vec; +use codec::{Decode, Encode}; +use frame_support::{ + pallet_prelude::*, storage_alias, weights::WeightMeter, DefaultNoBound, Identity, +}; +#[cfg(feature = "try-runtime")] +use sp_runtime::TryRuntimeError; + +mod v8 { + use super::*; + + #[derive(Encode, Decode)] + pub struct PrefabWasmModule { + #[codec(compact)] + pub instruction_weights_version: u32, + #[codec(compact)] + pub initial: u32, + #[codec(compact)] + pub maximum: u32, + pub code: Vec, + } + + #[storage_alias] + pub type CodeStorage = + StorageMap, Identity, CodeHash, PrefabWasmModule>; +} + +#[cfg(feature = "runtime-benchmarks")] +pub fn store_old_dummy_code(len: usize) { + use sp_runtime::traits::Hash; + let module = v8::PrefabWasmModule { + instruction_weights_version: 0, + initial: 0, + maximum: 0, + code: alloc::vec![42u8; len], + }; + let hash = T::Hashing::hash(&module.code); + v8::CodeStorage::::insert(hash, module); +} + +#[derive(Encode, Decode)] +struct PrefabWasmModule { + #[codec(compact)] + pub instruction_weights_version: u32, + #[codec(compact)] + pub initial: u32, + #[codec(compact)] + pub maximum: u32, + pub code: Vec, + pub determinism: Determinism, +} + +#[storage_alias] +type CodeStorage = StorageMap, Identity, CodeHash, PrefabWasmModule>; + +#[derive(Encode, Decode, MaxEncodedLen, DefaultNoBound)] +pub struct Migration { + last_code_hash: Option>, +} + +impl MigrationStep for Migration { + const VERSION: u16 = 9; + + fn max_step_weight() -> Weight { + T::WeightInfo::v9_migration_step(T::MaxCodeLen::get()) + } + + fn step(&mut self, meter: &mut WeightMeter) -> IsFinished { + let mut iter = if let Some(last_key) = self.last_code_hash.take() { + v8::CodeStorage::::iter_from(v8::CodeStorage::::hashed_key_for(last_key)) + } else { + v8::CodeStorage::::iter() + }; + + if let Some((key, old)) = iter.next() { + log::debug!(target: LOG_TARGET, "Migrating contract code {:?}", key); + let len = old.code.len() as u32; + let module = PrefabWasmModule { + instruction_weights_version: old.instruction_weights_version, + initial: old.initial, + maximum: old.maximum, + code: old.code, + determinism: Determinism::Enforced, + }; + CodeStorage::::insert(key, module); + self.last_code_hash = Some(key); + meter.consume(T::WeightInfo::v9_migration_step(len)); + IsFinished::No + } else { + log::debug!(target: LOG_TARGET, "No more contracts code to migrate"); + meter.consume(T::WeightInfo::v9_migration_step(0)); + IsFinished::Yes + } + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade_step() -> Result, TryRuntimeError> { + let sample: Vec<_> = v8::CodeStorage::::iter().take(100).collect(); + + log::debug!(target: LOG_TARGET, "Taking sample of {} contract codes", sample.len()); + Ok(sample.encode()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade_step(state: Vec) -> Result<(), TryRuntimeError> { + let sample = , v8::PrefabWasmModule)> as Decode>::decode(&mut &state[..]) + .expect("pre_upgrade_step provides a valid state; qed"); + + log::debug!(target: LOG_TARGET, "Validating sample of {} contract codes", sample.len()); + for (code_hash, old) in sample { + let module = CodeStorage::::get(&code_hash).unwrap(); + ensure!( + module.instruction_weights_version == old.instruction_weights_version, + "invalid instruction weights version" + ); + ensure!(module.determinism == Determinism::Enforced, "invalid determinism"); + ensure!(module.initial == old.initial, "invalid initial"); + ensure!(module.maximum == old.maximum, "invalid maximum"); + ensure!(module.code == old.code, "invalid code"); + } + + Ok(()) + } +} diff --git a/pallets/contracts/src/migration/v10.rs b/pallets/contracts/src/migration/v10.rs new file mode 100644 index 00000000..23e7fd23 --- /dev/null +++ b/pallets/contracts/src/migration/v10.rs @@ -0,0 +1,322 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Don't rely on reserved balances keeping an account alive +//! See . + +use crate::{ + exec::AccountIdOf, + migration::{IsFinished, MigrationStep}, + weights::WeightInfo, + CodeHash, Config, Pallet, TrieId, Weight, LOG_TARGET, +}; +use codec::{Decode, Encode}; +use core::{ + cmp::{max, min}, + ops::Deref, +}; +use frame_support::{ + pallet_prelude::*, + storage_alias, + traits::{ + tokens::{fungible::Inspect, Fortitude::Polite, Preservation::Preserve}, + ExistenceRequirement, ReservableCurrency, + }, + weights::WeightMeter, + DefaultNoBound, +}; +use sp_core::hexdisplay::HexDisplay; +use sp_runtime::{ + traits::{Hash, TrailingZeroInput, Zero}, + Perbill, Saturating, +}; + +#[cfg(feature = "try-runtime")] +use alloc::vec::Vec; +#[cfg(feature = "try-runtime")] +use sp_runtime::TryRuntimeError; + +mod v9 { + use super::*; + + pub type BalanceOf = ::AccountId, + >>::Balance; + + #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] + #[scale_info(skip_type_params(T, OldCurrency))] + pub struct ContractInfo + where + OldCurrency: ReservableCurrency<::AccountId>, + { + pub trie_id: TrieId, + pub code_hash: CodeHash, + pub storage_bytes: u32, + pub storage_items: u32, + pub storage_byte_deposit: BalanceOf, + pub storage_item_deposit: BalanceOf, + pub storage_base_deposit: BalanceOf, + } + + #[storage_alias] + pub type ContractInfoOf = StorageMap< + Pallet, + Twox64Concat, + ::AccountId, + ContractInfo, + >; +} + +#[cfg(feature = "runtime-benchmarks")] +pub fn store_old_contract_info( + account: T::AccountId, + info: crate::ContractInfo, +) where + OldCurrency: ReservableCurrency<::AccountId> + 'static, +{ + let info = v9::ContractInfo { + trie_id: info.trie_id, + code_hash: info.code_hash, + storage_bytes: Default::default(), + storage_items: Default::default(), + storage_byte_deposit: Default::default(), + storage_item_deposit: Default::default(), + storage_base_deposit: Default::default(), + }; + v9::ContractInfoOf::::insert(account, info); +} + +#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebugNoBound, TypeInfo, MaxEncodedLen)] +#[scale_info(skip_type_params(T))] +pub struct DepositAccount(AccountIdOf); + +impl Deref for DepositAccount { + type Target = AccountIdOf; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +#[scale_info(skip_type_params(T, OldCurrency))] +pub struct ContractInfo +where + OldCurrency: ReservableCurrency<::AccountId>, +{ + pub trie_id: TrieId, + deposit_account: DepositAccount, + pub code_hash: CodeHash, + storage_bytes: u32, + storage_items: u32, + pub storage_byte_deposit: v9::BalanceOf, + storage_item_deposit: v9::BalanceOf, + storage_base_deposit: v9::BalanceOf, +} + +#[derive(Encode, Decode, MaxEncodedLen, DefaultNoBound)] +pub struct Migration { + last_account: Option, + _phantom: PhantomData<(T, OldCurrency)>, +} + +#[storage_alias] +type ContractInfoOf = StorageMap< + Pallet, + Twox64Concat, + ::AccountId, + ContractInfo, +>; + +/// Formula: `hash("contract_depo_v1" ++ contract_addr)` +fn deposit_address( + contract_addr: &::AccountId, +) -> ::AccountId { + let entropy = (b"contract_depo_v1", contract_addr) + .using_encoded(::Hashing::hash); + Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref())) + .expect("infinite length input; no invalid inputs for type; qed") +} + +impl MigrationStep for Migration +where + OldCurrency: ReservableCurrency<::AccountId> + + Inspect<::AccountId, Balance = v9::BalanceOf>, +{ + const VERSION: u16 = 10; + + fn max_step_weight() -> Weight { + T::WeightInfo::v10_migration_step() + } + + fn step(&mut self, meter: &mut WeightMeter) -> IsFinished { + let mut iter = if let Some(last_account) = self.last_account.take() { + v9::ContractInfoOf::::iter_from( + v9::ContractInfoOf::::hashed_key_for(last_account), + ) + } else { + v9::ContractInfoOf::::iter() + }; + + if let Some((account, contract)) = iter.next() { + let min_balance = ::AccountId, + >>::minimum_balance(); + log::debug!(target: LOG_TARGET, "Account: 0x{} ", HexDisplay::from(&account.encode())); + + // Get the new deposit account address + let deposit_account: DepositAccount = DepositAccount(deposit_address::(&account)); + + // Calculate the existing deposit, that should be reserved on the contract account + let old_deposit = contract + .storage_base_deposit + .saturating_add(contract.storage_item_deposit) + .saturating_add(contract.storage_byte_deposit); + + // Unreserve the existing deposit + // Note we can't use repatriate_reserve, because it only works with existing accounts + let remaining = OldCurrency::unreserve(&account, old_deposit); + if !remaining.is_zero() { + log::warn!( + target: LOG_TARGET, + "Partially unreserved. Remaining {:?} out of {:?} asked", + remaining, + old_deposit + ); + } + + // Attempt to transfer the old deposit to the deposit account. + let amount = old_deposit + .saturating_sub(min_balance) + .min(OldCurrency::reducible_balance(&account, Preserve, Polite)); + + let new_deposit = OldCurrency::transfer( + &account, + &deposit_account, + amount, + ExistenceRequirement::KeepAlive, + ) + .map(|_| { + log::debug!( + target: LOG_TARGET, + "Transferred deposit ({:?}) to deposit account", + amount + ); + amount + }) + // If it fails we fallback to minting the ED. + .unwrap_or_else(|err| { + log::error!( + target: LOG_TARGET, + "Failed to transfer the base deposit, reason: {:?}", + err + ); + let _ = OldCurrency::deposit_creating(&deposit_account, min_balance); + min_balance + }); + + // Calculate the new base_deposit to store in the contract: + // Ideally, it should be the same as the old one + // Ideally, it should be at least 2xED (for the contract and deposit accounts). + // It can't be more than the `new_deposit`. + let new_base_deposit = min( + max(contract.storage_base_deposit, min_balance.saturating_add(min_balance)), + new_deposit, + ); + + // Calculate the ratio to adjust storage_byte and storage_item deposits. + let new_deposit_without_base = new_deposit.saturating_sub(new_base_deposit); + let old_deposit_without_base = + old_deposit.saturating_sub(contract.storage_base_deposit); + let ratio = Perbill::from_rational(new_deposit_without_base, old_deposit_without_base); + + // Calculate the new storage deposits based on the ratio + let storage_byte_deposit = ratio.mul_ceil(contract.storage_byte_deposit); + let storage_item_deposit = ratio.mul_ceil(contract.storage_item_deposit); + + // Recalculate the new base deposit, instead of using new_base_deposit to avoid rounding + // errors + let storage_base_deposit = new_deposit + .saturating_sub(storage_byte_deposit) + .saturating_sub(storage_item_deposit); + + let new_contract_info = ContractInfo { + trie_id: contract.trie_id, + deposit_account, + code_hash: contract.code_hash, + storage_bytes: contract.storage_bytes, + storage_items: contract.storage_items, + storage_byte_deposit, + storage_item_deposit, + storage_base_deposit, + }; + + ContractInfoOf::::insert(&account, new_contract_info); + + // Store last key for next migration step + self.last_account = Some(account); + + meter.consume(T::WeightInfo::v10_migration_step()); + IsFinished::No + } else { + log::debug!(target: LOG_TARGET, "Done Migrating contract info"); + meter.consume(T::WeightInfo::v10_migration_step()); + IsFinished::Yes + } + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade_step() -> Result, TryRuntimeError> { + let sample: Vec<_> = v9::ContractInfoOf::::iter().take(10).collect(); + + log::debug!(target: LOG_TARGET, "Taking sample of {} contracts", sample.len()); + Ok(sample.encode()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade_step(state: Vec) -> Result<(), TryRuntimeError> { + let sample = )> as Decode>::decode( + &mut &state[..], + ) + .expect("pre_upgrade_step provides a valid state; qed"); + + log::debug!(target: LOG_TARGET, "Validating sample of {} contracts", sample.len()); + for (account, old_contract) in sample { + log::debug!(target: LOG_TARGET, "==="); + log::debug!(target: LOG_TARGET, "Account: 0x{} ", HexDisplay::from(&account.encode())); + let contract = ContractInfoOf::::get(&account).unwrap(); + ensure!(old_contract.trie_id == contract.trie_id, "invalid trie_id"); + ensure!(old_contract.code_hash == contract.code_hash, "invalid code_hash"); + ensure!(old_contract.storage_bytes == contract.storage_bytes, "invalid storage_bytes"); + ensure!(old_contract.storage_items == contract.storage_items, "invalid storage_items"); + + let deposit = >::total_balance( + &contract.deposit_account, + ); + ensure!( + deposit == + contract + .storage_base_deposit + .saturating_add(contract.storage_item_deposit) + .saturating_add(contract.storage_byte_deposit), + "deposit mismatch" + ); + } + + Ok(()) + } +} diff --git a/pallets/contracts/src/migration/v11.rs b/pallets/contracts/src/migration/v11.rs new file mode 100644 index 00000000..bd128e22 --- /dev/null +++ b/pallets/contracts/src/migration/v11.rs @@ -0,0 +1,136 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Overflowing bounded DeletionQueue. +//! See . + +use crate::{ + migration::{IsFinished, MigrationStep}, + weights::WeightInfo, + Config, Pallet, TrieId, Weight, LOG_TARGET, +}; +use alloc::vec::Vec; +use codec::{Decode, Encode}; +use core::marker::PhantomData; +use frame_support::{pallet_prelude::*, storage_alias, weights::WeightMeter, DefaultNoBound}; +#[cfg(feature = "try-runtime")] +use sp_runtime::TryRuntimeError; + +mod v10 { + use super::*; + + #[derive(Encode, Decode, TypeInfo, MaxEncodedLen)] + pub struct DeletedContract { + pub(crate) trie_id: TrieId, + } + + #[storage_alias] + pub type DeletionQueue = StorageValue, Vec>; +} + +#[derive(Encode, Decode, TypeInfo, MaxEncodedLen, DefaultNoBound, Clone)] +#[scale_info(skip_type_params(T))] +pub struct DeletionQueueManager { + insert_counter: u32, + delete_counter: u32, + _phantom: PhantomData, +} + +#[cfg(any(feature = "runtime-benchmarks", feature = "try-runtime"))] +pub fn fill_old_queue(len: usize) { + let queue: Vec = + core::iter::repeat_with(|| v10::DeletedContract { trie_id: Default::default() }) + .take(len) + .collect(); + v10::DeletionQueue::::set(Some(queue)); +} + +#[storage_alias] +type DeletionQueue = StorageMap, Twox64Concat, u32, TrieId>; + +#[storage_alias] +type DeletionQueueCounter = StorageValue, DeletionQueueManager, ValueQuery>; + +#[derive(Encode, Decode, MaxEncodedLen, DefaultNoBound)] +pub struct Migration { + _phantom: PhantomData, +} + +impl MigrationStep for Migration { + const VERSION: u16 = 11; + + // It would be more correct to make our use the now removed [DeletionQueueDepth](https://github.com/paritytech/substrate/pull/13702/files#diff-70e9723e9db62816e35f6f885b6770a8449c75a6c2733e9fa7a245fe52c4656c) + // but in practice the queue is always empty, so 128 is a good enough approximation for not + // underestimating the weight of our migration. + fn max_step_weight() -> Weight { + T::WeightInfo::v11_migration_step(128) + } + + fn step(&mut self, meter: &mut WeightMeter) -> IsFinished { + let Some(old_queue) = v10::DeletionQueue::::take() else { + meter.consume(T::WeightInfo::v11_migration_step(0)); + return IsFinished::Yes + }; + let len = old_queue.len(); + + log::debug!( + target: LOG_TARGET, + "Migrating deletion queue with {} deleted contracts", + old_queue.len() + ); + + if !old_queue.is_empty() { + let mut queue = DeletionQueueManager::::default(); + for contract in old_queue { + >::insert(queue.insert_counter, contract.trie_id); + queue.insert_counter += 1; + } + + >::set(queue); + } + + meter.consume(T::WeightInfo::v11_migration_step(len as u32)); + IsFinished::Yes + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade_step() -> Result, TryRuntimeError> { + let old_queue = v10::DeletionQueue::::take().unwrap_or_default(); + + if old_queue.is_empty() { + let len = 10u32; + log::debug!( + target: LOG_TARGET, + "Injecting {len} entries to deletion queue to test migration" + ); + fill_old_queue::(len as usize); + return Ok(len.encode()) + } + + Ok((old_queue.len() as u32).encode()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade_step(state: Vec) -> Result<(), TryRuntimeError> { + let len = ::decode(&mut &state[..]) + .expect("pre_upgrade_step provides a valid state; qed"); + let counter = >::get(); + ensure!(counter.insert_counter == len, "invalid insert counter"); + ensure!(counter.delete_counter == 0, "invalid delete counter"); + Ok(()) + } +} diff --git a/pallets/contracts/src/migration/v12.rs b/pallets/contracts/src/migration/v12.rs new file mode 100644 index 00000000..3c33591e --- /dev/null +++ b/pallets/contracts/src/migration/v12.rs @@ -0,0 +1,351 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Move `OwnerInfo` to `CodeInfo`, add `determinism` field to the latter, clear `CodeStorage` and +//! repay deposits. + +use crate::{ + migration::{IsFinished, MigrationStep}, + weights::WeightInfo, + AccountIdOf, BalanceOf, CodeHash, Config, Determinism, Pallet, Weight, LOG_TARGET, +}; +use alloc::vec::Vec; +use codec::{Decode, Encode}; +use frame_support::{ + pallet_prelude::*, storage_alias, traits::ReservableCurrency, weights::WeightMeter, + DefaultNoBound, Identity, +}; +use scale_info::prelude::format; +use sp_core::hexdisplay::HexDisplay; +#[cfg(feature = "try-runtime")] +use sp_runtime::TryRuntimeError; +use sp_runtime::{traits::Zero, FixedPointNumber, FixedU128, Saturating}; + +mod v11 { + use super::*; + + pub type BalanceOf = ::AccountId, + >>::Balance; + + #[derive(Encode, Decode, scale_info::TypeInfo, MaxEncodedLen)] + #[codec(mel_bound())] + #[scale_info(skip_type_params(T, OldCurrency))] + pub struct OwnerInfo + where + OldCurrency: ReservableCurrency<::AccountId>, + { + pub owner: AccountIdOf, + #[codec(compact)] + pub deposit: BalanceOf, + #[codec(compact)] + pub refcount: u64, + } + + #[derive(Encode, Decode, scale_info::TypeInfo)] + #[codec(mel_bound())] + #[scale_info(skip_type_params(T))] + pub struct PrefabWasmModule { + #[codec(compact)] + pub instruction_weights_version: u32, + #[codec(compact)] + pub initial: u32, + #[codec(compact)] + pub maximum: u32, + pub code: Vec, + pub determinism: Determinism, + } + + #[storage_alias] + pub type OwnerInfoOf = + StorageMap, Identity, CodeHash, OwnerInfo>; + + #[storage_alias] + pub type CodeStorage = + StorageMap, Identity, CodeHash, PrefabWasmModule>; +} + +#[derive(Encode, Decode, scale_info::TypeInfo, MaxEncodedLen)] +#[codec(mel_bound())] +#[scale_info(skip_type_params(T, OldCurrency))] +pub struct CodeInfo +where + OldCurrency: ReservableCurrency<::AccountId>, +{ + owner: AccountIdOf, + #[codec(compact)] + deposit: v11::BalanceOf, + #[codec(compact)] + refcount: u64, + determinism: Determinism, + code_len: u32, +} + +#[storage_alias] +pub type CodeInfoOf = + StorageMap, Identity, CodeHash, CodeInfo>; + +#[storage_alias] +pub type PristineCode = StorageMap, Identity, CodeHash, Vec>; + +#[cfg(feature = "runtime-benchmarks")] +pub fn store_old_dummy_code(len: usize, account: T::AccountId) +where + OldCurrency: ReservableCurrency<::AccountId> + 'static, +{ + use sp_runtime::traits::Hash; + + let code = alloc::vec![42u8; len]; + let hash = T::Hashing::hash(&code); + PristineCode::::insert(hash, code.clone()); + + let module = v11::PrefabWasmModule { + instruction_weights_version: Default::default(), + initial: Default::default(), + maximum: Default::default(), + code, + determinism: Determinism::Enforced, + }; + v11::CodeStorage::::insert(hash, module); + + let info = v11::OwnerInfo { owner: account, deposit: u32::MAX.into(), refcount: u64::MAX }; + v11::OwnerInfoOf::::insert(hash, info); +} + +#[derive(Encode, Decode, MaxEncodedLen, DefaultNoBound)] +pub struct Migration +where + OldCurrency: ReservableCurrency<::AccountId>, + OldCurrency::Balance: From>, +{ + last_code_hash: Option>, + _phantom: PhantomData, +} + +impl MigrationStep for Migration +where + OldCurrency: ReservableCurrency<::AccountId> + 'static, + OldCurrency::Balance: From>, +{ + const VERSION: u16 = 12; + + fn max_step_weight() -> Weight { + T::WeightInfo::v12_migration_step(T::MaxCodeLen::get()) + } + + fn step(&mut self, meter: &mut WeightMeter) -> IsFinished { + let mut iter = if let Some(last_key) = self.last_code_hash.take() { + v11::OwnerInfoOf::::iter_from( + v11::OwnerInfoOf::::hashed_key_for(last_key), + ) + } else { + v11::OwnerInfoOf::::iter() + }; + if let Some((hash, old_info)) = iter.next() { + log::debug!(target: LOG_TARGET, "Migrating OwnerInfo for code_hash {:?}", hash); + + let module = v11::CodeStorage::::take(hash) + .expect(format!("No PrefabWasmModule found for code_hash: {:?}", hash).as_str()); + + let code_len = module.code.len(); + // We print this to measure the impact of the migration. + // Storage removed: deleted PrefabWasmModule's encoded len. + // Storage added: determinism field encoded len (as all other CodeInfo fields are the + // same as in the deleted OwnerInfo). + log::debug!(target: LOG_TARGET, "Storage removed: 1 item, {} bytes", &code_len,); + + // Storage usage prices could change over time, and accounts who uploaded their + // contracts code before the storage deposits where introduced, had not been ever + // charged with any deposit for that (see migration v6). + // + // This is why deposit to be refunded here is calculated as follows: + // + // 1. Calculate the deposit amount for storage before the migration, given current + // prices. + // 2. Given current reserved deposit amount, calculate the correction factor. + // 3. Calculate the deposit amount for storage after the migration, given current + // prices. + // 4. Calculate real deposit amount to be reserved after the migration. + let price_per_byte = T::DepositPerByte::get(); + let price_per_item = T::DepositPerItem::get(); + let bytes_before = module + .encoded_size() + .saturating_add(code_len) + .saturating_add(v11::OwnerInfo::::max_encoded_len()) + as u32; + let items_before = 3u32; + let deposit_expected_before = price_per_byte + .saturating_mul(bytes_before.into()) + .saturating_add(price_per_item.saturating_mul(items_before.into())); + let ratio = FixedU128::checked_from_rational(old_info.deposit, deposit_expected_before) + .unwrap_or_default() + .min(FixedU128::from_u32(1)); + let bytes_after = + code_len.saturating_add(CodeInfo::::max_encoded_len()) as u32; + let items_after = 2u32; + let deposit_expected_after = price_per_byte + .saturating_mul(bytes_after.into()) + .saturating_add(price_per_item.saturating_mul(items_after.into())); + let deposit = ratio.saturating_mul_int(deposit_expected_after); + + let info = CodeInfo:: { + determinism: module.determinism, + owner: old_info.owner, + deposit: deposit.into(), + refcount: old_info.refcount, + code_len: code_len as u32, + }; + + let amount = old_info.deposit.saturating_sub(info.deposit); + if !amount.is_zero() { + OldCurrency::unreserve(&info.owner, amount); + log::debug!( + target: LOG_TARGET, + "Deposit refunded: {:?} Balance, to: {:?}", + &amount, + HexDisplay::from(&info.owner.encode()) + ); + } else { + log::warn!( + target: LOG_TARGET, + "new deposit: {:?} >= old deposit: {:?}", + &info.deposit, + &old_info.deposit + ); + } + CodeInfoOf::::insert(hash, info); + + self.last_code_hash = Some(hash); + + meter.consume(T::WeightInfo::v12_migration_step(code_len as u32)); + IsFinished::No + } else { + log::debug!(target: LOG_TARGET, "No more OwnerInfo to migrate"); + meter.consume(T::WeightInfo::v12_migration_step(0)); + IsFinished::Yes + } + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade_step() -> Result, TryRuntimeError> { + let len = 100; + log::debug!(target: LOG_TARGET, "Taking sample of {} OwnerInfo(s)", len); + let sample: Vec<_> = v11::OwnerInfoOf::::iter() + .take(len) + .map(|(k, v)| { + let module = v11::CodeStorage::::get(k) + .expect("No PrefabWasmModule found for code_hash: {:?}"); + let info: CodeInfo = CodeInfo { + determinism: module.determinism, + deposit: v.deposit, + refcount: v.refcount, + owner: v.owner, + code_len: module.code.len() as u32, + }; + (k, info) + }) + .collect(); + + let storage: u32 = + v11::CodeStorage::::iter().map(|(_k, v)| v.encoded_size() as u32).sum(); + let mut deposit: v11::BalanceOf = Default::default(); + v11::OwnerInfoOf::::iter().for_each(|(_k, v)| deposit += v.deposit); + + Ok((sample, deposit, storage).encode()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade_step(state: Vec) -> Result<(), TryRuntimeError> { + let state = <( + Vec<(CodeHash, CodeInfo)>, + v11::BalanceOf, + u32, + ) as Decode>::decode(&mut &state[..]) + .unwrap(); + + log::debug!(target: LOG_TARGET, "Validating state of {} Codeinfo(s)", state.0.len()); + for (hash, old) in state.0 { + let info = CodeInfoOf::::get(&hash) + .expect(format!("CodeInfo for code_hash {:?} not found!", hash).as_str()); + ensure!(info.determinism == old.determinism, "invalid determinism"); + ensure!(info.owner == old.owner, "invalid owner"); + ensure!(info.refcount == old.refcount, "invalid refcount"); + } + + if let Some((k, _)) = v11::CodeStorage::::iter().next() { + log::warn!( + target: LOG_TARGET, + "CodeStorage is still NOT empty, found code_hash: {:?}", + k + ); + } else { + log::debug!(target: LOG_TARGET, "CodeStorage is empty."); + } + if let Some((k, _)) = v11::OwnerInfoOf::::iter().next() { + log::warn!( + target: LOG_TARGET, + "OwnerInfoOf is still NOT empty, found code_hash: {:?}", + k + ); + } else { + log::debug!(target: LOG_TARGET, "OwnerInfoOf is empty."); + } + + let mut deposit: v11::BalanceOf = Default::default(); + let mut items = 0u32; + let mut storage_info = 0u32; + CodeInfoOf::::iter().for_each(|(_k, v)| { + deposit += v.deposit; + items += 1; + storage_info += v.encoded_size() as u32; + }); + let mut storage_code = 0u32; + PristineCode::::iter().for_each(|(_k, v)| { + storage_code += v.len() as u32; + }); + let (_, old_deposit, storage_module) = state; + // CodeInfoOf::max_encoded_len == OwnerInfoOf::max_encoded_len + 1 + // I.e. code info adds up 1 byte per record. + let info_bytes_added = items; + // We removed 1 PrefabWasmModule, and added 1 byte of determinism flag, per contract code. + let storage_removed = storage_module.saturating_sub(info_bytes_added); + // module+code+info - bytes + let storage_was = storage_module + .saturating_add(storage_code) + .saturating_add(storage_info) + .saturating_sub(info_bytes_added); + // We removed 1 storage item (PrefabWasmMod) for every stored contract code (was stored 3 + // items per code). + let items_removed = items; + log::info!( + target: LOG_TARGET, + "Storage freed, bytes: {} (of {}), items: {} (of {})", + storage_removed, + storage_was, + items_removed, + items_removed * 3, + ); + log::info!( + target: LOG_TARGET, + "Deposits returned, total: {:?} Balance (of {:?} Balance)", + old_deposit.saturating_sub(deposit), + old_deposit, + ); + + Ok(()) + } +} diff --git a/pallets/contracts/src/migration/v13.rs b/pallets/contracts/src/migration/v13.rs new file mode 100644 index 00000000..d1888b33 --- /dev/null +++ b/pallets/contracts/src/migration/v13.rs @@ -0,0 +1,136 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Add `delegate_dependencies` to `ContractInfo`. +//! See . + +use crate::{ + migration::{IsFinished, MigrationStep}, + weights::WeightInfo, + AccountIdOf, BalanceOf, CodeHash, Config, Pallet, TrieId, Weight, LOG_TARGET, +}; +use codec::{Decode, Encode}; +use frame_support::{pallet_prelude::*, storage_alias, weights::WeightMeter, DefaultNoBound}; +use sp_runtime::BoundedBTreeMap; + +mod v12 { + use super::*; + + #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] + #[scale_info(skip_type_params(T))] + pub struct ContractInfo { + pub trie_id: TrieId, + pub deposit_account: AccountIdOf, + pub code_hash: CodeHash, + pub storage_bytes: u32, + pub storage_items: u32, + pub storage_byte_deposit: BalanceOf, + pub storage_item_deposit: BalanceOf, + pub storage_base_deposit: BalanceOf, + } + + #[storage_alias] + pub type ContractInfoOf = StorageMap< + Pallet, + Twox64Concat, + ::AccountId, + ContractInfo, + >; +} + +#[cfg(feature = "runtime-benchmarks")] +pub fn store_old_contract_info(account: T::AccountId, info: crate::ContractInfo) { + use sp_runtime::traits::{Hash, TrailingZeroInput}; + let entropy = (b"contract_depo_v1", account.clone()).using_encoded(T::Hashing::hash); + let deposit_account = Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref())) + .expect("infinite length input; no invalid inputs for type; qed"); + let info = v12::ContractInfo { + trie_id: info.trie_id.clone(), + deposit_account, + code_hash: info.code_hash, + storage_bytes: Default::default(), + storage_items: Default::default(), + storage_byte_deposit: Default::default(), + storage_item_deposit: Default::default(), + storage_base_deposit: Default::default(), + }; + v12::ContractInfoOf::::insert(account, info); +} + +#[storage_alias] +pub type ContractInfoOf = + StorageMap, Twox64Concat, ::AccountId, ContractInfo>; + +#[derive(Encode, Decode, CloneNoBound, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +#[scale_info(skip_type_params(T))] +pub struct ContractInfo { + trie_id: TrieId, + deposit_account: AccountIdOf, + code_hash: CodeHash, + storage_bytes: u32, + storage_items: u32, + storage_byte_deposit: BalanceOf, + storage_item_deposit: BalanceOf, + storage_base_deposit: BalanceOf, + delegate_dependencies: BoundedBTreeMap, BalanceOf, T::MaxDelegateDependencies>, +} + +#[derive(Encode, Decode, MaxEncodedLen, DefaultNoBound)] +pub struct Migration { + last_account: Option, +} + +impl MigrationStep for Migration { + const VERSION: u16 = 13; + + fn max_step_weight() -> Weight { + T::WeightInfo::v13_migration_step() + } + + fn step(&mut self, meter: &mut WeightMeter) -> IsFinished { + let mut iter = if let Some(last_account) = self.last_account.take() { + v12::ContractInfoOf::::iter_from(v12::ContractInfoOf::::hashed_key_for( + last_account, + )) + } else { + v12::ContractInfoOf::::iter() + }; + + if let Some((key, old)) = iter.next() { + log::debug!(target: LOG_TARGET, "Migrating contract {:?}", key); + let info = ContractInfo { + trie_id: old.trie_id, + deposit_account: old.deposit_account, + code_hash: old.code_hash, + storage_bytes: old.storage_bytes, + storage_items: old.storage_items, + storage_byte_deposit: old.storage_byte_deposit, + storage_item_deposit: old.storage_item_deposit, + storage_base_deposit: old.storage_base_deposit, + delegate_dependencies: Default::default(), + }; + ContractInfoOf::::insert(key.clone(), info); + self.last_account = Some(key); + meter.consume(T::WeightInfo::v13_migration_step()); + IsFinished::No + } else { + log::debug!(target: LOG_TARGET, "No more contracts to migrate"); + meter.consume(T::WeightInfo::v13_migration_step()); + IsFinished::Yes + } + } +} diff --git a/pallets/contracts/src/migration/v14.rs b/pallets/contracts/src/migration/v14.rs new file mode 100644 index 00000000..11336fe2 --- /dev/null +++ b/pallets/contracts/src/migration/v14.rs @@ -0,0 +1,274 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Update the code owner balance, make the code upload deposit balance to be held instead of +//! reserved. Since [`Currency`](frame_support::traits::Currency) has been +//! [deprecated](https://github.com/paritytech/substrate/pull/12951), we need the deposits to be +//! handled by the [`frame_support::traits::fungible`] traits. + +use crate::{ + exec::AccountIdOf, + migration::{IsFinished, MigrationStep}, + weights::WeightInfo, + BalanceOf, CodeHash, Config, Determinism, HoldReason, Pallet, Weight, LOG_TARGET, +}; +#[cfg(feature = "try-runtime")] +use alloc::collections::btree_map::BTreeMap; +use codec::{Decode, Encode}; +#[cfg(feature = "try-runtime")] +use environmental::Vec; +#[cfg(feature = "try-runtime")] +use frame_support::traits::fungible::{Inspect, InspectHold}; +use frame_support::{ + pallet_prelude::*, + storage_alias, + traits::{fungible::MutateHold, ReservableCurrency}, + weights::WeightMeter, + DefaultNoBound, +}; +use sp_core::hexdisplay::HexDisplay; +#[cfg(feature = "try-runtime")] +use sp_runtime::TryRuntimeError; +use sp_runtime::{traits::Zero, Saturating}; + +mod v13 { + use super::*; + + pub type BalanceOf = ::AccountId, + >>::Balance; + + #[derive(Encode, Decode, scale_info::TypeInfo, MaxEncodedLen)] + #[codec(mel_bound())] + #[scale_info(skip_type_params(T, OldCurrency))] + pub struct CodeInfo + where + T: Config, + OldCurrency: ReservableCurrency<::AccountId>, + { + pub owner: AccountIdOf, + #[codec(compact)] + pub deposit: v13::BalanceOf, + #[codec(compact)] + pub refcount: u64, + pub determinism: Determinism, + pub code_len: u32, + } + + #[storage_alias] + pub type CodeInfoOf = + StorageMap, Identity, CodeHash, CodeInfo>; +} + +#[cfg(feature = "runtime-benchmarks")] +pub fn store_dummy_code(account: T::AccountId) +where + T: Config, + OldCurrency: ReservableCurrency<::AccountId> + 'static, +{ + use alloc::vec; + use sp_runtime::traits::Hash; + + let len = T::MaxCodeLen::get(); + let code = vec![42u8; len as usize]; + let hash = T::Hashing::hash(&code); + + let info = v13::CodeInfo { + owner: account, + deposit: 10_000u32.into(), + refcount: u64::MAX, + determinism: Determinism::Enforced, + code_len: len, + }; + v13::CodeInfoOf::::insert(hash, info); +} + +#[cfg(feature = "try-runtime")] +#[derive(Encode, Decode)] +/// Accounts for the balance allocation of a code owner. +struct BalanceAllocation +where + T: Config, + OldCurrency: ReservableCurrency<::AccountId>, +{ + /// Total reserved balance as code upload deposit for the owner. + reserved: v13::BalanceOf, + /// Total balance of the owner. + total: v13::BalanceOf, +} + +#[derive(Encode, Decode, MaxEncodedLen, DefaultNoBound)] +pub struct Migration +where + T: Config, + OldCurrency: ReservableCurrency<::AccountId>, +{ + last_code_hash: Option>, + _phantom: PhantomData<(T, OldCurrency)>, +} + +impl MigrationStep for Migration +where + T: Config, + OldCurrency: 'static + ReservableCurrency<::AccountId>, + BalanceOf: From, +{ + const VERSION: u16 = 14; + + fn max_step_weight() -> Weight { + T::WeightInfo::v14_migration_step() + } + + fn step(&mut self, meter: &mut WeightMeter) -> IsFinished { + let mut iter = if let Some(last_hash) = self.last_code_hash.take() { + v13::CodeInfoOf::::iter_from( + v13::CodeInfoOf::::hashed_key_for(last_hash), + ) + } else { + v13::CodeInfoOf::::iter() + }; + + if let Some((hash, code_info)) = iter.next() { + log::debug!(target: LOG_TARGET, "Migrating code upload deposit for 0x{:?}", HexDisplay::from(&code_info.owner.encode())); + + let remaining = OldCurrency::unreserve(&code_info.owner, code_info.deposit); + + if remaining > Zero::zero() { + log::warn!( + target: LOG_TARGET, + "Code owner's account 0x{:?} for code {:?} has some non-unreservable deposit {:?} from a total of {:?} that will remain in reserved.", + HexDisplay::from(&code_info.owner.encode()), + hash, + remaining, + code_info.deposit + ); + } + + let unreserved = code_info.deposit.saturating_sub(remaining); + let amount = BalanceOf::::from(unreserved); + + log::debug!( + target: LOG_TARGET, + "Holding {:?} on the code owner's account 0x{:?} for code {:?}.", + amount, + HexDisplay::from(&code_info.owner.encode()), + hash, + ); + + T::Currency::hold( + &HoldReason::CodeUploadDepositReserve.into(), + &code_info.owner, + amount, + ) + .unwrap_or_else(|err| { + log::error!( + target: LOG_TARGET, + "Failed to hold {:?} from the code owner's account 0x{:?} for code {:?}, reason: {:?}.", + amount, + HexDisplay::from(&code_info.owner.encode()), + hash, + err + ); + }); + + self.last_code_hash = Some(hash); + meter.consume(T::WeightInfo::v14_migration_step()); + IsFinished::No + } else { + log::debug!(target: LOG_TARGET, "No more code upload deposit to migrate"); + meter.consume(T::WeightInfo::v14_migration_step()); + IsFinished::Yes + } + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade_step() -> Result, TryRuntimeError> { + let info: Vec<_> = v13::CodeInfoOf::::iter().collect(); + + let mut owner_balance_allocation = + BTreeMap::, BalanceAllocation>::new(); + + // Calculates the balance allocation by accumulating the code upload deposits of all codes + // owned by an owner. + for (_, code_info) in info { + owner_balance_allocation + .entry(code_info.owner.clone()) + .and_modify(|alloc| { + alloc.reserved = alloc.reserved.saturating_add(code_info.deposit); + }) + .or_insert(BalanceAllocation { + reserved: code_info.deposit, + total: OldCurrency::total_balance(&code_info.owner), + }); + } + + Ok(owner_balance_allocation.encode()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade_step(state: Vec) -> Result<(), TryRuntimeError> { + let owner_balance_allocation = + , BalanceAllocation> as Decode>::decode( + &mut &state[..], + ) + .expect("pre_upgrade_step provides a valid state; qed"); + + let mut total_held: BalanceOf = Zero::zero(); + let count = owner_balance_allocation.len(); + for (owner, old_balance_allocation) in owner_balance_allocation { + let held = + T::Currency::balance_on_hold(&HoldReason::CodeUploadDepositReserve.into(), &owner); + log::debug!( + target: LOG_TARGET, + "Validating code upload deposit for owner 0x{:?}, reserved: {:?}, held: {:?}", + HexDisplay::from(&owner.encode()), + old_balance_allocation.reserved, + held + ); + ensure!(held == old_balance_allocation.reserved.into(), "Held amount mismatch"); + + log::debug!( + target: LOG_TARGET, + "Validating total balance for owner 0x{:?}, new: {:?}, old: {:?}", + HexDisplay::from(&owner.encode()), + T::Currency::total_balance(&owner), + old_balance_allocation.total + ); + ensure!( + T::Currency::total_balance(&owner) == + BalanceOf::::decode(&mut &old_balance_allocation.total.encode()[..]) + .unwrap(), + "Balance mismatch " + ); + total_held += held; + } + + log::info!( + target: LOG_TARGET, + "Code owners processed: {:?}.", + count + ); + + log::info!( + target: LOG_TARGET, + "Total held amount for code upload deposit: {:?}", + total_held + ); + + Ok(()) + } +} diff --git a/pallets/contracts/src/migration/v15.rs b/pallets/contracts/src/migration/v15.rs new file mode 100644 index 00000000..11f07282 --- /dev/null +++ b/pallets/contracts/src/migration/v15.rs @@ -0,0 +1,332 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Move contracts' _reserved_ balance from the `deposit_account` to be _held_ in the contract's +//! account instead. Since [`Currency`](frame_support::traits::Currency) has been +//! [deprecated](https://github.com/paritytech/substrate/pull/12951), we need the deposits to be +//! handled by the [`frame_support::traits::fungible`] traits instead. For this transfer the +//! balance from the deposit account to the contract's account and hold it in there. +//! Then the deposit account is not needed anymore and we can get rid of it. + +use crate::{ + migration::{IsFinished, MigrationStep}, + weights::WeightInfo, + AccountIdOf, BalanceOf, CodeHash, Config, HoldReason, Pallet, TrieId, Weight, LOG_TARGET, +}; +#[cfg(feature = "try-runtime")] +use alloc::vec::Vec; +#[cfg(feature = "try-runtime")] +use frame_support::traits::fungible::InspectHold; +use frame_support::{ + pallet_prelude::*, + storage_alias, + traits::{ + fungible::{Mutate, MutateHold}, + tokens::{fungible::Inspect, Fortitude, Preservation}, + }, + weights::WeightMeter, + BoundedBTreeMap, DefaultNoBound, +}; +use frame_system::Pallet as System; +use sp_core::hexdisplay::HexDisplay; +#[cfg(feature = "try-runtime")] +use sp_runtime::TryRuntimeError; +use sp_runtime::{traits::Zero, Saturating}; + +mod v14 { + use super::*; + + #[derive( + Encode, Decode, CloneNoBound, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen, + )] + #[scale_info(skip_type_params(T))] + pub struct ContractInfo { + pub trie_id: TrieId, + pub deposit_account: AccountIdOf, + pub code_hash: CodeHash, + pub storage_bytes: u32, + pub storage_items: u32, + pub storage_byte_deposit: BalanceOf, + pub storage_item_deposit: BalanceOf, + pub storage_base_deposit: BalanceOf, + pub delegate_dependencies: + BoundedBTreeMap, BalanceOf, T::MaxDelegateDependencies>, + } + + #[storage_alias] + pub type ContractInfoOf = StorageMap< + Pallet, + Twox64Concat, + ::AccountId, + ContractInfo, + >; +} + +#[cfg(feature = "runtime-benchmarks")] +pub fn store_old_contract_info(account: T::AccountId, info: crate::ContractInfo) { + use sp_runtime::traits::{Hash, TrailingZeroInput}; + let entropy = (b"contract_depo_v1", account.clone()).using_encoded(T::Hashing::hash); + let deposit_account = Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref())) + .expect("infinite length input; no invalid inputs for type; qed"); + let info = v14::ContractInfo { + trie_id: info.trie_id.clone(), + deposit_account, + code_hash: info.code_hash, + storage_bytes: Default::default(), + storage_items: Default::default(), + storage_byte_deposit: info.storage_byte_deposit, + storage_item_deposit: Default::default(), + storage_base_deposit: info.storage_base_deposit(), + delegate_dependencies: info.delegate_dependencies().clone(), + }; + v14::ContractInfoOf::::insert(account, info); +} + +#[derive(Encode, Decode, CloneNoBound, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +#[scale_info(skip_type_params(T))] +struct ContractInfo { + pub trie_id: TrieId, + pub code_hash: CodeHash, + pub storage_bytes: u32, + pub storage_items: u32, + pub storage_byte_deposit: BalanceOf, + pub storage_item_deposit: BalanceOf, + pub storage_base_deposit: BalanceOf, + pub delegate_dependencies: + BoundedBTreeMap, BalanceOf, T::MaxDelegateDependencies>, +} + +#[storage_alias] +type ContractInfoOf = + StorageMap, Twox64Concat, ::AccountId, ContractInfo>; + +#[derive(Encode, Decode, MaxEncodedLen, DefaultNoBound)] +pub struct Migration { + last_account: Option, +} + +impl MigrationStep for Migration { + const VERSION: u16 = 15; + + fn max_step_weight() -> Weight { + T::WeightInfo::v15_migration_step() + } + + fn step(&mut self, meter: &mut WeightMeter) -> IsFinished { + let mut iter = if let Some(last_account) = self.last_account.take() { + v14::ContractInfoOf::::iter_from(v14::ContractInfoOf::::hashed_key_for( + last_account, + )) + } else { + v14::ContractInfoOf::::iter() + }; + + if let Some((account, old_contract)) = iter.next() { + let deposit_account = &old_contract.deposit_account; + System::::dec_consumers(deposit_account); + + // Get the deposit balance to transfer. + let total_deposit_balance = T::Currency::total_balance(deposit_account); + let reducible_deposit_balance = T::Currency::reducible_balance( + deposit_account, + Preservation::Expendable, + Fortitude::Force, + ); + + if total_deposit_balance > reducible_deposit_balance { + // This should never happen, as by design all balance in the deposit account is + // storage deposit and therefore reducible after decrementing the consumer + // reference. + log::warn!( + target: LOG_TARGET, + "Deposit account 0x{:?} for contract 0x{:?} has some non-reducible balance {:?} from a total of {:?} that will remain in there.", + HexDisplay::from(&deposit_account.encode()), + HexDisplay::from(&account.encode()), + total_deposit_balance.saturating_sub(reducible_deposit_balance), + total_deposit_balance + ); + } + + // Move balance reserved from the deposit account back to the contract account. + // Let the deposit account die. + log::debug!( + target: LOG_TARGET, + "Transferring {:?} from the deposit account 0x{:?} to the contract 0x{:?}.", + reducible_deposit_balance, + HexDisplay::from(&deposit_account.encode()), + HexDisplay::from(&account.encode()) + ); + let transferred_deposit_balance = T::Currency::transfer( + deposit_account, + &account, + reducible_deposit_balance, + Preservation::Expendable, + ) + .unwrap_or_else(|err| { + log::error!( + target: LOG_TARGET, + "Failed to transfer {:?} from the deposit account 0x{:?} to the contract 0x{:?}, reason: {:?}.", + reducible_deposit_balance, + HexDisplay::from(&deposit_account.encode()), + HexDisplay::from(&account.encode()), + err + ); + Zero::zero() + }); + + // Hold the reserved balance. + if transferred_deposit_balance == Zero::zero() { + log::warn!( + target: LOG_TARGET, + "No balance to hold as storage deposit on the contract 0x{:?}.", + HexDisplay::from(&account.encode()) + ); + } else { + log::debug!( + target: LOG_TARGET, + "Holding {:?} as storage deposit on the contract 0x{:?}.", + transferred_deposit_balance, + HexDisplay::from(&account.encode()) + ); + + T::Currency::hold( + &HoldReason::StorageDepositReserve.into(), + &account, + transferred_deposit_balance, + ) + .unwrap_or_else(|err| { + log::error!( + target: LOG_TARGET, + "Failed to hold {:?} as storage deposit on the contract 0x{:?}, reason: {:?}.", + transferred_deposit_balance, + HexDisplay::from(&account.encode()), + err + ); + }); + } + + log::debug!(target: LOG_TARGET, "==="); + let info = ContractInfo { + trie_id: old_contract.trie_id, + code_hash: old_contract.code_hash, + storage_bytes: old_contract.storage_bytes, + storage_items: old_contract.storage_items, + storage_byte_deposit: old_contract.storage_byte_deposit, + storage_item_deposit: old_contract.storage_item_deposit, + storage_base_deposit: old_contract.storage_base_deposit, + delegate_dependencies: old_contract.delegate_dependencies, + }; + ContractInfoOf::::insert(account.clone(), info); + + // Store last key for next migration step + self.last_account = Some(account); + + meter.consume(T::WeightInfo::v15_migration_step()); + IsFinished::No + } else { + log::info!(target: LOG_TARGET, "Done Migrating Storage Deposits."); + meter.consume(T::WeightInfo::v15_migration_step()); + IsFinished::Yes + } + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade_step() -> Result, TryRuntimeError> { + let sample: Vec<_> = v14::ContractInfoOf::::iter().take(100).collect(); + + log::debug!(target: LOG_TARGET, "Taking sample of {} contracts", sample.len()); + + let state: Vec<(T::AccountId, v14::ContractInfo, BalanceOf, BalanceOf)> = sample + .iter() + .map(|(account, contract)| { + ( + account.clone(), + contract.clone(), + T::Currency::total_balance(&account), + T::Currency::total_balance(&contract.deposit_account), + ) + }) + .collect(); + + Ok(state.encode()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade_step(state: Vec) -> Result<(), TryRuntimeError> { + let sample = + , BalanceOf, BalanceOf)> as Decode>::decode( + &mut &state[..], + ) + .expect("pre_upgrade_step provides a valid state; qed"); + + log::debug!(target: LOG_TARGET, "Validating sample of {} contracts", sample.len()); + for (account, old_contract, old_account_balance, old_deposit_balance) in sample { + log::debug!(target: LOG_TARGET, "==="); + log::debug!(target: LOG_TARGET, "Account: 0x{} ", HexDisplay::from(&account.encode())); + + let on_hold = + T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &account); + let account_balance = T::Currency::total_balance(&account); + + log::debug!( + target: LOG_TARGET, + "Validating balances match. Old deposit account's balance: {:?}. Contract's on hold: {:?}. Old contract's total balance: {:?}, Contract's total balance: {:?}.", + old_deposit_balance, + on_hold, + old_account_balance, + account_balance + ); + ensure!( + old_account_balance.saturating_add(old_deposit_balance) == account_balance, + "total balance mismatch" + ); + ensure!(old_deposit_balance == on_hold, "deposit mismatch"); + ensure!( + !System::::account_exists(&old_contract.deposit_account), + "deposit account still exists" + ); + + let migration_contract_info = ContractInfoOf::::try_get(&account).unwrap(); + let crate_contract_info = crate::ContractInfoOf::::try_get(&account).unwrap(); + ensure!( + migration_contract_info.trie_id == crate_contract_info.trie_id, + "trie_id mismatch" + ); + ensure!( + migration_contract_info.code_hash == crate_contract_info.code_hash, + "code_hash mismatch" + ); + ensure!( + migration_contract_info.storage_byte_deposit == + crate_contract_info.storage_byte_deposit, + "storage_byte_deposit mismatch" + ); + ensure!( + migration_contract_info.storage_base_deposit == + crate_contract_info.storage_base_deposit(), + "storage_base_deposit mismatch" + ); + ensure!( + &migration_contract_info.delegate_dependencies == + crate_contract_info.delegate_dependencies(), + "delegate_dependencies mismatch" + ); + } + + Ok(()) + } +} diff --git a/pallets/contracts/src/migration/v16.rs b/pallets/contracts/src/migration/v16.rs new file mode 100644 index 00000000..3d5b2d2a --- /dev/null +++ b/pallets/contracts/src/migration/v16.rs @@ -0,0 +1,106 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Remove ED from storage base deposit. +//! See . + +use crate::{ + migration::{IsFinished, MigrationStep}, + weights::WeightInfo, + BalanceOf, CodeHash, Config, Pallet, TrieId, Weight, WeightMeter, LOG_TARGET, +}; +use codec::{Decode, Encode}; +use frame_support::{pallet_prelude::*, storage_alias, DefaultNoBound}; +use sp_runtime::{BoundedBTreeMap, Saturating}; + +#[cfg(feature = "runtime-benchmarks")] +pub fn store_old_contract_info( + account: T::AccountId, + info: &crate::ContractInfo, +) -> BalanceOf { + let storage_base_deposit = Pallet::::min_balance() + 1u32.into(); + ContractInfoOf::::insert( + account, + ContractInfo { + trie_id: info.trie_id.clone(), + code_hash: info.code_hash, + storage_bytes: Default::default(), + storage_items: Default::default(), + storage_byte_deposit: Default::default(), + storage_item_deposit: Default::default(), + storage_base_deposit, + delegate_dependencies: Default::default(), + }, + ); + + storage_base_deposit +} + +#[storage_alias] +pub type ContractInfoOf = + StorageMap, Twox64Concat, ::AccountId, ContractInfo>; + +#[derive(Encode, Decode, CloneNoBound, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +#[scale_info(skip_type_params(T))] +pub struct ContractInfo { + trie_id: TrieId, + code_hash: CodeHash, + storage_bytes: u32, + storage_items: u32, + storage_byte_deposit: BalanceOf, + storage_item_deposit: BalanceOf, + pub storage_base_deposit: BalanceOf, + delegate_dependencies: BoundedBTreeMap, BalanceOf, T::MaxDelegateDependencies>, +} + +#[derive(Encode, Decode, MaxEncodedLen, DefaultNoBound)] +pub struct Migration { + last_account: Option, +} + +impl MigrationStep for Migration { + const VERSION: u16 = 16; + + fn max_step_weight() -> Weight { + T::WeightInfo::v16_migration_step() + } + + fn step(&mut self, meter: &mut WeightMeter) -> IsFinished { + let mut iter = if let Some(last_account) = self.last_account.take() { + ContractInfoOf::::iter_keys_from(ContractInfoOf::::hashed_key_for(last_account)) + } else { + ContractInfoOf::::iter_keys() + }; + + if let Some(key) = iter.next() { + log::debug!(target: LOG_TARGET, "Migrating contract {:?}", key); + ContractInfoOf::::mutate(key.clone(), |info| { + let ed = Pallet::::min_balance(); + let mut updated_info = info.take().expect("Item exists; qed"); + updated_info.storage_base_deposit.saturating_reduce(ed); + *info = Some(updated_info); + }); + self.last_account = Some(key); + meter.consume(T::WeightInfo::v16_migration_step()); + IsFinished::No + } else { + log::debug!(target: LOG_TARGET, "No more contracts to migrate"); + meter.consume(T::WeightInfo::v16_migration_step()); + IsFinished::Yes + } + } +} diff --git a/pallets/contracts/src/primitives.rs b/pallets/contracts/src/primitives.rs new file mode 100644 index 00000000..622a69f5 --- /dev/null +++ b/pallets/contracts/src/primitives.rs @@ -0,0 +1,252 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! A crate that hosts a common definitions that are relevant for the pallet-contracts. + +use alloc::vec::Vec; +use codec::{Decode, Encode, MaxEncodedLen}; +use frame_support::weights::Weight; +use pallet_contracts_uapi::ReturnFlags; +use scale_info::TypeInfo; +use sp_runtime::{ + traits::{Saturating, Zero}, + DispatchError, RuntimeDebug, +}; + +/// Result type of a `bare_call` or `bare_instantiate` call as well as `ContractsApi::call` and +/// `ContractsApi::instantiate`. +/// +/// It contains the execution result together with some auxiliary information. +/// +/// #Note +/// +/// It has been extended to include `events` at the end of the struct while not bumping the +/// `ContractsApi` version. Therefore when SCALE decoding a `ContractResult` its trailing data +/// should be ignored to avoid any potential compatibility issues. +#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)] +pub struct ContractResult { + /// How much weight was consumed during execution. + pub gas_consumed: Weight, + /// How much weight is required as gas limit in order to execute this call. + /// + /// This value should be used to determine the weight limit for on-chain execution. + /// + /// # Note + /// + /// This can only different from [`Self::gas_consumed`] when weight pre charging + /// is used. Currently, only `seal_call_runtime` makes use of pre charging. + /// Additionally, any `seal_call` or `seal_instantiate` makes use of pre-charging + /// when a non-zero `gas_limit` argument is supplied. + pub gas_required: Weight, + /// How much balance was paid by the origin into the contract's deposit account in order to + /// pay for storage. + /// + /// The storage deposit is never actually charged from the origin in case of [`Self::result`] + /// is `Err`. This is because on error all storage changes are rolled back including the + /// payment of the deposit. + pub storage_deposit: StorageDeposit, + /// An optional debug message. This message is only filled when explicitly requested + /// by the code that calls into the contract. Otherwise it is empty. + /// + /// The contained bytes are valid UTF-8. This is not declared as `String` because + /// this type is not allowed within the runtime. + /// + /// Clients should not make any assumptions about the format of the buffer. + /// They should just display it as-is. It is **not** only a collection of log lines + /// provided by a contract but a formatted buffer with different sections. + /// + /// # Note + /// + /// The debug message is never generated during on-chain execution. It is reserved for + /// RPC calls. + pub debug_message: Vec, + /// The execution result of the wasm code. + pub result: R, + /// The events that were emitted during execution. It is an option as event collection is + /// optional. + pub events: Option>, +} + +/// Result type of a `bare_call` call as well as `ContractsApi::call`. +pub type ContractExecResult = + ContractResult, Balance, EventRecord>; + +/// Result type of a `bare_instantiate` call as well as `ContractsApi::instantiate`. +pub type ContractInstantiateResult = + ContractResult, DispatchError>, Balance, EventRecord>; + +/// Result type of a `bare_code_upload` call. +pub type CodeUploadResult = + Result, DispatchError>; + +/// Result type of a `get_storage` call. +pub type GetStorageResult = Result>, ContractAccessError>; + +/// The possible errors that can happen querying the storage of a contract. +#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, MaxEncodedLen, RuntimeDebug, TypeInfo)] +pub enum ContractAccessError { + /// The given address doesn't point to a contract. + DoesntExist, + /// Storage key cannot be decoded from the provided input data. + KeyDecodingFailed, + /// Storage is migrating. Try again later. + MigrationInProgress, +} + +/// Output of a contract call or instantiation which ran to completion. +#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug, TypeInfo)] +pub struct ExecReturnValue { + /// Flags passed along by `seal_return`. Empty when `seal_return` was never called. + pub flags: ReturnFlags, + /// Buffer passed along by `seal_return`. Empty when `seal_return` was never called. + pub data: Vec, +} + +impl ExecReturnValue { + /// The contract did revert all storage changes. + pub fn did_revert(&self) -> bool { + self.flags.contains(ReturnFlags::REVERT) + } +} + +/// The result of a successful contract instantiation. +#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug, TypeInfo)] +pub struct InstantiateReturnValue { + /// The output of the called constructor. + pub result: ExecReturnValue, + /// The account id of the new contract. + pub account_id: AccountId, +} + +/// The result of successfully uploading a contract. +#[derive(Clone, PartialEq, Eq, Encode, Decode, MaxEncodedLen, RuntimeDebug, TypeInfo)] +pub struct CodeUploadReturnValue { + /// The key under which the new code is stored. + pub code_hash: CodeHash, + /// The deposit that was reserved at the caller. Is zero when the code already existed. + pub deposit: Balance, +} + +/// Reference to an existing code hash or a new wasm module. +#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)] +pub enum Code { + /// A wasm module as raw bytes. + Upload(Vec), + /// The code hash of an on-chain wasm blob. + Existing(Hash), +} + +/// The amount of balance that was either charged or refunded in order to pay for storage. +#[derive( + Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, MaxEncodedLen, RuntimeDebug, TypeInfo, +)] +pub enum StorageDeposit { + /// The transaction reduced storage consumption. + /// + /// This means that the specified amount of balance was transferred from the involved + /// deposit accounts to the origin. + Refund(Balance), + /// The transaction increased storage consumption. + /// + /// This means that the specified amount of balance was transferred from the origin + /// to the involved deposit accounts. + Charge(Balance), +} + +impl Default for StorageDeposit { + fn default() -> Self { + Self::Charge(Zero::zero()) + } +} + +impl StorageDeposit { + /// Returns how much balance is charged or `0` in case of a refund. + pub fn charge_or_zero(&self) -> Balance { + match self { + Self::Charge(amount) => *amount, + Self::Refund(_) => Zero::zero(), + } + } + + pub fn is_zero(&self) -> bool { + match self { + Self::Charge(amount) => amount.is_zero(), + Self::Refund(amount) => amount.is_zero(), + } + } +} + +impl StorageDeposit +where + Balance: Saturating + Ord + Copy, +{ + /// This is essentially a saturating signed add. + pub fn saturating_add(&self, rhs: &Self) -> Self { + use StorageDeposit::*; + match (self, rhs) { + (Charge(lhs), Charge(rhs)) => Charge(lhs.saturating_add(*rhs)), + (Refund(lhs), Refund(rhs)) => Refund(lhs.saturating_add(*rhs)), + (Charge(lhs), Refund(rhs)) => + if lhs >= rhs { + Charge(lhs.saturating_sub(*rhs)) + } else { + Refund(rhs.saturating_sub(*lhs)) + }, + (Refund(lhs), Charge(rhs)) => + if lhs > rhs { + Refund(lhs.saturating_sub(*rhs)) + } else { + Charge(rhs.saturating_sub(*lhs)) + }, + } + } + + /// This is essentially a saturating signed sub. + pub fn saturating_sub(&self, rhs: &Self) -> Self { + use StorageDeposit::*; + match (self, rhs) { + (Charge(lhs), Refund(rhs)) => Charge(lhs.saturating_add(*rhs)), + (Refund(lhs), Charge(rhs)) => Refund(lhs.saturating_add(*rhs)), + (Charge(lhs), Charge(rhs)) => + if lhs >= rhs { + Charge(lhs.saturating_sub(*rhs)) + } else { + Refund(rhs.saturating_sub(*lhs)) + }, + (Refund(lhs), Refund(rhs)) => + if lhs > rhs { + Refund(lhs.saturating_sub(*rhs)) + } else { + Charge(rhs.saturating_sub(*lhs)) + }, + } + } + + /// If the amount of deposit (this type) is constrained by a `limit` this calculates how + /// much balance (if any) is still available from this limit. + /// + /// # Note + /// + /// In case of a refund the return value can be larger than `limit`. + pub fn available(&self, limit: &Balance) -> Balance { + use StorageDeposit::*; + match self { + Charge(amount) => limit.saturating_sub(*amount), + Refund(amount) => limit.saturating_add(*amount), + } + } +} diff --git a/pallets/contracts/src/schedule.rs b/pallets/contracts/src/schedule.rs new file mode 100644 index 00000000..80b8c54b --- /dev/null +++ b/pallets/contracts/src/schedule.rs @@ -0,0 +1,149 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This module contains the cost schedule and supporting code that constructs a +//! sane default schedule from a `WeightInfo` implementation. + +use crate::{weights::WeightInfo, Config}; + +use codec::{Decode, Encode}; +use core::marker::PhantomData; +use frame_support::DefaultNoBound; +use scale_info::TypeInfo; +#[cfg(feature = "std")] +use serde::{Deserialize, Serialize}; + +/// Definition of the cost schedule and other parameterizations for the wasm vm. +/// +/// Its [`Default`] implementation is the designated way to initialize this type. It uses +/// the benchmarked information supplied by [`Config::WeightInfo`]. All of its fields are +/// public and can therefore be modified. For example in order to change some of the limits +/// and set a custom instruction weight version the following code could be used: +/// ```rust +/// use pallet_contracts::{Schedule, Limits, InstructionWeights, Config}; +/// +/// fn create_schedule() -> Schedule { +/// Schedule { +/// limits: Limits { +/// memory_pages: 16, +/// .. Default::default() +/// }, +/// instruction_weights: InstructionWeights { +/// .. Default::default() +/// }, +/// .. Default::default() +/// } +/// } +/// ``` +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "std", serde(bound(serialize = "", deserialize = "")))] +#[cfg_attr(feature = "runtime-benchmarks", derive(frame_support::DebugNoBound))] +#[derive(Clone, Encode, Decode, PartialEq, Eq, DefaultNoBound, TypeInfo)] +#[scale_info(skip_type_params(T))] +pub struct Schedule { + /// Describes the upper limits on various metrics. + pub limits: Limits, + + /// The weights for individual wasm instructions. + pub instruction_weights: InstructionWeights, +} + +impl Schedule { + /// Returns the reference time per engine fuel. + pub fn ref_time_by_fuel(&self) -> u64 { + self.instruction_weights.base as u64 + } +} + +/// Describes the upper limits on various metrics. +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "runtime-benchmarks", derive(Debug))] +#[derive(Clone, Encode, Decode, PartialEq, Eq, TypeInfo)] +pub struct Limits { + /// The maximum number of topics supported by an event. + pub event_topics: u32, + + /// Maximum number of memory pages allowed for a contract. + pub memory_pages: u32, + + /// The maximum length of a subject in bytes used for PRNG generation. + pub subject_len: u32, + + /// The maximum size of a storage value and event payload in bytes. + pub payload_len: u32, + + /// The maximum node runtime memory. This is for integrity checks only and does not affect the + /// real setting. + pub runtime_memory: u32, + + /// The maximum validator node runtime memory. This is for integrity checks only and does not + /// affect the real setting. + pub validator_runtime_memory: u32, + + /// The additional ref_time added to the `deposit_event` host function call per event data + /// byte. + pub event_ref_time: u64, +} + +impl Limits { + /// The maximum memory size in bytes that a contract can occupy. + pub fn max_memory_size(&self) -> u32 { + self.memory_pages * 64 * 1024 + } +} + +/// Gas metering of Wasm executed instructions is being done on the engine side. +/// This struct holds a reference value used to gas units scaling between host and engine. +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "runtime-benchmarks", derive(frame_support::DebugNoBound))] +#[derive(Clone, Encode, Decode, PartialEq, Eq, TypeInfo)] +#[scale_info(skip_type_params(T))] +pub struct InstructionWeights { + /// Base instruction `ref_time` Weight. + /// Should match to wasmi's `1` fuel (see ). + pub base: u32, + /// The type parameter is used in the default implementation. + #[codec(skip)] + pub _phantom: PhantomData, +} + +impl Default for Limits { + fn default() -> Self { + Self { + event_topics: 4, + memory_pages: 16, + subject_len: 32, + payload_len: 16 * 1024, + runtime_memory: 1024 * 1024 * 128, + validator_runtime_memory: 1024 * 1024 * 512, + event_ref_time: 60_000, + } + } +} + +impl Default for InstructionWeights { + /// We execute 6 different instructions therefore we have to divide the actual + /// computed gas costs by 6 to have a rough estimate as to how expensive each + /// single executed instruction is going to be. + fn default() -> Self { + let instr_cost = T::WeightInfo::instr_i64_load_store(1) + .saturating_sub(T::WeightInfo::instr_i64_load_store(0)) + .ref_time() as u32; + let base = instr_cost / 6; + Self { base, _phantom: PhantomData } + } +} diff --git a/pallets/contracts/src/storage.rs b/pallets/contracts/src/storage.rs new file mode 100644 index 00000000..c0201266 --- /dev/null +++ b/pallets/contracts/src/storage.rs @@ -0,0 +1,480 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This module contains routines for accessing and altering a contract related state. + +pub mod meter; + +use crate::{ + exec::{AccountIdOf, Key}, + weights::WeightInfo, + BalanceOf, CodeHash, CodeInfo, Config, ContractInfoOf, DeletionQueue, DeletionQueueCounter, + Error, TrieId, SENTINEL, +}; +use alloc::vec::Vec; +use codec::{Decode, Encode, MaxEncodedLen}; +use core::marker::PhantomData; +use frame_support::{ + storage::child::{self, ChildInfo}, + weights::{Weight, WeightMeter}, + CloneNoBound, DefaultNoBound, +}; +use scale_info::TypeInfo; +use sp_core::Get; +use sp_io::KillStorageResult; +use sp_runtime::{ + traits::{Hash, Saturating, Zero}, + BoundedBTreeMap, DispatchError, DispatchResult, RuntimeDebug, +}; + +use self::meter::Diff; + +/// Information for managing an account and its sub trie abstraction. +/// This is the required info to cache for an account. +#[derive(Encode, Decode, CloneNoBound, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +#[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, + /// How many bytes of storage are accumulated in this contract's child trie. + storage_bytes: u32, + /// How many items of storage are accumulated in this contract's child trie. + 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. + 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. + storage_base_deposit: BalanceOf, + /// Map of code hashes and deposit balances. + /// + /// Tracks the code hash and deposit held for locking delegate dependencies. Dependencies added + /// to the map can not be removed from the chain state and can be safely used for delegate + /// calls. + delegate_dependencies: BoundedBTreeMap, BalanceOf, T::MaxDelegateDependencies>, +} + +impl ContractInfo { + /// Constructs a new contract info **without** writing it to storage. + /// + /// This returns an `Err` if an contract with the supplied `account` already exists + /// in storage. + pub fn new( + account: &AccountIdOf, + nonce: u64, + code_hash: CodeHash, + ) -> Result { + if >::contains_key(account) { + return Err(Error::::DuplicateContract.into()) + } + + let trie_id = { + let buf = (account, nonce).using_encoded(T::Hashing::hash); + buf.as_ref() + .to_vec() + .try_into() + .expect("Runtime uses a reasonable hash size. Hence sizeof(T::Hash) <= 128; qed") + }; + + let contract = Self { + trie_id, + code_hash, + storage_bytes: 0, + storage_items: 0, + storage_byte_deposit: Zero::zero(), + storage_item_deposit: Zero::zero(), + storage_base_deposit: Zero::zero(), + delegate_dependencies: Default::default(), + }; + + Ok(contract) + } + + /// Returns the number of locked delegate dependencies. + pub fn delegate_dependencies_count(&self) -> usize { + self.delegate_dependencies.len() + } + + /// Associated child trie unique id is built from the hash part of the trie id. + pub fn child_trie_info(&self) -> ChildInfo { + ChildInfo::new_default(self.trie_id.as_ref()) + } + + /// 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) + } + + /// Returns the storage base deposit of the contract. + pub fn storage_base_deposit(&self) -> BalanceOf { + self.storage_base_deposit + } + + /// Reads a storage kv pair of a contract. + /// + /// The read is performed from the `trie_id` only. The `address` is not necessary. If the + /// contract doesn't store under the given `key` `None` is returned. + pub fn read(&self, key: &Key) -> Option> { + child::get_raw(&self.child_trie_info(), key.hash().as_slice()) + } + + /// Returns `Some(len)` (in bytes) if a storage item exists at `key`. + /// + /// Returns `None` if the `key` wasn't previously set by `set_storage` or + /// was deleted. + pub fn size(&self, key: &Key) -> Option { + child::len(&self.child_trie_info(), key.hash().as_slice()) + } + + /// Update a storage entry into a contract's kv storage. + /// + /// If the `new_value` is `None` then the kv pair is removed. If `take` is true + /// a [`WriteOutcome::Taken`] is returned instead of a [`WriteOutcome::Overwritten`]. + /// + /// This function also records how much storage was created or removed if a `storage_meter` + /// is supplied. It should only be absent for testing or benchmarking code. + pub fn write( + &self, + key: &Key, + new_value: Option>, + storage_meter: Option<&mut meter::NestedMeter>, + take: bool, + ) -> Result { + let hashed_key = key.hash(); + self.write_raw(&hashed_key, new_value, storage_meter, take) + } + + /// Update a storage entry into a contract's kv storage. + /// Function used in benchmarks, which can simulate prefix collision in keys. + #[cfg(feature = "runtime-benchmarks")] + pub fn bench_write_raw( + &self, + key: &[u8], + new_value: Option>, + take: bool, + ) -> Result { + self.write_raw(key, new_value, None, take) + } + + fn write_raw( + &self, + key: &[u8], + new_value: Option>, + storage_meter: Option<&mut meter::NestedMeter>, + take: bool, + ) -> Result { + let child_trie_info = &self.child_trie_info(); + let (old_len, old_value) = if take { + let val = child::get_raw(child_trie_info, key); + (val.as_ref().map(|v| v.len() as u32), val) + } else { + (child::len(child_trie_info, key), None) + }; + + if let Some(storage_meter) = storage_meter { + let mut diff = meter::Diff::default(); + match (old_len, new_value.as_ref().map(|v| v.len() as u32)) { + (Some(old_len), Some(new_len)) => + if new_len > old_len { + diff.bytes_added = new_len - old_len; + } else { + diff.bytes_removed = old_len - new_len; + }, + (None, Some(new_len)) => { + diff.bytes_added = new_len; + diff.items_added = 1; + }, + (Some(old_len), None) => { + diff.bytes_removed = old_len; + diff.items_removed = 1; + }, + (None, None) => (), + } + storage_meter.charge(&diff); + } + + match &new_value { + Some(new_value) => child::put_raw(child_trie_info, key, new_value), + None => child::kill(child_trie_info, key), + } + + Ok(match (old_len, old_value) { + (None, _) => WriteOutcome::New, + (Some(old_len), None) => WriteOutcome::Overwritten(old_len), + (Some(_), Some(old_value)) => WriteOutcome::Taken(old_value), + }) + } + + /// Sets and returns the contract base deposit. + /// + /// The base deposit is updated when the `code_hash` of the contract changes, as it depends on + /// the deposit paid to upload the contract's code. + pub fn update_base_deposit(&mut self, code_info: &CodeInfo) -> BalanceOf { + let info_deposit = + Diff { bytes_added: self.encoded_size() as u32, items_added: 1, ..Default::default() } + .update_contract::(None) + .charge_or_zero(); + + // Instantiating the contract prevents its code to be deleted, therefore the base deposit + // includes a fraction (`T::CodeHashLockupDepositPercent`) of the original storage deposit + // to prevent abuse. + let upload_deposit = T::CodeHashLockupDepositPercent::get().mul_ceil(code_info.deposit()); + + let deposit = info_deposit.saturating_add(upload_deposit); + self.storage_base_deposit = deposit; + deposit + } + + /// Adds a new delegate dependency to the contract. + /// The `amount` is the amount of funds that will be reserved for the dependency. + /// + /// Returns an error if the maximum number of delegate_dependencies is reached or if + /// the delegate dependency already exists. + pub fn lock_delegate_dependency( + &mut self, + code_hash: CodeHash, + amount: BalanceOf, + ) -> DispatchResult { + self.delegate_dependencies + .try_insert(code_hash, amount) + .map_err(|_| Error::::MaxDelegateDependenciesReached)? + .map_or(Ok(()), |_| Err(Error::::DelegateDependencyAlreadyExists)) + .map_err(Into::into) + } + + /// Removes the delegate dependency from the contract and returns the deposit held for this + /// dependency. + /// + /// Returns an error if the entry doesn't exist. + pub fn unlock_delegate_dependency( + &mut self, + code_hash: &CodeHash, + ) -> Result, DispatchError> { + self.delegate_dependencies + .remove(code_hash) + .ok_or(Error::::DelegateDependencyNotFound.into()) + } + + /// Returns the delegate_dependencies of the contract. + pub fn delegate_dependencies( + &self, + ) -> &BoundedBTreeMap, BalanceOf, T::MaxDelegateDependencies> { + &self.delegate_dependencies + } + + /// Push a contract's trie to the deletion queue for lazy removal. + /// + /// You must make sure that the contract is also removed when queuing the trie for deletion. + pub fn queue_trie_for_deletion(&self) { + DeletionQueueManager::::load().insert(self.trie_id.clone()); + } + + /// Calculates the weight that is necessary to remove one key from the trie and how many + /// of those keys can be deleted from the deletion queue given the supplied weight limit. + pub fn deletion_budget(meter: &WeightMeter) -> (Weight, u32) { + let base_weight = T::WeightInfo::on_process_deletion_queue_batch(); + let weight_per_key = T::WeightInfo::on_initialize_per_trie_key(1) - + T::WeightInfo::on_initialize_per_trie_key(0); + + // `weight_per_key` being zero makes no sense and would constitute a failure to + // benchmark properly. We opt for not removing any keys at all in this case. + let key_budget = meter + .limit() + .saturating_sub(base_weight) + .checked_div_per_component(&weight_per_key) + .unwrap_or(0) as u32; + + (weight_per_key, key_budget) + } + + /// Delete as many items from the deletion queue possible within the supplied weight limit. + pub fn process_deletion_queue_batch(meter: &mut WeightMeter) { + if meter.try_consume(T::WeightInfo::on_process_deletion_queue_batch()).is_err() { + return + }; + + let mut queue = >::load(); + if queue.is_empty() { + return; + } + + let (weight_per_key, budget) = Self::deletion_budget(&meter); + let mut remaining_key_budget = budget; + while remaining_key_budget > 0 { + let Some(entry) = queue.next() else { break }; + + #[allow(deprecated)] + let outcome = child::kill_storage( + &ChildInfo::new_default(&entry.trie_id), + Some(remaining_key_budget), + ); + + match outcome { + // This happens when our budget wasn't large enough to remove all keys. + KillStorageResult::SomeRemaining(keys_removed) => { + remaining_key_budget.saturating_reduce(keys_removed); + break + }, + KillStorageResult::AllRemoved(keys_removed) => { + entry.remove(); + // charge at least one key even if none were removed. + remaining_key_budget = remaining_key_budget.saturating_sub(keys_removed.max(1)); + }, + }; + } + + meter.consume(weight_per_key.saturating_mul(u64::from(budget - remaining_key_budget))) + } + + /// Returns the code hash of the contract specified by `account` ID. + pub fn load_code_hash(account: &AccountIdOf) -> Option> { + >::get(account).map(|i| i.code_hash) + } +} + +/// Information about what happened to the pre-existing value when calling [`ContractInfo::write`]. +#[cfg_attr(any(test, feature = "runtime-benchmarks"), derive(Debug, PartialEq))] +pub enum WriteOutcome { + /// No value existed at the specified key. + New, + /// A value of the returned length was overwritten. + Overwritten(u32), + /// The returned value was taken out of storage before being overwritten. + /// + /// This is only returned when specifically requested because it causes additional work + /// depending on the size of the pre-existing value. When not requested [`Self::Overwritten`] + /// is returned instead. + Taken(Vec), +} + +impl WriteOutcome { + /// Extracts the size of the overwritten value or `0` if there + /// was no value in storage. + pub fn old_len(&self) -> u32 { + match self { + Self::New => 0, + Self::Overwritten(len) => *len, + Self::Taken(value) => value.len() as u32, + } + } + + /// Extracts the size of the overwritten value or `SENTINEL` if there + /// was no value in storage. + /// + /// # Note + /// + /// We cannot use `0` as sentinel value because there could be a zero sized + /// storage entry which is different from a non existing one. + pub fn old_len_with_sentinel(&self) -> u32 { + match self { + Self::New => SENTINEL, + Self::Overwritten(len) => *len, + Self::Taken(value) => value.len() as u32, + } + } +} + +/// Manage the removal of contracts storage that are marked for deletion. +/// +/// When a contract is deleted by calling `seal_terminate` it becomes inaccessible +/// immediately, but the deletion of the storage items it has accumulated is performed +/// later by pulling the contract from the queue in the `on_idle` hook. +#[derive(Encode, Decode, TypeInfo, MaxEncodedLen, DefaultNoBound, Clone)] +#[scale_info(skip_type_params(T))] +pub struct DeletionQueueManager { + /// Counter used as a key for inserting a new deleted contract in the queue. + /// The counter is incremented after each insertion. + insert_counter: u32, + /// The index used to read the next element to be deleted in the queue. + /// The counter is incremented after each deletion. + delete_counter: u32, + + _phantom: PhantomData, +} + +/// View on a contract that is marked for deletion. +struct DeletionQueueEntry<'a, T: Config> { + /// the trie id of the contract to delete. + trie_id: TrieId, + + /// A mutable reference on the queue so that the contract can be removed, and none can be added + /// or read in the meantime. + queue: &'a mut DeletionQueueManager, +} + +impl<'a, T: Config> DeletionQueueEntry<'a, T> { + /// Remove the contract from the deletion queue. + fn remove(self) { + >::remove(self.queue.delete_counter); + self.queue.delete_counter = self.queue.delete_counter.wrapping_add(1); + >::set(self.queue.clone()); + } +} + +impl DeletionQueueManager { + /// Load the `DeletionQueueCounter`, so we can perform read or write operations on the + /// DeletionQueue storage. + fn load() -> Self { + >::get() + } + + /// Returns `true` if the queue contains no elements. + fn is_empty(&self) -> bool { + self.insert_counter.wrapping_sub(self.delete_counter) == 0 + } + + /// Insert a contract in the deletion queue. + fn insert(&mut self, trie_id: TrieId) { + >::insert(self.insert_counter, trie_id); + self.insert_counter = self.insert_counter.wrapping_add(1); + >::set(self.clone()); + } + + /// Fetch the next contract to be deleted. + /// + /// Note: + /// we use the delete counter to get the next value to read from the queue and thus don't pay + /// the cost of an extra call to `sp_io::storage::next_key` to lookup the next entry in the map + fn next(&mut self) -> Option> { + if self.is_empty() { + return None + } + + let entry = >::get(self.delete_counter); + entry.map(|trie_id| DeletionQueueEntry { trie_id, queue: self }) + } +} + +#[cfg(test)] +impl DeletionQueueManager { + pub fn from_test_values(insert_counter: u32, delete_counter: u32) -> Self { + Self { insert_counter, delete_counter, _phantom: Default::default() } + } + pub fn as_test_tuple(&self) -> (u32, u32) { + (self.insert_counter, self.delete_counter) + } +} diff --git a/pallets/contracts/src/storage/meter.rs b/pallets/contracts/src/storage/meter.rs new file mode 100644 index 00000000..951cb259 --- /dev/null +++ b/pallets/contracts/src/storage/meter.rs @@ -0,0 +1,908 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This module contains functions to meter the storage deposit. + +use crate::{ + storage::ContractInfo, AccountIdOf, BalanceOf, CodeInfo, Config, Error, Event, HoldReason, + Inspect, Origin, Pallet, StorageDeposit as Deposit, System, LOG_TARGET, +}; + +use alloc::vec::Vec; +use core::{fmt::Debug, marker::PhantomData}; +use frame_support::{ + ensure, + traits::{ + fungible::{Mutate, MutateHold}, + tokens::{ + Fortitude, Fortitude::Polite, Precision, Preservation, Restriction, WithdrawConsequence, + }, + Get, + }, + DefaultNoBound, RuntimeDebugNoBound, +}; +use sp_runtime::{ + traits::{Saturating, Zero}, + DispatchError, FixedPointNumber, FixedU128, +}; + +/// Deposit that uses the native fungible's balance type. +pub type DepositOf = Deposit>; + +/// A production root storage meter that actually charges from its origin. +pub type Meter = RawMeter; + +/// A production nested storage meter that actually charges from its origin. +pub type NestedMeter = RawMeter; + +/// A production storage meter that actually charges from its origin. +/// +/// This can be used where we want to be generic over the state (Root vs. Nested). +pub type GenericMeter = RawMeter; + +/// A trait that allows to decouple the metering from the charging of balance. +/// +/// This mostly exists for testing so that the charging can be mocked. +pub trait Ext { + /// This checks whether `origin` is able to afford the storage deposit limit. + /// + /// It is necessary to do this check beforehand so that the charge won't fail later on. + /// + /// `origin`: The origin of the call stack from which is responsible for putting down a deposit. + /// `limit`: The limit with which the meter was constructed. + /// `min_leftover`: How much `free_balance` in addition to the existential deposit (ed) should + /// be left inside the `origin` account. + /// + /// Returns the limit that should be used by the meter. If origin can't afford the `limit` + /// it returns `Err`. + fn check_limit( + origin: &T::AccountId, + limit: Option>, + min_leftover: BalanceOf, + ) -> Result, DispatchError>; + /// This is called to inform the implementer that some balance should be charged due to + /// some interaction of the `origin` with a `contract`. + /// + /// The balance transfer can either flow from `origin` to `contract` or the other way + /// around depending on whether `amount` constitutes a `Charge` or a `Refund`. + /// It should be used in combination with `check_limit` to check that no more balance than this + /// limit is ever charged. + fn charge( + origin: &T::AccountId, + contract: &T::AccountId, + amount: &DepositOf, + state: &ContractState, + ) -> Result<(), DispatchError>; +} + +/// This [`Ext`] is used for actual on-chain execution when balance needs to be charged. +/// +/// It uses [`frame_support::traits::fungible::Mutate`] in order to do accomplish the reserves. +pub enum ReservingExt {} + +/// Used to implement a type state pattern for the meter. +/// +/// It is sealed and cannot be implemented outside of this module. +pub trait State: private::Sealed {} + +/// State parameter that constitutes a meter that is in its root state. +#[derive(Default, Debug)] +pub struct Root; + +/// State parameter that constitutes a meter that is in its nested state. +/// Its value indicates whether the nested meter has its own limit. +#[derive(DefaultNoBound, RuntimeDebugNoBound)] +pub enum Nested { + #[default] + DerivedLimit, + OwnLimit, +} + +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, 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 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>, + /// We store the nested state to determine if it has a special limit for sub-call. + nested: S, + /// Type parameter only used in impls. + _phantom: PhantomData, +} + +/// This type is used to describe a storage change when charging from the meter. +#[derive(Default, RuntimeDebugNoBound)] +pub struct Diff { + /// How many bytes were added to storage. + pub bytes_added: u32, + /// How many bytes were removed from storage. + pub bytes_removed: u32, + /// How many storage items were added to storage. + pub items_added: u32, + /// How many storage items were removed from storage. + pub items_removed: u32, +} + +impl Diff { + /// 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) + }; + + // 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) + } +} + +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), + } + } +} + +/// The state of a contract. +/// +/// In case of termination the beneficiary is indicated. +#[derive(RuntimeDebugNoBound, Clone, PartialEq, Eq)] +pub enum ContractState { + Alive, + Terminated { beneficiary: AccountIdOf }, +} + +/// 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. +/// The only exception is when a special (tougher) deposit limit is specified for a cross-contract +/// call. In that case the limit is enforced once the call is returned, rolling it back if +/// exhausted. +#[derive(RuntimeDebugNoBound, Clone)] +struct Charge { + contract: T::AccountId, + amount: DepositOf, + state: ContractState, +} + +/// 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. Upon termination the `reducible_balance` in the + /// contract's account is transferred to the [`beneficiary`]. + Terminated { deposit: DepositOf, beneficiary: AccountIdOf }, +} + +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, beneficiary: _ } | Self::Checked(deposit) => + deposit.clone(), + } + } +} + +impl Default for Contribution { + fn default() -> Self { + Self::Alive(Default::default()) + } +} + +/// Functions that apply to all states. +impl RawMeter +where + T: Config, + E: Ext, + S: State + Default + Debug, +{ + /// Create a new child that has its `limit`. + /// Passing `0` as the limit is interpreted as to take whatever is remaining from its parent. + /// + /// This is called whenever a new subcall is initiated in order to track the storage + /// 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, limit: BalanceOf) -> RawMeter { + debug_assert!(matches!(self.contract_state(), ContractState::Alive)); + // If a special limit is specified higher than it is available, + // we want to enforce the lesser limit to the nested meter, to fail in the sub-call. + let limit = self.available().min(limit); + if limit.is_zero() { + RawMeter { limit: self.available(), ..Default::default() } + } else { + RawMeter { limit, nested: Nested::OwnLimit, ..Default::default() } + } + } + + /// Absorb a child that was spawned to handle a sub call. + /// + /// This should be called whenever a sub call comes to its end and it is **not** reverted. + /// This does the actual balance transfer from/to `origin` and `contract` based on the + /// overall storage consumption of the call. It also updates the supplied contract info. + /// + /// In case a contract reverted the child meter should just be dropped in order to revert + /// any changes it recorded. + /// + /// # Parameters + /// + /// - `absorbed`: The child storage meter that should be absorbed. + /// - `origin`: The origin that spawned the original root meter. + /// - `contract`: The contract's account 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, + absorbed: RawMeter, + contract: &T::AccountId, + info: Option<&mut ContractInfo>, + ) { + let own_deposit = absorbed.own_contribution.update_contract(info); + self.total_deposit = self + .total_deposit + .saturating_add(&absorbed.total_deposit) + .saturating_add(&own_deposit); + self.charges.extend_from_slice(&absorbed.charges); + if !own_deposit.is_zero() { + self.charges.push(Charge { + contract: contract.clone(), + amount: own_deposit, + state: absorbed.contract_state(), + }); + } + } + + /// The amount of balance that is still available from the original `limit`. + fn available(&self) -> BalanceOf { + self.total_deposit.available(&self.limit) + } + + /// Returns the state of the currently executed contract. + fn contract_state(&self) -> ContractState { + match &self.own_contribution { + Contribution::Terminated { deposit: _, beneficiary } => + ContractState::Terminated { beneficiary: beneficiary.clone() }, + _ => ContractState::Alive, + } + } +} + +/// Functions that only apply to the root state. +impl RawMeter +where + T: Config, + E: Ext, +{ + /// Create new storage meter for the specified `origin` and `limit`. + /// + /// This tries to [`Ext::check_limit`] on `origin` and fails if this is not possible. + pub fn new( + origin: &Origin, + limit: Option>, + min_leftover: BalanceOf, + ) -> Result { + // Check the limit only if the origin is not root. + return match origin { + Origin::Root => Ok(Self { + limit: limit.unwrap_or(T::DefaultDepositLimit::get()), + ..Default::default() + }), + Origin::Signed(o) => { + let limit = E::check_limit(o, limit, min_leftover)?; + Ok(Self { limit, ..Default::default() }) + }, + } + } + + /// The total amount of deposit that should change hands as result of the execution + /// 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 try_into_deposit(self, origin: &Origin) -> Result, DispatchError> { + // Only refund or charge deposit if the origin is not root. + let origin = match origin { + Origin::Root => return Ok(Deposit::Charge(Zero::zero())), + Origin::Signed(o) => o, + }; + for charge in self.charges.iter().filter(|c| matches!(c.amount, Deposit::Refund(_))) { + E::charge(origin, &charge.contract, &charge.amount, &charge.state)?; + } + for charge in self.charges.iter().filter(|c| matches!(c.amount, Deposit::Charge(_))) { + E::charge(origin, &charge.contract, &charge.amount, &charge.state)?; + } + Ok(self.total_deposit) + } +} + +/// Functions that only apply to the nested state. +impl RawMeter +where + T: Config, + E: Ext, +{ + /// Charges `diff` from the meter. + pub fn charge(&mut self, diff: &Diff) { + match &mut self.own_contribution { + Contribution::Alive(own) => *own = own.saturating_add(diff), + _ => panic!("Charge is never called after termination; qed"), + }; + } + + /// Adds a deposit charge. + /// + /// Use this method instead of [`Self::charge`] when the charge is not the result of a storage + /// change. This is the case when a `delegate_dependency` is added or removed, or when the + /// `code_hash` is updated. [`Self::charge`] cannot be used here because we keep track of the + /// deposit charge separately from the storage charge. + pub fn charge_deposit(&mut self, contract: T::AccountId, amount: DepositOf) { + self.total_deposit = self.total_deposit.saturating_add(&amount); + self.charges.push(Charge { contract, amount, state: ContractState::Alive }); + } + + /// Charges from `origin` a storage deposit for contract instantiation. + /// + /// This immediately transfers the balance in order to create the account. + pub fn charge_instantiate( + &mut self, + origin: &T::AccountId, + contract: &T::AccountId, + contract_info: &mut ContractInfo, + code_info: &CodeInfo, + ) -> Result<(), DispatchError> { + debug_assert!(matches!(self.contract_state(), ContractState::Alive)); + + // We need to make sure that the contract's account exists. + let ed = Pallet::::min_balance(); + self.total_deposit = Deposit::Charge(ed); + T::Currency::transfer(origin, contract, ed, Preservation::Preserve)?; + + // A consumer is added at account creation and removed it on termination, otherwise the + // runtime could remove the account. As long as a contract exists its account must exist. + // With the consumer, a correct runtime cannot remove the account. + System::::inc_consumers(contract)?; + + let deposit = contract_info.update_base_deposit(&code_info); + let deposit = Deposit::Charge(deposit); + + self.charge_deposit(contract.clone(), deposit); + Ok(()) + } + + /// Call to tell the meter that the currently executing contract was terminated. + /// + /// This will manipulate the meter so that all storage deposit accumulated in + /// `contract_info` will be refunded to the `origin` of the meter. And the free + /// (`reducible_balance`) will be sent to the `beneficiary`. + pub fn terminate(&mut self, info: &ContractInfo, beneficiary: T::AccountId) { + debug_assert!(matches!(self.contract_state(), ContractState::Alive)); + self.own_contribution = Contribution::Terminated { + deposit: Deposit::Refund(info.total_deposit()), + beneficiary, + }; + } + + /// [`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 normally need to call this **once** for every call stack and not for every cross contract + /// call. However, if a dedicated limit is specified for a sub-call, this needs to be called + /// once the sub-call has returned. For this, the [`Self::enforce_subcall_limit`] wrapper is + /// used. + 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 matches!(self.contract_state(), ContractState::Alive) { + self.own_contribution = Contribution::Checked(deposit); + } + if let Deposit::Charge(amount) = total_deposit { + if amount > self.limit { + return Err(>::StorageDepositLimitExhausted.into()) + } + } + Ok(()) + } + + /// This is a wrapper around [`Self::enforce_limit`] to use on the exit from a sub-call to + /// enforce its special limit if needed. + pub fn enforce_subcall_limit( + &mut self, + info: Option<&mut ContractInfo>, + ) -> Result<(), DispatchError> { + match self.nested { + Nested::OwnLimit => self.enforce_limit(info), + Nested::DerivedLimit => Ok(()), + } + } +} + +impl Ext for ReservingExt { + fn check_limit( + origin: &T::AccountId, + limit: Option>, + min_leftover: BalanceOf, + ) -> Result, DispatchError> { + // We are sending the `min_leftover` and the `min_balance` from the origin + // account as part of a contract call. Hence origin needs to have those left over + // as free balance after accounting for all deposits. + let max = T::Currency::reducible_balance(origin, Preservation::Preserve, Polite) + .saturating_sub(min_leftover) + .saturating_sub(Pallet::::min_balance()); + let default = max.min(T::DefaultDepositLimit::get()); + let limit = limit.unwrap_or(default); + ensure!( + limit <= max && + matches!(T::Currency::can_withdraw(origin, limit), WithdrawConsequence::Success), + >::StorageDepositNotEnoughFunds, + ); + Ok(limit) + } + + fn charge( + origin: &T::AccountId, + contract: &T::AccountId, + amount: &DepositOf, + state: &ContractState, + ) -> Result<(), DispatchError> { + match amount { + Deposit::Charge(amount) | Deposit::Refund(amount) if amount.is_zero() => return Ok(()), + Deposit::Charge(amount) => { + // This could fail if the `origin` does not have enough liquidity. Ideally, though, + // this should have been checked before with `check_limit`. + T::Currency::transfer_and_hold( + &HoldReason::StorageDepositReserve.into(), + origin, + contract, + *amount, + Precision::Exact, + Preservation::Preserve, + Fortitude::Polite, + )?; + + Pallet::::deposit_event(Event::StorageDepositTransferredAndHeld { + from: origin.clone(), + to: contract.clone(), + amount: *amount, + }); + }, + Deposit::Refund(amount) => { + let transferred = T::Currency::transfer_on_hold( + &HoldReason::StorageDepositReserve.into(), + contract, + origin, + *amount, + Precision::BestEffort, + Restriction::Free, + Fortitude::Polite, + )?; + + Pallet::::deposit_event(Event::StorageDepositTransferredAndReleased { + from: contract.clone(), + to: origin.clone(), + amount: transferred, + }); + + if transferred < *amount { + // This should never happen, if it does it means that there is a bug in the + // runtime logic. In the rare case this happens we try to refund as much as we + // can, thus the `Precision::BestEffort`. + log::error!( + target: LOG_TARGET, + "Failed to repatriate full storage deposit {:?} from contract {:?} to origin {:?}. Transferred {:?}.", + amount, contract, origin, transferred, + ); + } + }, + } + if let ContractState::::Terminated { beneficiary } = state { + System::::dec_consumers(&contract); + // Whatever is left in the contract is sent to the termination beneficiary. + T::Currency::transfer( + &contract, + &beneficiary, + T::Currency::reducible_balance(&contract, Preservation::Expendable, Polite), + Preservation::Expendable, + )?; + } + Ok(()) + } +} + +mod private { + pub trait Sealed {} + impl Sealed for super::Root {} + impl Sealed for super::Nested {} +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + exec::AccountIdOf, + tests::{Test, ALICE, BOB, CHARLIE}, + }; + use frame_support::parameter_types; + use pretty_assertions::assert_eq; + + type TestMeter = RawMeter; + + parameter_types! { + static TestExtTestValue: TestExt = Default::default(); + } + + #[derive(Debug, PartialEq, Eq, Clone)] + struct LimitCheck { + origin: AccountIdOf, + limit: BalanceOf, + min_leftover: BalanceOf, + } + + #[derive(Debug, PartialEq, Eq, Clone)] + struct Charge { + origin: AccountIdOf, + contract: AccountIdOf, + amount: DepositOf, + state: ContractState, + } + + #[derive(Default, Debug, PartialEq, Eq, Clone)] + pub struct TestExt { + limit_checks: Vec, + charges: Vec, + } + + impl TestExt { + fn clear(&mut self) { + self.limit_checks.clear(); + self.charges.clear(); + } + } + + impl Ext for TestExt { + fn check_limit( + origin: &AccountIdOf, + limit: Option>, + min_leftover: BalanceOf, + ) -> Result, DispatchError> { + let limit = limit.unwrap_or(42); + TestExtTestValue::mutate(|ext| { + ext.limit_checks + .push(LimitCheck { origin: origin.clone(), limit, min_leftover }) + }); + Ok(limit) + } + + fn charge( + origin: &AccountIdOf, + contract: &AccountIdOf, + amount: &DepositOf, + state: &ContractState, + ) -> Result<(), DispatchError> { + TestExtTestValue::mutate(|ext| { + ext.charges.push(Charge { + origin: origin.clone(), + contract: contract.clone(), + amount: amount.clone(), + state: state.clone(), + }) + }); + Ok(()) + } + } + + fn clear_ext() { + TestExtTestValue::mutate(|ext| ext.clear()) + } + + struct ChargingTestCase { + origin: Origin, + deposit: DepositOf, + expected: TestExt, + } + + #[derive(Default)] + struct StorageInfo { + bytes: u32, + items: u32, + bytes_deposit: BalanceOf, + items_deposit: BalanceOf, + } + + fn new_info(info: StorageInfo) -> ContractInfo { + ContractInfo:: { + trie_id: Default::default(), + code_hash: Default::default(), + 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(), + delegate_dependencies: Default::default(), + } + } + + #[test] + fn new_reserves_balance_works() { + clear_ext(); + + TestMeter::new(&Origin::from_account_id(ALICE), Some(1_000), 0).unwrap(); + + assert_eq!( + TestExtTestValue::get(), + TestExt { + limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], + ..Default::default() + } + ) + } + + #[test] + fn empty_charge_works() { + clear_ext(); + + let mut meter = TestMeter::new(&Origin::from_account_id(ALICE), Some(1_000), 0).unwrap(); + assert_eq!(meter.available(), 1_000); + + // an empty charge does not create a `Charge` entry + let mut nested0 = meter.nested(BalanceOf::::zero()); + nested0.charge(&Default::default()); + meter.absorb(nested0, &BOB, None); + + assert_eq!( + TestExtTestValue::get(), + TestExt { + limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], + ..Default::default() + } + ) + } + + #[test] + fn charging_works() { + let test_cases = vec![ + ChargingTestCase { + origin: Origin::::from_account_id(ALICE), + deposit: Deposit::Refund(28), + expected: TestExt { + limit_checks: vec![LimitCheck { origin: ALICE, limit: 100, min_leftover: 0 }], + charges: vec![ + Charge { + origin: ALICE, + contract: CHARLIE, + amount: Deposit::Refund(10), + state: ContractState::Alive, + }, + Charge { + origin: ALICE, + contract: CHARLIE, + amount: Deposit::Refund(20), + state: ContractState::Alive, + }, + Charge { + origin: ALICE, + contract: BOB, + amount: Deposit::Charge(2), + state: ContractState::Alive, + }, + ], + }, + }, + ChargingTestCase { + origin: Origin::::Root, + deposit: Deposit::Charge(0), + expected: TestExt { limit_checks: vec![], charges: vec![] }, + }, + ]; + + for test_case in test_cases { + clear_ext(); + + let mut meter = TestMeter::new(&test_case.origin, Some(100), 0).unwrap(); + assert_eq!(meter.available(), 100); + + let mut nested0_info = new_info(StorageInfo { + bytes: 100, + items: 5, + bytes_deposit: 100, + items_deposit: 10, + }); + let mut nested0 = meter.nested(BalanceOf::::zero()); + 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(StorageInfo { + bytes: 100, + items: 10, + bytes_deposit: 100, + items_deposit: 20, + }); + let mut nested1 = nested0.nested(BalanceOf::::zero()); + nested1.charge(&Diff { items_removed: 5, ..Default::default() }); + nested0.absorb(nested1, &CHARLIE, Some(&mut nested1_info)); + + let mut nested2_info = new_info(StorageInfo { + bytes: 100, + items: 7, + bytes_deposit: 100, + items_deposit: 20, + }); + let mut nested2 = nested0.nested(BalanceOf::::zero()); + 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)); + + assert_eq!(meter.try_into_deposit(&test_case.origin).unwrap(), test_case.deposit); + + 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(), test_case.expected) + } + } + + #[test] + fn termination_works() { + let test_cases = vec![ + ChargingTestCase { + origin: Origin::::from_account_id(ALICE), + deposit: Deposit::Refund(108), + expected: TestExt { + limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], + charges: vec![ + Charge { + origin: ALICE, + contract: CHARLIE, + amount: Deposit::Refund(120), + state: ContractState::Terminated { beneficiary: CHARLIE }, + }, + Charge { + origin: ALICE, + contract: BOB, + amount: Deposit::Charge(12), + state: ContractState::Alive, + }, + ], + }, + }, + ChargingTestCase { + origin: Origin::::Root, + deposit: Deposit::Charge(0), + expected: TestExt { limit_checks: vec![], charges: vec![] }, + }, + ]; + + for test_case in test_cases { + clear_ext(); + + let mut meter = TestMeter::new(&test_case.origin, Some(1_000), 0).unwrap(); + assert_eq!(meter.available(), 1_000); + + let mut nested0 = meter.nested(BalanceOf::::zero()); + 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(BalanceOf::::zero()); + nested1.charge(&Diff { items_removed: 5, ..Default::default() }); + nested1.charge(&Diff { bytes_added: 20, ..Default::default() }); + nested1.terminate(&nested1_info, CHARLIE); + nested0.enforce_limit(Some(&mut nested1_info)).unwrap(); + nested0.absorb(nested1, &CHARLIE, None); + + meter.absorb(nested0, &BOB, None); + assert_eq!(meter.try_into_deposit(&test_case.origin).unwrap(), test_case.deposit); + assert_eq!(TestExtTestValue::get(), test_case.expected) + } + } +} diff --git a/pallets/contracts/src/test_utils.rs b/pallets/contracts/src/test_utils.rs new file mode 100644 index 00000000..564b2d2e --- /dev/null +++ b/pallets/contracts/src/test_utils.rs @@ -0,0 +1,30 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Shared utilities for testing contracts. +//! This is not part of the tests module because it is made public for other crates to use. +#![cfg(feature = "std")] +use frame_support::weights::Weight; +pub use sp_runtime::AccountId32; + +pub const ALICE: AccountId32 = AccountId32::new([1u8; 32]); +pub const BOB: AccountId32 = AccountId32::new([2u8; 32]); +pub const CHARLIE: AccountId32 = AccountId32::new([3u8; 32]); +pub const DJANGO: AccountId32 = AccountId32::new([4u8; 32]); + +pub const GAS_LIMIT: Weight = Weight::from_parts(100_000_000_000, 3 * 1024 * 1024); +pub mod builder; diff --git a/pallets/contracts/src/test_utils/builder.rs b/pallets/contracts/src/test_utils/builder.rs new file mode 100644 index 00000000..94540eca --- /dev/null +++ b/pallets/contracts/src/test_utils/builder.rs @@ -0,0 +1,220 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use super::GAS_LIMIT; +use crate::{ + AccountIdLookupOf, AccountIdOf, BalanceOf, Code, CodeHash, CollectEvents, Config, + ContractExecResult, ContractInstantiateResult, DebugInfo, Determinism, EventRecordOf, + ExecReturnValue, InstantiateReturnValue, OriginFor, Pallet, Weight, +}; +use codec::{Encode, HasCompact}; +use core::fmt::Debug; +use frame_support::pallet_prelude::DispatchResultWithPostInfo; +use paste::paste; +use scale_info::TypeInfo; + +/// Helper macro to generate a builder for contract API calls. +macro_rules! builder { + // Entry point to generate a builder for the given method. + ( + $method:ident($($field:ident: $type:ty,)*) -> $result:ty; + $($extra:item)* + ) => { + paste!{ + builder!([< $method:camel Builder >], $method($($field: $type,)* ) -> $result; $($extra)*); + } + }; + // Generate the builder struct and its methods. + ( + $name:ident, + $method:ident($($field:ident: $type:ty,)*) -> $result:ty; + $($extra:item)* + ) => { + #[doc = concat!("A builder to construct a ", stringify!($method), " call")] + pub struct $name { + $($field: $type,)* + } + + #[allow(dead_code)] + impl $name + where + as HasCompact>::Type: Clone + Eq + PartialEq + Debug + TypeInfo + Encode, + { + $( + #[doc = concat!("Set the ", stringify!($field))] + pub fn $field(mut self, value: $type) -> Self { + self.$field = value; + self + } + )* + + #[doc = concat!("Build the ", stringify!($method), " call")] + pub fn build(self) -> $result { + Pallet::::$method( + $(self.$field,)* + ) + } + + $($extra)* + } + } +} + +builder!( + instantiate_with_code( + origin: OriginFor, + value: BalanceOf, + gas_limit: Weight, + storage_deposit_limit: Option< as codec::HasCompact>::Type>, + code: Vec, + data: Vec, + salt: Vec, + ) -> DispatchResultWithPostInfo; + + /// Create an [`InstantiateWithCodeBuilder`] with default values. + pub fn instantiate_with_code(origin: OriginFor, code: Vec) -> Self { + Self { + origin: origin, + value: 0u32.into(), + gas_limit: GAS_LIMIT, + storage_deposit_limit: None, + code, + data: vec![], + salt: vec![], + } + } +); + +builder!( + instantiate( + origin: OriginFor, + value: BalanceOf, + gas_limit: Weight, + storage_deposit_limit: Option< as codec::HasCompact>::Type>, + code_hash: CodeHash, + data: Vec, + salt: Vec, + ) -> DispatchResultWithPostInfo; + + /// Create an [`InstantiateBuilder`] with default values. + pub fn instantiate(origin: OriginFor, code_hash: CodeHash) -> Self { + Self { + origin, + value: 0u32.into(), + gas_limit: GAS_LIMIT, + storage_deposit_limit: None, + code_hash, + data: vec![], + salt: vec![], + } + } +); + +builder!( + bare_instantiate( + origin: AccountIdOf, + value: BalanceOf, + gas_limit: Weight, + storage_deposit_limit: Option>, + code: Code>, + data: Vec, + salt: Vec, + debug: DebugInfo, + collect_events: CollectEvents, + ) -> ContractInstantiateResult, BalanceOf, EventRecordOf>; + + /// Build the instantiate call and unwrap the result. + pub fn build_and_unwrap_result(self) -> InstantiateReturnValue> { + self.build().result.unwrap() + } + + /// Build the instantiate call and unwrap the account id. + pub fn build_and_unwrap_account_id(self) -> AccountIdOf { + self.build().result.unwrap().account_id + } + + pub fn bare_instantiate(origin: AccountIdOf, code: Code>) -> Self { + Self { + origin, + value: 0u32.into(), + gas_limit: GAS_LIMIT, + storage_deposit_limit: None, + code, + data: vec![], + salt: vec![], + debug: DebugInfo::Skip, + collect_events: CollectEvents::Skip, + } + } +); + +builder!( + call( + origin: OriginFor, + dest: AccountIdLookupOf, + value: BalanceOf, + gas_limit: Weight, + storage_deposit_limit: Option< as codec::HasCompact>::Type>, + data: Vec, + ) -> DispatchResultWithPostInfo; + + /// Create a [`CallBuilder`] with default values. + pub fn call(origin: OriginFor, dest: AccountIdLookupOf) -> Self { + CallBuilder { + origin, + dest, + value: 0u32.into(), + gas_limit: GAS_LIMIT, + storage_deposit_limit: None, + data: vec![], + } + } +); + +builder!( + bare_call( + origin: AccountIdOf, + dest: AccountIdOf, + value: BalanceOf, + gas_limit: Weight, + storage_deposit_limit: Option>, + data: Vec, + debug: DebugInfo, + collect_events: CollectEvents, + determinism: Determinism, + ) -> ContractExecResult, EventRecordOf>; + + /// Build the call and unwrap the result. + pub fn build_and_unwrap_result(self) -> ExecReturnValue { + self.build().result.unwrap() + } + + /// Create a [`BareCallBuilder`] with default values. + pub fn bare_call(origin: AccountIdOf, dest: AccountIdOf) -> Self { + Self { + origin, + dest, + value: 0u32.into(), + gas_limit: GAS_LIMIT, + storage_deposit_limit: None, + data: vec![], + debug: DebugInfo::Skip, + collect_events: CollectEvents::Skip, + determinism: Determinism::Enforced, + } + } +); diff --git a/pallets/contracts/src/tests.rs b/pallets/contracts/src/tests.rs new file mode 100644 index 00000000..c3b6e327 --- /dev/null +++ b/pallets/contracts/src/tests.rs @@ -0,0 +1,4396 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +mod pallet_dummy; +mod test_debug; + +use self::{ + test_debug::TestDebug, + test_utils::{ensure_stored, expected_deposit}, +}; +use crate::{ + self as pallet_contracts, + chain_extension::{ + ChainExtension, Environment, Ext, InitState, RegisteredChainExtension, + Result as ExtensionResult, RetVal, ReturnFlags, + }, + exec::{Frame, Key}, + migration::codegen::LATEST_MIGRATION_VERSION, + primitives::CodeUploadReturnValue, + storage::DeletionQueueManager, + tests::test_utils::{get_contract, get_contract_checked}, + wasm::{Determinism, LoadingMode, ReturnErrorCode as RuntimeReturnCode}, + weights::WeightInfo, + Array, BalanceOf, Code, CodeHash, CodeInfoOf, CollectEvents, Config, ContractInfo, + ContractInfoOf, DebugInfo, DefaultAddressGenerator, DeletionQueueCounter, Error, HoldReason, + MigrationInProgress, Origin, Pallet, PristineCode, Schedule, +}; +use assert_matches::assert_matches; +use codec::{Decode, Encode}; +use frame_support::{ + assert_err, assert_err_ignore_postinfo, assert_err_with_weight, assert_noop, assert_ok, + derive_impl, + dispatch::{DispatchErrorWithPostInfo, PostDispatchInfo}, + pallet_prelude::EnsureOrigin, + parameter_types, + storage::child, + traits::{ + fungible::{BalancedHold, Inspect, Mutate, MutateHold}, + tokens::Preservation, + ConstU32, ConstU64, Contains, OnIdle, OnInitialize, StorageVersion, + }, + weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight, WeightMeter}, +}; +use frame_system::{EventRecord, Phase}; +use pallet_contracts_fixtures::compile_module; +use pretty_assertions::{assert_eq, assert_ne}; +use sp_core::ByteArray; +use sp_io::hashing::blake2_256; +use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; +use sp_runtime::{ + testing::H256, + traits::{BlakeTwo256, Convert, IdentityLookup}, + AccountId32, BuildStorage, DispatchError, Perbill, TokenError, +}; + +type Block = frame_system::mocking::MockBlock; + +frame_support::construct_runtime!( + pub enum Test + { + System: frame_system, + Balances: pallet_balances, + Timestamp: pallet_timestamp, + Randomness: pallet_insecure_randomness_collective_flip, + Utility: pallet_utility, + Contracts: pallet_contracts, + Proxy: pallet_proxy, + Dummy: pallet_dummy + } +); + +macro_rules! assert_return_code { + ( $x:expr , $y:expr $(,)? ) => {{ + 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::CodeInfoOf::::get($code_hash).map(|m| m.refcount()).unwrap(); + assert_eq!(is, $should); + }}; +} + +pub mod test_utils { + use super::{Contracts, DepositPerByte, DepositPerItem, Test}; + use crate::{ + exec::AccountIdOf, BalanceOf, CodeHash, CodeInfo, CodeInfoOf, Config, ContractInfo, + ContractInfoOf, Nonce, PristineCode, + }; + use codec::{Encode, MaxEncodedLen}; + use frame_support::traits::fungible::{InspectHold, Mutate}; + + pub fn place_contract(address: &AccountIdOf, code_hash: CodeHash) { + let nonce = >::mutate(|counter| { + *counter += 1; + *counter + }); + set_balance(address, Contracts::min_balance() * 10); + >::insert(code_hash, CodeInfo::new(address.clone())); + let contract = >::new(&address, nonce, code_hash).unwrap(); + >::insert(address, contract); + } + pub fn set_balance(who: &AccountIdOf, amount: u64) { + let _ = ::Currency::set_balance(who, amount); + } + pub fn get_balance(who: &AccountIdOf) -> u64 { + ::Currency::free_balance(who) + } + pub fn get_balance_on_hold( + reason: &::RuntimeHoldReason, + who: &AccountIdOf, + ) -> u64 { + ::Currency::balance_on_hold(reason.into(), 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 get_code_deposit(code_hash: &CodeHash) -> BalanceOf { + crate::CodeInfoOf::::get(code_hash).unwrap().deposit() + } + pub fn contract_info_storage_deposit( + addr: &::AccountId, + ) -> BalanceOf { + let contract_info = self::get_contract(&addr); + let info_size = contract_info.encoded_size() as u64; + DepositPerByte::get() + .saturating_mul(info_size) + .saturating_add(DepositPerItem::get()) + } + pub fn expected_deposit(code_len: usize) -> u64 { + // For code_info, the deposit for max_encoded_len is taken. + let code_info_len = CodeInfo::::max_encoded_len() as u64; + // Calculate deposit to be reserved. + // We add 2 storage items: one for code, other for code_info + DepositPerByte::get().saturating_mul(code_len as u64 + code_info_len) + + DepositPerItem::get().saturating_mul(2) + } + pub fn ensure_stored(code_hash: CodeHash) -> usize { + // Assert that code_info is stored + assert!(CodeInfoOf::::contains_key(&code_hash)); + // Assert that contract code is stored, and get its size. + PristineCode::::try_get(&code_hash).unwrap().len() + } +} + +mod builder { + use super::Test; + use crate::{ + test_utils::{builder::*, AccountId32, ALICE}, + tests::RuntimeOrigin, + AccountIdLookupOf, Code, CodeHash, + }; + + pub fn bare_instantiate(code: Code>) -> BareInstantiateBuilder { + BareInstantiateBuilder::::bare_instantiate(ALICE, code) + } + + pub fn bare_call(dest: AccountId32) -> BareCallBuilder { + BareCallBuilder::::bare_call(ALICE, dest) + } + + pub fn instantiate_with_code(code: Vec) -> InstantiateWithCodeBuilder { + InstantiateWithCodeBuilder::::instantiate_with_code( + RuntimeOrigin::signed(ALICE), + code, + ) + } + + pub fn instantiate(code_hash: CodeHash) -> InstantiateBuilder { + InstantiateBuilder::::instantiate(RuntimeOrigin::signed(ALICE), code_hash) + } + + pub fn call(dest: AccountIdLookupOf) -> CallBuilder { + CallBuilder::::call(RuntimeOrigin::signed(ALICE), dest) + } +} + +impl Test { + pub fn set_unstable_interface(unstable_interface: bool) { + UNSTABLE_INTERFACE.with(|v| *v.borrow_mut() = unstable_interface); + } +} + +parameter_types! { + static TestExtensionTestValue: TestExtension = Default::default(); +} + +#[derive(Clone)] +pub struct TestExtension { + enabled: bool, + last_seen_buffer: Vec, + last_seen_input_len: u32, +} + +#[derive(Default)] +pub struct RevertingExtension; + +#[derive(Default)] +pub struct DisabledExtension; + +#[derive(Default)] +pub struct TempStorageExtension { + storage: u32, +} + +impl TestExtension { + fn disable() { + TestExtensionTestValue::mutate(|e| e.enabled = false) + } + + fn last_seen_buffer() -> Vec { + TestExtensionTestValue::get().last_seen_buffer.clone() + } + + fn last_seen_input_len() -> u32 { + TestExtensionTestValue::get().last_seen_input_len + } +} + +impl Default for TestExtension { + fn default() -> Self { + Self { enabled: true, last_seen_buffer: vec![], last_seen_input_len: 0 } + } +} + +impl ChainExtension for TestExtension { + fn call(&mut self, env: Environment) -> ExtensionResult + where + E: Ext, + { + let func_id = env.func_id(); + let id = env.ext_id() as u32 | func_id as u32; + match func_id { + 0 => { + let mut env = env.buf_in_buf_out(); + let input = env.read(8)?; + env.write(&input, false, None)?; + TestExtensionTestValue::mutate(|e| e.last_seen_buffer = input); + Ok(RetVal::Converging(id)) + }, + 1 => { + let env = env.only_in(); + TestExtensionTestValue::mutate(|e| e.last_seen_input_len = env.val1()); + Ok(RetVal::Converging(id)) + }, + 2 => { + let mut env = env.buf_in_buf_out(); + let mut enc = &env.read(9)?[4..8]; + let weight = Weight::from_parts( + u32::decode(&mut enc).map_err(|_| Error::::ContractTrapped)?.into(), + 0, + ); + env.charge_weight(weight)?; + Ok(RetVal::Converging(id)) + }, + 3 => Ok(RetVal::Diverging { flags: ReturnFlags::REVERT, data: vec![42, 99] }), + _ => { + panic!("Passed unknown id to test chain extension: {}", func_id); + }, + } + } + + fn enabled() -> bool { + TestExtensionTestValue::get().enabled + } +} + +impl RegisteredChainExtension for TestExtension { + const ID: u16 = 0; +} + +impl ChainExtension for RevertingExtension { + fn call(&mut self, _env: Environment) -> ExtensionResult + where + E: Ext, + { + Ok(RetVal::Diverging { flags: ReturnFlags::REVERT, data: vec![0x4B, 0x1D] }) + } + + fn enabled() -> bool { + TestExtensionTestValue::get().enabled + } +} + +impl RegisteredChainExtension for RevertingExtension { + const ID: u16 = 1; +} + +impl ChainExtension for DisabledExtension { + fn call(&mut self, _env: Environment) -> ExtensionResult + where + E: Ext, + { + panic!("Disabled chain extensions are never called") + } + + fn enabled() -> bool { + false + } +} + +impl RegisteredChainExtension for DisabledExtension { + const ID: u16 = 2; +} + +impl ChainExtension for TempStorageExtension { + fn call(&mut self, env: Environment) -> ExtensionResult + where + E: Ext, + { + let func_id = env.func_id(); + match func_id { + 0 => self.storage = 42, + 1 => assert_eq!(self.storage, 42, "Storage is preserved inside the same call."), + 2 => { + assert_eq!(self.storage, 0, "Storage is different for different calls."); + self.storage = 99; + }, + 3 => assert_eq!(self.storage, 99, "Storage is preserved inside the same call."), + _ => { + panic!("Passed unknown id to test chain extension: {}", func_id); + }, + } + Ok(RetVal::Converging(0)) + } + + fn enabled() -> bool { + TestExtensionTestValue::get().enabled + } +} + +impl RegisteredChainExtension for TempStorageExtension { + const ID: u16 = 3; +} + +parameter_types! { + pub BlockWeights: frame_system::limits::BlockWeights = + frame_system::limits::BlockWeights::simple_max( + Weight::from_parts(2u64 * WEIGHT_REF_TIME_PER_SECOND, u64::MAX), + ); + pub static ExistentialDeposit: u64 = 1; +} + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] +impl frame_system::Config for Test { + type Block = Block; + type AccountId = AccountId32; + type Lookup = IdentityLookup; + type AccountData = pallet_balances::AccountData; +} + +impl pallet_insecure_randomness_collective_flip::Config for Test {} + +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] +impl pallet_balances::Config for Test { + type ExistentialDeposit = ExistentialDeposit; + type ReserveIdentifier = [u8; 8]; + type AccountStore = System; +} + +#[derive_impl(pallet_timestamp::config_preludes::TestDefaultConfig)] +impl pallet_timestamp::Config for Test {} + +impl pallet_utility::Config for Test { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type PalletsOrigin = OriginCaller; + type WeightInfo = (); +} + +impl pallet_proxy::Config for Test { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type Currency = Balances; + type ProxyType = (); + type ProxyDepositBase = ConstU64<1>; + type ProxyDepositFactor = ConstU64<1>; + type MaxProxies = ConstU32<32>; + type WeightInfo = (); + type MaxPending = ConstU32<32>; + type CallHasher = BlakeTwo256; + type AnnouncementDepositBase = ConstU64<1>; + type AnnouncementDepositFactor = ConstU64<1>; +} + +impl pallet_dummy::Config for Test {} + +parameter_types! { + pub MySchedule: Schedule = { + let schedule = >::default(); + schedule + }; + pub static DepositPerByte: BalanceOf = 1; + pub const DepositPerItem: BalanceOf = 2; + pub static MaxDelegateDependencies: u32 = 32; + pub static MaxTransientStorageSize: u32 = 4 * 1024; + + pub static CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0); + // We need this one set high enough for running benchmarks. + pub static DefaultDepositLimit: BalanceOf = 10_000_000; +} + +impl Convert> for Test { + fn convert(w: Weight) -> BalanceOf { + w.ref_time() + } +} + +/// A filter whose filter function can be swapped at runtime. +pub struct TestFilter; + +#[derive(Clone)] +pub struct Filters { + filter: fn(&RuntimeCall) -> bool, +} + +impl Default for Filters { + fn default() -> Self { + Filters { filter: (|_| true) } + } +} + +parameter_types! { + static CallFilter: Filters = Default::default(); +} + +impl TestFilter { + pub fn set_filter(filter: fn(&RuntimeCall) -> bool) { + CallFilter::mutate(|fltr| fltr.filter = filter); + } +} + +impl Contains for TestFilter { + fn contains(call: &RuntimeCall) -> bool { + (CallFilter::get().filter)(call) + } +} + +parameter_types! { + pub static UploadAccount: Option<::AccountId> = None; + pub static InstantiateAccount: Option<::AccountId> = None; +} + +pub struct EnsureAccount(core::marker::PhantomData<(T, A)>); +impl>>> + EnsureOrigin<::RuntimeOrigin> for EnsureAccount +where + ::AccountId: From, +{ + type Success = T::AccountId; + + fn try_origin(o: T::RuntimeOrigin) -> Result { + let who = as EnsureOrigin<_>>::try_origin(o.clone())?; + if matches!(A::get(), Some(a) if who != a) { + return Err(o) + } + + Ok(who) + } + + #[cfg(feature = "runtime-benchmarks")] + fn try_successful_origin() -> Result { + Err(()) + } +} +parameter_types! { + pub static UnstableInterface: bool = true; +} + +#[derive_impl(crate::config_preludes::TestDefaultConfig)] +impl Config for Test { + type Time = Timestamp; + type Randomness = Randomness; + type Currency = Balances; + type CallFilter = TestFilter; + type CallStack = [Frame; 5]; + type ChainExtension = + (TestExtension, DisabledExtension, RevertingExtension, TempStorageExtension); + type Schedule = MySchedule; + type DepositPerByte = DepositPerByte; + type DepositPerItem = DepositPerItem; + type DefaultDepositLimit = DefaultDepositLimit; + type AddressGenerator = DefaultAddressGenerator; + type UnsafeUnstableInterface = UnstableInterface; + type UploadOrigin = EnsureAccount; + type InstantiateOrigin = EnsureAccount; + type Migrations = crate::migration::codegen::BenchMigrations; + type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; + type MaxDelegateDependencies = MaxDelegateDependencies; + type MaxTransientStorageSize = MaxTransientStorageSize; + type Debug = TestDebug; +} + +pub const ALICE: AccountId32 = AccountId32::new([1u8; 32]); +pub const BOB: AccountId32 = AccountId32::new([2u8; 32]); +pub const CHARLIE: AccountId32 = AccountId32::new([3u8; 32]); +pub const DJANGO: AccountId32 = AccountId32::new([4u8; 32]); + +pub const GAS_LIMIT: Weight = Weight::from_parts(100_000_000_000, 3 * 1024 * 1024); + +pub struct ExtBuilder { + existential_deposit: u64, + storage_version: Option, + code_hashes: Vec>, +} + +impl Default for ExtBuilder { + fn default() -> Self { + Self { + existential_deposit: ExistentialDeposit::get(), + storage_version: None, + code_hashes: vec![], + } + } +} + +impl ExtBuilder { + pub fn existential_deposit(mut self, existential_deposit: u64) -> Self { + self.existential_deposit = existential_deposit; + self + } + pub fn with_code_hashes(mut self, code_hashes: Vec>) -> Self { + self.code_hashes = code_hashes; + self + } + pub fn set_associated_consts(&self) { + EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit); + } + pub fn set_storage_version(mut self, version: u16) -> Self { + self.storage_version = Some(StorageVersion::new(version)); + self + } + pub fn build(self) -> sp_io::TestExternalities { + sp_tracing::try_init_simple(); + self.set_associated_consts(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + pallet_balances::GenesisConfig:: { balances: vec![] } + .assimilate_storage(&mut t) + .unwrap(); + let mut ext = sp_io::TestExternalities::new(t); + ext.register_extension(KeystoreExt::new(MemoryKeystore::new())); + ext.execute_with(|| { + use frame_support::traits::OnGenesis; + + Pallet::::on_genesis(); + if let Some(storage_version) = self.storage_version { + storage_version.put::>(); + } + System::set_block_number(1) + }); + ext.execute_with(|| { + for code_hash in self.code_hashes { + CodeInfoOf::::insert(code_hash, crate::CodeInfo::new(ALICE)); + } + }); + ext + } +} + +fn initialize_block(number: u64) { + System::reset_events(); + System::initialize(&number, &[0u8; 32].into(), &Default::default()); +} + +struct ExtensionInput<'a> { + extension_id: u16, + func_id: u16, + extra: &'a [u8], +} + +impl<'a> ExtensionInput<'a> { + fn to_vec(&self) -> Vec { + ((self.extension_id as u32) << 16 | (self.func_id as u32)) + .to_le_bytes() + .iter() + .chain(self.extra) + .cloned() + .collect() + } +} + +impl<'a> From> for Vec { + fn from(input: ExtensionInput) -> Vec { + input.to_vec() + } +} + +impl Default for Origin { + fn default() -> Self { + Self::Signed(ALICE) + } +} +// Perform a call to a plain account. +// The actual transfer fails because we can only call contracts. +// Then we check that at least the base costs where charged (no runtime gas costs.) +#[test] +fn calling_plain_account_fails() { + ExtBuilder::default().build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 100_000_000); + let base_cost = <::WeightInfo as WeightInfo>::call(); + + assert_eq!( + builder::call(BOB).build(), + Err(DispatchErrorWithPostInfo { + error: Error::::ContractNotFound.into(), + post_info: PostDispatchInfo { + actual_weight: Some(base_cost), + pays_fee: Default::default(), + }, + }) + ); + }); +} + +#[test] +fn migration_on_idle_hooks_works() { + // Defines expectations of how many migration steps can be done given the weight limit. + let tests = [ + (Weight::zero(), LATEST_MIGRATION_VERSION - 2), + (::WeightInfo::migrate() + 1.into(), LATEST_MIGRATION_VERSION - 1), + (Weight::MAX, LATEST_MIGRATION_VERSION), + ]; + + for (weight, expected_version) in tests { + ExtBuilder::default() + .set_storage_version(LATEST_MIGRATION_VERSION - 2) + .build() + .execute_with(|| { + MigrationInProgress::::set(Some(Default::default())); + Contracts::on_idle(System::block_number(), weight); + assert_eq!(StorageVersion::get::>(), expected_version); + }); + } +} + +#[test] +fn migration_in_progress_works() { + let (wasm, code_hash) = compile_module::("dummy").unwrap(); + + ExtBuilder::default().existential_deposit(1).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + MigrationInProgress::::set(Some(Default::default())); + + assert_err!( + Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + vec![], + None, + Determinism::Enforced + ), + Error::::MigrationInProgress, + ); + assert_err!( + Contracts::remove_code(RuntimeOrigin::signed(ALICE), code_hash), + Error::::MigrationInProgress, + ); + assert_err!( + Contracts::set_code(RuntimeOrigin::signed(ALICE), BOB.clone(), code_hash), + Error::::MigrationInProgress, + ); + assert_err_ignore_postinfo!(builder::call(BOB).build(), Error::::MigrationInProgress); + assert_err_ignore_postinfo!( + builder::instantiate_with_code(wasm).value(100_000).build(), + Error::::MigrationInProgress, + ); + assert_err_ignore_postinfo!( + builder::instantiate(code_hash).value(100_000).build(), + Error::::MigrationInProgress, + ); + }); +} + +#[test] +fn instantiate_and_call_and_deposit_event() { + let (wasm, code_hash) = compile_module::("event_and_return_on_deploy").unwrap(); + + ExtBuilder::default().existential_deposit(1).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + let value = 100; + + // 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( + RuntimeOrigin::signed(ALICE), + wasm, + None, + Determinism::Enforced + )); + + // Drop previous events + initialize_block(2); + + // Check at the end to get hash on error easily + let addr = builder::bare_instantiate(Code::Existing(code_hash)) + .value(value) + .build_and_unwrap_account_id(); + assert!(ContractInfoOf::::contains_key(&addr)); + + assert_eq!( + System::events(), + vec![ + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::System(frame_system::Event::NewAccount { + account: addr.clone() + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Endowed { + account: addr.clone(), + free_balance: min_balance, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: ALICE, + to: addr.clone(), + amount: min_balance, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: ALICE, + to: addr.clone(), + amount: value, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::ContractEmitted { + contract: addr.clone(), + data: vec![1, 2, 3, 4] + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Instantiated { + deployer: ALICE, + contract: addr.clone() + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts( + pallet_contracts::Event::StorageDepositTransferredAndHeld { + from: ALICE, + to: addr.clone(), + amount: test_utils::contract_info_storage_deposit(&addr), + } + ), + topics: vec![], + }, + ] + ); + }); +} + +#[test] +fn deposit_event_max_value_limit() { + let (wasm, _code_hash) = compile_module::("event_size").unwrap(); + + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + // Create + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(30_000) + .build_and_unwrap_account_id(); + + // Call contract with allowed storage value. + assert_ok!(builder::call(addr.clone()) + .gas_limit(GAS_LIMIT.set_ref_time(GAS_LIMIT.ref_time() * 2)) // we are copying a huge buffer, + .data(::Schedule::get().limits.payload_len.encode()) + .build()); + + // Call contract with too large a storage value. + assert_err_ignore_postinfo!( + builder::call(addr) + .data((::Schedule::get().limits.payload_len + 1).encode()) + .build(), + Error::::ValueTooLarge, + ); + }); +} + +// Fail out of fuel (ref_time weight) in the engine. +#[test] +fn run_out_of_fuel_engine() { + let (wasm, _code_hash) = compile_module::("run_out_of_gas").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(100 * min_balance) + .build_and_unwrap_account_id(); + + // Call the contract with a fixed gas limit. It must run out of gas because it just + // loops forever. + assert_err_ignore_postinfo!( + builder::call(addr) + .gas_limit(Weight::from_parts(1_000_000_000_000, u64::MAX)) + .build(), + Error::::OutOfGas, + ); + }); +} + +// Fail out of fuel (ref_time weight) in the host. +#[test] +fn run_out_of_fuel_host() { + let (code, _hash) = compile_module::("chain_extension").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + + let addr = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + let gas_limit = Weight::from_parts(u32::MAX as u64, GAS_LIMIT.proof_size()); + + // Use chain extension to charge more ref_time than it is available. + let result = builder::bare_call(addr.clone()) + .gas_limit(gas_limit) + .data(ExtensionInput { extension_id: 0, func_id: 2, extra: &u32::MAX.encode() }.into()) + .build() + .result; + assert_err!(result, >::OutOfGas); + }); +} + +#[test] +fn gas_syncs_work() { + let (code, _code_hash) = compile_module::("caller_is_origin_n").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let addr = builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_account_id(); + + let result = builder::bare_call(addr.clone()).data(0u32.encode()).build(); + assert_ok!(result.result); + let engine_consumed_noop = result.gas_consumed.ref_time(); + + let result = builder::bare_call(addr.clone()).data(1u32.encode()).build(); + assert_ok!(result.result); + let gas_consumed_once = result.gas_consumed.ref_time(); + let host_consumed_once = ::WeightInfo::seal_caller_is_origin().ref_time(); + let engine_consumed_once = gas_consumed_once - host_consumed_once - engine_consumed_noop; + + let result = builder::bare_call(addr).data(2u32.encode()).build(); + assert_ok!(result.result); + let gas_consumed_twice = result.gas_consumed.ref_time(); + let host_consumed_twice = host_consumed_once * 2; + let engine_consumed_twice = gas_consumed_twice - host_consumed_twice - engine_consumed_noop; + + // Second contract just repeats first contract's instructions twice. + // If runtime syncs gas with the engine properly, this should pass. + assert_eq!(engine_consumed_twice, engine_consumed_once * 2); + }); +} + +/// Check that contracts with the same account id have different trie ids. +/// Check the `Nonce` storage item for more information. +#[test] +fn instantiate_unique_trie_id() { + let (wasm, code_hash) = compile_module::("self_destruct").unwrap(); + + ExtBuilder::default().existential_deposit(500).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, None, Determinism::Enforced) + .unwrap(); + + // Instantiate the contract and store its trie id for later comparison. + let addr = + builder::bare_instantiate(Code::Existing(code_hash)).build_and_unwrap_account_id(); + let trie_id = get_contract(&addr).trie_id; + + // Try to instantiate it again without termination should yield an error. + assert_err_ignore_postinfo!( + builder::instantiate(code_hash).build(), + >::DuplicateContract, + ); + + // Terminate the contract. + assert_ok!(builder::call(addr.clone()).build()); + + // Re-Instantiate after termination. + assert_ok!(builder::instantiate(code_hash).build()); + + // Trie ids shouldn't match or we might have a collision + assert_ne!(trie_id, get_contract(&addr).trie_id); + }); +} + +#[test] +fn storage_work() { + let (code, _code_hash) = compile_module::("storage").unwrap(); + + ExtBuilder::default().build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + let addr = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + builder::bare_call(addr).build_and_unwrap_result(); + }); +} + +#[test] +fn storage_max_value_limit() { + let (wasm, _code_hash) = compile_module::("storage_size").unwrap(); + + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + // Create + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(30_000) + .build_and_unwrap_account_id(); + get_contract(&addr); + + // Call contract with allowed storage value. + assert_ok!(builder::call(addr.clone()) + .gas_limit(GAS_LIMIT.set_ref_time(GAS_LIMIT.ref_time() * 2)) // we are copying a huge buffer + .data(::Schedule::get().limits.payload_len.encode()) + .build()); + + // Call contract with too large a storage value. + assert_err_ignore_postinfo!( + builder::call(addr) + .data((::Schedule::get().limits.payload_len + 1).encode()) + .build(), + Error::::ValueTooLarge, + ); + }); +} + +#[test] +fn transient_storage_work() { + let (code, _code_hash) = compile_module::("transient_storage").unwrap(); + + ExtBuilder::default().build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + let addr = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + builder::bare_call(addr).build_and_unwrap_result(); + }); +} + +#[test] +fn transient_storage_limit_in_call() { + let (wasm_caller, _code_hash_caller) = + compile_module::("create_transient_storage_and_call").unwrap(); + let (wasm_callee, _code_hash_callee) = compile_module::("set_transient_storage").unwrap(); + ExtBuilder::default().build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + + // Create both contracts: Constructors do nothing. + let addr_caller = builder::bare_instantiate(Code::Upload(wasm_caller)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + let addr_callee = builder::bare_instantiate(Code::Upload(wasm_callee)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + let storage_value_size = 1000; + MaxTransientStorageSize::set(4 * 1024); + // Call contracts with storage values within the limit. + // Caller and Callee contracts each set a transient storage value of size 1000. + assert_ok!(builder::call(addr_caller.clone()) + .data((storage_value_size, storage_value_size, &addr_callee).encode()) + .build(),); + + MaxTransientStorageSize::set(512); + // Call a contract with a storage value that is too large. + // Limit exceeded in the caller contract. + assert_err_ignore_postinfo!( + builder::call(addr_caller.clone()) + .data((storage_value_size, storage_value_size, &addr_callee).encode()) + .build(), + >::OutOfTransientStorage, + ); + + MaxTransientStorageSize::set(1536); + // Call a contract with a storage value that is too large. + // Limit exceeded in the callee contract. + assert_err_ignore_postinfo!( + builder::call(addr_caller) + .data((storage_value_size, storage_value_size, &addr_callee).encode()) + .build(), + >::ContractTrapped + ); + }); +} + +#[test] +fn deploy_and_call_other_contract() { + let (caller_wasm, _caller_code_hash) = compile_module::("caller_contract").unwrap(); + let (callee_wasm, callee_code_hash) = compile_module::("return_with_data").unwrap(); + + ExtBuilder::default().existential_deposit(1).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + + // Create + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let caller_addr = builder::bare_instantiate(Code::Upload(caller_wasm)) + .value(100_000) + .build_and_unwrap_account_id(); + Contracts::bare_upload_code(ALICE, callee_wasm, None, Determinism::Enforced).unwrap(); + + let callee_addr = Contracts::contract_address( + &caller_addr, + &callee_code_hash, + &[0, 1, 34, 51, 68, 85, 102, 119], // hard coded in wasm + &[], + ); + + // Drop previous events + initialize_block(2); + + // Call BOB contract, which attempts to instantiate and call the callee contract and + // makes various assertions on the results from those calls. + assert_ok!(builder::call(caller_addr.clone()) + .data(callee_code_hash.as_ref().to_vec()) + .build()); + + assert_eq!( + System::events(), + vec![ + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::System(frame_system::Event::NewAccount { + account: callee_addr.clone() + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Endowed { + account: callee_addr.clone(), + free_balance: min_balance, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: ALICE, + to: callee_addr.clone(), + amount: min_balance, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: caller_addr.clone(), + to: callee_addr.clone(), + amount: 32768 // hardcoded in wasm + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Instantiated { + deployer: caller_addr.clone(), + contract: callee_addr.clone(), + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: caller_addr.clone(), + to: callee_addr.clone(), + amount: 32768, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(caller_addr.clone()), + contract: callee_addr.clone(), + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(ALICE), + contract: caller_addr.clone(), + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts( + pallet_contracts::Event::StorageDepositTransferredAndHeld { + from: ALICE, + to: callee_addr.clone(), + amount: test_utils::contract_info_storage_deposit(&callee_addr), + } + ), + topics: vec![], + }, + ] + ); + }); +} + +#[test] +fn delegate_call() { + let (caller_wasm, _caller_code_hash) = compile_module::("delegate_call").unwrap(); + let (callee_wasm, callee_code_hash) = compile_module::("delegate_call_lib").unwrap(); + + ExtBuilder::default().existential_deposit(500).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Instantiate the 'caller' + let caller_addr = builder::bare_instantiate(Code::Upload(caller_wasm)) + .value(300_000) + .build_and_unwrap_account_id(); + // Only upload 'callee' code + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + callee_wasm, + Some(codec::Compact(100_000)), + Determinism::Enforced, + )); + + assert_ok!(builder::call(caller_addr.clone()) + .value(1337) + .data(callee_code_hash.as_ref().to_vec()) + .build()); + }); +} + +#[test] +fn track_check_uncheck_module_call() { + let (wasm, code_hash) = compile_module::("dummy").unwrap(); + ExtBuilder::default().build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + Contracts::bare_upload_code(ALICE, wasm, None, Determinism::Enforced).unwrap(); + builder::bare_instantiate(Code::Existing(code_hash)).build_and_unwrap_result(); + }); + + // It should have recorded 1 `Checked` for the upload and 1 `Unchecked` for the instantiate. + let record = crate::wasm::tracker::LOADED_MODULE.with(|stack| stack.borrow().clone()); + assert_eq!(record, vec![LoadingMode::Checked, LoadingMode::Unchecked]); +} + +#[test] +fn transfer_expendable_cannot_kill_account() { + let (wasm, _code_hash) = compile_module::("dummy").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Instantiate the BOB contract. + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(1_000) + .build_and_unwrap_account_id(); + + // Check that the BOB contract has been instantiated. + get_contract(&addr); + + let total_balance = ::Currency::total_balance(&addr); + + assert_eq!( + test_utils::get_balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr), + test_utils::contract_info_storage_deposit(&addr) + ); + + // Some ot the total balance is held, so it can't be transferred. + assert_err!( + <::Currency as Mutate>::transfer( + &addr, + &ALICE, + total_balance, + Preservation::Expendable, + ), + TokenError::FundsUnavailable, + ); + + assert_eq!(::Currency::total_balance(&addr), total_balance); + }); +} + +#[test] +fn cannot_self_destruct_through_draining() { + let (wasm, _code_hash) = compile_module::("drain").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let value = 1_000; + let min_balance = Contracts::min_balance(); + + // Instantiate the BOB contract. + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(value) + .build_and_unwrap_account_id(); + + // Check that the BOB contract has been instantiated. + get_contract(&addr); + + // Call BOB which makes it send all funds to the zero address + // The contract code asserts that the transfer fails with the correct error code + assert_ok!(builder::call(addr.clone()).build()); + + // Make sure the account wasn't remove by sending all free balance away. + assert_eq!( + ::Currency::total_balance(&addr), + value + test_utils::contract_info_storage_deposit(&addr) + min_balance, + ); + }); +} + +#[test] +fn cannot_self_destruct_through_storage_refund_after_price_change() { + let (wasm, _code_hash) = compile_module::("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + + // Instantiate the BOB contract. + let addr = builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_account_id(); + + let info_deposit = test_utils::contract_info_storage_deposit(&addr); + + // Check that the contract has been instantiated and has the minimum balance + assert_eq!(get_contract(&addr).total_deposit(), info_deposit); + assert_eq!(get_contract(&addr).extra_deposit(), 0); + assert_eq!(::Currency::total_balance(&addr), info_deposit + min_balance); + + // Create 100 bytes of storage with a price of per byte and a single storage item of price 2 + assert_ok!(builder::call(addr.clone()).data(100u32.to_le_bytes().to_vec()).build()); + assert_eq!(get_contract(&addr).total_deposit(), info_deposit + 102); + + // 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!(builder::call(addr.clone()).data(0u32.to_le_bytes().to_vec()).build()); + + // Make sure the account wasn't removed by the refund + assert_eq!( + ::Currency::total_balance(&addr), + get_contract(&addr).total_deposit() + min_balance, + ); + assert_eq!(get_contract(&addr).extra_deposit(), 2); + }); +} + +#[test] +fn cannot_self_destruct_while_live() { + let (wasm, _code_hash) = compile_module::("self_destruct").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Instantiate the BOB contract. + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(100_000) + .build_and_unwrap_account_id(); + + // Check that the BOB contract has been instantiated. + 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!( + builder::call(addr.clone()).data(vec![0]).build(), + Error::::ContractTrapped, + ); + + // Check that BOB is still there. + get_contract(&addr); + }); +} + +#[test] +fn self_destruct_works() { + let (wasm, code_hash) = compile_module::("self_destruct").unwrap(); + ExtBuilder::default().existential_deposit(1_000).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let _ = ::Currency::set_balance(&DJANGO, 1_000_000); + let min_balance = Contracts::min_balance(); + + // Instantiate the BOB contract. + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(100_000) + .build_and_unwrap_account_id(); + + // Check that the BOB contract has been instantiated. + let _ = get_contract(&addr); + + let info_deposit = test_utils::contract_info_storage_deposit(&addr); + + // Drop all previous events + initialize_block(2); + + // Call BOB without input data which triggers termination. + assert_matches!(builder::call(addr.clone()).build(), Ok(_)); + + // Check that code is still there but refcount dropped to zero. + assert_refcount!(&code_hash, 0); + + // Check that account is gone + assert!(get_contract_checked(&addr).is_none()); + assert_eq!(::Currency::total_balance(&addr), 0); + + // Check that the beneficiary (django) got remaining balance. + assert_eq!( + ::Currency::free_balance(DJANGO), + 1_000_000 + 100_000 + min_balance + ); + + // Check that the Alice is missing Django's benefit. Within ALICE's total balance there's + // also the code upload deposit held. + assert_eq!( + ::Currency::total_balance(&ALICE), + 1_000_000 - (100_000 + min_balance) + ); + + pretty_assertions::assert_eq!( + System::events(), + vec![ + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Terminated { + contract: addr.clone(), + beneficiary: DJANGO + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(ALICE), + contract: addr.clone(), + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts( + pallet_contracts::Event::StorageDepositTransferredAndReleased { + from: addr.clone(), + to: ALICE, + amount: info_deposit, + } + ), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::System(frame_system::Event::KilledAccount { + account: addr.clone() + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: addr.clone(), + to: DJANGO, + amount: 100_000 + min_balance, + }), + topics: vec![], + }, + ], + ); + }); +} + +// This tests that one contract cannot prevent another from self-destructing by sending it +// additional funds after it has been drained. +#[test] +fn destroy_contract_and_transfer_funds() { + let (callee_wasm, callee_code_hash) = compile_module::("self_destruct").unwrap(); + let (caller_wasm, _caller_code_hash) = compile_module::("destroy_and_transfer").unwrap(); + + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + // Create code hash for bob to instantiate + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + Contracts::bare_upload_code(ALICE, callee_wasm, None, Determinism::Enforced).unwrap(); + + // This deploys the BOB contract, which in turn deploys the CHARLIE contract during + // construction. + let addr_bob = builder::bare_instantiate(Code::Upload(caller_wasm)) + .value(200_000) + .data(callee_code_hash.as_ref().to_vec()) + .build_and_unwrap_account_id(); + + // Check that the CHARLIE contract has been instantiated. + let addr_charlie = + Contracts::contract_address(&addr_bob, &callee_code_hash, &[], &[0x47, 0x11]); + get_contract(&addr_charlie); + + // Call BOB, which calls CHARLIE, forcing CHARLIE to self-destruct. + assert_ok!(builder::call(addr_bob).data(addr_charlie.encode()).build()); + + // Check that CHARLIE has moved on to the great beyond (ie. died). + assert!(get_contract_checked(&addr_charlie).is_none()); + }); +} + +#[test] +fn cannot_self_destruct_in_constructor() { + let (wasm, _) = compile_module::("self_destructing_constructor").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Fail to instantiate the BOB because the constructor calls seal_terminate. + assert_err_ignore_postinfo!( + builder::instantiate_with_code(wasm).value(100_000).build(), + Error::::TerminatedInConstructor, + ); + }); +} + +#[test] +fn crypto_hashes() { + let (wasm, _code_hash) = compile_module::("crypto_hashes").unwrap(); + + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Instantiate the CRYPTO_HASHES contract. + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(100_000) + .build_and_unwrap_account_id(); + // Perform the call. + let input = b"_DEAD_BEEF"; + use sp_io::hashing::*; + // Wraps a hash function into a more dynamic form usable for testing. + macro_rules! dyn_hash_fn { + ($name:ident) => { + Box::new(|input| $name(input).as_ref().to_vec().into_boxed_slice()) + }; + } + // All hash functions and their associated output byte lengths. + let test_cases: &[(Box Box<[u8]>>, usize)] = &[ + (dyn_hash_fn!(sha2_256), 32), + (dyn_hash_fn!(keccak_256), 32), + (dyn_hash_fn!(blake2_256), 32), + (dyn_hash_fn!(blake2_128), 16), + ]; + // Test the given hash functions for the input: "_DEAD_BEEF" + for (n, (hash_fn, expected_size)) in test_cases.iter().enumerate() { + // We offset data in the contract tables by 1. + let mut params = vec![(n + 1) as u8]; + params.extend_from_slice(input); + let result = builder::bare_call(addr.clone()).data(params).build_and_unwrap_result(); + assert!(!result.did_revert()); + let expected = hash_fn(input.as_ref()); + assert_eq!(&result.data[..*expected_size], &*expected); + } + }) +} + +#[test] +fn transfer_return_code() { + let (wasm, _code_hash) = compile_module::("transfer_return_code").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + // Contract has only the minimal balance so any transfer will fail. + ::Currency::set_balance(&addr, min_balance); + let result = builder::bare_call(addr.clone()).build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::TransferFailed); + }); +} + +#[test] +fn call_return_code() { + let (caller_code, _caller_hash) = compile_module::("call_return_code").unwrap(); + let (callee_code, _callee_hash) = compile_module::("ok_trap_revert").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + let _ = ::Currency::set_balance(&CHARLIE, 1000 * min_balance); + + let addr_bob = builder::bare_instantiate(Code::Upload(caller_code)) + .value(min_balance * 100) + .data(vec![0]) + .build_and_unwrap_account_id(); + ::Currency::set_balance(&addr_bob, min_balance); + + // Contract calls into Django which is no valid contract + let result = builder::bare_call(addr_bob.clone()) + .data(AsRef::<[u8]>::as_ref(&DJANGO).to_vec()) + .build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::NotCallable); + + let addr_django = builder::bare_instantiate(Code::Upload(callee_code)) + .origin(CHARLIE) + .value(min_balance * 100) + .data(vec![0]) + .build_and_unwrap_account_id(); + ::Currency::set_balance(&addr_django, min_balance); + + // Contract has only the minimal balance so any transfer will fail. + let result = builder::bare_call(addr_bob.clone()) + .data( + AsRef::<[u8]>::as_ref(&addr_django) + .iter() + .chain(&0u32.to_le_bytes()) + .cloned() + .collect(), + ) + .build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::TransferFailed); + + // Contract has enough balance but callee reverts because "1" is passed. + ::Currency::set_balance(&addr_bob, min_balance + 1000); + let result = builder::bare_call(addr_bob.clone()) + .data( + AsRef::<[u8]>::as_ref(&addr_django) + .iter() + .chain(&1u32.to_le_bytes()) + .cloned() + .collect(), + ) + .build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::CalleeReverted); + + // Contract has enough balance but callee traps because "2" is passed. + let result = builder::bare_call(addr_bob) + .data( + AsRef::<[u8]>::as_ref(&addr_django) + .iter() + .chain(&2u32.to_le_bytes()) + .cloned() + .collect(), + ) + .build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::CalleeTrapped); + }); +} + +#[test] +fn instantiate_return_code() { + let (caller_code, _caller_hash) = compile_module::("instantiate_return_code").unwrap(); + let (callee_code, callee_hash) = compile_module::("ok_trap_revert").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + let _ = ::Currency::set_balance(&CHARLIE, 1000 * min_balance); + let callee_hash = callee_hash.as_ref().to_vec(); + + assert_ok!(builder::instantiate_with_code(callee_code).value(min_balance * 100).build()); + + let addr = builder::bare_instantiate(Code::Upload(caller_code)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + // Contract has only the minimal balance so any transfer will fail. + ::Currency::set_balance(&addr, min_balance); + let result = builder::bare_call(addr.clone()) + .data(callee_hash.clone()) + .build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::TransferFailed); + + // Contract has enough balance but the passed code hash is invalid + ::Currency::set_balance(&addr, min_balance + 10_000); + let result = builder::bare_call(addr.clone()).data(vec![0; 33]).build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::CodeNotFound); + + // Contract has enough balance but callee reverts because "1" is passed. + let result = builder::bare_call(addr.clone()) + .data(callee_hash.iter().chain(&1u32.to_le_bytes()).cloned().collect()) + .build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::CalleeReverted); + + // Contract has enough balance but callee traps because "2" is passed. + let result = builder::bare_call(addr) + .data(callee_hash.iter().chain(&2u32.to_le_bytes()).cloned().collect()) + .build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::CalleeTrapped); + }); +} + +#[test] +fn disabled_chain_extension_wont_deploy() { + let (code, _hash) = compile_module::("chain_extension").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + TestExtension::disable(); + assert_err_ignore_postinfo!( + builder::instantiate_with_code(code).value(3 * min_balance).build(), + >::CodeRejected, + ); + }); +} + +#[test] +fn disabled_chain_extension_errors_on_call() { + let (code, _hash) = compile_module::("chain_extension").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + let addr = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + TestExtension::disable(); + assert_err_ignore_postinfo!( + builder::call(addr.clone()).build(), + Error::::CodeRejected, + ); + }); +} + +#[test] +fn chain_extension_works() { + let (code, _hash) = compile_module::("chain_extension").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + let addr = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + // 0 = read input buffer and pass it through as output + let input: Vec = ExtensionInput { extension_id: 0, func_id: 0, extra: &[99] }.into(); + let result = builder::bare_call(addr.clone()).data(input.clone()).build(); + assert_eq!(TestExtension::last_seen_buffer(), input); + assert_eq!(result.result.unwrap().data, input); + + // 1 = treat inputs as integer primitives and store the supplied integers + builder::bare_call(addr.clone()) + .data(ExtensionInput { extension_id: 0, func_id: 1, extra: &[] }.into()) + .build_and_unwrap_result(); + assert_eq!(TestExtension::last_seen_input_len(), 4); + + // 2 = charge some extra weight (amount supplied in the fifth byte) + let result = builder::bare_call(addr.clone()) + .data(ExtensionInput { extension_id: 0, func_id: 2, extra: &0u32.encode() }.into()) + .build(); + assert_ok!(result.result); + let gas_consumed = result.gas_consumed; + let result = builder::bare_call(addr.clone()) + .data(ExtensionInput { extension_id: 0, func_id: 2, extra: &42u32.encode() }.into()) + .build(); + assert_ok!(result.result); + assert_eq!(result.gas_consumed.ref_time(), gas_consumed.ref_time() + 42); + let result = builder::bare_call(addr.clone()) + .data(ExtensionInput { extension_id: 0, func_id: 2, extra: &95u32.encode() }.into()) + .build(); + assert_ok!(result.result); + assert_eq!(result.gas_consumed.ref_time(), gas_consumed.ref_time() + 95); + + // 3 = diverging chain extension call that sets flags to 0x1 and returns a fixed buffer + let result = builder::bare_call(addr.clone()) + .data(ExtensionInput { extension_id: 0, func_id: 3, extra: &[] }.into()) + .build_and_unwrap_result(); + assert_eq!(result.flags, ReturnFlags::REVERT); + assert_eq!(result.data, vec![42, 99]); + + // diverging to second chain extension that sets flags to 0x1 and returns a fixed buffer + // We set the MSB part to 1 (instead of 0) which routes the request into the second + // extension + let result = builder::bare_call(addr.clone()) + .data(ExtensionInput { extension_id: 1, func_id: 0, extra: &[] }.into()) + .build_and_unwrap_result(); + assert_eq!(result.flags, ReturnFlags::REVERT); + assert_eq!(result.data, vec![0x4B, 0x1D]); + + // Diverging to third chain extension that is disabled + // We set the MSB part to 2 (instead of 0) which routes the request into the third extension + assert_err_ignore_postinfo!( + builder::call(addr.clone()) + .data(ExtensionInput { extension_id: 2, func_id: 0, extra: &[] }.into()) + .build(), + Error::::NoChainExtension, + ); + }); +} + +#[test] +fn chain_extension_temp_storage_works() { + let (code, _hash) = compile_module::("chain_extension_temp_storage").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + let addr = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + // Call func 0 and func 1 back to back. + let stop_recursion = 0u8; + let mut input: Vec = ExtensionInput { extension_id: 3, func_id: 0, extra: &[] }.into(); + input.extend_from_slice( + ExtensionInput { extension_id: 3, func_id: 1, extra: &[stop_recursion] } + .to_vec() + .as_ref(), + ); + + assert_ok!(builder::bare_call(addr.clone()).data(input.clone()).build().result); + }) +} + +#[test] +fn lazy_removal_works() { + let (code, _hash) = compile_module::("self_destruct").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + + let addr = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + let info = get_contract(&addr); + let trie = &info.child_trie_info(); + + // Put value into the contracts child trie + child::put(trie, &[99], &42); + + // Terminate the contract + assert_ok!(builder::call(addr.clone()).build()); + + // Contract info should be gone + assert!(!>::contains_key(&addr)); + + // But value should be still there as the lazy removal did not run, yet. + assert_matches!(child::get(trie, &[99]), Some(42)); + + // Run the lazy removal + Contracts::on_idle(System::block_number(), Weight::MAX); + + // Value should be gone now + assert_matches!(child::get::(trie, &[99]), None); + }); +} + +#[test] +fn lazy_batch_removal_works() { + let (code, _hash) = compile_module::("self_destruct").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + let mut tries: Vec = vec![]; + + for i in 0..3u8 { + let addr = builder::bare_instantiate(Code::Upload(code.clone())) + .value(min_balance * 100) + .salt(vec![i]) + .build_and_unwrap_account_id(); + + let info = get_contract(&addr); + let trie = &info.child_trie_info(); + + // Put value into the contracts child trie + child::put(trie, &[99], &42); + + // Terminate the contract. Contract info should be gone, but value should be still there + // as the lazy removal did not run, yet. + assert_ok!(builder::call(addr.clone()).build()); + + assert!(!>::contains_key(&addr)); + assert_matches!(child::get(trie, &[99]), Some(42)); + + tries.push(trie.clone()) + } + + // Run single lazy removal + Contracts::on_idle(System::block_number(), Weight::MAX); + + // The single lazy removal should have removed all queued tries + for trie in tries.iter() { + assert_matches!(child::get::(trie, &[99]), None); + } + }); +} + +#[test] +fn lazy_removal_partial_remove_works() { + let (code, _hash) = compile_module::("self_destruct").unwrap(); + + // We create a contract with some extra keys above the weight limit + let extra_keys = 7u32; + let mut meter = WeightMeter::with_limit(Weight::from_parts(5_000_000_000, 100 * 1024)); + let (weight_per_key, max_keys) = ContractInfo::::deletion_budget(&meter); + let vals: Vec<_> = (0..max_keys + extra_keys) + .map(|i| (blake2_256(&i.encode()), (i as u32), (i as u32).encode())) + .collect(); + + let mut ext = ExtBuilder::default().existential_deposit(50).build(); + + let trie = ext.execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + + let addr = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + let info = get_contract(&addr); + + // Put value into the contracts child trie + for val in &vals { + info.write(&Key::Fix(val.0), Some(val.2.clone()), None, false).unwrap(); + } + >::insert(&addr, info.clone()); + + // Terminate the contract + assert_ok!(builder::call(addr.clone()).build()); + + // Contract info should be gone + assert!(!>::contains_key(&addr)); + + let trie = info.child_trie_info(); + + // But value should be still there as the lazy removal did not run, yet. + for val in &vals { + assert_eq!(child::get::(&trie, &blake2_256(&val.0)), Some(val.1)); + } + + trie.clone() + }); + + // The lazy removal limit only applies to the backend but not to the overlay. + // This commits all keys from the overlay to the backend. + ext.commit_all().unwrap(); + + ext.execute_with(|| { + // Run the lazy removal + ContractInfo::::process_deletion_queue_batch(&mut meter); + + // Weight should be exhausted because we could not even delete all keys + assert!(!meter.can_consume(weight_per_key)); + + let mut num_deleted = 0u32; + let mut num_remaining = 0u32; + + for val in &vals { + match child::get::(&trie, &blake2_256(&val.0)) { + None => num_deleted += 1, + Some(x) if x == val.1 => num_remaining += 1, + Some(_) => panic!("Unexpected value in contract storage"), + } + } + + // All but one key is removed + assert_eq!(num_deleted + num_remaining, vals.len() as u32); + assert_eq!(num_deleted, max_keys); + assert_eq!(num_remaining, extra_keys); + }); +} + +#[test] +fn lazy_removal_does_no_run_on_low_remaining_weight() { + let (code, _hash) = compile_module::("self_destruct").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + + let addr = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + let info = get_contract(&addr); + let trie = &info.child_trie_info(); + + // Put value into the contracts child trie + child::put(trie, &[99], &42); + + // Terminate the contract + assert_ok!(builder::call(addr.clone()).build()); + + // Contract info should be gone + assert!(!>::contains_key(&addr)); + + // But value should be still there as the lazy removal did not run, yet. + assert_matches!(child::get(trie, &[99]), Some(42)); + + // Assign a remaining weight which is too low for a successful deletion of the contract + let low_remaining_weight = + <::WeightInfo as WeightInfo>::on_process_deletion_queue_batch(); + + // Run the lazy removal + Contracts::on_idle(System::block_number(), low_remaining_weight); + + // Value should still be there, since remaining weight was too low for removal + assert_matches!(child::get::(trie, &[99]), Some(42)); + + // Run the lazy removal while deletion_queue is not full + Contracts::on_initialize(System::block_number()); + + // Value should still be there, since deletion_queue was not full + assert_matches!(child::get::(trie, &[99]), Some(42)); + + // Run on_idle with max remaining weight, this should remove the value + Contracts::on_idle(System::block_number(), Weight::MAX); + + // Value should be gone + assert_matches!(child::get::(trie, &[99]), None); + }); +} + +#[test] +fn lazy_removal_does_not_use_all_weight() { + let (code, _hash) = compile_module::("self_destruct").unwrap(); + + let mut meter = WeightMeter::with_limit(Weight::from_parts(5_000_000_000, 100 * 1024)); + let mut ext = ExtBuilder::default().existential_deposit(50).build(); + + let (trie, vals, weight_per_key) = ext.execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + + let addr = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + let info = get_contract(&addr); + let (weight_per_key, max_keys) = ContractInfo::::deletion_budget(&meter); + assert!(max_keys > 0); + + // We create a contract with one less storage item than we can remove within the limit + let vals: Vec<_> = (0..max_keys - 1) + .map(|i| (blake2_256(&i.encode()), (i as u32), (i as u32).encode())) + .collect(); + + // Put value into the contracts child trie + for val in &vals { + info.write(&Key::Fix(val.0), Some(val.2.clone()), None, false).unwrap(); + } + >::insert(&addr, info.clone()); + + // Terminate the contract + assert_ok!(builder::call(addr.clone()).build()); + + // Contract info should be gone + assert!(!>::contains_key(&addr)); + + let trie = info.child_trie_info(); + + // But value should be still there as the lazy removal did not run, yet. + for val in &vals { + assert_eq!(child::get::(&trie, &blake2_256(&val.0)), Some(val.1)); + } + + (trie, vals, weight_per_key) + }); + + // The lazy removal limit only applies to the backend but not to the overlay. + // This commits all keys from the overlay to the backend. + ext.commit_all().unwrap(); + + ext.execute_with(|| { + // Run the lazy removal + ContractInfo::::process_deletion_queue_batch(&mut meter); + let base_weight = + <::WeightInfo as WeightInfo>::on_process_deletion_queue_batch(); + assert_eq!(meter.consumed(), weight_per_key.mul(vals.len() as _) + base_weight); + + // All the keys are removed + for val in vals { + assert_eq!(child::get::(&trie, &blake2_256(&val.0)), None); + } + }); +} + +#[test] +fn deletion_queue_ring_buffer_overflow() { + let (code, _hash) = compile_module::("self_destruct").unwrap(); + let mut ext = ExtBuilder::default().existential_deposit(50).build(); + + // setup the deletion queue with custom counters + ext.execute_with(|| { + let queue = DeletionQueueManager::from_test_values(u32::MAX - 1, u32::MAX - 1); + >::set(queue); + }); + + // commit the changes to the storage + ext.commit_all().unwrap(); + + ext.execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + let mut tries: Vec = vec![]; + + // add 3 contracts to the deletion queue + for i in 0..3u8 { + let addr = builder::bare_instantiate(Code::Upload(code.clone())) + .value(min_balance * 100) + .salt(vec![i]) + .build_and_unwrap_account_id(); + + let info = get_contract(&addr); + let trie = &info.child_trie_info(); + + // Put value into the contracts child trie + child::put(trie, &[99], &42); + + // Terminate the contract. Contract info should be gone, but value should be still + // there as the lazy removal did not run, yet. + assert_ok!(builder::call(addr.clone()).build()); + + assert!(!>::contains_key(&addr)); + assert_matches!(child::get(trie, &[99]), Some(42)); + + tries.push(trie.clone()) + } + + // Run single lazy removal + Contracts::on_idle(System::block_number(), Weight::MAX); + + // The single lazy removal should have removed all queued tries + for trie in tries.iter() { + assert_matches!(child::get::(trie, &[99]), None); + } + + // insert and delete counter values should go from u32::MAX - 1 to 1 + assert_eq!(>::get().as_test_tuple(), (1, 1)); + }) +} +#[test] +fn refcounter() { + let (wasm, code_hash) = compile_module::("self_destruct").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + + // Create two contracts with the same code and check that they do in fact share it. + let addr0 = builder::bare_instantiate(Code::Upload(wasm.clone())) + .value(min_balance * 100) + .salt(vec![0]) + .build_and_unwrap_account_id(); + let addr1 = builder::bare_instantiate(Code::Upload(wasm.clone())) + .value(min_balance * 100) + .salt(vec![1]) + .build_and_unwrap_account_id(); + assert_refcount!(code_hash, 2); + + // Sharing should also work with the usual instantiate call + let addr2 = builder::bare_instantiate(Code::Existing(code_hash)) + .value(min_balance * 100) + .salt(vec![2]) + .build_and_unwrap_account_id(); + assert_refcount!(code_hash, 3); + + // Terminating one contract should decrement the refcount + assert_ok!(builder::call(addr0).build()); + assert_refcount!(code_hash, 2); + + // remove another one + assert_ok!(builder::call(addr1).build()); + assert_refcount!(code_hash, 1); + + // Pristine code should still be there + PristineCode::::get(code_hash).unwrap(); + + // remove the last contract + assert_ok!(builder::call(addr2).build()); + assert_refcount!(code_hash, 0); + + // refcount is `0` but code should still exists because it needs to be removed manually + assert!(crate::PristineCode::::contains_key(&code_hash)); + }); +} + +#[test] +fn debug_message_works() { + let (wasm, _code_hash) = compile_module::("debug_message_works").unwrap(); + + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(30_000) + .build_and_unwrap_account_id(); + let result = builder::bare_call(addr).debug(DebugInfo::UnsafeDebug).build(); + + assert_matches!(result.result, Ok(_)); + assert_eq!(std::str::from_utf8(&result.debug_message).unwrap(), "Hello World!"); + }); +} + +#[test] +fn debug_message_logging_disabled() { + let (wasm, _code_hash) = compile_module::("debug_message_logging_disabled").unwrap(); + + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(30_000) + .build_and_unwrap_account_id(); + // disable logging by passing `false` + let result = builder::bare_call(addr.clone()).build(); + assert_matches!(result.result, Ok(_)); + // the dispatchables always run without debugging + assert_ok!(Contracts::call(RuntimeOrigin::signed(ALICE), addr, 0, GAS_LIMIT, None, vec![])); + assert!(result.debug_message.is_empty()); + }); +} + +#[test] +fn debug_message_invalid_utf8() { + let (wasm, _code_hash) = compile_module::("debug_message_invalid_utf8").unwrap(); + + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(30_000) + .build_and_unwrap_account_id(); + let result = builder::bare_call(addr).debug(DebugInfo::UnsafeDebug).build(); + assert_ok!(result.result); + assert!(result.debug_message.is_empty()); + }); +} + +#[test] +fn gas_estimation_for_subcalls() { + let (caller_code, _caller_hash) = compile_module::("call_with_limit").unwrap(); + let (call_runtime_code, _caller_hash) = compile_module::("call_runtime").unwrap(); + let (dummy_code, _callee_hash) = compile_module::("dummy").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 2_000 * min_balance); + + let addr_caller = builder::bare_instantiate(Code::Upload(caller_code)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + let addr_dummy = builder::bare_instantiate(Code::Upload(dummy_code)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + let addr_call_runtime = builder::bare_instantiate(Code::Upload(call_runtime_code)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + // Run the test for all of those weight limits for the subcall + let weights = [ + Weight::zero(), + GAS_LIMIT, + GAS_LIMIT * 2, + GAS_LIMIT / 5, + Weight::from_parts(0, GAS_LIMIT.proof_size()), + Weight::from_parts(GAS_LIMIT.ref_time(), 0), + ]; + + // This call is passed to the sub call in order to create a large `required_weight` + let runtime_call = RuntimeCall::Dummy(pallet_dummy::Call::overestimate_pre_charge { + pre_charge: Weight::from_parts(10_000_000_000, 512 * 1024), + actual_weight: Weight::from_parts(1, 1), + }) + .encode(); + + // Encodes which contract should be sub called with which input + let sub_calls: [(&[u8], Vec<_>, bool); 2] = [ + (addr_dummy.as_ref(), vec![], false), + (addr_call_runtime.as_ref(), runtime_call, true), + ]; + + for weight in weights { + for (sub_addr, sub_input, out_of_gas_in_subcall) in &sub_calls { + let input: Vec = sub_addr + .iter() + .cloned() + .chain(weight.ref_time().to_le_bytes()) + .chain(weight.proof_size().to_le_bytes()) + .chain(sub_input.clone()) + .collect(); + + // Call in order to determine the gas that is required for this call + let result = builder::bare_call(addr_caller.clone()).data(input.clone()).build(); + assert_ok!(&result.result); + + // If the out of gas happens in the subcall the caller contract + // will just trap. Otherwise we would need to forward an error + // code to signal that the sub contract ran out of gas. + let error: DispatchError = if *out_of_gas_in_subcall { + assert!(result.gas_required.all_gt(result.gas_consumed)); + >::ContractTrapped.into() + } else { + assert_eq!(result.gas_required, result.gas_consumed); + >::OutOfGas.into() + }; + + // Make the same call using the estimated gas. Should succeed. + assert_ok!( + builder::bare_call(addr_caller.clone()) + .gas_limit(result.gas_required) + .storage_deposit_limit(Some(result.storage_deposit.charge_or_zero())) + .data(input.clone()) + .build() + .result + ); + + // Check that it fails with too little ref_time + assert_err!( + builder::bare_call(addr_caller.clone()) + .gas_limit(result.gas_required.sub_ref_time(1)) + .storage_deposit_limit(Some(result.storage_deposit.charge_or_zero())) + .data(input.clone()) + .build() + .result, + error, + ); + + // Check that it fails with too little proof_size + assert_err!( + builder::bare_call(addr_caller.clone()) + .gas_limit(result.gas_required.sub_proof_size(1)) + .storage_deposit_limit(Some(result.storage_deposit.charge_or_zero())) + .data(input) + .build() + .result, + error, + ); + } + } + }); +} + +#[test] +fn gas_estimation_call_runtime() { + let (caller_code, _caller_hash) = compile_module::("call_runtime").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + let _ = ::Currency::set_balance(&CHARLIE, 1000 * min_balance); + + let addr_caller = builder::bare_instantiate(Code::Upload(caller_code)) + .value(min_balance * 100) + .salt(vec![0]) + .build_and_unwrap_account_id(); + + // Call something trivial with a huge gas limit so that we can observe the effects + // of pre-charging. This should create a difference between consumed and required. + let call = RuntimeCall::Dummy(pallet_dummy::Call::overestimate_pre_charge { + pre_charge: Weight::from_parts(10_000_000, 1_000), + actual_weight: Weight::from_parts(100, 100), + }); + let result = builder::bare_call(addr_caller.clone()).data(call.encode()).build(); + // contract encodes the result of the dispatch runtime + let outcome = u32::decode(&mut result.result.unwrap().data.as_ref()).unwrap(); + assert_eq!(outcome, 0); + assert!(result.gas_required.all_gt(result.gas_consumed)); + + // Make the same call using the required gas. Should succeed. + assert_ok!( + builder::bare_call(addr_caller) + .gas_limit(result.gas_required) + .data(call.encode()) + .build() + .result + ); + }); +} + +#[test] +fn call_runtime_reentrancy_guarded() { + let (caller_code, _caller_hash) = compile_module::("call_runtime").unwrap(); + let (callee_code, _callee_hash) = compile_module::("dummy").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + let _ = ::Currency::set_balance(&CHARLIE, 1000 * min_balance); + + let addr_caller = builder::bare_instantiate(Code::Upload(caller_code)) + .value(min_balance * 100) + .salt(vec![0]) + .build_and_unwrap_account_id(); + + let addr_callee = builder::bare_instantiate(Code::Upload(callee_code)) + .value(min_balance * 100) + .salt(vec![1]) + .build_and_unwrap_account_id(); + + // Call pallet_contracts call() dispatchable + let call = RuntimeCall::Contracts(crate::Call::call { + dest: addr_callee, + value: 0, + gas_limit: GAS_LIMIT / 3, + storage_deposit_limit: None, + data: vec![], + }); + + // Call runtime to re-enter back to contracts engine by + // calling dummy contract + let result = builder::bare_call(addr_caller.clone()) + .data(call.encode()) + .build_and_unwrap_result(); + // Call to runtime should fail because of the re-entrancy guard + assert_return_code!(result, RuntimeReturnCode::CallRuntimeFailed); + }); +} + +#[test] +fn ecdsa_recover() { + let (wasm, _code_hash) = compile_module::("ecdsa_recover").unwrap(); + + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Instantiate the ecdsa_recover contract. + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(100_000) + .build_and_unwrap_account_id(); + + #[rustfmt::skip] + let signature: [u8; 65] = [ + 161, 234, 203, 74, 147, 96, 51, 212, 5, 174, 231, 9, 142, 48, 137, 201, + 162, 118, 192, 67, 239, 16, 71, 216, 125, 86, 167, 139, 70, 7, 86, 241, + 33, 87, 154, 251, 81, 29, 160, 4, 176, 239, 88, 211, 244, 232, 232, 52, + 211, 234, 100, 115, 230, 47, 80, 44, 152, 166, 62, 50, 8, 13, 86, 175, + 28, + ]; + #[rustfmt::skip] + let message_hash: [u8; 32] = [ + 162, 28, 244, 179, 96, 76, 244, 178, 188, 83, 230, 248, 143, 106, 77, 117, + 239, 95, 244, 171, 65, 95, 62, 153, 174, 166, 182, 28, 130, 73, 196, 208 + ]; + #[rustfmt::skip] + const EXPECTED_COMPRESSED_PUBLIC_KEY: [u8; 33] = [ + 2, 121, 190, 102, 126, 249, 220, 187, 172, 85, 160, 98, 149, 206, 135, 11, + 7, 2, 155, 252, 219, 45, 206, 40, 217, 89, 242, 129, 91, 22, 248, 23, + 152, + ]; + let mut params = vec![]; + params.extend_from_slice(&signature); + params.extend_from_slice(&message_hash); + assert!(params.len() == 65 + 32); + let result = builder::bare_call(addr.clone()).data(params).build_and_unwrap_result(); + assert!(!result.did_revert()); + assert_eq!(result.data, EXPECTED_COMPRESSED_PUBLIC_KEY); + }) +} + +#[test] +fn bare_instantiate_returns_events() { + let (wasm, _code_hash) = compile_module::("transfer_return_code").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + + let result = builder::bare_instantiate(Code::Upload(wasm)) + .value(min_balance * 100) + .collect_events(CollectEvents::UnsafeCollect) + .build(); + + let events = result.events.unwrap(); + assert!(!events.is_empty()); + assert_eq!(events, System::events()); + }); +} + +#[test] +fn bare_instantiate_does_not_return_events() { + let (wasm, _code_hash) = compile_module::("transfer_return_code").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + + let result = builder::bare_instantiate(Code::Upload(wasm)).value(min_balance * 100).build(); + + let events = result.events; + assert!(!System::events().is_empty()); + assert!(events.is_none()); + }); +} + +#[test] +fn bare_call_returns_events() { + let (wasm, _code_hash) = compile_module::("transfer_return_code").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + let result = builder::bare_call(addr.clone()) + .collect_events(CollectEvents::UnsafeCollect) + .build(); + + let events = result.events.unwrap(); + assert_return_code!(&result.result.unwrap(), RuntimeReturnCode::Success); + assert!(!events.is_empty()); + assert_eq!(events, System::events()); + }); +} + +#[test] +fn bare_call_does_not_return_events() { + let (wasm, _code_hash) = compile_module::("transfer_return_code").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + let result = builder::bare_call(addr.clone()).build(); + + let events = result.events; + assert_return_code!(&result.result.unwrap(), RuntimeReturnCode::Success); + assert!(!System::events().is_empty()); + assert!(events.is_none()); + }); +} + +#[test] +fn sr25519_verify() { + let (wasm, _code_hash) = compile_module::("sr25519_verify").unwrap(); + + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Instantiate the sr25519_verify contract. + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(100_000) + .build_and_unwrap_account_id(); + + let call_with = |message: &[u8; 11]| { + // Alice's signature for "hello world" + #[rustfmt::skip] + let signature: [u8; 64] = [ + 184, 49, 74, 238, 78, 165, 102, 252, 22, 92, 156, 176, 124, 118, 168, 116, 247, + 99, 0, 94, 2, 45, 9, 170, 73, 222, 182, 74, 60, 32, 75, 64, 98, 174, 69, 55, 83, + 85, 180, 98, 208, 75, 231, 57, 205, 62, 4, 105, 26, 136, 172, 17, 123, 99, 90, 255, + 228, 54, 115, 63, 30, 207, 205, 131, + ]; + + // Alice's public key + #[rustfmt::skip] + let public_key: [u8; 32] = [ + 212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, + 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125, + ]; + + let mut params = vec![]; + params.extend_from_slice(&signature); + params.extend_from_slice(&public_key); + params.extend_from_slice(message); + + builder::bare_call(addr.clone()).data(params).build_and_unwrap_result() + }; + + // verification should succeed for "hello world" + assert_return_code!(call_with(&b"hello world"), RuntimeReturnCode::Success); + + // verification should fail for other messages + assert_return_code!(call_with(&b"hello worlD"), RuntimeReturnCode::Sr25519VerifyFailed); + }); +} + +#[test] +fn failed_deposit_charge_should_roll_back_call() { + let (wasm_caller, _) = compile_module::("call_runtime_and_call").unwrap(); + let (wasm_callee, _) = compile_module::("store_call").unwrap(); + const ED: u64 = 200; + + let execute = || { + ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Instantiate both contracts. + let addr_caller = builder::bare_instantiate(Code::Upload(wasm_caller.clone())) + .build_and_unwrap_account_id(); + let addr_callee = builder::bare_instantiate(Code::Upload(wasm_callee.clone())) + .build_and_unwrap_account_id(); + + // Give caller proxy access to Alice. + assert_ok!(Proxy::add_proxy(RuntimeOrigin::signed(ALICE), addr_caller.clone(), (), 0)); + + // Create a Proxy call that will attempt to transfer away Alice's balance. + let transfer_call = + Box::new(RuntimeCall::Balances(pallet_balances::Call::transfer_allow_death { + dest: CHARLIE, + value: pallet_balances::Pallet::::free_balance(&ALICE) - 2 * ED, + })); + + // Wrap the transfer call in a proxy call. + let transfer_proxy_call = RuntimeCall::Proxy(pallet_proxy::Call::proxy { + real: ALICE, + force_proxy_type: Some(()), + call: transfer_call, + }); + + let data = ( + (ED - DepositPerItem::get()) as u32, // storage length + addr_callee, + transfer_proxy_call, + ); + + builder::call(addr_caller).data(data.encode()).build() + }) + }; + + // With a low enough deposit per byte, the call should succeed. + let result = execute().unwrap(); + + // Bump the deposit per byte to a high value to trigger a FundsUnavailable error. + DEPOSIT_PER_BYTE.with(|c| *c.borrow_mut() = 20); + assert_err_with_weight!(execute(), TokenError::FundsUnavailable, result.actual_weight); +} + +#[test] +fn upload_code_works() { + let (wasm, code_hash) = compile_module::("dummy").unwrap(); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Drop previous events + initialize_block(2); + + assert!(!PristineCode::::contains_key(&code_hash)); + + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm, + Some(codec::Compact(1_000)), + Determinism::Enforced, + )); + // Ensure the contract was stored and get expected deposit amount to be reserved. + let deposit_expected = expected_deposit(ensure_stored(code_hash)); + + assert_eq!( + System::events(), + vec![EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::CodeStored { + code_hash, + deposit_held: deposit_expected, + uploader: ALICE + }), + topics: vec![], + },] + ); + }); +} + +#[test] +fn upload_code_limit_too_low() { + let (wasm, _code_hash) = compile_module::("dummy").unwrap(); + let deposit_expected = expected_deposit(wasm.len()); + let deposit_insufficient = deposit_expected.saturating_sub(1); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Drop previous events + initialize_block(2); + + assert_noop!( + Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm, + Some(codec::Compact(deposit_insufficient)), + Determinism::Enforced + ), + >::StorageDepositLimitExhausted, + ); + + assert_eq!(System::events(), vec![]); + }); +} + +#[test] +fn upload_code_not_enough_balance() { + let (wasm, _code_hash) = compile_module::("dummy").unwrap(); + let deposit_expected = expected_deposit(wasm.len()); + let deposit_insufficient = deposit_expected.saturating_sub(1); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, deposit_insufficient); + + // Drop previous events + initialize_block(2); + + assert_noop!( + Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm, + Some(codec::Compact(1_000)), + Determinism::Enforced + ), + >::StorageDepositNotEnoughFunds, + ); + + assert_eq!(System::events(), vec![]); + }); +} + +#[test] +fn remove_code_works() { + let (wasm, code_hash) = compile_module::("dummy").unwrap(); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Drop previous events + initialize_block(2); + + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm, + Some(codec::Compact(1_000)), + Determinism::Enforced, + )); + // Ensure the contract was stored and get expected deposit amount to be reserved. + let deposit_expected = expected_deposit(ensure_stored(code_hash)); + + assert_ok!(Contracts::remove_code(RuntimeOrigin::signed(ALICE), code_hash)); + assert_eq!( + System::events(), + vec![ + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::CodeStored { + code_hash, + deposit_held: deposit_expected, + uploader: ALICE + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::CodeRemoved { + code_hash, + deposit_released: deposit_expected, + remover: ALICE + }), + topics: vec![], + }, + ] + ); + }); +} + +#[test] +fn remove_code_wrong_origin() { + let (wasm, code_hash) = compile_module::("dummy").unwrap(); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Drop previous events + initialize_block(2); + + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm, + Some(codec::Compact(1_000)), + Determinism::Enforced, + )); + // Ensure the contract was stored and get expected deposit amount to be reserved. + let deposit_expected = expected_deposit(ensure_stored(code_hash)); + + assert_noop!( + Contracts::remove_code(RuntimeOrigin::signed(BOB), code_hash), + sp_runtime::traits::BadOrigin, + ); + + assert_eq!( + System::events(), + vec![EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::CodeStored { + code_hash, + deposit_held: deposit_expected, + uploader: ALICE + }), + topics: vec![], + },] + ); + }); +} + +#[test] +fn remove_code_in_use() { + let (wasm, code_hash) = compile_module::("dummy").unwrap(); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + assert_ok!(builder::instantiate_with_code(wasm).build()); + + // Drop previous events + initialize_block(2); + + assert_noop!( + Contracts::remove_code(RuntimeOrigin::signed(ALICE), code_hash), + >::CodeInUse, + ); + + assert_eq!(System::events(), vec![]); + }); +} + +#[test] +fn remove_code_not_found() { + let (_wasm, code_hash) = compile_module::("dummy").unwrap(); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Drop previous events + initialize_block(2); + + assert_noop!( + Contracts::remove_code(RuntimeOrigin::signed(ALICE), code_hash), + >::CodeNotFound, + ); + + assert_eq!(System::events(), vec![]); + }); +} + +#[test] +fn instantiate_with_zero_balance_works() { + let (wasm, code_hash) = compile_module::("dummy").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + + // Drop previous events + initialize_block(2); + + // Instantiate the BOB contract. + let addr = builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_account_id(); + + // Ensure the contract was stored and get expected deposit amount to be reserved. + let deposit_expected = expected_deposit(ensure_stored(code_hash)); + + // Make sure the account exists even though no free balance was send + assert_eq!(::Currency::free_balance(&addr), min_balance); + assert_eq!( + ::Currency::total_balance(&addr), + min_balance + test_utils::contract_info_storage_deposit(&addr) + ); + + assert_eq!( + System::events(), + vec![ + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::CodeStored { + code_hash, + deposit_held: deposit_expected, + uploader: ALICE + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::System(frame_system::Event::NewAccount { + account: addr.clone(), + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Endowed { + account: addr.clone(), + free_balance: min_balance, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: ALICE, + to: addr.clone(), + amount: min_balance, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Instantiated { + deployer: ALICE, + contract: addr.clone(), + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts( + pallet_contracts::Event::StorageDepositTransferredAndHeld { + from: ALICE, + to: addr.clone(), + amount: test_utils::contract_info_storage_deposit(&addr), + } + ), + topics: vec![], + }, + ] + ); + }); +} + +#[test] +fn instantiate_with_below_existential_deposit_works() { + let (wasm, code_hash) = compile_module::("dummy").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + let value = 50; + + // Drop previous events + initialize_block(2); + + // Instantiate the BOB contract. + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(value) + .build_and_unwrap_account_id(); + + // Ensure the contract was stored and get expected deposit amount to be reserved. + let deposit_expected = expected_deposit(ensure_stored(code_hash)); + // Make sure the account exists even though not enough free balance was send + assert_eq!(::Currency::free_balance(&addr), min_balance + value); + assert_eq!( + ::Currency::total_balance(&addr), + min_balance + value + test_utils::contract_info_storage_deposit(&addr) + ); + + assert_eq!( + System::events(), + vec![ + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::CodeStored { + code_hash, + deposit_held: deposit_expected, + uploader: ALICE + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::System(frame_system::Event::NewAccount { + account: addr.clone() + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Endowed { + account: addr.clone(), + free_balance: min_balance, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: ALICE, + to: addr.clone(), + amount: min_balance, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: ALICE, + to: addr.clone(), + amount: 50, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Instantiated { + deployer: ALICE, + contract: addr.clone(), + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts( + pallet_contracts::Event::StorageDepositTransferredAndHeld { + from: ALICE, + to: addr.clone(), + amount: test_utils::contract_info_storage_deposit(&addr), + } + ), + topics: vec![], + }, + ] + ); + }); +} + +#[test] +fn storage_deposit_works() { + let (wasm, _code_hash) = compile_module::("multi_store").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + let addr = builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_account_id(); + + let mut deposit = test_utils::contract_info_storage_deposit(&addr); + + // Drop previous events + initialize_block(2); + + // Create storage + assert_ok!(builder::call(addr.clone()) + .value(42) + .data((1_000u32, 5_000u32).encode()) + .build()); + // 4 is for creating 2 storage items + let charged0 = 4 + 1_000 + 5_000; + deposit += charged0; + assert_eq!(get_contract(&addr).total_deposit(), deposit); + + // Add more storage (but also remove some) + assert_ok!(builder::call(addr.clone()).data((2_000u32, 4_900u32).encode()).build()); + let charged1 = 1_000 - 100; + deposit += charged1; + assert_eq!(get_contract(&addr).total_deposit(), deposit); + + // Remove more storage (but also add some) + assert_ok!(builder::call(addr.clone()).data((2_100u32, 900u32).encode()).build()); + // -1 for numeric instability + let refunded0 = 4_000 - 100 - 1; + deposit -= refunded0; + assert_eq!(get_contract(&addr).total_deposit(), deposit); + + assert_eq!( + System::events(), + vec![ + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: ALICE, + to: addr.clone(), + amount: 42, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(ALICE), + contract: addr.clone(), + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts( + pallet_contracts::Event::StorageDepositTransferredAndHeld { + from: ALICE, + to: addr.clone(), + amount: charged0, + } + ), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(ALICE), + contract: addr.clone(), + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts( + pallet_contracts::Event::StorageDepositTransferredAndHeld { + from: ALICE, + to: addr.clone(), + amount: charged1, + } + ), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(ALICE), + contract: addr.clone(), + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts( + pallet_contracts::Event::StorageDepositTransferredAndReleased { + from: addr.clone(), + to: ALICE, + amount: refunded0, + } + ), + topics: vec![], + }, + ] + ); + }); +} + +#[test] +fn storage_deposit_callee_works() { + let (wasm_caller, _code_hash_caller) = compile_module::("call").unwrap(); + let (wasm_callee, _code_hash_callee) = compile_module::("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + + // Create both contracts: Constructors do nothing. + let addr_caller = + builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_account_id(); + let addr_callee = + builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_account_id(); + + assert_ok!(builder::call(addr_caller).data((100u32, &addr_callee).encode()).build()); + + let callee = get_contract(&addr_callee); + let deposit = DepositPerByte::get() * 100 + DepositPerItem::get() * 1; + + assert_eq!(test_utils::get_balance(&addr_callee), min_balance); + assert_eq!( + callee.total_deposit(), + deposit + test_utils::contract_info_storage_deposit(&addr_callee) + ); + }); +} + +#[test] +fn set_code_extrinsic() { + let (wasm, code_hash) = compile_module::("dummy").unwrap(); + let (new_wasm, new_code_hash) = compile_module::("crypto_hashes").unwrap(); + + assert_ne!(code_hash, new_code_hash); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + let addr = builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_account_id(); + + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + new_wasm, + None, + Determinism::Enforced + )); + + // Drop previous events + initialize_block(2); + + 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(RuntimeOrigin::signed(ALICE), addr.clone(), new_code_hash), + sp_runtime::traits::BadOrigin, + ); + 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(RuntimeOrigin::root(), BOB, new_code_hash), + >::ContractNotFound, + ); + 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(RuntimeOrigin::root(), addr.clone(), Default::default()), + >::CodeNotFound, + ); + 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(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!( + System::events(), + vec![EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(pallet_contracts::Event::ContractCodeUpdated { + contract: addr.clone(), + new_code_hash, + old_code_hash: code_hash, + }), + topics: vec![], + },] + ); + }); +} + +#[test] +fn slash_cannot_kill_account() { + let (wasm, _code_hash) = compile_module::("dummy").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let value = 700; + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + + let addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(value) + .build_and_unwrap_account_id(); + + // Drop previous events + initialize_block(2); + + let info_deposit = test_utils::contract_info_storage_deposit(&addr); + + assert_eq!( + test_utils::get_balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr), + info_deposit + ); + + assert_eq!( + ::Currency::total_balance(&addr), + info_deposit + value + min_balance + ); + + // Try to destroy the account of the contract by slashing the total balance. + // The account does not get destroyed because slashing only affects the balance held under + // certain `reason`. Slashing can for example happen if the contract takes part in staking. + let _ = ::Currency::slash( + &HoldReason::StorageDepositReserve.into(), + &addr, + ::Currency::total_balance(&addr), + ); + + // Slashing only removed the balance held. + assert_eq!(::Currency::total_balance(&addr), value + min_balance); + }); +} + +#[test] +fn contract_reverted() { + let (wasm, code_hash) = compile_module::("return_with_data").unwrap(); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let flags = ReturnFlags::REVERT; + let buffer = [4u8, 8, 15, 16, 23, 42]; + let input = (flags.bits(), buffer).encode(); + + // We just upload the code for later use + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm.clone(), + None, + Determinism::Enforced + )); + + // Calling extrinsic: revert leads to an error + assert_err_ignore_postinfo!( + builder::instantiate(code_hash).data(input.clone()).build(), + >::ContractReverted, + ); + + // Calling extrinsic: revert leads to an error + assert_err_ignore_postinfo!( + builder::instantiate_with_code(wasm).data(input.clone()).build(), + >::ContractReverted, + ); + + // Calling directly: revert leads to success but the flags indicate the error + // This is just a different way of transporting the error that allows the read out + // the `data` which is only there on success. Obviously, the contract isn't + // instantiated. + let result = builder::bare_instantiate(Code::Existing(code_hash)) + .data(input.clone()) + .build_and_unwrap_result(); + assert_eq!(result.result.flags, flags); + assert_eq!(result.result.data, buffer); + assert!(!>::contains_key(result.account_id)); + + // Pass empty flags and therefore successfully instantiate the contract for later use. + let addr = builder::bare_instantiate(Code::Existing(code_hash)) + .data(ReturnFlags::empty().bits().encode()) + .build_and_unwrap_account_id(); + + // Calling extrinsic: revert leads to an error + assert_err_ignore_postinfo!( + builder::call(addr.clone()).data(input.clone()).build(), + >::ContractReverted, + ); + + // Calling directly: revert leads to success but the flags indicate the error + let result = builder::bare_call(addr.clone()).data(input).build_and_unwrap_result(); + assert_eq!(result.flags, flags); + assert_eq!(result.data, buffer); + }); +} + +#[test] +fn set_code_hash() { + let (wasm, code_hash) = compile_module::("set_code_hash").unwrap(); + let (new_wasm, new_code_hash) = compile_module::("new_set_code_hash_contract").unwrap(); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Instantiate the 'caller' + let contract_addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(300_000) + .build_and_unwrap_account_id(); + // upload new code + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + new_wasm.clone(), + None, + Determinism::Enforced + )); + + System::reset_events(); + + // First call sets new code_hash and returns 1 + let result = builder::bare_call(contract_addr.clone()) + .data(new_code_hash.as_ref().to_vec()) + .debug(DebugInfo::UnsafeDebug) + .build_and_unwrap_result(); + assert_return_code!(result, 1); + + // Second calls new contract code that returns 2 + let result = builder::bare_call(contract_addr.clone()) + .debug(DebugInfo::UnsafeDebug) + .build_and_unwrap_result(); + assert_return_code!(result, 2); + + // Checking for the last event only + assert_eq!( + &System::events(), + &[ + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::ContractCodeUpdated { + contract: contract_addr.clone(), + new_code_hash, + old_code_hash: code_hash, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(ALICE), + contract: contract_addr.clone(), + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(ALICE), + contract: contract_addr.clone(), + }), + topics: vec![], + }, + ], + ); + }); +} + +#[test] +fn storage_deposit_limit_is_enforced() { + let (wasm, _code_hash) = compile_module::("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + + // Setting insufficient storage_deposit should fail. + assert_err!( + builder::bare_instantiate(Code::Upload(wasm.clone())) + // expected deposit is 2 * ed + 3 for the call + .storage_deposit_limit(Some((2 * min_balance + 3 - 1).into())) + .build() + .result, + >::StorageDepositLimitExhausted, + ); + + // Instantiate the BOB contract. + let addr = builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_account_id(); + + let info_deposit = test_utils::contract_info_storage_deposit(&addr); + // Check that the BOB contract has been instantiated and has the minimum balance + assert_eq!(get_contract(&addr).total_deposit(), info_deposit); + assert_eq!(::Currency::total_balance(&addr), info_deposit + min_balance); + + // Create 1 byte of storage with a price of per byte, + // setting insufficient deposit limit, as it requires 3 Balance: + // 2 for the item added + 1 for the new storage item. + assert_err_ignore_postinfo!( + builder::call(addr.clone()) + .storage_deposit_limit(Some(codec::Compact(2))) + .data(1u32.to_le_bytes().to_vec()) + .build(), + >::StorageDepositLimitExhausted, + ); + + // To check that deposit limit fallbacks to DefaultDepositLimit, + // we customize it here. + DEFAULT_DEPOSIT_LIMIT.with(|c| *c.borrow_mut() = 3); + + // Create 1 byte of storage, should cost 3 Balance: + // 2 for the item added + 1 for the new storage item. + // Should pass as it fallbacks to DefaultDepositLimit. + assert_ok!(builder::call(addr.clone()).data(1u32.to_le_bytes().to_vec()).build()); + + // Use 4 more bytes of the storage for the same item, which requires 4 Balance. + // Should fail as DefaultDepositLimit is 3 and hence isn't enough. + assert_err_ignore_postinfo!( + builder::call(addr.clone()).data(5u32.to_le_bytes().to_vec()).build(), + >::StorageDepositLimitExhausted, + ); + }); +} + +#[test] +fn deposit_limit_in_nested_calls() { + let (wasm_caller, _code_hash_caller) = + compile_module::("create_storage_and_call").unwrap(); + let (wasm_callee, _code_hash_callee) = compile_module::("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Create both contracts: Constructors do nothing. + let addr_caller = + builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_account_id(); + let addr_callee = + builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_account_id(); + + // Create 100 bytes of storage with a price of per byte + // This is 100 Balance + 2 Balance for the item + assert_ok!(builder::call(addr_callee.clone()) + .storage_deposit_limit(Some(codec::Compact(102))) + .data(100u32.to_le_bytes().to_vec()) + .build()); + + // We do not remove any storage but add a storage item of 12 bytes in the caller + // contract. This would cost 12 + 2 = 14 Balance. + // The nested call doesn't get a special limit, which is set by passing 0 to it. + // This should fail as the specified parent's limit is less than the cost: 13 < + // 14. + assert_err_ignore_postinfo!( + builder::call(addr_caller.clone()) + .storage_deposit_limit(Some(codec::Compact(13))) + .data((100u32, &addr_callee, 0u64).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); + // Now we specify the parent's limit high enough to cover the caller's storage additions. + // However, we use a single byte more in the callee, hence the storage deposit should be 15 + // Balance. + // The nested call doesn't get a special limit, which is set by passing 0 to it. + // This should fail as the specified parent's limit is less than the cost: 14 + // < 15. + assert_err_ignore_postinfo!( + builder::call(addr_caller.clone()) + .storage_deposit_limit(Some(codec::Compact(14))) + .data((101u32, &addr_callee, 0u64).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); + + // Now we specify the parent's limit high enough to cover both the caller's and callee's + // storage additions. However, we set a special deposit limit of 1 Balance for the nested + // call. This should fail as callee adds up 2 bytes to the storage, meaning that the nested + // call should have a deposit limit of at least 2 Balance. The sub-call should be rolled + // back, which is covered by the next test case. + assert_err_ignore_postinfo!( + builder::call(addr_caller.clone()) + .storage_deposit_limit(Some(codec::Compact(16))) + .data((102u32, &addr_callee, 1u64).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); + + // Refund in the callee contract but not enough to cover the 14 Balance required by the + // caller. Note that if previous sub-call wouldn't roll back, this call would pass making + // the test case fail. We don't set a special limit for the nested call here. + assert_err_ignore_postinfo!( + builder::call(addr_caller.clone()) + .storage_deposit_limit(Some(codec::Compact(0))) + .data((87u32, &addr_callee, 0u64).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); + + let _ = ::Currency::set_balance(&ALICE, 1_000); + + // Require more than the sender's balance. + // We don't set a special limit for the nested call. + assert_err_ignore_postinfo!( + builder::call(addr_caller.clone()) + .data((1200u32, &addr_callee, 1u64).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); + + // Same as above but allow for the additional deposit of 1 Balance in parent. + // We set the special deposit limit of 1 Balance for the nested call, which isn't + // enforced as callee frees up storage. This should pass. + assert_ok!(builder::call(addr_caller.clone()) + .storage_deposit_limit(Some(codec::Compact(1))) + .data((87u32, &addr_callee, 1u64).encode()) + .build()); + }); +} + +#[test] +fn deposit_limit_in_nested_instantiate() { + let (wasm_caller, _code_hash_caller) = + compile_module::("create_storage_and_instantiate").unwrap(); + let (wasm_callee, code_hash_callee) = compile_module::("store_deploy").unwrap(); + const ED: u64 = 5; + ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let _ = ::Currency::set_balance(&BOB, 1_000_000); + // Create caller contract + let addr_caller = builder::bare_instantiate(Code::Upload(wasm_caller)) + .value(10_000u64) // this balance is later passed to the deployed contract + .build_and_unwrap_account_id(); + // Deploy a contract to get its occupied storage size + let addr = builder::bare_instantiate(Code::Upload(wasm_callee)) + .data(vec![0, 0, 0, 0]) + .build_and_unwrap_account_id(); + + let callee_info_len = ContractInfoOf::::get(&addr).unwrap().encoded_size() as u64; + + // We don't set a special deposit limit for the nested instantiation. + // + // The deposit limit set for the parent is insufficient for the instantiation, which + // requires: + // - callee_info_len + 2 for storing the new contract info, + // - ED for deployed contract account, + // - 2 for the storage item of 0 bytes being created in the callee constructor + // or (callee_info_len + 2 + ED + 2) Balance in total. + // + // Provided the limit is set to be 1 Balance less, + // this call should fail on the return from the caller contract. + assert_err_ignore_postinfo!( + builder::call(addr_caller.clone()) + .origin(RuntimeOrigin::signed(BOB)) + .storage_deposit_limit(Some(codec::Compact(callee_info_len + 2 + ED + 1))) + .data((0u32, &code_hash_callee, 0u64).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); + // The charges made on instantiation should be rolled back. + assert_eq!(::Currency::free_balance(&BOB), 1_000_000); + + // Now we give enough limit for the instantiation itself, but require for 1 more storage + // byte in the constructor. Hence +1 Balance to the limit is needed. This should fail on the + // return from constructor. + assert_err_ignore_postinfo!( + builder::call(addr_caller.clone()) + .origin(RuntimeOrigin::signed(BOB)) + .storage_deposit_limit(Some(codec::Compact(callee_info_len + 2 + ED + 2))) + .data((1u32, &code_hash_callee, 0u64).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); + // The charges made on the instantiation should be rolled back. + assert_eq!(::Currency::free_balance(&BOB), 1_000_000); + + // Now we set enough limit in parent call, but an insufficient limit for child instantiate. + // This should fail during the charging for the instantiation in + // `RawMeter::charge_instantiate()` + assert_err_ignore_postinfo!( + builder::call(addr_caller.clone()) + .origin(RuntimeOrigin::signed(BOB)) + .storage_deposit_limit(Some(codec::Compact(callee_info_len + 2 + ED + 2))) + .data((0u32, &code_hash_callee, callee_info_len + 2 + ED + 1).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); + // The charges made on the instantiation should be rolled back. + assert_eq!(::Currency::free_balance(&BOB), 1_000_000); + + // Same as above but requires for single added storage + // item of 1 byte to be covered by the limit, which implies 3 more Balance. + // Now we set enough limit for the parent call, but insufficient limit for child + // instantiate. This should fail right after the constructor execution. + assert_err_ignore_postinfo!( + builder::call(addr_caller.clone()) + .origin(RuntimeOrigin::signed(BOB)) + .storage_deposit_limit(Some(codec::Compact(callee_info_len + 2 + ED + 3))) // enough parent limit + .data((1u32, &code_hash_callee, callee_info_len + 2 + ED + 2).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); + // The charges made on the instantiation should be rolled back. + assert_eq!(::Currency::free_balance(&BOB), 1_000_000); + + // Set enough deposit limit for the child instantiate. This should succeed. + let result = builder::bare_call(addr_caller.clone()) + .origin(BOB) + .storage_deposit_limit(Some(codec::Compact(callee_info_len + 2 + ED + 4).into())) + .data((1u32, &code_hash_callee, callee_info_len + 2 + ED + 3).encode()) + .build(); + + let returned = result.result.unwrap(); + // All balance of the caller except ED has been transferred to the callee. + // No deposit has been taken from it. + assert_eq!(::Currency::free_balance(&addr_caller), ED); + // Get address of the deployed contract. + let addr_callee = AccountId32::from_slice(&returned.data[0..32]).unwrap(); + // 10_000 should be sent to callee from the caller contract, plus ED to be sent from the + // origin. + assert_eq!(::Currency::free_balance(&addr_callee), 10_000 + ED); + // The origin should be charged with: + // - callee instantiation deposit = (callee_info_len + 2) + // - callee account ED + // - for writing an item of 1 byte to storage = 3 Balance + assert_eq!( + ::Currency::free_balance(&BOB), + 1_000_000 - (callee_info_len + 2 + ED + 3) + ); + // Check that deposit due to be charged still includes these 3 Balance + assert_eq!(result.storage_deposit.charge_or_zero(), (callee_info_len + 2 + ED + 3)) + }); +} + +#[test] +fn deposit_limit_honors_liquidity_restrictions() { + let (wasm, _code_hash) = compile_module::("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let bobs_balance = 1_000; + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let _ = ::Currency::set_balance(&BOB, bobs_balance); + let min_balance = Contracts::min_balance(); + + // Instantiate the BOB contract. + let addr = builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_account_id(); + + let info_deposit = test_utils::contract_info_storage_deposit(&addr); + // Check that the contract has been instantiated and has the minimum balance + assert_eq!(get_contract(&addr).total_deposit(), info_deposit); + assert_eq!(::Currency::total_balance(&addr), info_deposit + min_balance); + + // check that the hold is honored + ::Currency::hold( + &HoldReason::CodeUploadDepositReserve.into(), + &BOB, + bobs_balance - min_balance, + ) + .unwrap(); + assert_err_ignore_postinfo!( + builder::call(addr.clone()) + .origin(RuntimeOrigin::signed(BOB)) + .storage_deposit_limit(Some(codec::Compact(200))) + .data(100u32.to_le_bytes().to_vec()) + .build(), + >::StorageDepositNotEnoughFunds, + ); + assert_eq!(::Currency::free_balance(&BOB), min_balance); + }); +} + +#[test] +fn deposit_limit_honors_existential_deposit() { + let (wasm, _code_hash) = compile_module::("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let _ = ::Currency::set_balance(&BOB, 1_000); + let min_balance = Contracts::min_balance(); + + // Instantiate the BOB contract. + let addr = builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_account_id(); + + let info_deposit = test_utils::contract_info_storage_deposit(&addr); + + // Check that the contract has been instantiated and has the minimum balance + assert_eq!(get_contract(&addr).total_deposit(), info_deposit); + assert_eq!(::Currency::total_balance(&addr), min_balance + info_deposit); + + // check that the deposit can't bring the account below the existential deposit + assert_err_ignore_postinfo!( + builder::call(addr.clone()) + .origin(RuntimeOrigin::signed(BOB)) + .storage_deposit_limit(Some(codec::Compact(900))) + .data(100u32.to_le_bytes().to_vec()) + .build(), + >::StorageDepositNotEnoughFunds, + ); + assert_eq!(::Currency::free_balance(&BOB), 1_000); + }); +} + +#[test] +fn deposit_limit_honors_min_leftover() { + let (wasm, _code_hash) = compile_module::("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let _ = ::Currency::set_balance(&BOB, 1_000); + let min_balance = Contracts::min_balance(); + + // Instantiate the BOB contract. + let addr = builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_account_id(); + + let info_deposit = test_utils::contract_info_storage_deposit(&addr); + + // Check that the contract has been instantiated and has the minimum balance and the storage + // deposit + assert_eq!(get_contract(&addr).total_deposit(), info_deposit); + assert_eq!(::Currency::total_balance(&addr), info_deposit + min_balance); + + // check that the minimum leftover (value send) is considered + assert_err_ignore_postinfo!( + builder::call(addr.clone()) + .origin(RuntimeOrigin::signed(BOB)) + .value(400) + .storage_deposit_limit(Some(codec::Compact(500))) + .data(100u32.to_le_bytes().to_vec()) + .build(), + >::StorageDepositNotEnoughFunds, + ); + assert_eq!(::Currency::free_balance(&BOB), 1_000); + }); +} + +#[test] +fn upload_should_enforce_deterministic_mode_when_possible() { + let upload = |fixture, determinism| { + let (wasm, code_hash) = compile_module::(fixture).unwrap(); + ExtBuilder::default() + .build() + .execute_with(|| -> Result { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + Contracts::bare_upload_code(ALICE, wasm, None, determinism)?; + let info = CodeInfoOf::::get(code_hash).unwrap(); + Ok(info.determinism()) + }) + }; + + assert_eq!(upload("dummy", Determinism::Enforced), Ok(Determinism::Enforced)); + assert_eq!(upload("dummy", Determinism::Relaxed), Ok(Determinism::Enforced)); + assert_eq!(upload("float_instruction", Determinism::Relaxed), Ok(Determinism::Relaxed)); + assert!(upload("float_instruction", Determinism::Enforced).is_err()); +} + +#[test] +fn cannot_instantiate_indeterministic_code() { + let (wasm, code_hash) = compile_module::("float_instruction").unwrap(); + let (caller_wasm, _) = compile_module::("instantiate_return_code").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Try to instantiate directly from code + assert_err_ignore_postinfo!( + builder::instantiate_with_code(wasm.clone()).build(), + >::CodeRejected, + ); + assert_err!( + builder::bare_instantiate(Code::Upload(wasm.clone())).build().result, + >::CodeRejected, + ); + + // Try to upload a non-deterministic code as deterministic + assert_err!( + Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm.clone(), + None, + Determinism::Enforced + ), + >::CodeRejected, + ); + + // Try to instantiate from already stored indeterministic code hash + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm, + None, + Determinism::Relaxed, + )); + + assert_err_ignore_postinfo!( + builder::instantiate(code_hash).build(), + >::Indeterministic, + ); + assert_err!( + builder::bare_instantiate(Code::Existing(code_hash)).build().result, + >::Indeterministic, + ); + + // Deploy contract which instantiates another contract + let addr = + builder::bare_instantiate(Code::Upload(caller_wasm)).build_and_unwrap_account_id(); + + // Try to instantiate `code_hash` from another contract in deterministic mode + assert_err!( + builder::bare_call(addr.clone()).data(code_hash.encode()).build().result, + >::Indeterministic, + ); + + // Instantiations are not allowed even in non-determinism mode + assert_err!( + builder::bare_call(addr.clone()).data(code_hash.encode()).build().result, + >::Indeterministic, + ); + }); +} + +#[test] +fn cannot_set_code_indeterministic_code() { + let (wasm, code_hash) = compile_module::("float_instruction").unwrap(); + let (caller_wasm, _) = compile_module::("set_code_hash").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Put the non-deterministic contract on-chain + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm, + None, + Determinism::Relaxed, + )); + + // Create the contract that will call `seal_set_code_hash` + let caller_addr = + builder::bare_instantiate(Code::Upload(caller_wasm)).build_and_unwrap_account_id(); + + // We do not allow to set the code hash to a non-deterministic wasm + assert_err!( + builder::bare_call(caller_addr.clone()).data(code_hash.encode()).build().result, + >::Indeterministic, + ); + }); +} + +#[test] +fn delegate_call_indeterministic_code() { + let (wasm, code_hash) = compile_module::("float_instruction").unwrap(); + let (caller_wasm, _) = compile_module::("delegate_call_simple").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Put the non-deterministic contract on-chain + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm, + None, + Determinism::Relaxed, + )); + + // Create the contract that will call `seal_delegate_call` + let caller_addr = + builder::bare_instantiate(Code::Upload(caller_wasm)).build_and_unwrap_account_id(); + + // The delegate call will fail in deterministic mode + assert_err!( + builder::bare_call(caller_addr.clone()).data(code_hash.encode()).build().result, + >::Indeterministic, + ); + + // The delegate call will work on non-deterministic mode + assert_ok!( + builder::bare_call(caller_addr.clone()) + .data(code_hash.encode()) + .determinism(Determinism::Relaxed) + .build() + .result + ); + }); +} + +#[test] +fn locking_delegate_dependency_works() { + // set hash lock up deposit to 30%, to test deposit calculation. + CODE_HASH_LOCKUP_DEPOSIT_PERCENT.with(|c| *c.borrow_mut() = Perbill::from_percent(30)); + MAX_DELEGATE_DEPENDENCIES.with(|c| *c.borrow_mut() = 1); + + let (wasm_caller, self_code_hash) = + compile_module::("locking_delegate_dependency").unwrap(); + let (wasm_callee, code_hash) = compile_module::("dummy").unwrap(); + let (wasm_other, other_code_hash) = compile_module::("call").unwrap(); + + // Define inputs with various actions to test locking / unlocking delegate_dependencies. + // See the contract for more details. + let noop_input = (0u32, code_hash); + let lock_delegate_dependency_input = (1u32, code_hash); + let unlock_delegate_dependency_input = (2u32, code_hash); + let terminate_input = (3u32, code_hash); + + // Instantiate the caller contract with the given input. + let instantiate = |input: &(u32, H256)| { + builder::bare_instantiate(Code::Upload(wasm_caller.clone())) + .data(input.encode()) + .build() + }; + + // Call contract with the given input. + let call = |addr_caller: &AccountId32, input: &(u32, H256)| { + builder::bare_call(addr_caller.clone()).data(input.encode()).build() + }; + const ED: u64 = 2000; + ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { + let _ = Balances::set_balance(&ALICE, 1_000_000); + + // Instantiate with lock_delegate_dependency should fail since the code is not yet on chain. + assert_err!( + instantiate(&lock_delegate_dependency_input).result, + Error::::CodeNotFound + ); + + // Upload the delegated code. + let CodeUploadReturnValue { deposit, .. } = + Contracts::bare_upload_code(ALICE, wasm_callee.clone(), None, Determinism::Enforced) + .unwrap(); + + // Instantiate should now work. + let addr_caller = instantiate(&lock_delegate_dependency_input).result.unwrap().account_id; + + // There should be a dependency and a deposit. + let contract = test_utils::get_contract(&addr_caller); + + let dependency_deposit = &CodeHashLockupDepositPercent::get().mul_ceil(deposit); + assert_eq!(contract.delegate_dependencies().get(&code_hash), Some(dependency_deposit)); + assert_eq!( + test_utils::get_balance_on_hold( + &HoldReason::StorageDepositReserve.into(), + &addr_caller + ), + dependency_deposit + contract.storage_base_deposit() + ); + + // Removing the code should fail, since we have added a dependency. + assert_err!( + Contracts::remove_code(RuntimeOrigin::signed(ALICE), code_hash), + >::CodeInUse + ); + + // Locking an already existing dependency should fail. + assert_err!( + call(&addr_caller, &lock_delegate_dependency_input).result, + Error::::DelegateDependencyAlreadyExists + ); + + // Locking self should fail. + assert_err!( + call(&addr_caller, &(1u32, self_code_hash)).result, + Error::::CannotAddSelfAsDelegateDependency + ); + + // Locking more than the maximum allowed delegate_dependencies should fail. + Contracts::bare_upload_code(ALICE, wasm_other, None, Determinism::Enforced).unwrap(); + assert_err!( + call(&addr_caller, &(1u32, other_code_hash)).result, + Error::::MaxDelegateDependenciesReached + ); + + // Unlocking dependency should work. + assert_ok!(call(&addr_caller, &unlock_delegate_dependency_input).result); + + // Dependency should be removed, and deposit should be returned. + let contract = test_utils::get_contract(&addr_caller); + assert!(contract.delegate_dependencies().is_empty()); + assert_eq!( + test_utils::get_balance_on_hold( + &HoldReason::StorageDepositReserve.into(), + &addr_caller + ), + contract.storage_base_deposit() + ); + + // Removing a nonexistent dependency should fail. + assert_err!( + call(&addr_caller, &unlock_delegate_dependency_input).result, + Error::::DelegateDependencyNotFound + ); + + // Locking a dependency with a storage limit too low should fail. + DEFAULT_DEPOSIT_LIMIT.with(|c| *c.borrow_mut() = dependency_deposit - 1); + assert_err!( + call(&addr_caller, &lock_delegate_dependency_input).result, + Error::::StorageDepositLimitExhausted + ); + + // Since we unlocked the dependency we should now be able to remove the code. + assert_ok!(Contracts::remove_code(RuntimeOrigin::signed(ALICE), code_hash)); + + // Calling should fail since the delegated contract is not on chain anymore. + assert_err!(call(&addr_caller, &noop_input).result, Error::::ContractTrapped); + + // Restore initial deposit limit and add the dependency back. + DEFAULT_DEPOSIT_LIMIT.with(|c| *c.borrow_mut() = 10_000_000); + Contracts::bare_upload_code(ALICE, wasm_callee, None, Determinism::Enforced).unwrap(); + call(&addr_caller, &lock_delegate_dependency_input).result.unwrap(); + + // Call terminate should work, and return the deposit. + let balance_before = test_utils::get_balance(&ALICE); + assert_ok!(call(&addr_caller, &terminate_input).result); + assert_eq!( + test_utils::get_balance(&ALICE), + ED + balance_before + contract.storage_base_deposit() + dependency_deposit + ); + + // Terminate should also remove the dependency, so we can remove the code. + assert_ok!(Contracts::remove_code(RuntimeOrigin::signed(ALICE), code_hash)); + }); +} + +#[test] +fn native_dependency_deposit_works() { + let (wasm, code_hash) = compile_module::("set_code_hash").unwrap(); + let (dummy_wasm, dummy_code_hash) = compile_module::("dummy").unwrap(); + + // Set hash lock up deposit to 30%, to test deposit calculation. + CODE_HASH_LOCKUP_DEPOSIT_PERCENT.with(|c| *c.borrow_mut() = Perbill::from_percent(30)); + + // Test with both existing and uploaded code + for code in [Code::Upload(wasm.clone()), Code::Existing(code_hash)] { + ExtBuilder::default().build().execute_with(|| { + let _ = Balances::set_balance(&ALICE, 1_000_000); + let lockup_deposit_percent = CodeHashLockupDepositPercent::get(); + + // Upload the dummy contract, + Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + dummy_wasm.clone(), + None, + Determinism::Enforced, + ) + .unwrap(); + + // Upload `set_code_hash` contracts if using Code::Existing. + let add_upload_deposit = match code { + Code::Existing(_) => { + Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm.clone(), + None, + Determinism::Enforced, + ) + .unwrap(); + false + }, + Code::Upload(_) => true, + }; + + // Instantiate the set_code_hash contract. + let res = builder::bare_instantiate(code).build(); + + let addr = res.result.unwrap().account_id; + let base_deposit = test_utils::contract_info_storage_deposit(&addr); + let upload_deposit = test_utils::get_code_deposit(&code_hash); + let extra_deposit = add_upload_deposit.then(|| upload_deposit).unwrap_or_default(); + + // Check initial storage_deposit + // The base deposit should be: contract_info_storage_deposit + 30% * deposit + let deposit = + extra_deposit + base_deposit + lockup_deposit_percent.mul_ceil(upload_deposit); + + assert_eq!(res.storage_deposit.charge_or_zero(), deposit + Contracts::min_balance()); + + // call set_code_hash + builder::bare_call(addr.clone()) + .data(dummy_code_hash.encode()) + .build_and_unwrap_result(); + + // Check updated storage_deposit + let code_deposit = test_utils::get_code_deposit(&dummy_code_hash); + let deposit = base_deposit + lockup_deposit_percent.mul_ceil(code_deposit); + assert_eq!(test_utils::get_contract(&addr).storage_base_deposit(), deposit); + + assert_eq!( + test_utils::get_balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr), + deposit + ); + }); + } +} + +#[test] +fn reentrance_count_works_with_call() { + let (wasm, _code_hash) = compile_module::("reentrance_count_call").unwrap(); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + let contract_addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(300_000) + .build_and_unwrap_account_id(); + + // passing reentrant count to the input + let input = 0.encode(); + + builder::bare_call(contract_addr) + .data(input) + .debug(DebugInfo::UnsafeDebug) + .build_and_unwrap_result(); + }); +} + +#[test] +fn reentrance_count_works_with_delegated_call() { + let (wasm, code_hash) = compile_module::("reentrance_count_delegated_call").unwrap(); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + let contract_addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(300_000) + .build_and_unwrap_account_id(); + + // adding a callstack height to the input + let input = (code_hash, 1).encode(); + + builder::bare_call(contract_addr.clone()) + .data(input) + .debug(DebugInfo::UnsafeDebug) + .build_and_unwrap_result(); + }); +} + +#[test] +fn account_reentrance_count_works() { + let (wasm, _code_hash) = compile_module::("account_reentrance_count_call").unwrap(); + let (wasm_reentrance_count, _code_hash_reentrance_count) = + compile_module::("reentrance_count_call").unwrap(); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + let contract_addr = builder::bare_instantiate(Code::Upload(wasm)) + .value(300_000) + .build_and_unwrap_account_id(); + + let another_contract_addr = builder::bare_instantiate(Code::Upload(wasm_reentrance_count)) + .value(300_000) + .build_and_unwrap_account_id(); + + let result1 = builder::bare_call(contract_addr.clone()) + .data(contract_addr.encode()) + .debug(DebugInfo::UnsafeDebug) + .build_and_unwrap_result(); + + let result2 = builder::bare_call(contract_addr.clone()) + .data(another_contract_addr.encode()) + .debug(DebugInfo::UnsafeDebug) + .build_and_unwrap_result(); + + assert_eq!(result1.data, 1.encode()); + assert_eq!(result2.data, 0.encode()); + }); +} + +#[test] +fn root_cannot_upload_code() { + let (wasm, _) = compile_module::("dummy").unwrap(); + + ExtBuilder::default().build().execute_with(|| { + assert_noop!( + Contracts::upload_code(RuntimeOrigin::root(), wasm, None, Determinism::Enforced), + DispatchError::BadOrigin, + ); + }); +} + +#[test] +fn root_cannot_remove_code() { + let (_, code_hash) = compile_module::("dummy").unwrap(); + + ExtBuilder::default().build().execute_with(|| { + assert_noop!( + Contracts::remove_code(RuntimeOrigin::root(), code_hash), + DispatchError::BadOrigin, + ); + }); +} + +#[test] +fn signed_cannot_set_code() { + let (_, code_hash) = compile_module::("dummy").unwrap(); + + ExtBuilder::default().build().execute_with(|| { + assert_noop!( + Contracts::set_code(RuntimeOrigin::signed(ALICE), BOB, code_hash), + DispatchError::BadOrigin, + ); + }); +} + +#[test] +fn none_cannot_call_code() { + ExtBuilder::default().build().execute_with(|| { + assert_noop!( + builder::call(BOB).origin(RuntimeOrigin::none()).build(), + DispatchError::BadOrigin, + ); + }); +} + +#[test] +fn root_can_call() { + let (wasm, _) = compile_module::("dummy").unwrap(); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + let addr = builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_account_id(); + + // Call the contract. + assert_ok!(builder::call(addr.clone()).origin(RuntimeOrigin::root()).build()); + }); +} + +#[test] +fn root_cannot_instantiate_with_code() { + let (wasm, _) = compile_module::("dummy").unwrap(); + + ExtBuilder::default().build().execute_with(|| { + assert_err_ignore_postinfo!( + builder::instantiate_with_code(wasm).origin(RuntimeOrigin::root()).build(), + DispatchError::BadOrigin + ); + }); +} + +#[test] +fn root_cannot_instantiate() { + let (_, code_hash) = compile_module::("dummy").unwrap(); + + ExtBuilder::default().build().execute_with(|| { + assert_err_ignore_postinfo!( + builder::instantiate(code_hash).origin(RuntimeOrigin::root()).build(), + DispatchError::BadOrigin + ); + }); +} + +#[test] +fn only_upload_origin_can_upload() { + let (wasm, _) = compile_module::("dummy").unwrap(); + UploadAccount::set(Some(ALICE)); + ExtBuilder::default().build().execute_with(|| { + let _ = Balances::set_balance(&ALICE, 1_000_000); + let _ = Balances::set_balance(&BOB, 1_000_000); + + assert_err!( + Contracts::upload_code( + RuntimeOrigin::root(), + wasm.clone(), + None, + Determinism::Enforced, + ), + DispatchError::BadOrigin + ); + + assert_err!( + Contracts::upload_code( + RuntimeOrigin::signed(BOB), + wasm.clone(), + None, + Determinism::Enforced, + ), + DispatchError::BadOrigin + ); + + // Only alice is allowed to upload contract code. + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm.clone(), + None, + Determinism::Enforced, + )); + }); +} + +#[test] +fn only_instantiation_origin_can_instantiate() { + let (code, code_hash) = compile_module::("dummy").unwrap(); + InstantiateAccount::set(Some(ALICE)); + ExtBuilder::default().build().execute_with(|| { + let _ = Balances::set_balance(&ALICE, 1_000_000); + let _ = Balances::set_balance(&BOB, 1_000_000); + + assert_err_ignore_postinfo!( + builder::instantiate_with_code(code.clone()) + .origin(RuntimeOrigin::root()) + .build(), + DispatchError::BadOrigin + ); + + assert_err_ignore_postinfo!( + builder::instantiate_with_code(code.clone()) + .origin(RuntimeOrigin::signed(BOB)) + .build(), + DispatchError::BadOrigin + ); + + // Only Alice can instantiate + assert_ok!(builder::instantiate_with_code(code).build()); + + // Bob cannot instantiate with either `instantiate_with_code` or `instantiate`. + assert_err_ignore_postinfo!( + builder::instantiate(code_hash).origin(RuntimeOrigin::signed(BOB)).build(), + DispatchError::BadOrigin + ); + }); +} + +#[test] +fn balance_api_returns_free_balance() { + let (wasm, _code_hash) = compile_module::("balance").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Instantiate the BOB contract without any extra balance. + let addr = + builder::bare_instantiate(Code::Upload(wasm.to_vec())).build_and_unwrap_account_id(); + + let value = 0; + // Call BOB which makes it call the balance runtime API. + // The contract code asserts that the returned balance is 0. + assert_ok!(builder::call(addr.clone()).value(value).build()); + + let value = 1; + // Calling with value will trap the contract. + assert_err_ignore_postinfo!( + builder::call(addr.clone()).value(value).build(), + >::ContractTrapped + ); + }); +} + +#[test] +fn gas_consumed_is_linear_for_nested_calls() { + let (code, _code_hash) = compile_module::("recurse").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + let addr = builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_account_id(); + + let max_call_depth = ::CallStack::size() as u32; + let [gas_0, gas_1, gas_2, gas_max] = { + [0u32, 1u32, 2u32, max_call_depth] + .iter() + .map(|i| { + let result = builder::bare_call(addr.clone()).data(i.encode()).build(); + assert_ok!(result.result); + result.gas_consumed + }) + .collect::>() + .try_into() + .unwrap() + }; + + let gas_per_recursion = gas_2.checked_sub(&gas_1).unwrap(); + assert_eq!(gas_max, gas_0 + gas_per_recursion * max_call_depth as u64); + }); +} + +#[test] +fn read_only_call_cannot_store() { + let (wasm_caller, _code_hash_caller) = compile_module::("read_only_call").unwrap(); + let (wasm_callee, _code_hash_callee) = compile_module::("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Create both contracts: Constructors do nothing. + let addr_caller = + builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_account_id(); + let addr_callee = + builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_account_id(); + + // Read-only call fails when modifying storage. + assert_err_ignore_postinfo!( + builder::call(addr_caller).data((&addr_callee, 100u32).encode()).build(), + >::ContractTrapped + ); + }); +} + +#[test] +fn read_only_call_cannot_transfer() { + let (wasm_caller, _code_hash_caller) = + compile_module::("call_with_flags_and_value").unwrap(); + let (wasm_callee, _code_hash_callee) = compile_module::("dummy").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Create both contracts: Constructors do nothing. + let addr_caller = + builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_account_id(); + let addr_callee = + builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_account_id(); + + // Read-only call fails when a non-zero value is set. + assert_err_ignore_postinfo!( + builder::call(addr_caller) + .data( + (addr_callee, pallet_contracts_uapi::CallFlags::READ_ONLY.bits(), 100u64) + .encode() + ) + .build(), + >::StateChangeDenied + ); + }); +} + +#[test] +fn read_only_subsequent_call_cannot_store() { + let (wasm_read_only_caller, _code_hash_caller) = + compile_module::("read_only_call").unwrap(); + let (wasm_caller, _code_hash_caller) = + compile_module::("call_with_flags_and_value").unwrap(); + let (wasm_callee, _code_hash_callee) = compile_module::("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Create contracts: Constructors do nothing. + let addr_caller = builder::bare_instantiate(Code::Upload(wasm_read_only_caller)) + .build_and_unwrap_account_id(); + let addr_subsequent_caller = + builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_account_id(); + let addr_callee = + builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_account_id(); + + // Subsequent call input. + let input = (&addr_callee, pallet_contracts_uapi::CallFlags::empty().bits(), 0u64, 100u32); + + // Read-only call fails when modifying storage. + assert_err_ignore_postinfo!( + builder::call(addr_caller) + .data((&addr_subsequent_caller, input).encode()) + .build(), + >::ContractTrapped + ); + }); +} + +#[test] +fn read_only_call_works() { + let (wasm_caller, _code_hash_caller) = compile_module::("read_only_call").unwrap(); + let (wasm_callee, _code_hash_callee) = compile_module::("dummy").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Create both contracts: Constructors do nothing. + let addr_caller = + builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_account_id(); + let addr_callee = + builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_account_id(); + + assert_ok!(builder::call(addr_caller.clone()).data(addr_callee.encode()).build()); + }); +} diff --git a/pallets/contracts/src/tests/pallet_dummy.rs b/pallets/contracts/src/tests/pallet_dummy.rs new file mode 100644 index 00000000..2af8475d --- /dev/null +++ b/pallets/contracts/src/tests/pallet_dummy.rs @@ -0,0 +1,53 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub use pallet::*; + +#[frame_support::pallet(dev_mode)] +pub mod pallet { + use frame_support::{ + dispatch::{Pays, PostDispatchInfo}, + ensure, + pallet_prelude::DispatchResultWithPostInfo, + weights::Weight, + }; + use frame_system::pallet_prelude::*; + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: frame_system::Config {} + + #[pallet::call] + impl Pallet { + /// Dummy function that overcharges the predispatch weight, allowing us to test the correct + /// values of [`ContractResult::gas_consumed`] and [`ContractResult::gas_required`] in + /// tests. + #[pallet::call_index(1)] + #[pallet::weight(*pre_charge)] + pub fn overestimate_pre_charge( + origin: OriginFor, + pre_charge: Weight, + actual_weight: Weight, + ) -> DispatchResultWithPostInfo { + ensure_signed(origin)?; + ensure!(pre_charge.any_gt(actual_weight), "pre_charge must be > actual_weight"); + Ok(PostDispatchInfo { actual_weight: Some(actual_weight), pays_fee: Pays::Yes }) + } + } +} diff --git a/pallets/contracts/src/tests/test_debug.rs b/pallets/contracts/src/tests/test_debug.rs new file mode 100644 index 00000000..c9b6557b --- /dev/null +++ b/pallets/contracts/src/tests/test_debug.rs @@ -0,0 +1,229 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use super::*; +use crate::{ + debug::{CallInterceptor, CallSpan, ExecResult, ExportedFunction, Tracing}, + primitives::ExecReturnValue, + AccountIdOf, +}; +use frame_support::traits::Currency; +use pretty_assertions::assert_eq; +use std::cell::RefCell; + +#[derive(Clone, PartialEq, Eq, Debug)] +struct DebugFrame { + contract_account: AccountId32, + call: ExportedFunction, + input: Vec, + result: Option>, +} + +thread_local! { + static DEBUG_EXECUTION_TRACE: RefCell> = RefCell::new(Vec::new()); + static INTERCEPTED_ADDRESS: RefCell> = RefCell::new(None); +} + +pub struct TestDebug; +pub struct TestCallSpan { + contract_account: AccountId32, + call: ExportedFunction, + input: Vec, +} + +impl Tracing for TestDebug { + type CallSpan = TestCallSpan; + + fn new_call_span( + contract_account: &AccountIdOf, + entry_point: ExportedFunction, + input_data: &[u8], + ) -> TestCallSpan { + DEBUG_EXECUTION_TRACE.with(|d| { + d.borrow_mut().push(DebugFrame { + contract_account: contract_account.clone(), + call: entry_point, + input: input_data.to_vec(), + result: None, + }) + }); + TestCallSpan { + contract_account: contract_account.clone(), + call: entry_point, + input: input_data.to_vec(), + } + } +} + +impl CallInterceptor for TestDebug { + fn intercept_call( + contract_address: &::AccountId, + _entry_point: &ExportedFunction, + _input_data: &[u8], + ) -> Option { + INTERCEPTED_ADDRESS.with(|i| { + if i.borrow().as_ref() == Some(contract_address) { + Some(Ok(ExecReturnValue { flags: ReturnFlags::REVERT, data: vec![] })) + } else { + None + } + }) + } +} + +impl CallSpan for TestCallSpan { + fn after_call(self, output: &ExecReturnValue) { + DEBUG_EXECUTION_TRACE.with(|d| { + d.borrow_mut().push(DebugFrame { + contract_account: self.contract_account, + call: self.call, + input: self.input, + result: Some(output.data.clone()), + }) + }); + } +} + +#[test] +fn debugging_works() { + let (wasm_caller, _) = compile_module::("call").unwrap(); + let (wasm_callee, _) = compile_module::("store_call").unwrap(); + + fn current_stack() -> Vec { + DEBUG_EXECUTION_TRACE.with(|stack| stack.borrow().clone()) + } + + fn deploy(wasm: Vec) -> AccountId32 { + Contracts::bare_instantiate( + ALICE, + 0, + GAS_LIMIT, + None, + Code::Upload(wasm), + vec![], + vec![], + DebugInfo::Skip, + CollectEvents::Skip, + ) + .result + .unwrap() + .account_id + } + + fn constructor_frame(contract_account: &AccountId32, after: bool) -> DebugFrame { + DebugFrame { + contract_account: contract_account.clone(), + call: ExportedFunction::Constructor, + input: vec![], + result: if after { Some(vec![]) } else { None }, + } + } + + fn call_frame(contract_account: &AccountId32, args: Vec, after: bool) -> DebugFrame { + DebugFrame { + contract_account: contract_account.clone(), + call: ExportedFunction::Call, + input: args, + result: if after { Some(vec![]) } else { None }, + } + } + + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = Balances::deposit_creating(&ALICE, 1_000_000); + + assert_eq!(current_stack(), vec![]); + + let addr_caller = deploy(wasm_caller); + let addr_callee = deploy(wasm_callee); + + assert_eq!( + current_stack(), + vec![ + constructor_frame(&addr_caller, false), + constructor_frame(&addr_caller, true), + constructor_frame(&addr_callee, false), + constructor_frame(&addr_callee, true), + ] + ); + + let main_args = (100u32, &addr_callee.clone()).encode(); + let inner_args = (100u32).encode(); + + assert_ok!(Contracts::call( + RuntimeOrigin::signed(ALICE), + addr_caller.clone(), + 0, + GAS_LIMIT, + None, + main_args.clone() + )); + + let stack_top = current_stack()[4..].to_vec(); + assert_eq!( + stack_top, + vec![ + call_frame(&addr_caller, main_args.clone(), false), + call_frame(&addr_callee, inner_args.clone(), false), + call_frame(&addr_callee, inner_args, true), + call_frame(&addr_caller, main_args, true), + ] + ); + }); +} + +#[test] +fn call_interception_works() { + let (wasm, _) = compile_module::("dummy").unwrap(); + + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = Balances::deposit_creating(&ALICE, 1_000_000); + + let account_id = Contracts::bare_instantiate( + ALICE, + 0, + GAS_LIMIT, + None, + Code::Upload(wasm), + vec![], + // some salt to ensure that the address of this contract is unique among all tests + vec![0x41, 0x41, 0x41, 0x41], + DebugInfo::Skip, + CollectEvents::Skip, + ) + .result + .unwrap() + .account_id; + + // no interception yet + assert_ok!(Contracts::call( + RuntimeOrigin::signed(ALICE), + account_id.clone(), + 0, + GAS_LIMIT, + None, + vec![], + )); + + // intercept calls to this contract + INTERCEPTED_ADDRESS.with(|i| *i.borrow_mut() = Some(account_id.clone())); + + assert_err_ignore_postinfo!( + Contracts::call(RuntimeOrigin::signed(ALICE), account_id, 0, GAS_LIMIT, None, vec![],), + >::ContractReverted, + ); + }); +} diff --git a/pallets/contracts/src/transient_storage.rs b/pallets/contracts/src/transient_storage.rs new file mode 100644 index 00000000..c795a966 --- /dev/null +++ b/pallets/contracts/src/transient_storage.rs @@ -0,0 +1,698 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This module contains routines for accessing and altering a contract transient storage. + +use crate::{ + exec::{AccountIdOf, Key}, + storage::WriteOutcome, + Config, Error, +}; +use codec::Encode; +use core::marker::PhantomData; +use frame_support::DefaultNoBound; +use sp_runtime::{DispatchError, DispatchResult, Saturating}; +use sp_std::{collections::btree_map::BTreeMap, mem, vec::Vec}; + +/// Meter entry tracks transaction allocations. +#[derive(Default, Debug)] +pub struct MeterEntry { + /// Allocations made in the current transaction. + pub amount: u32, + /// Allocations limit in the current transaction. + pub limit: u32, +} + +impl MeterEntry { + /// Create a new entry. + fn new(limit: u32) -> Self { + Self { limit, amount: Default::default() } + } + + /// Check if the allocated amount exceeds the limit. + fn exceeds_limit(&self, amount: u32) -> bool { + self.amount.saturating_add(amount) > self.limit + } + + /// Absorb the allocation amount of the nested entry into the current entry. + fn absorb(&mut self, rhs: Self) { + self.amount.saturating_accrue(rhs.amount) + } +} + +// The storage meter enforces a limit for each transaction, +// which is calculated as free_storage * (1 - 1/16) for each subsequent frame. +#[derive(DefaultNoBound)] +pub struct StorageMeter { + nested_meters: Vec, + root_meter: MeterEntry, + _phantom: PhantomData, +} + +impl StorageMeter { + const STORAGE_FRACTION_DENOMINATOR: u32 = 16; + /// Create a new storage allocation meter. + fn new(memory_limit: u32) -> Self { + Self { root_meter: MeterEntry::new(memory_limit), ..Default::default() } + } + + /// Charge the allocated amount of transaction storage from the meter. + fn charge(&mut self, amount: u32) -> DispatchResult { + let meter = self.current_mut(); + if meter.exceeds_limit(amount) { + return Err(Error::::OutOfTransientStorage.into()); + } + meter.amount.saturating_accrue(amount); + Ok(()) + } + + /// Revert a transaction meter. + fn revert(&mut self) { + self.nested_meters.pop().expect( + "A call to revert a meter must be preceded by a corresponding call to start a meter; + the code within this crate makes sure that this is always the case; qed", + ); + } + + /// Start a transaction meter. + fn start(&mut self) { + let meter = self.current(); + let mut transaction_limit = meter.limit.saturating_sub(meter.amount); + if !self.nested_meters.is_empty() { + // Allow use of (1 - 1/STORAGE_FRACTION_DENOMINATOR) of free storage for subsequent + // calls. + transaction_limit.saturating_reduce( + transaction_limit.saturating_div(Self::STORAGE_FRACTION_DENOMINATOR), + ); + } + + self.nested_meters.push(MeterEntry::new(transaction_limit)); + } + + /// Commit a transaction meter. + fn commit(&mut self) { + let transaction_meter = self.nested_meters.pop().expect( + "A call to commit a meter must be preceded by a corresponding call to start a meter; + the code within this crate makes sure that this is always the case; qed", + ); + self.current_mut().absorb(transaction_meter) + } + + /// The total allocated amount of memory. + #[cfg(test)] + fn total_amount(&self) -> u32 { + self.nested_meters + .iter() + .fold(self.root_meter.amount, |acc, e| acc.saturating_add(e.amount)) + } + + /// A mutable reference to the current meter entry. + pub fn current_mut(&mut self) -> &mut MeterEntry { + self.nested_meters.last_mut().unwrap_or(&mut self.root_meter) + } + + /// A reference to the current meter entry. + pub fn current(&self) -> &MeterEntry { + self.nested_meters.last().unwrap_or(&self.root_meter) + } +} + +/// An entry representing a journal change. +struct JournalEntry { + key: Vec, + prev_value: Option>, +} + +impl JournalEntry { + /// Create a new change. + fn new(key: Vec, prev_value: Option>) -> Self { + Self { key, prev_value } + } + + /// Revert the change. + fn revert(self, storage: &mut Storage) { + storage.write(&self.key, self.prev_value); + } +} + +/// A journal containing transient storage modifications. +struct Journal(Vec); + +impl Journal { + /// Create a new journal. + fn new() -> Self { + Self(Default::default()) + } + + /// Add a change to the journal. + fn push(&mut self, entry: JournalEntry) { + self.0.push(entry); + } + + /// Length of the journal. + fn len(&self) -> usize { + self.0.len() + } + + /// Roll back all journal changes until the chackpoint + fn rollback(&mut self, storage: &mut Storage, checkpoint: usize) { + self.0.drain(checkpoint..).rev().for_each(|entry| entry.revert(storage)); + } +} + +/// Storage for maintaining the current transaction state. +#[derive(Default)] +struct Storage(BTreeMap, Vec>); + +impl Storage { + /// Read the storage entry. + fn read(&self, key: &Vec) -> Option> { + self.0.get(key).cloned() + } + + /// Write the storage entry. + fn write(&mut self, key: &Vec, value: Option>) -> Option> { + if let Some(value) = value { + // Insert storage entry. + self.0.insert(key.clone(), value) + } else { + // Remove storage entry. + self.0.remove(key) + } + } +} + +/// Transient storage behaves almost identically to regular storage but is discarded after each +/// transaction. It consists of a `BTreeMap` for the current state, a journal of all changes, and a +/// list of checkpoints. On entry to the `start_transaction` function, a marker (checkpoint) is +/// added to the list. New values are written to the current state, and the previous value is +/// recorded in the journal (`write`). When the `commit_transaction` function is called, the marker +/// to the journal index (checkpoint) of when that call was entered is discarded. +/// On `rollback_transaction`, all entries are reverted up to the last checkpoint. +pub struct TransientStorage { + // The storage and journal size is limited by the storage meter. + storage: Storage, + journal: Journal, + // The size of the StorageMeter is limited by the stack depth. + meter: StorageMeter, + // The size of the checkpoints is limited by the stack depth. + checkpoints: Vec, +} + +impl TransientStorage { + /// Create new transient storage with the supplied memory limit. + pub fn new(memory_limit: u32) -> Self { + TransientStorage { + storage: Default::default(), + journal: Journal::new(), + checkpoints: Default::default(), + meter: StorageMeter::new(memory_limit), + } + } + + /// Read the storage value. If the entry does not exist, `None` is returned. + pub fn read(&self, account: &AccountIdOf, key: &Key) -> Option> { + self.storage.read(&Self::storage_key(&account.encode(), &key.hash())) + } + + /// Write a value to storage. + /// + /// If the `value` is `None`, then the entry is removed. If `take` is true, + /// a [`WriteOutcome::Taken`] is returned instead of a [`WriteOutcome::Overwritten`]. + /// If the entry did not exist, [`WriteOutcome::New`] is returned. + pub fn write( + &mut self, + account: &AccountIdOf, + key: &Key, + value: Option>, + take: bool, + ) -> Result { + let key = Self::storage_key(&account.encode(), &key.hash()); + let prev_value = self.storage.read(&key); + // Skip if the same value is being set. + if prev_value != value { + // Calculate the allocation size. + if let Some(value) = &value { + // Charge the key, value and journal entry. + // If a new value is written, a new journal entry is created. The previous value is + // moved to the journal along with its key, and the new value is written to + // storage. + let key_len = key.capacity(); + let mut amount = value + .capacity() + .saturating_add(key_len) + .saturating_add(mem::size_of::()); + if prev_value.is_none() { + // Charge a new storage entry. + // If there was no previous value, a new entry is added to storage (BTreeMap) + // containing a Vec for the key and a Vec for the value. The value was already + // included in the amount. + amount.saturating_accrue(key_len.saturating_add(mem::size_of::>())); + } + self.meter.charge(amount as _)?; + } + self.storage.write(&key, value); + // Update the journal. + self.journal.push(JournalEntry::new(key, prev_value.clone())); + } + + Ok(match (take, prev_value) { + (_, None) => WriteOutcome::New, + (false, Some(prev_value)) => WriteOutcome::Overwritten(prev_value.len() as _), + (true, Some(prev_value)) => WriteOutcome::Taken(prev_value), + }) + } + + /// Start a new nested transaction. + /// + /// This allows to either commit or roll back all changes that are made after this call. + /// For every transaction there must be a matching call to either `rollback_transaction` + /// or `commit_transaction`. + pub fn start_transaction(&mut self) { + self.meter.start(); + self.checkpoints.push(self.journal.len()); + } + + /// Rollback the last transaction started by `start_transaction`. + /// + /// Any changes made during that transaction are discarded. + /// + /// # Panics + /// + /// Will panic if there is no open transaction. + pub fn rollback_transaction(&mut self) { + let checkpoint = self + .checkpoints + .pop() + .expect( + "A call to rollback_transaction must be preceded by a corresponding call to start_transaction; + the code within this crate makes sure that this is always the case; qed" + ); + self.meter.revert(); + self.journal.rollback(&mut self.storage, checkpoint); + } + + /// Commit the last transaction started by `start_transaction`. + /// + /// Any changes made during that transaction are committed. + /// + /// # Panics + /// + /// Will panic if there is no open transaction. + pub fn commit_transaction(&mut self) { + self.checkpoints + .pop() + .expect( + "A call to commit_transaction must be preceded by a corresponding call to start_transaction; + the code within this crate makes sure that this is always the case; qed" + ); + self.meter.commit(); + } + + /// The storage allocation meter used for transaction metering. + #[cfg(any(test, feature = "runtime-benchmarks"))] + pub fn meter(&mut self) -> &mut StorageMeter { + return &mut self.meter + } + + fn storage_key(account: &[u8], key: &[u8]) -> Vec { + let mut storage_key = Vec::with_capacity(account.len() + key.len()); + storage_key.extend_from_slice(&account); + storage_key.extend_from_slice(&key); + storage_key + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + tests::{Test, ALICE, BOB, CHARLIE}, + Error, + }; + use core::u32::MAX; + + // Calculate the allocation size for the given entry. + fn allocation_size( + account: &AccountIdOf, + key: &Key, + value: Option>, + ) -> u32 { + let mut storage: TransientStorage = TransientStorage::::new(MAX); + storage + .write(account, key, value, false) + .expect("Could not write to transient storage."); + storage.meter().current().amount + } + + #[test] + fn read_write_works() { + let mut storage: TransientStorage = TransientStorage::::new(2048); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + storage.write(&ALICE, &Key::Fix([2; 32]), Some(vec![2]), true), + Ok(WriteOutcome::New) + ); + assert_eq!( + storage.write(&BOB, &Key::Fix([3; 32]), Some(vec![3]), false), + Ok(WriteOutcome::New) + ); + assert_eq!(storage.read(&ALICE, &Key::Fix([1; 32])), Some(vec![1])); + assert_eq!(storage.read(&ALICE, &Key::Fix([2; 32])), Some(vec![2])); + assert_eq!(storage.read(&BOB, &Key::Fix([3; 32])), Some(vec![3])); + // Overwrite values. + assert_eq!( + storage.write(&ALICE, &Key::Fix([2; 32]), Some(vec![4, 5]), false), + Ok(WriteOutcome::Overwritten(1)) + ); + assert_eq!( + storage.write(&BOB, &Key::Fix([3; 32]), Some(vec![6, 7]), true), + Ok(WriteOutcome::Taken(vec![3])) + ); + assert_eq!(storage.read(&ALICE, &Key::Fix([1; 32])), Some(vec![1])); + assert_eq!(storage.read(&ALICE, &Key::Fix([2; 32])), Some(vec![4, 5])); + assert_eq!(storage.read(&BOB, &Key::Fix([3; 32])), Some(vec![6, 7])); + + // Check for an empty value. + assert_eq!( + storage.write(&BOB, &Key::Fix([3; 32]), Some(vec![]), true), + Ok(WriteOutcome::Taken(vec![6, 7])) + ); + assert_eq!(storage.read(&BOB, &Key::Fix([3; 32])), Some(vec![])); + + assert_eq!( + storage.write(&BOB, &Key::Fix([3; 32]), None, true), + Ok(WriteOutcome::Taken(vec![])) + ); + assert_eq!(storage.read(&BOB, &Key::Fix([3; 32])), None); + } + + #[test] + fn read_write_with_var_sized_keys_works() { + let mut storage = TransientStorage::::new(2048); + assert_eq!( + storage.write( + &ALICE, + &Key::::try_from_var([1; 64].to_vec()).unwrap(), + Some(vec![1]), + false + ), + Ok(WriteOutcome::New) + ); + assert_eq!( + storage.write( + &BOB, + &Key::::try_from_var([2; 64].to_vec()).unwrap(), + Some(vec![2, 3]), + false + ), + Ok(WriteOutcome::New) + ); + assert_eq!( + storage.read(&ALICE, &Key::::try_from_var([1; 64].to_vec()).unwrap()), + Some(vec![1]) + ); + assert_eq!( + storage.read(&BOB, &Key::::try_from_var([2; 64].to_vec()).unwrap()), + Some(vec![2, 3]) + ); + // Overwrite values. + assert_eq!( + storage.write( + &ALICE, + &Key::::try_from_var([1; 64].to_vec()).unwrap(), + Some(vec![4, 5]), + false + ), + Ok(WriteOutcome::Overwritten(1)) + ); + assert_eq!( + storage.read(&ALICE, &Key::::try_from_var([1; 64].to_vec()).unwrap()), + Some(vec![4, 5]) + ); + } + + #[test] + fn rollback_transaction_works() { + let mut storage = TransientStorage::::new(1024); + + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1]), false), + Ok(WriteOutcome::New) + ); + storage.rollback_transaction(); + assert_eq!(storage.read(&ALICE, &Key::Fix([1; 32])), None) + } + + #[test] + fn commit_transaction_works() { + let mut storage = TransientStorage::::new(1024); + + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1]), false), + Ok(WriteOutcome::New) + ); + storage.commit_transaction(); + assert_eq!(storage.read(&ALICE, &Key::Fix([1; 32])), Some(vec![1])) + } + + #[test] + fn overwrite_and_commmit_transaction_works() { + let mut storage = TransientStorage::::new(1024); + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1, 2]), false), + Ok(WriteOutcome::Overwritten(1)) + ); + storage.commit_transaction(); + assert_eq!(storage.read(&ALICE, &Key::Fix([1; 32])), Some(vec![1, 2])) + } + + #[test] + fn rollback_in_nested_transaction_works() { + let mut storage = TransientStorage::::new(1024); + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1]), false), + Ok(WriteOutcome::New) + ); + storage.start_transaction(); + assert_eq!( + storage.write(&BOB, &Key::Fix([1; 32]), Some(vec![1]), false), + Ok(WriteOutcome::New) + ); + storage.rollback_transaction(); + storage.commit_transaction(); + assert_eq!(storage.read(&ALICE, &Key::Fix([1; 32])), Some(vec![1])); + assert_eq!(storage.read(&BOB, &Key::Fix([1; 32])), None) + } + + #[test] + fn commit_in_nested_transaction_works() { + let mut storage = TransientStorage::::new(1024); + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1]), false), + Ok(WriteOutcome::New) + ); + storage.start_transaction(); + assert_eq!( + storage.write(&BOB, &Key::Fix([1; 32]), Some(vec![2]), false), + Ok(WriteOutcome::New) + ); + storage.start_transaction(); + assert_eq!( + storage.write(&CHARLIE, &Key::Fix([1; 32]), Some(vec![3]), false), + Ok(WriteOutcome::New) + ); + storage.commit_transaction(); + storage.commit_transaction(); + storage.commit_transaction(); + assert_eq!(storage.read(&ALICE, &Key::Fix([1; 32])), Some(vec![1])); + assert_eq!(storage.read(&BOB, &Key::Fix([1; 32])), Some(vec![2])); + assert_eq!(storage.read(&CHARLIE, &Key::Fix([1; 32])), Some(vec![3])); + } + + #[test] + fn rollback_all_transactions_works() { + let mut storage = TransientStorage::::new(1024); + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1]), false), + Ok(WriteOutcome::New) + ); + storage.start_transaction(); + assert_eq!( + storage.write(&BOB, &Key::Fix([1; 32]), Some(vec![2]), false), + Ok(WriteOutcome::New) + ); + storage.start_transaction(); + assert_eq!( + storage.write(&CHARLIE, &Key::Fix([1; 32]), Some(vec![3]), false), + Ok(WriteOutcome::New) + ); + storage.commit_transaction(); + storage.commit_transaction(); + storage.rollback_transaction(); + assert_eq!(storage.read(&ALICE, &Key::Fix([1; 32])), None); + assert_eq!(storage.read(&BOB, &Key::Fix([1; 32])), None); + assert_eq!(storage.read(&CHARLIE, &Key::Fix([1; 32])), None); + } + + #[test] + fn metering_transactions_works() { + let size = allocation_size(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096])); + let mut storage = TransientStorage::::new(size * 2); + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + let limit = storage.meter().current().limit; + storage.commit_transaction(); + + storage.start_transaction(); + assert_eq!(storage.meter().current().limit, limit - size); + assert_eq!(storage.meter().current().limit - storage.meter().current().amount, size); + assert_eq!( + storage.write(&ALICE, &Key::Fix([2; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + assert_eq!(storage.meter().current().amount, size); + storage.commit_transaction(); + assert_eq!(storage.meter().total_amount(), size * 2); + } + + #[test] + fn metering_nested_transactions_works() { + let size = allocation_size(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096])); + let mut storage = TransientStorage::::new(size * 3); + + storage.start_transaction(); + let limit = storage.meter().current().limit; + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + storage.start_transaction(); + assert_eq!(storage.meter().total_amount(), size); + assert!(storage.meter().current().limit < limit - size); + assert_eq!( + storage.write(&ALICE, &Key::Fix([2; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + storage.commit_transaction(); + assert_eq!(storage.meter().current().limit, limit); + assert_eq!(storage.meter().total_amount(), storage.meter().current().amount); + storage.commit_transaction(); + } + + #[test] + fn metering_transaction_fails() { + let size = allocation_size(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096])); + let mut storage = TransientStorage::::new(size - 1); + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096]), false), + Err(Error::::OutOfTransientStorage.into()) + ); + assert_eq!(storage.meter.current().amount, 0); + storage.commit_transaction(); + assert_eq!(storage.meter.total_amount(), 0); + } + + #[test] + fn metering_nested_transactions_fails() { + let size = allocation_size(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096])); + let mut storage = TransientStorage::::new(size * 2); + + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([2; 32]), Some(vec![1u8; 4096]), false), + Err(Error::::OutOfTransientStorage.into()) + ); + storage.commit_transaction(); + storage.commit_transaction(); + assert_eq!(storage.meter.total_amount(), size); + } + + #[test] + fn metering_nested_transaction_with_rollback_works() { + let size = allocation_size(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096])); + let mut storage = TransientStorage::::new(size * 2); + + storage.start_transaction(); + let limit = storage.meter.current().limit; + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([2; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + storage.rollback_transaction(); + + assert_eq!(storage.meter.total_amount(), 0); + assert_eq!(storage.meter.current().limit, limit); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + let amount = storage.meter().current().amount; + assert_eq!(storage.meter().total_amount(), amount); + storage.commit_transaction(); + } + + #[test] + fn metering_with_rollback_works() { + let size = allocation_size(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096])); + let mut storage = TransientStorage::::new(size * 5); + + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + let amount = storage.meter.total_amount(); + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([2; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + storage.start_transaction(); + assert_eq!( + storage.write(&BOB, &Key::Fix([1; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + storage.commit_transaction(); + storage.rollback_transaction(); + assert_eq!(storage.meter.total_amount(), amount); + storage.commit_transaction(); + } +} diff --git a/pallets/contracts/src/wasm/mod.rs b/pallets/contracts/src/wasm/mod.rs new file mode 100644 index 00000000..f4ee7645 --- /dev/null +++ b/pallets/contracts/src/wasm/mod.rs @@ -0,0 +1,3917 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This module provides a means for executing contracts +//! represented in wasm. + +mod prepare; +mod runtime; + +#[cfg(doc)] +pub use crate::wasm::runtime::api_doc; + +#[cfg(test)] +pub use { + crate::wasm::{prepare::tracker, runtime::ReturnErrorCode}, + runtime::STABLE_API_COUNT, + tests::MockExt, +}; + +#[cfg(feature = "runtime-benchmarks")] +pub use crate::wasm::runtime::{BenchEnv, ReturnData, TrapReason}; + +pub use crate::wasm::{ + prepare::{LoadedModule, LoadingMode}, + runtime::{ + AllowDeprecatedInterface, AllowUnstableInterface, Environment, Runtime, RuntimeCosts, + }, +}; + +use crate::{ + exec::{ExecResult, Executable, ExportedFunction, Ext}, + gas::{GasMeter, Token}, + weights::WeightInfo, + AccountIdOf, BadOrigin, BalanceOf, CodeHash, CodeInfoOf, CodeVec, Config, Error, Event, + HoldReason, Pallet, PristineCode, Schedule, Weight, LOG_TARGET, +}; +use alloc::vec::Vec; +use codec::{Decode, Encode, MaxEncodedLen}; +use frame_support::{ + dispatch::DispatchResult, + ensure, + traits::{fungible::MutateHold, tokens::Precision::BestEffort}, +}; +use sp_core::Get; +use sp_runtime::{DispatchError, RuntimeDebug}; +use wasmi::{CompilationMode, InstancePre, Linker, Memory, MemoryType, StackLimits, Store}; + +const BYTES_PER_PAGE: usize = 64 * 1024; + +/// Validated Wasm module ready for execution. +/// This data structure is immutable once created and stored. +#[derive(Encode, Decode, scale_info::TypeInfo)] +#[codec(mel_bound())] +#[scale_info(skip_type_params(T))] +pub struct WasmBlob { + code: CodeVec, + // This isn't needed for contract execution and is not stored alongside it. + #[codec(skip)] + code_info: CodeInfo, + // This is for not calculating the hash every time we need it. + #[codec(skip)] + code_hash: CodeHash, +} + +/// Contract code related data, such as: +/// +/// - owner of the contract, i.e. account uploaded its code, +/// - storage deposit amount, +/// - reference count, +/// - determinism marker. +/// +/// It is stored in a separate storage entry to avoid loading the code when not necessary. +#[derive(Clone, Encode, Decode, scale_info::TypeInfo, MaxEncodedLen)] +#[codec(mel_bound())] +#[scale_info(skip_type_params(T))] +pub struct CodeInfo { + /// The account that has uploaded the contract code and hence is allowed to remove it. + owner: AccountIdOf, + /// The amount of balance that was deposited by the owner in order to store it on-chain. + #[codec(compact)] + deposit: BalanceOf, + /// The number of instantiated contracts that use this as their code. + #[codec(compact)] + refcount: u64, + /// Marks if the code might contain non-deterministic features and is therefore never allowed + /// to be run on-chain. Specifically, such a code can never be instantiated into a contract + /// and can just be used through a delegate call. + determinism: Determinism, + /// length of the code in bytes. + code_len: u32, +} + +/// Defines the required determinism level of a wasm blob when either running or uploading code. +#[derive( + Clone, Copy, Encode, Decode, scale_info::TypeInfo, MaxEncodedLen, RuntimeDebug, PartialEq, Eq, +)] +pub enum Determinism { + /// The execution should be deterministic and hence no indeterministic instructions are + /// allowed. + /// + /// Dispatchables always use this mode in order to make on-chain execution deterministic. + Enforced, + /// Allow calling or uploading an indeterministic code. + /// + /// This is only possible when calling into `pallet-contracts` directly via + /// [`crate::Pallet::bare_call`]. + /// + /// # Note + /// + /// **Never** use this mode for on-chain execution. + Relaxed, +} + +impl ExportedFunction { + /// The wasm export name for the function. + fn identifier(&self) -> &str { + match self { + Self::Constructor => "deploy", + Self::Call => "call", + } + } +} + +/// Cost of code loading from storage. +#[cfg_attr(test, derive(Debug, PartialEq, Eq))] +#[derive(Clone, Copy)] +struct CodeLoadToken(u32); + +impl Token for CodeLoadToken { + fn weight(&self) -> Weight { + T::WeightInfo::call_with_code_per_byte(self.0) + .saturating_sub(T::WeightInfo::call_with_code_per_byte(0)) + } +} + +impl WasmBlob { + /// Create the module by checking the `code`. + pub fn from_code( + code: Vec, + schedule: &Schedule, + owner: AccountIdOf, + determinism: Determinism, + ) -> Result { + prepare::prepare::( + code.try_into().map_err(|_| (>::CodeTooLarge.into(), ""))?, + schedule, + owner, + determinism, + ) + } + + /// Remove the code from storage and refund the deposit to its owner. + /// + /// Applies all necessary checks before removing the code. + pub fn remove(origin: &T::AccountId, code_hash: CodeHash) -> DispatchResult { + >::try_mutate_exists(&code_hash, |existing| { + if let Some(code_info) = existing { + ensure!(code_info.refcount == 0, >::CodeInUse); + ensure!(&code_info.owner == origin, BadOrigin); + let _ = T::Currency::release( + &HoldReason::CodeUploadDepositReserve.into(), + &code_info.owner, + code_info.deposit, + BestEffort, + ); + let deposit_released = code_info.deposit; + let remover = code_info.owner.clone(); + + *existing = None; + >::remove(&code_hash); + >::deposit_event(Event::CodeRemoved { + code_hash, + deposit_released, + remover, + }); + Ok(()) + } else { + Err(>::CodeNotFound.into()) + } + }) + } + + /// Creates and returns an instance of the supplied code. + /// + /// This is either used for later executing a contract or for validation of a contract. + /// When validating we pass `()` as `host_state`. Please note that such a dummy instance must + /// **never** be called/executed, since it will panic the executor. + pub fn instantiate( + contract: LoadedModule, + host_state: H, + schedule: &Schedule, + allow_deprecated: AllowDeprecatedInterface, + ) -> Result<(Store, Memory, InstancePre), &'static str> + where + E: Environment, + { + let mut store = Store::new(&contract.engine, host_state); + let mut linker = Linker::new(&contract.engine); + E::define( + &mut store, + &mut linker, + if T::UnsafeUnstableInterface::get() { + AllowUnstableInterface::Yes + } else { + AllowUnstableInterface::No + }, + allow_deprecated, + ) + .map_err(|_| "can't define host functions to Linker")?; + + // Query wasmi for memory limits specified in the module's import entry. + let memory_limits = contract.scan_imports::(schedule)?; + // Here we allocate this memory in the _store_. It allocates _inital_ value, but allows it + // to grow up to maximum number of memory pages, if necessary. + let qed = "We checked the limits versus our Schedule, + which specifies the max amount of memory pages + well below u16::MAX; qed"; + let memory = Memory::new( + &mut store, + MemoryType::new(memory_limits.0, Some(memory_limits.1)).expect(qed), + ) + .expect(qed); + + linker + .define("env", "memory", memory) + .expect("We just created the Linker. It has no definitions with this name; qed"); + + let instance = linker.instantiate(&mut store, &contract.module).map_err(|err| { + log::debug!(target: LOG_TARGET, "failed to instantiate module: {:?}", err); + "can't instantiate module with provided definitions" + })?; + + Ok((store, memory, instance)) + } + + /// Puts the module blob into storage, and returns the deposit collected for the storage. + pub fn store_code(&mut self) -> Result, Error> { + let code_hash = *self.code_hash(); + >::mutate(code_hash, |stored_code_info| { + match stored_code_info { + // Contract code is already stored in storage. Nothing to be done here. + Some(_) => Ok(Default::default()), + // Upload a new contract code. + // We need to store the code and its code_info, and collect the deposit. + // This `None` case happens only with freshly uploaded modules. This means that + // the `owner` is always the origin of the current transaction. + None => { + let deposit = self.code_info.deposit; + T::Currency::hold( + &HoldReason::CodeUploadDepositReserve.into(), + &self.code_info.owner, + deposit, + ) + .map_err(|_| >::StorageDepositNotEnoughFunds)?; + + self.code_info.refcount = 0; + >::insert(code_hash, &self.code); + *stored_code_info = Some(self.code_info.clone()); + >::deposit_event(Event::CodeStored { + code_hash, + deposit_held: deposit, + uploader: self.code_info.owner.clone(), + }); + Ok(deposit) + }, + } + }) + } + + /// Create the module without checking the passed code. + /// + /// # Note + /// + /// This is useful for benchmarking where we don't want validation of the module to skew + /// our results. This also does not collect any deposit from the `owner`. Also useful + /// during testing when we want to deploy codes that do not pass the instantiation checks. + #[cfg(any(test, feature = "runtime-benchmarks"))] + pub fn from_code_unchecked( + code: Vec, + schedule: &Schedule, + owner: T::AccountId, + ) -> Result { + prepare::benchmarking::prepare(code, schedule, owner) + } +} + +impl CodeInfo { + #[cfg(test)] + pub fn new(owner: T::AccountId) -> Self { + CodeInfo { + owner, + deposit: Default::default(), + refcount: 0, + code_len: 0, + determinism: Determinism::Enforced, + } + } + + /// Returns the determinism of the module. + pub fn determinism(&self) -> Determinism { + self.determinism + } + + /// Returns reference count of the module. + pub fn refcount(&self) -> u64 { + self.refcount + } + + /// Return mutable reference to the refcount of the module. + pub fn refcount_mut(&mut self) -> &mut u64 { + &mut self.refcount + } + + /// Returns the deposit of the module. + pub fn deposit(&self) -> BalanceOf { + self.deposit + } +} + +use crate::{ExecError, ExecReturnValue}; +use wasmi::Func; +enum InstanceOrExecReturn<'a, E: Ext> { + Instance((Func, Store>)), + ExecReturn(ExecReturnValue), +} + +type PreExecResult<'a, E> = Result, ExecError>; + +impl WasmBlob { + /// Sync the frame's gas meter with the engine's one. + pub fn process_result>( + mut store: Store>, + result: Result<(), wasmi::Error>, + ) -> ExecResult { + let engine_fuel = store.get_fuel().expect("Fuel metering is enabled; qed"); + let gas_meter = store.data_mut().ext().gas_meter_mut(); + let _ = gas_meter.sync_from_executor(engine_fuel)?; + store.into_data().to_execution_result(result) + } + + #[cfg(feature = "runtime-benchmarks")] + pub fn bench_prepare_call>( + self, + ext: &mut E, + input_data: Vec, + ) -> (Func, Store>) { + use InstanceOrExecReturn::*; + match Self::prepare_execute( + self, + Runtime::new(ext, input_data), + &ExportedFunction::Call, + CompilationMode::Eager, + ) + .expect("Benchmark should provide valid module") + { + Instance((func, store)) => (func, store), + ExecReturn(_) => panic!("Expected Instance"), + } + } + + fn prepare_execute<'a, E: Ext>( + self, + runtime: Runtime<'a, E>, + function: &'a ExportedFunction, + compilation_mode: CompilationMode, + ) -> PreExecResult<'a, E> { + let code = self.code.as_slice(); + // Instantiate the Wasm module to the engine. + let schedule = ::Schedule::get(); + + let contract = LoadedModule::new::( + &code, + self.code_info.determinism, + Some(StackLimits::default()), + LoadingMode::Unchecked, + compilation_mode, + ) + .map_err(|err| { + log::debug!(target: LOG_TARGET, "failed to create wasmi module: {err:?}"); + Error::::CodeRejected + })?; + + let (mut store, memory, instance) = Self::instantiate::( + contract, + runtime, + &schedule, + match function { + ExportedFunction::Call => AllowDeprecatedInterface::Yes, + ExportedFunction::Constructor => AllowDeprecatedInterface::No, + }, + ) + .map_err(|msg| { + log::debug!(target: LOG_TARGET, "failed to instantiate code to wasmi: {}", msg); + Error::::CodeRejected + })?; + store.data_mut().set_memory(memory); + + // Set fuel limit for the wasmi execution. + // We normalize it by the base instruction weight, as its cost in wasmi engine is `1`. + let fuel_limit = store + .data_mut() + .ext() + .gas_meter_mut() + .gas_left() + .ref_time() + .checked_div(T::Schedule::get().ref_time_by_fuel()) + .ok_or(Error::::InvalidSchedule)?; + store + .set_fuel(fuel_limit) + .expect("We've set up engine to fuel consuming mode; qed"); + + // Start function should already see the correct refcount in case it will be ever inspected. + if let &ExportedFunction::Constructor = function { + E::increment_refcount(self.code_hash)?; + } + + // Any abort in start function (includes `return` + `terminate`) will make us skip the + // call into the subsequent exported function. This means that calling `return` returns data + // from the whole contract execution. + match instance.start(&mut store) { + Ok(instance) => { + let exported_func = instance + .get_export(&store, function.identifier()) + .and_then(|export| export.into_func()) + .ok_or_else(|| { + log::error!(target: LOG_TARGET, "failed to find entry point"); + Error::::CodeRejected + })?; + + Ok(InstanceOrExecReturn::Instance((exported_func, store))) + }, + Err(err) => Self::process_result(store, Err(err)).map(InstanceOrExecReturn::ExecReturn), + } + } +} + +impl Executable for WasmBlob { + fn from_storage( + code_hash: CodeHash, + gas_meter: &mut GasMeter, + ) -> Result { + let code_info = >::get(code_hash).ok_or(Error::::CodeNotFound)?; + gas_meter.charge(CodeLoadToken(code_info.code_len))?; + let code = >::get(code_hash).ok_or(Error::::CodeNotFound)?; + Ok(Self { code, code_info, code_hash }) + } + + fn execute>( + self, + ext: &mut E, + function: &ExportedFunction, + input_data: Vec, + ) -> ExecResult { + use InstanceOrExecReturn::*; + match Self::prepare_execute( + self, + Runtime::new(ext, input_data), + function, + CompilationMode::Lazy, + )? { + Instance((func, mut store)) => { + let result = func.call(&mut store, &[], &mut []); + Self::process_result(store, result) + }, + ExecReturn(exec_return) => Ok(exec_return), + } + } + + fn code_hash(&self) -> &CodeHash { + &self.code_hash + } + + fn code_info(&self) -> &CodeInfo { + &self.code_info + } + + fn code_len(&self) -> u32 { + self.code.len() as u32 + } + + fn is_deterministic(&self) -> bool { + matches!(self.code_info.determinism, Determinism::Enforced) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + exec::{AccountIdOf, ErrorOrigin, ExecError, Executable, Ext, Key, SeedOf}, + gas::GasMeter, + primitives::ExecReturnValue, + storage::WriteOutcome, + tests::{RuntimeCall, Test, ALICE, BOB}, + transient_storage::TransientStorage, + BalanceOf, CodeHash, Error, Origin, Pallet as Contracts, + }; + use assert_matches::assert_matches; + use frame_support::{ + assert_err, assert_ok, dispatch::DispatchResultWithPostInfo, weights::Weight, + }; + use frame_system::pallet_prelude::BlockNumberFor; + use pallet_contracts_uapi::ReturnFlags; + use pretty_assertions::assert_eq; + use sp_core::H256; + use sp_runtime::DispatchError; + use std::{ + borrow::BorrowMut, + cell::RefCell, + collections::{ + hash_map::{Entry, HashMap}, + HashSet, + }, + }; + + #[derive(Debug, PartialEq, Eq)] + struct InstantiateEntry { + code_hash: H256, + value: u64, + data: Vec, + gas_left: u64, + salt: Vec, + } + + #[derive(Debug, PartialEq, Eq)] + struct TerminationEntry { + beneficiary: AccountIdOf, + } + + #[derive(Debug, PartialEq, Eq)] + struct TransferEntry { + to: AccountIdOf, + value: u64, + } + + #[derive(Debug, PartialEq, Eq)] + struct CallEntry { + to: AccountIdOf, + value: u64, + data: Vec, + allows_reentry: bool, + read_only: bool, + } + + #[derive(Debug, PartialEq, Eq)] + struct CallCodeEntry { + code_hash: H256, + data: Vec, + } + + pub struct MockExt { + storage: HashMap, Vec>, + transient_storage: TransientStorage, + instantiates: Vec, + terminations: Vec, + calls: Vec, + code_calls: Vec, + transfers: Vec, + // (topics, data) + events: Vec<(Vec, Vec)>, + runtime_calls: RefCell>, + schedule: Schedule, + gas_meter: GasMeter, + debug_buffer: Vec, + ecdsa_recover: RefCell>, + sr25519_verify: RefCell, [u8; 32])>>, + code_hashes: Vec>, + caller: Origin, + delegate_dependencies: RefCell>>, + } + + /// The call is mocked and just returns this hardcoded value. + fn call_return_data() -> Vec { + vec![0xDE, 0xAD, 0xBE, 0xEF] + } + + impl Default for MockExt { + fn default() -> Self { + Self { + code_hashes: Default::default(), + storage: Default::default(), + transient_storage: TransientStorage::new(1024 * 1024), + instantiates: Default::default(), + terminations: Default::default(), + calls: Default::default(), + code_calls: Default::default(), + transfers: Default::default(), + events: Default::default(), + runtime_calls: Default::default(), + schedule: Default::default(), + gas_meter: GasMeter::new(Weight::from_parts(10_000_000_000, 10 * 1024 * 1024)), + debug_buffer: Default::default(), + ecdsa_recover: Default::default(), + caller: Default::default(), + sr25519_verify: Default::default(), + delegate_dependencies: Default::default(), + } + } + } + + impl Ext for MockExt { + type T = Test; + + fn call( + &mut self, + _gas_limit: Weight, + _deposit_limit: BalanceOf, + to: AccountIdOf, + value: u64, + data: Vec, + allows_reentry: bool, + read_only: bool, + ) -> Result { + self.calls.push(CallEntry { to, value, data, allows_reentry, read_only }); + Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: call_return_data() }) + } + fn delegate_call( + &mut self, + code_hash: CodeHash, + data: Vec, + ) -> Result { + self.code_calls.push(CallCodeEntry { code_hash, data }); + Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: call_return_data() }) + } + fn instantiate( + &mut self, + gas_limit: Weight, + _deposit_limit: BalanceOf, + code_hash: CodeHash, + value: u64, + data: Vec, + salt: &[u8], + ) -> Result<(AccountIdOf, ExecReturnValue), ExecError> { + self.instantiates.push(InstantiateEntry { + code_hash, + value, + data: data.to_vec(), + gas_left: gas_limit.ref_time(), + salt: salt.to_vec(), + }); + Ok(( + Contracts::::contract_address(&ALICE, &code_hash, &data, salt), + ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() }, + )) + } + fn set_code_hash(&mut self, hash: CodeHash) -> DispatchResult { + self.code_hashes.push(hash); + Ok(()) + } + fn transfer(&mut self, to: &AccountIdOf, value: u64) -> DispatchResult { + self.transfers.push(TransferEntry { to: to.clone(), value }); + Ok(()) + } + fn terminate(&mut self, beneficiary: &AccountIdOf) -> DispatchResult { + self.terminations.push(TerminationEntry { beneficiary: beneficiary.clone() }); + Ok(()) + } + fn get_storage(&mut self, key: &Key) -> Option> { + self.storage.get(&key.to_vec()).cloned() + } + fn get_storage_size(&mut self, key: &Key) -> Option { + self.storage.get(&key.to_vec()).map(|val| val.len() as u32) + } + fn set_storage( + &mut self, + key: &Key, + value: Option>, + take_old: bool, + ) -> Result { + let key = key.to_vec(); + let entry = self.storage.entry(key.clone()); + let result = match (entry, take_old) { + (Entry::Vacant(_), _) => WriteOutcome::New, + (Entry::Occupied(entry), false) => + WriteOutcome::Overwritten(entry.remove().len() as u32), + (Entry::Occupied(entry), true) => WriteOutcome::Taken(entry.remove()), + }; + if let Some(value) = value { + self.storage.insert(key, value); + } + Ok(result) + } + fn get_transient_storage(&self, key: &Key) -> Option> { + self.transient_storage.read(self.address(), key) + } + fn get_transient_storage_size(&self, key: &Key) -> Option { + self.transient_storage.read(self.address(), key).map(|value| value.len() as _) + } + fn set_transient_storage( + &mut self, + key: &Key, + value: Option>, + take_old: bool, + ) -> Result { + let account_id = self.address().clone(); + self.transient_storage.write(&account_id, key, value, take_old) + } + fn caller(&self) -> Origin { + self.caller.clone() + } + fn is_contract(&self, _address: &AccountIdOf) -> bool { + true + } + fn code_hash(&self, _address: &AccountIdOf) -> Option> { + Some(H256::from_slice(&[0x11; 32])) + } + fn own_code_hash(&mut self) -> &CodeHash { + const HASH: H256 = H256::repeat_byte(0x10); + &HASH + } + fn caller_is_origin(&self) -> bool { + false + } + fn caller_is_root(&self) -> bool { + &self.caller == &Origin::Root + } + fn address(&self) -> &AccountIdOf { + &BOB + } + fn balance(&self) -> u64 { + 228 + } + fn value_transferred(&self) -> u64 { + 1337 + } + fn now(&self) -> &u64 { + &1111 + } + fn minimum_balance(&self) -> u64 { + 666 + } + fn random(&self, subject: &[u8]) -> (SeedOf, BlockNumberFor) { + (H256::from_slice(subject), 42) + } + fn deposit_event(&mut self, topics: Vec, data: Vec) { + self.events.push((topics, data)) + } + fn block_number(&self) -> u64 { + 121 + } + fn max_value_size(&self) -> u32 { + 16_384 + } + fn get_weight_price(&self, weight: Weight) -> BalanceOf { + BalanceOf::::from(1312_u32) + .saturating_mul(weight.ref_time().into()) + .saturating_add( + BalanceOf::::from(103_u32).saturating_mul(weight.proof_size()), + ) + } + fn schedule(&self) -> &Schedule { + &self.schedule + } + fn gas_meter(&self) -> &GasMeter { + &self.gas_meter + } + fn gas_meter_mut(&mut self) -> &mut GasMeter { + &mut self.gas_meter + } + fn charge_storage(&mut self, _diff: &crate::storage::meter::Diff) {} + + fn debug_buffer_enabled(&self) -> bool { + true + } + fn append_debug_buffer(&mut self, msg: &str) -> bool { + self.debug_buffer.extend(msg.as_bytes()); + true + } + fn call_runtime( + &self, + call: ::RuntimeCall, + ) -> DispatchResultWithPostInfo { + self.runtime_calls.borrow_mut().push(call); + Ok(Default::default()) + } + fn ecdsa_recover( + &self, + signature: &[u8; 65], + message_hash: &[u8; 32], + ) -> Result<[u8; 33], ()> { + self.ecdsa_recover.borrow_mut().push((*signature, *message_hash)); + Ok([3; 33]) + } + fn sr25519_verify(&self, signature: &[u8; 64], message: &[u8], pub_key: &[u8; 32]) -> bool { + self.sr25519_verify.borrow_mut().push((*signature, message.to_vec(), *pub_key)); + true + } + fn contract_info(&mut self) -> &mut crate::ContractInfo { + unimplemented!() + } + #[cfg(feature = "runtime-benchmarks")] + fn transient_storage(&mut self) -> &mut TransientStorage { + unimplemented!() + } + fn ecdsa_to_eth_address(&self, _pk: &[u8; 33]) -> Result<[u8; 20], ()> { + Ok([2u8; 20]) + } + fn reentrance_count(&self) -> u32 { + 12 + } + fn account_reentrance_count(&self, _account_id: &AccountIdOf) -> u32 { + 12 + } + fn nonce(&mut self) -> u64 { + 995 + } + fn increment_refcount(_code_hash: CodeHash) -> DispatchResult { + Ok(()) + } + fn decrement_refcount(_code_hash: CodeHash) {} + fn lock_delegate_dependency(&mut self, code: CodeHash) -> DispatchResult { + self.delegate_dependencies.borrow_mut().insert(code); + Ok(()) + } + fn unlock_delegate_dependency(&mut self, code: &CodeHash) -> DispatchResult { + self.delegate_dependencies.borrow_mut().remove(code); + Ok(()) + } + + fn locked_delegate_dependencies_count(&mut self) -> usize { + self.delegate_dependencies.borrow().len() + } + + fn is_read_only(&self) -> bool { + false + } + } + + /// Execute the supplied code. + /// + /// Not used directly but through the wrapper functions defined below. + fn execute_internal>( + wat: &str, + input_data: Vec, + mut ext: E, + entry_point: &ExportedFunction, + unstable_interface: bool, + skip_checks: bool, + ) -> ExecResult { + type RuntimeConfig = ::T; + RuntimeConfig::set_unstable_interface(unstable_interface); + let wasm = wat::parse_str(wat).unwrap(); + let executable = if skip_checks { + WasmBlob::::from_code_unchecked( + wasm, + ext.borrow_mut().schedule(), + ALICE, + )? + } else { + WasmBlob::::from_code( + wasm, + ext.borrow_mut().schedule(), + ALICE, + Determinism::Enforced, + ) + .map_err(|err| err.0)? + }; + executable.execute(ext.borrow_mut(), entry_point, input_data) + } + + /// Execute the `call` function within the supplied code. + fn execute>(wat: &str, input_data: Vec, ext: E) -> ExecResult { + execute_internal(wat, input_data, ext, &ExportedFunction::Call, true, false) + } + + /// Execute the `deploy` function within the supplied code. + fn execute_instantiate>( + wat: &str, + input_data: Vec, + ext: E, + ) -> ExecResult { + execute_internal(wat, input_data, ext, &ExportedFunction::Constructor, true, false) + } + + /// Execute the supplied code with disabled unstable functions. + /// + /// In our test config unstable functions are disabled so that we can test them. + /// In order to test that code using them is properly rejected we temporarily disable + /// them when this test is run. + #[cfg(not(feature = "runtime-benchmarks"))] + fn execute_no_unstable>( + wat: &str, + input_data: Vec, + ext: E, + ) -> ExecResult { + execute_internal(wat, input_data, ext, &ExportedFunction::Call, false, false) + } + + /// Execute code without validating it first. + /// + /// This is mainly useful in order to test code which uses deprecated functions. Those + /// would fail when validating the code. + fn execute_unvalidated>( + wat: &str, + input_data: Vec, + ext: E, + ) -> ExecResult { + execute_internal(wat, input_data, ext, &ExportedFunction::Call, false, true) + } + + /// Execute instantiation entry point of code without validating it first. + /// + /// Same as `execute_unvalidated` except that the `deploy` entry point is ran. + #[cfg(not(feature = "runtime-benchmarks"))] + fn execute_instantiate_unvalidated>( + wat: &str, + input_data: Vec, + ext: E, + ) -> ExecResult { + execute_internal(wat, input_data, ext, &ExportedFunction::Constructor, false, true) + } + + const CODE_TRANSFER: &str = r#" +(module + ;; seal_transfer( + ;; account_ptr: u32, + ;; account_len: u32, + ;; value_ptr: u32, + ;; value_len: u32, + ;;) -> u32 + (import "seal0" "seal_transfer" (func $seal_transfer (param i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + (func (export "call") + (drop + (call $seal_transfer + (i32.const 4) ;; Pointer to "account" address. + (i32.const 32) ;; Length of "account" address. + (i32.const 36) ;; Pointer to the buffer with value to transfer + (i32.const 8) ;; Length of the buffer with value to transfer. + ) + ) + ) + (func (export "deploy")) + + ;; Destination AccountId (ALICE) + (data (i32.const 4) + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + ) + + ;; Amount of value to transfer. + ;; Represented by u64 (8 bytes long) in little endian. + (data (i32.const 36) "\99\00\00\00\00\00\00\00") +) +"#; + + #[test] + fn contract_transfer() { + let mut mock_ext = MockExt::default(); + assert_ok!(execute(CODE_TRANSFER, vec![], &mut mock_ext)); + + assert_eq!(&mock_ext.transfers, &[TransferEntry { to: ALICE, value: 153 }]); + } + + const CODE_CALL: &str = r#" +(module + ;; seal_call( + ;; callee_ptr: u32, + ;; callee_len: u32, + ;; gas: u64, + ;; value_ptr: u32, + ;; value_len: u32, + ;; input_data_ptr: u32, + ;; input_data_len: u32, + ;; output_ptr: u32, + ;; output_len_ptr: u32 + ;;) -> u32 + (import "seal0" "seal_call" (func $seal_call (param i32 i32 i64 i32 i32 i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + (func (export "call") + (drop + (call $seal_call + (i32.const 4) ;; Pointer to "callee" address. + (i32.const 32) ;; Length of "callee" address. + (i64.const 0) ;; How much gas to devote for the execution. 0 = all. + (i32.const 36) ;; Pointer to the buffer with value to transfer + (i32.const 8) ;; Length of the buffer with value to transfer. + (i32.const 44) ;; 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 + ) + ) + ) + (func (export "deploy")) + + ;; Destination AccountId (ALICE) + (data (i32.const 4) + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + ) + + ;; Amount of value to transfer. + ;; Represented by u64 (8 bytes long) in little endian. + (data (i32.const 36) "\06\00\00\00\00\00\00\00") + + (data (i32.const 44) "\01\02\03\04") +) +"#; + + #[test] + fn contract_call() { + let mut mock_ext = MockExt::default(); + assert_ok!(execute(CODE_CALL, vec![], &mut mock_ext)); + + assert_eq!( + &mock_ext.calls, + &[CallEntry { + to: ALICE, + value: 6, + data: vec![1, 2, 3, 4], + allows_reentry: true, + read_only: false + }] + ); + } + + #[test] + fn contract_delegate_call() { + const CODE: &str = r#" +(module + ;; seal_delegate_call( + ;; flags: u32, + ;; code_hash_ptr: u32, + ;; input_data_ptr: u32, + ;; input_data_len: u32, + ;; output_ptr: u32, + ;; output_len_ptr: u32 + ;;) -> u32 + (import "seal0" "seal_delegate_call" (func $seal_delegate_call (param i32 i32 i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + (func (export "call") + (drop + (call $seal_delegate_call + (i32.const 0) ;; No flags are set + (i32.const 4) ;; Pointer to "callee" code_hash. + (i32.const 36) ;; 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 + ) + ) + ) + (func (export "deploy")) + + ;; Callee code_hash + (data (i32.const 4) + "\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11" + "\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11" + ) + + (data (i32.const 36) "\01\02\03\04") +) +"#; + let mut mock_ext = MockExt::default(); + assert_ok!(execute(CODE, vec![], &mut mock_ext)); + + assert_eq!( + &mock_ext.code_calls, + &[CallCodeEntry { code_hash: [0x11; 32].into(), data: vec![1, 2, 3, 4] }] + ); + } + + #[test] + fn contract_call_forward_input() { + const CODE: &str = r#" +(module + (import "seal1" "seal_call" (func $seal_call (param i32 i32 i64 i32 i32 i32 i32 i32) (result i32))) + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "env" "memory" (memory 1 1)) + (func (export "call") + (drop + (call $seal_call + (i32.const 1) ;; Set FORWARD_INPUT bit + (i32.const 4) ;; Pointer to "callee" address. + (i64.const 0) ;; How much gas to devote for the execution. 0 = all. + (i32.const 36) ;; Pointer to the buffer with value to transfer + (i32.const 44) ;; 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 + ) + ) + + ;; triggers a trap because we already forwarded the input + (call $seal_input (i32.const 1) (i32.const 44)) + ) + + (func (export "deploy")) + + ;; Destination AccountId (ALICE) + (data (i32.const 4) + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + ) + + ;; Amount of value to transfer. + ;; Represented by u64 (8 bytes long) in little endian. + (data (i32.const 36) "\2A\00\00\00\00\00\00\00") + + ;; The input is ignored because we forward our own input + (data (i32.const 44) "\01\02\03\04") +) +"#; + let mut mock_ext = MockExt::default(); + let input = vec![0xff, 0x2a, 0x99, 0x88]; + assert_err!(execute(CODE, input.clone(), &mut mock_ext), >::InputForwarded,); + + assert_eq!( + &mock_ext.calls, + &[CallEntry { + to: ALICE, + value: 0x2a, + data: input, + allows_reentry: false, + read_only: false + }] + ); + } + + #[test] + fn contract_call_clone_input() { + const CODE: &str = r#" +(module + (import "seal1" "seal_call" (func $seal_call (param i32 i32 i64 i32 i32 i32 i32 i32) (result i32))) + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + (func (export "call") + (drop + (call $seal_call + (i32.const 11) ;; Set FORWARD_INPUT | CLONE_INPUT | ALLOW_REENTRY bits + (i32.const 4) ;; Pointer to "callee" address. + (i64.const 0) ;; How much gas to devote for the execution. 0 = all. + (i32.const 36) ;; Pointer to the buffer with value to transfer + (i32.const 44) ;; 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 + ) + ) + + ;; works because the input was cloned + (call $seal_input (i32.const 0) (i32.const 44)) + + ;; return the input to caller for inspection + (call $seal_return (i32.const 0) (i32.const 0) (i32.load (i32.const 44))) + ) + + (func (export "deploy")) + + ;; Destination AccountId (ALICE) + (data (i32.const 4) + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + ) + + ;; Amount of value to transfer. + ;; Represented by u64 (8 bytes long) in little endian. + (data (i32.const 36) "\2A\00\00\00\00\00\00\00") + + ;; The input is ignored because we forward our own input + (data (i32.const 44) "\01\02\03\04") +) +"#; + let mut mock_ext = MockExt::default(); + let input = vec![0xff, 0x2a, 0x99, 0x88]; + let result = execute(CODE, input.clone(), &mut mock_ext).unwrap(); + assert_eq!(result.data, input); + assert_eq!( + &mock_ext.calls, + &[CallEntry { + to: ALICE, + value: 0x2a, + data: input, + allows_reentry: true, + read_only: false + }] + ); + } + + #[test] + fn contract_call_tail_call() { + const CODE: &str = r#" +(module + (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 (export "call") + (drop + (call $seal_call + (i32.const 5) ;; Set FORWARD_INPUT | TAIL_CALL bit + (i32.const 4) ;; Pointer to "callee" address. + (i64.const 0) ;; How much gas to devote for the execution. 0 = all. + (i32.const 36) ;; Pointer to the buffer with value to transfer + (i32.const 0) ;; Pointer to input data buffer address + (i32.const 0) ;; 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 + ) + ) + + ;; a tail call never returns + (unreachable) + ) + + (func (export "deploy")) + + ;; Destination AccountId (ALICE) + (data (i32.const 4) + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + ) + + ;; Amount of value to transfer. + ;; Represented by u64 (8 bytes long) in little endian. + (data (i32.const 36) "\2A\00\00\00\00\00\00\00") +) +"#; + let mut mock_ext = MockExt::default(); + let input = vec![0xff, 0x2a, 0x99, 0x88]; + let result = execute(CODE, input.clone(), &mut mock_ext).unwrap(); + assert_eq!(result.data, call_return_data()); + assert_eq!( + &mock_ext.calls, + &[CallEntry { + to: ALICE, + value: 0x2a, + data: input, + allows_reentry: false, + read_only: false + }] + ); + } + + #[test] + fn contains_storage_works() { + const CODE: &str = r#" +(module + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal1" "contains_storage" (func $contains_storage (param i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + + ;; size of input buffer + ;; [0, 4) size of input buffer (128+32 = 160 bytes = 0xA0) + (data (i32.const 0) "\A0") + + ;; [4, 164) input buffer + + (func (export "call") + ;; Receive key + (call $seal_input + (i32.const 4) ;; Where we take input and store it + (i32.const 0) ;; Where we take and store the length of the data + ) + ;; Call seal_clear_storage and save what it returns at 0 + (i32.store (i32.const 0) + (call $contains_storage + (i32.const 8) ;; key_ptr + (i32.load (i32.const 4)) ;; key_len + ) + ) + (call $seal_return + (i32.const 0) ;; flags + (i32.const 0) ;; returned value + (i32.const 4) ;; length of returned value + ) + ) + + (func (export "deploy")) +) +"#; + + let mut ext = MockExt::default(); + ext.set_storage( + &Key::::try_from_var([1u8; 64].to_vec()).unwrap(), + Some(vec![42u8]), + false, + ) + .unwrap(); + ext.set_storage( + &Key::::try_from_var([2u8; 19].to_vec()).unwrap(), + Some(vec![]), + false, + ) + .unwrap(); + + //value does not exist (wrong key length) + let input = (63, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + // sentinel returned + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), crate::SENTINEL); + + // value exists + let input = (64, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + // true as u32 returned + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 1); + // getter does not remove the value from storage + assert_eq!(ext.storage.get(&[1u8; 64].to_vec()).unwrap(), &[42u8]); + + // value exists (test for 0 sized) + let input = (19, [2u8; 19]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + // true as u32 returned + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 0); + // getter does not remove the value from storage + assert_eq!(ext.storage.get(&[2u8; 19].to_vec()).unwrap(), &([] as [u8; 0])); + } + + const CODE_INSTANTIATE: &str = r#" +(module + ;; seal_instantiate( + ;; code_ptr: u32, + ;; code_len: u32, + ;; gas: u64, + ;; value_ptr: u32, + ;; value_len: u32, + ;; input_data_ptr: u32, + ;; input_data_len: u32, + ;; input_data_len: u32, + ;; address_ptr: u32, + ;; address_len_ptr: u32, + ;; output_ptr: u32, + ;; output_len_ptr: u32 + ;; ) -> u32 + (import "seal0" "seal_instantiate" (func $seal_instantiate + (param i32 i32 i64 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32) (result i32) + )) + (import "env" "memory" (memory 1 1)) + (func (export "call") + (drop + (call $seal_instantiate + (i32.const 16) ;; Pointer to `code_hash` + (i32.const 32) ;; Length of `code_hash` + (i64.const 0) ;; How much gas to devote for the execution. 0 = all. + (i32.const 4) ;; Pointer to the buffer with value to transfer + (i32.const 8) ;; Length of the buffer with value to transfer + (i32.const 12) ;; 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 address + (i32.const 0) ;; Length is ignored in this case + (i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output + (i32.const 0) ;; Length is ignored in this case + (i32.const 0) ;; salt_ptr + (i32.const 4) ;; salt_len + ) + ) + ) + (func (export "deploy")) + + ;; Salt + (data (i32.const 0) "\42\43\44\45") + ;; Amount of value to transfer. + ;; Represented by u64 (8 bytes long) in little endian. + (data (i32.const 4) "\03\00\00\00\00\00\00\00") + ;; Input data to pass to the contract being instantiated. + (data (i32.const 12) "\01\02\03\04") + ;; Hash of code. + (data (i32.const 16) + "\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11" + "\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11" + ) +) +"#; + + #[test] + fn contract_instantiate() { + let mut mock_ext = MockExt::default(); + assert_ok!(execute(CODE_INSTANTIATE, vec![], &mut mock_ext)); + + assert_matches!( + &mock_ext.instantiates[..], + [InstantiateEntry { + code_hash, + value: 3, + data, + gas_left: _, + salt, + }] if + code_hash == &[0x11; 32].into() && + data == &vec![1, 2, 3, 4] && + salt == &vec![0x42, 0x43, 0x44, 0x45] + ); + } + + const CODE_TERMINATE: &str = r#" +(module + ;; seal_terminate( + ;; beneficiary_ptr: u32, + ;; beneficiary_len: u32, + ;; ) + (import "seal0" "seal_terminate" (func $seal_terminate (param i32 i32))) + (import "env" "memory" (memory 1 1)) + (func (export "call") + (call $seal_terminate + (i32.const 4) ;; Pointer to "beneficiary" address. + (i32.const 32) ;; Length of "beneficiary" address. + ) + ) + (func (export "deploy")) + + ;; Beneficiary AccountId to transfer the funds. + (data (i32.const 4) + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + ) +) +"#; + + #[test] + fn contract_terminate() { + let mut mock_ext = MockExt::default(); + execute(CODE_TERMINATE, vec![], &mut mock_ext).unwrap(); + + assert_eq!(&mock_ext.terminations, &[TerminationEntry { beneficiary: ALICE }]); + } + + const CODE_TRANSFER_LIMITED_GAS: &str = r#" +(module + ;; seal_call( + ;; callee_ptr: u32, + ;; callee_len: u32, + ;; gas: u64, + ;; value_ptr: u32, + ;; value_len: u32, + ;; input_data_ptr: u32, + ;; input_data_len: u32, + ;; output_ptr: u32, + ;; output_len_ptr: u32 + ;;) -> u32 + (import "seal0" "seal_call" (func $seal_call (param i32 i32 i64 i32 i32 i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + (func (export "call") + (drop + (call $seal_call + (i32.const 4) ;; Pointer to "callee" address. + (i32.const 32) ;; Length of "callee" address. + (i64.const 228) ;; How much gas to devote for the execution. + (i32.const 36) ;; Pointer to the buffer with value to transfer + (i32.const 8) ;; Length of the buffer with value to transfer. + (i32.const 44) ;; 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 cas + ) + ) + ) + (func (export "deploy")) + + ;; Destination AccountId to transfer the funds. + (data (i32.const 4) + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + ) + ;; Amount of value to transfer. + ;; Represented by u64 (8 bytes long) in little endian. + (data (i32.const 36) "\06\00\00\00\00\00\00\00") + + (data (i32.const 44) "\01\02\03\04") +) +"#; + + #[test] + fn contract_call_limited_gas() { + let mut mock_ext = MockExt::default(); + assert_ok!(execute(&CODE_TRANSFER_LIMITED_GAS, vec![], &mut mock_ext)); + + assert_eq!( + &mock_ext.calls, + &[CallEntry { + to: ALICE, + value: 6, + data: vec![1, 2, 3, 4], + allows_reentry: true, + read_only: false + }] + ); + } + + const CODE_ECDSA_RECOVER: &str = r#" +(module + ;; seal_ecdsa_recover( + ;; signature_ptr: u32, + ;; message_hash_ptr: u32, + ;; output_ptr: u32 + ;; ) -> u32 + (import "seal0" "seal_ecdsa_recover" (func $seal_ecdsa_recover (param i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + (func (export "call") + (drop + (call $seal_ecdsa_recover + (i32.const 36) ;; Pointer to signature. + (i32.const 4) ;; Pointer to message hash. + (i32.const 36) ;; Pointer for output - public key. + ) + ) + ) + (func (export "deploy")) + + ;; Hash of message. + (data (i32.const 4) + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + ) + ;; Signature + (data (i32.const 36) + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01" + ) +) +"#; + + #[test] + fn contract_ecdsa_recover() { + let mut mock_ext = MockExt::default(); + assert_ok!(execute(&CODE_ECDSA_RECOVER, vec![], &mut mock_ext)); + assert_eq!(mock_ext.ecdsa_recover.into_inner(), [([1; 65], [1; 32])]); + } + + #[test] + fn contract_ecdsa_to_eth_address() { + /// calls `seal_ecdsa_to_eth_address` for the constant and ensures the result equals the + /// expected one. + const CODE_ECDSA_TO_ETH_ADDRESS: &str = r#" +(module + (import "seal0" "seal_ecdsa_to_eth_address" (func $seal_ecdsa_to_eth_address (param i32 i32) (result i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + (func (export "call") + ;; fill the buffer with the eth address. + (call $seal_ecdsa_to_eth_address (i32.const 0) (i32.const 0)) + + ;; Return the contents of the buffer + (call $seal_return + (i32.const 0) + (i32.const 0) + (i32.const 20) + ) + + ;; seal_return doesn't return, so this is effectively unreachable. + (unreachable) + ) + (func (export "deploy")) +) +"#; + + let output = execute(CODE_ECDSA_TO_ETH_ADDRESS, vec![], MockExt::default()).unwrap(); + assert_eq!( + output, + ExecReturnValue { flags: ReturnFlags::empty(), data: [0x02; 20].to_vec() } + ); + } + + #[test] + fn contract_sr25519() { + const CODE_SR25519: &str = r#" +(module + (import "seal0" "sr25519_verify" (func $sr25519_verify (param i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + (func (export "call") + (drop + (call $sr25519_verify + (i32.const 0) ;; Pointer to signature. + (i32.const 64) ;; Pointer to public key. + (i32.const 16) ;; message length. + (i32.const 96) ;; Pointer to message. + ) + ) + ) + (func (export "deploy")) + + ;; Signature (64 bytes) + (data (i32.const 0) + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + ) + + ;; public key (32 bytes) + (data (i32.const 64) + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + ) + + ;; message. (16 bytes) + (data (i32.const 96) + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + ) +) +"#; + let mut mock_ext = MockExt::default(); + assert_ok!(execute(&CODE_SR25519, vec![], &mut mock_ext)); + assert_eq!(mock_ext.sr25519_verify.into_inner(), [([1; 64], [1; 16].to_vec(), [1; 32])]); + } + + const CODE_GET_STORAGE: &str = r#" +(module + (import "seal0" "seal_get_storage" (func $seal_get_storage (param i32 i32 i32) (result i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0, 32) key for get storage + (data (i32.const 0) + "\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11" + "\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11" + ) + + ;; [32, 36) buffer size = 4k in little endian + (data (i32.const 32) "\00\10") + + ;; [36; inf) buffer where the result is copied + + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + + (func (export "call") + (local $buf_size i32) + + ;; Load a storage value into contract memory. + (call $assert + (i32.eq + (call $seal_get_storage + (i32.const 0) ;; The pointer to the storage key to fetch + (i32.const 36) ;; Pointer to the output buffer + (i32.const 32) ;; Pointer to the size of the buffer + ) + + ;; Return value 0 means that the value is found and there were + ;; no errors. + (i32.const 0) + ) + ) + + ;; Find out the size of the buffer + (local.set $buf_size + (i32.load (i32.const 32)) + ) + + ;; Return the contents of the buffer + (call $seal_return + (i32.const 0) + (i32.const 36) + (local.get $buf_size) + ) + + ;; env:seal_return doesn't return, so this is effectively unreachable. + (unreachable) + ) + + (func (export "deploy")) +) +"#; + + #[test] + fn get_storage_puts_data_into_buf() { + let mut mock_ext = MockExt::default(); + mock_ext.storage.insert([0x11; 32].to_vec(), [0x22; 32].to_vec()); + + let output = execute(CODE_GET_STORAGE, vec![], mock_ext).unwrap(); + + assert_eq!( + output, + ExecReturnValue { flags: ReturnFlags::empty(), data: [0x22; 32].to_vec() } + ); + } + + /// calls `seal_caller` and compares the result with the constant (ALICE's address part). + const CODE_CALLER: &str = r#" +(module + (import "seal0" "seal_caller" (func $seal_caller (param i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; size of our buffer is 32 bytes + (data (i32.const 32) "\20") + + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + + (func (export "call") + ;; fill the buffer with the caller. + (call $seal_caller (i32.const 0) (i32.const 32)) + + ;; assert len == 32 + (call $assert + (i32.eq + (i32.load (i32.const 32)) + (i32.const 32) + ) + ) + + ;; assert that the first 8 bytes are the beginning of "ALICE" + (call $assert + (i64.eq + (i64.load (i32.const 0)) + (i64.const 0x0101010101010101) + ) + ) + ) + + (func (export "deploy")) +) +"#; + + #[test] + fn caller() { + assert_ok!(execute(CODE_CALLER, vec![], MockExt::default())); + } + + #[test] + fn caller_traps_when_no_account_id() { + let mut ext = MockExt::default(); + ext.caller = Origin::Root; + assert_eq!( + execute(CODE_CALLER, vec![], ext), + Err(ExecError { error: DispatchError::RootNotAllowed, origin: ErrorOrigin::Caller }) + ); + } + + /// calls `seal_address` and compares the result with the constant (BOB's address part). + const CODE_ADDRESS: &str = r#" +(module + (import "seal0" "seal_address" (func $seal_address (param i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; size of our buffer is 32 bytes + (data (i32.const 32) "\20") + + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + + (func (export "call") + ;; fill the buffer with the self address. + (call $seal_address (i32.const 0) (i32.const 32)) + + ;; assert size == 32 + (call $assert + (i32.eq + (i32.load (i32.const 32)) + (i32.const 32) + ) + ) + + ;; assert that the first 8 bytes are the beginning of "BOB" + (call $assert + (i64.eq + (i64.load (i32.const 0)) + (i64.const 0x0202020202020202) + ) + ) + ) + + (func (export "deploy")) +) +"#; + + #[test] + fn address() { + assert_ok!(execute(CODE_ADDRESS, vec![], MockExt::default())); + } + + const CODE_BALANCE: &str = r#" +(module + (import "seal0" "seal_balance" (func $seal_balance (param i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; size of our buffer is 32 bytes + (data (i32.const 32) "\20") + + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + + (func (export "call") + ;; This stores the balance in the buffer + (call $seal_balance (i32.const 0) (i32.const 32)) + + ;; assert len == 8 + (call $assert + (i32.eq + (i32.load (i32.const 32)) + (i32.const 8) + ) + ) + + ;; assert that contents of the buffer is equal to the i64 value of 228. + (call $assert + (i64.eq + (i64.load (i32.const 0)) + (i64.const 228) + ) + ) + ) + (func (export "deploy")) +) +"#; + + #[test] + fn balance() { + assert_ok!(execute(CODE_BALANCE, vec![], MockExt::default())); + } + + const CODE_GAS_PRICE: &str = r#" +(module + (import "seal1" "weight_to_fee" (func $seal_weight_to_fee (param i64 i64 i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; size of our buffer is 32 bytes + (data (i32.const 32) "\20") + + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + + (func (export "call") + ;; This stores the gas price in the buffer + (call $seal_weight_to_fee (i64.const 2) (i64.const 1) (i32.const 0) (i32.const 32)) + + ;; assert len == 8 + (call $assert + (i32.eq + (i32.load (i32.const 32)) + (i32.const 8) + ) + ) + + ;; assert that contents of the buffer is equal to the i64 value of 2 * 1312 + 103 = 2727. + (call $assert + (i64.eq + (i64.load (i32.const 0)) + (i64.const 2727) + ) + ) + ) + (func (export "deploy")) +) +"#; + + #[test] + fn gas_price() { + assert_ok!(execute(CODE_GAS_PRICE, vec![], MockExt::default())); + } + + const CODE_GAS_LEFT: &str = r#" +(module + (import "seal1" "gas_left" (func $seal_gas_left (param i32 i32))) + (import "seal0" "clear_storage" (func $clear_storage (param i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; Make output buffer size 20 bytes + (data (i32.const 20) "\14") + + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + + (func (export "call") + ;; Burn some PoV, clear_storage consumes some PoV as in order to clear the storage we need to we need to read its size first. + (call $clear_storage (i32.const 0)) + + ;; This stores the weight left to the buffer + (call $seal_gas_left (i32.const 0) (i32.const 20)) + + ;; Assert len <= 16 (max encoded Weight len) + (call $assert + (i32.le_u + (i32.load (i32.const 20)) + (i32.const 16) + ) + ) + + ;; Burn some PoV, clear_storage consumes some PoV as in order to clear the storage we need to we need to read its size first. + (call $clear_storage (i32.const 0)) + + ;; Return weight left and its encoded value len + (call $seal_return (i32.const 0) (i32.const 0) (i32.load (i32.const 20))) + + (unreachable) + ) + (func (export "deploy")) +) +"#; + + #[test] + fn gas_left() { + let mut ext = MockExt::default(); + let gas_limit = ext.gas_meter.gas_left(); + + let output = execute(CODE_GAS_LEFT, vec![], &mut ext).unwrap(); + + let weight_left = Weight::decode(&mut &*output.data).unwrap(); + let actual_left = ext.gas_meter.gas_left(); + + assert!(weight_left.all_lt(gas_limit), "gas_left must be less than initial"); + assert!(weight_left.all_gt(actual_left), "gas_left must be greater than final"); + } + + const CODE_VALUE_TRANSFERRED: &str = r#" +(module + (import "seal0" "seal_value_transferred" (func $seal_value_transferred (param i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; size of our buffer is 32 bytes + (data (i32.const 32) "\20") + + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + + (func (export "call") + ;; This stores the value transferred in the buffer + (call $seal_value_transferred (i32.const 0) (i32.const 32)) + + ;; assert len == 8 + (call $assert + (i32.eq + (i32.load (i32.const 32)) + (i32.const 8) + ) + ) + + ;; assert that contents of the buffer is equal to the i64 value of 1337. + (call $assert + (i64.eq + (i64.load (i32.const 0)) + (i64.const 1337) + ) + ) + ) + (func (export "deploy")) +) +"#; + + #[test] + fn value_transferred() { + assert_ok!(execute(CODE_VALUE_TRANSFERRED, vec![], MockExt::default())); + } + + const START_FN_DOES_RUN: &str = r#" +(module + (import "seal0" "seal_deposit_event" (func $seal_deposit_event (param i32 i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + (start $start) + (func $start + (call $seal_deposit_event + (i32.const 0) ;; Pointer to the start of topics buffer + (i32.const 0) ;; The length of the topics buffer. + (i32.const 0) ;; Pointer to the start of the data buffer + (i32.const 13) ;; Length of the buffer + ) + ) + + (func (export "call")) + + (func (export "deploy")) + + (data (i32.const 0) "\00\01\2A\00\00\00\00\00\00\00\E5\14\00") +) +"#; + + #[test] + fn start_fn_does_run_on_call() { + let mut ext = MockExt::default(); + execute(START_FN_DOES_RUN, vec![], &mut ext).unwrap(); + assert_eq!( + ext.events[0].1, + [0x00_u8, 0x01, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, 0x14, 0x00] + ); + } + + #[test] + fn start_fn_does_run_on_deploy() { + let mut ext = MockExt::default(); + execute_instantiate(START_FN_DOES_RUN, vec![], &mut ext).unwrap(); + assert_eq!( + ext.events[0].1, + [0x00_u8, 0x01, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, 0x14, 0x00] + ); + } + + const CODE_TIMESTAMP_NOW: &str = r#" +(module + (import "seal0" "seal_now" (func $seal_now (param i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; size of our buffer is 32 bytes + (data (i32.const 32) "\20") + + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + + (func (export "call") + ;; This stores the block timestamp in the buffer + (call $seal_now (i32.const 0) (i32.const 32)) + + ;; assert len == 8 + (call $assert + (i32.eq + (i32.load (i32.const 32)) + (i32.const 8) + ) + ) + + ;; assert that contents of the buffer is equal to the i64 value of 1111. + (call $assert + (i64.eq + (i64.load (i32.const 0)) + (i64.const 1111) + ) + ) + ) + (func (export "deploy")) +) +"#; + + const CODE_TIMESTAMP_NOW_UNPREFIXED: &str = r#" +(module + (import "seal0" "now" (func $now (param i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; size of our buffer is 32 bytes + (data (i32.const 32) "\20") + + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + + (func (export "call") + ;; This stores the block timestamp in the buffer + (call $now (i32.const 0) (i32.const 32)) + + ;; assert len == 8 + (call $assert + (i32.eq + (i32.load (i32.const 32)) + (i32.const 8) + ) + ) + + ;; assert that contents of the buffer is equal to the i64 value of 1111. + (call $assert + (i64.eq + (i64.load (i32.const 0)) + (i64.const 1111) + ) + ) + ) + (func (export "deploy")) +) +"#; + + #[test] + fn now() { + assert_ok!(execute(CODE_TIMESTAMP_NOW, vec![], MockExt::default())); + assert_ok!(execute(CODE_TIMESTAMP_NOW_UNPREFIXED, vec![], MockExt::default())); + } + + const CODE_MINIMUM_BALANCE: &str = r#" +(module + (import "seal0" "seal_minimum_balance" (func $seal_minimum_balance (param i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; size of our buffer is 32 bytes + (data (i32.const 32) "\20") + + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + + (func (export "call") + (call $seal_minimum_balance (i32.const 0) (i32.const 32)) + + ;; assert len == 8 + (call $assert + (i32.eq + (i32.load (i32.const 32)) + (i32.const 8) + ) + ) + + ;; assert that contents of the buffer is equal to the i64 value of 666. + (call $assert + (i64.eq + (i64.load (i32.const 0)) + (i64.const 666) + ) + ) + ) + (func (export "deploy")) +) +"#; + + #[test] + fn minimum_balance() { + assert_ok!(execute(CODE_MINIMUM_BALANCE, vec![], MockExt::default())); + } + + const CODE_RANDOM: &str = r#" +(module + (import "seal0" "seal_random" (func $seal_random (param i32 i32 i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0,128) is reserved for the result of PRNG. + + ;; the subject used for the PRNG. [128,160) + (data (i32.const 128) + "\00\01\02\03\04\05\06\07\08\09\0A\0B\0C\0D\0E\0F" + "\00\01\02\03\04\05\06\07\08\09\0A\0B\0C\0D\0E\0F" + ) + + ;; size of our buffer is 128 bytes + (data (i32.const 160) "\80") + + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + + (func (export "call") + ;; This stores the block random seed in the buffer + (call $seal_random + (i32.const 128) ;; Pointer in memory to the start of the subject buffer + (i32.const 32) ;; The subject buffer's length + (i32.const 0) ;; Pointer to the output buffer + (i32.const 160) ;; Pointer to the output buffer length + ) + + ;; assert len == 32 + (call $assert + (i32.eq + (i32.load (i32.const 160)) + (i32.const 32) + ) + ) + + ;; return the random data + (call $seal_return + (i32.const 0) + (i32.const 0) + (i32.const 32) + ) + ) + (func (export "deploy")) +) +"#; + + #[test] + fn random() { + let output = execute_unvalidated(CODE_RANDOM, vec![], MockExt::default()).unwrap(); + + // The mock ext just returns the same data that was passed as the subject. + assert_eq!( + output, + ExecReturnValue { + flags: ReturnFlags::empty(), + data: array_bytes::hex_into_unchecked( + "000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F" + ) + }, + ); + } + + const CODE_RANDOM_V1: &str = r#" +(module + (import "seal1" "seal_random" (func $seal_random (param i32 i32 i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0,128) is reserved for the result of PRNG. + + ;; the subject used for the PRNG. [128,160) + (data (i32.const 128) + "\00\01\02\03\04\05\06\07\08\09\0A\0B\0C\0D\0E\0F" + "\00\01\02\03\04\05\06\07\08\09\0A\0B\0C\0D\0E\0F" + ) + + ;; size of our buffer is 128 bytes + (data (i32.const 160) "\80") + + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + + (func (export "call") + ;; This stores the block random seed in the buffer + (call $seal_random + (i32.const 128) ;; Pointer in memory to the start of the subject buffer + (i32.const 32) ;; The subject buffer's length + (i32.const 0) ;; Pointer to the output buffer + (i32.const 160) ;; Pointer to the output buffer length + ) + + ;; assert len == 32 + (call $assert + (i32.eq + (i32.load (i32.const 160)) + (i32.const 40) + ) + ) + + ;; return the random data + (call $seal_return + (i32.const 0) + (i32.const 0) + (i32.const 40) + ) + ) + (func (export "deploy")) +) +"#; + + #[test] + fn random_v1() { + let output = execute_unvalidated(CODE_RANDOM_V1, vec![], MockExt::default()).unwrap(); + + // The mock ext just returns the same data that was passed as the subject. + assert_eq!( + output, + ExecReturnValue { + flags: ReturnFlags::empty(), + data: ( + array_bytes::hex2array_unchecked::<_, 32>( + "000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F" + ), + 42u64, + ) + .encode() + }, + ); + } + + const CODE_DEPOSIT_EVENT: &str = r#" +(module + (import "seal0" "seal_deposit_event" (func $seal_deposit_event (param i32 i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + (func (export "call") + (call $seal_deposit_event + (i32.const 32) ;; Pointer to the start of topics buffer + (i32.const 33) ;; The length of the topics buffer. + (i32.const 8) ;; Pointer to the start of the data buffer + (i32.const 13) ;; Length of the buffer + ) + ) + (func (export "deploy")) + + (data (i32.const 8) "\00\01\2A\00\00\00\00\00\00\00\E5\14\00") + + ;; Encoded Vec>, the buffer has length of 33 bytes. + (data (i32.const 32) "\04\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33" + "\33\33\33\33\33\33\33\33\33") +) +"#; + + #[test] + fn deposit_event() { + let mut mock_ext = MockExt::default(); + assert_ok!(execute(CODE_DEPOSIT_EVENT, vec![], &mut mock_ext)); + + assert_eq!( + mock_ext.events, + vec![( + vec![H256::repeat_byte(0x33)], + vec![0x00, 0x01, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, 0x14, 0x00] + )] + ); + + assert!(mock_ext.gas_meter.gas_left().ref_time() > 0); + } + + const CODE_DEPOSIT_EVENT_DUPLICATES: &str = r#" +(module + (import "seal0" "seal_deposit_event" (func $seal_deposit_event (param i32 i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + (func (export "call") + (call $seal_deposit_event + (i32.const 32) ;; Pointer to the start of topics buffer + (i32.const 129) ;; The length of the topics buffer. + (i32.const 8) ;; Pointer to the start of the data buffer + (i32.const 13) ;; Length of the buffer + ) + ) + (func (export "deploy")) + + (data (i32.const 8) "\00\01\2A\00\00\00\00\00\00\00\E5\14\00") + + ;; Encoded Vec>, the buffer has length of 129 bytes. + (data (i32.const 32) "\10" +"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" +"\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02" +"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" +"\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04") +) +"#; + + /// Checks that the runtime allows duplicate topics. + #[test] + fn deposit_event_duplicates_allowed() { + let mut mock_ext = MockExt::default(); + assert_ok!(execute(CODE_DEPOSIT_EVENT_DUPLICATES, vec![], &mut mock_ext,)); + + assert_eq!( + mock_ext.events, + vec![( + vec![ + H256::repeat_byte(0x01), + H256::repeat_byte(0x02), + H256::repeat_byte(0x01), + H256::repeat_byte(0x04) + ], + vec![0x00, 0x01, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, 0x14, 0x00] + )] + ); + } + + const CODE_DEPOSIT_EVENT_MAX_TOPICS: &str = r#" +(module + (import "seal0" "seal_deposit_event" (func $seal_deposit_event (param i32 i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + (func (export "call") + (call $seal_deposit_event + (i32.const 32) ;; Pointer to the start of topics buffer + (i32.const 161) ;; The length of the topics buffer. + (i32.const 8) ;; Pointer to the start of the data buffer + (i32.const 13) ;; Length of the buffer + ) + ) + (func (export "deploy")) + + (data (i32.const 8) "\00\01\2A\00\00\00\00\00\00\00\E5\14\00") + + ;; Encoded Vec>, the buffer has length of 161 bytes. + (data (i32.const 32) "\14" +"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" +"\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02" +"\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03" +"\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04" +"\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05") +) +"#; + + /// Checks that the runtime traps if there are more than `max_topic_events` topics. + #[test] + fn deposit_event_max_topics() { + assert_eq!( + execute(CODE_DEPOSIT_EVENT_MAX_TOPICS, vec![], MockExt::default(),), + Err(ExecError { + error: Error::::TooManyTopics.into(), + origin: ErrorOrigin::Caller, + }) + ); + } + + /// calls `seal_block_number` compares the result with the constant 121. + const CODE_BLOCK_NUMBER: &str = r#" +(module + (import "seal0" "seal_block_number" (func $seal_block_number (param i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; size of our buffer is 32 bytes + (data (i32.const 32) "\20") + + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + + (func (export "call") + ;; This stores the block height in the buffer + (call $seal_block_number (i32.const 0) (i32.const 32)) + + ;; assert len == 8 + (call $assert + (i32.eq + (i32.load (i32.const 32)) + (i32.const 8) + ) + ) + + ;; assert that contents of the buffer is equal to the i64 value of 121. + (call $assert + (i64.eq + (i64.load (i32.const 0)) + (i64.const 121) + ) + ) + ) + + (func (export "deploy")) +) +"#; + + #[test] + fn block_number() { + let _ = execute(CODE_BLOCK_NUMBER, vec![], MockExt::default()).unwrap(); + } + + const CODE_RETURN_WITH_DATA: &str = r#" +(module + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + (data (i32.const 32) "\20") + + ;; Deploy routine is the same as call. + (func (export "deploy") + (call $call) + ) + + ;; Call reads the first 4 bytes (LE) as the exit status and returns the rest as output data. + (func $call (export "call") + ;; Copy input data this contract memory. + (call $seal_input + (i32.const 0) ;; Pointer where to store input + (i32.const 32) ;; Pointer to the length of the buffer + ) + + ;; Copy all but the first 4 bytes of the input data as the output data. + (call $seal_return + (i32.load (i32.const 0)) + (i32.const 4) + (i32.sub (i32.load (i32.const 32)) (i32.const 4)) + ) + (unreachable) + ) +) +"#; + + #[test] + fn seal_return_with_success_status() { + let output = execute( + CODE_RETURN_WITH_DATA, + array_bytes::hex2bytes_unchecked("00000000445566778899"), + MockExt::default(), + ) + .unwrap(); + + assert_eq!( + output, + ExecReturnValue { + flags: ReturnFlags::empty(), + data: array_bytes::hex2bytes_unchecked("445566778899"), + } + ); + assert!(!output.did_revert()); + } + + #[test] + fn return_with_revert_status() { + let output = execute( + CODE_RETURN_WITH_DATA, + array_bytes::hex2bytes_unchecked("010000005566778899"), + MockExt::default(), + ) + .unwrap(); + + assert_eq!( + output, + ExecReturnValue { + flags: ReturnFlags::REVERT, + data: array_bytes::hex2bytes_unchecked("5566778899"), + } + ); + assert!(output.did_revert()); + } + + const CODE_OUT_OF_BOUNDS_ACCESS: &str = r#" +(module + (import "seal0" "seal_terminate" (func $seal_terminate (param i32 i32))) + (import "env" "memory" (memory 1 1)) + + (func (export "deploy")) + + (func (export "call") + (call $seal_terminate + (i32.const 65536) ;; Pointer to "account" address (out of bound). + (i32.const 8) ;; Length of "account" address. + ) + ) +) +"#; + + #[test] + fn contract_out_of_bounds_access() { + let mut mock_ext = MockExt::default(); + let result = execute(CODE_OUT_OF_BOUNDS_ACCESS, vec![], &mut mock_ext); + + assert_eq!( + result, + Err(ExecError { + error: Error::::DecodingFailed.into(), + origin: ErrorOrigin::Caller, + }) + ); + } + + const CODE_DECODE_FAILURE: &str = r#" +(module + (import "seal0" "seal_terminate" (func $seal_terminate (param i32 i32))) + (import "env" "memory" (memory 1 1)) + + (func (export "deploy")) + + (func (export "call") + (call $seal_terminate + (i32.const 0) ;; Pointer to "account" address. + (i32.const 4) ;; Length of "account" address (too small -> decode fail). + ) + ) +) +"#; + + #[test] + fn contract_decode_length_ignored() { + let mut mock_ext = MockExt::default(); + let result = execute(CODE_DECODE_FAILURE, vec![], &mut mock_ext); + // AccountID implements `MaxEncodeLen` and therefore the supplied length is + // no longer needed nor used to determine how much is read from contract memory. + assert_ok!(result); + } + + #[test] + fn debug_message_works() { + const CODE_DEBUG_MESSAGE: &str = r#" +(module + (import "seal0" "seal_debug_message" (func $seal_debug_message (param i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + (data (i32.const 0) "Hello World!") + + (func (export "call") + (call $seal_debug_message + (i32.const 0) ;; Pointer to the text buffer + (i32.const 12) ;; The size of the buffer + ) + drop + ) + + (func (export "deploy")) +) +"#; + let mut ext = MockExt::default(); + execute(CODE_DEBUG_MESSAGE, vec![], &mut ext).unwrap(); + + assert_eq!(std::str::from_utf8(&ext.debug_buffer).unwrap(), "Hello World!"); + } + + #[test] + fn debug_message_invalid_utf8_fails() { + const CODE_DEBUG_MESSAGE_FAIL: &str = r#" +(module + (import "seal0" "seal_debug_message" (func $seal_debug_message (param i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + (data (i32.const 0) "\fc") + + (func (export "call") + (call $seal_debug_message + (i32.const 0) ;; Pointer to the text buffer + (i32.const 1) ;; The size of the buffer + ) + drop + ) + + (func (export "deploy")) +) +"#; + let mut ext = MockExt::default(); + let result = execute(CODE_DEBUG_MESSAGE_FAIL, vec![], &mut ext); + assert_ok!(result); + assert!(ext.debug_buffer.is_empty()); + } + + const CODE_CALL_RUNTIME: &str = r#" +(module + (import "seal0" "call_runtime" (func $call_runtime (param i32 i32) (result i32))) + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; 0x1000 = 4k in little endian + ;; size of input buffer + (data (i32.const 0) "\00\10") + + (func (export "call") + ;; Receive the encoded call + (call $seal_input + (i32.const 4) ;; Pointer to the input buffer + (i32.const 0) ;; Size of the length buffer + ) + ;; Just use the call passed as input and store result to memory + (i32.store (i32.const 0) + (call $call_runtime + (i32.const 4) ;; Pointer where the call is stored + (i32.load (i32.const 0)) ;; Size of the call + ) + ) + (call $seal_return + (i32.const 0) ;; flags + (i32.const 0) ;; returned value + (i32.const 4) ;; length of returned value + ) + ) + + (func (export "deploy")) +) +"#; + + #[test] + fn call_runtime_works() { + let call = + RuntimeCall::System(frame_system::Call::remark { remark: b"Hello World".to_vec() }); + let mut ext = MockExt::default(); + let result = execute(CODE_CALL_RUNTIME, call.encode(), &mut ext).unwrap(); + assert_eq!(*ext.runtime_calls.borrow(), vec![call]); + // 0 = ReturnCode::Success + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 0); + } + + #[test] + fn call_runtime_panics_on_invalid_call() { + let mut ext = MockExt::default(); + let result = execute(CODE_CALL_RUNTIME, vec![0x42], &mut ext); + assert_eq!( + result, + Err(ExecError { + error: Error::::DecodingFailed.into(), + origin: ErrorOrigin::Caller, + }) + ); + assert_eq!(*ext.runtime_calls.borrow(), vec![]); + } + + #[test] + fn set_storage_works() { + const CODE: &str = r#" +(module + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "seal2" "set_storage" (func $set_storage (param i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0, 4) size of input buffer + ;; 4k in little endian + (data (i32.const 0) "\00\10") + + ;; [4, 4100) input buffer + + (func (export "call") + ;; Receive (key ++ value_to_write) + (call $seal_input + (i32.const 4) ;; Pointer to the input buffer + (i32.const 0) ;; Size of the input buffer + ) + ;; Store the passed value to the passed key and store result to memory + (i32.store (i32.const 168) + (call $set_storage + (i32.const 8) ;; key_ptr + (i32.load (i32.const 4)) ;; key_len + (i32.add ;; value_ptr = 8 + key_len + (i32.const 8) + (i32.load (i32.const 4))) + (i32.sub ;; value_len (input_size - (key_len + key_len_len)) + (i32.load (i32.const 0)) + (i32.add + (i32.load (i32.const 4)) + (i32.const 4) + ) + ) + ) + ) + (call $seal_return + (i32.const 0) ;; flags + (i32.const 168) ;; ptr to returned value + (i32.const 4) ;; length of returned value + ) + ) + + (func (export "deploy")) +) +"#; + + let mut ext = MockExt::default(); + + // value did not exist before -> sentinel returned + let input = (32, [1u8; 32], [42u8, 48]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), crate::SENTINEL); + assert_eq!(ext.storage.get(&[1u8; 32].to_vec()).unwrap(), &[42u8, 48]); + + // value do exist -> length of old value returned + let input = (32, [1u8; 32], [0u8; 0]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 2); + assert_eq!(ext.storage.get(&[1u8; 32].to_vec()).unwrap(), &[0u8; 0]); + + // value do exist -> length of old value returned (test for zero sized val) + let input = (32, [1u8; 32], [99u8]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 0); + assert_eq!(ext.storage.get(&[1u8; 32].to_vec()).unwrap(), &[99u8]); + } + + #[test] + fn get_storage_works() { + const CODE: &str = r#" +(module + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "seal1" "get_storage" (func $get_storage (param i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0, 4) size of input buffer (160 bytes as we copy the key+len here) + (data (i32.const 0) "\A0") + + ;; [4, 8) size of output buffer + ;; 4k in little endian + (data (i32.const 4) "\00\10") + + ;; [8, 168) input buffer + ;; [168, 4264) output buffer + + (func (export "call") + ;; Receive (key ++ value_to_write) + (call $seal_input + (i32.const 8) ;; Pointer to the input buffer + (i32.const 0) ;; Size of the input buffer + ) + ;; Load a storage value and result of this call into the output buffer + (i32.store (i32.const 168) + (call $get_storage + (i32.const 12) ;; key_ptr + (i32.load (i32.const 8)) ;; key_len + (i32.const 172) ;; Pointer to the output buffer + (i32.const 4) ;; Pointer to the size of the buffer + ) + ) + (call $seal_return + (i32.const 0) ;; flags + (i32.const 168) ;; output buffer ptr + (i32.add ;; length: output size + 4 (retval) + (i32.load (i32.const 4)) + (i32.const 4) + ) + ) + ) + + (func (export "deploy")) +) +"#; + + let mut ext = MockExt::default(); + + ext.set_storage( + &Key::::try_from_var([1u8; 64].to_vec()).unwrap(), + Some(vec![42u8]), + false, + ) + .unwrap(); + + ext.set_storage( + &Key::::try_from_var([2u8; 19].to_vec()).unwrap(), + Some(vec![]), + false, + ) + .unwrap(); + + // value does not exist + let input = (63, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::KeyNotFound as u32 + ); + + // value exists + let input = (64, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::Success as u32 + ); + assert_eq!(ext.storage.get(&[1u8; 64].to_vec()).unwrap(), &[42u8]); + assert_eq!(&result.data[4..], &[42u8]); + + // value exists (test for 0 sized) + let input = (19, [2u8; 19]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::Success as u32 + ); + assert_eq!(ext.storage.get(&[2u8; 19].to_vec()), Some(&vec![])); + assert_eq!(&result.data[4..], &([] as [u8; 0])); + } + + #[test] + fn clear_storage_works() { + const CODE: &str = r#" +(module + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "seal1" "clear_storage" (func $clear_storage (param i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + ;; size of input buffer + ;; [0, 4) size of input buffer (128+32 = 160 bytes = 0xA0) + (data (i32.const 0) "\A0") + + ;; [4, 164) input buffer + + (func (export "call") + ;; Receive key + (call $seal_input + (i32.const 4) ;; Where we take input and store it + (i32.const 0) ;; Where we take and store the length of thedata + ) + ;; Call seal_clear_storage and save what it returns at 0 + (i32.store (i32.const 0) + (call $clear_storage + (i32.const 8) ;; key_ptr + (i32.load (i32.const 4)) ;; key_len + ) + ) + (call $seal_return + (i32.const 0) ;; flags + (i32.const 0) ;; returned value + (i32.const 4) ;; length of returned value + ) + ) + + (func (export "deploy")) +) +"#; + + let mut ext = MockExt::default(); + + ext.set_storage( + &Key::::try_from_var([1u8; 64].to_vec()).unwrap(), + Some(vec![42u8]), + false, + ) + .unwrap(); + ext.set_storage( + &Key::::try_from_var([2u8; 19].to_vec()).unwrap(), + Some(vec![]), + false, + ) + .unwrap(); + + // value did not exist + let input = (32, [3u8; 32]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + // sentinel returned + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), crate::SENTINEL); + assert_eq!(ext.storage.get(&[3u8; 32].to_vec()), None); + + // value did exist + let input = (64, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + // length returned + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 1); + // value cleared + assert_eq!(ext.storage.get(&[1u8; 64].to_vec()), None); + + //value did not exist (wrong key length) + let input = (63, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + // sentinel returned + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), crate::SENTINEL); + assert_eq!(ext.storage.get(&[1u8; 64].to_vec()), None); + + // value exists + let input = (19, [2u8; 19]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + // length returned (test for 0 sized) + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 0); + // value cleared + assert_eq!(ext.storage.get(&[2u8; 19].to_vec()), None); + } + + #[test] + fn take_storage_works() { + const CODE: &str = r#" +(module + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "take_storage" (func $take_storage (param i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0, 4) size of input buffer (160 bytes as we copy the key+len here) + (data (i32.const 0) "\A0") + + ;; [4, 8) size of output buffer + ;; 4k in little endian + (data (i32.const 4) "\00\10") + + ;; [8, 168) input buffer + ;; [168, 4264) output buffer + + (func (export "call") + ;; Receive key + (call $seal_input + (i32.const 8) ;; Pointer to the input buffer + (i32.const 0) ;; Size of the length buffer + ) + + ;; Load a storage value and result of this call into the output buffer + (i32.store (i32.const 168) + (call $take_storage + (i32.const 12) ;; key_ptr + (i32.load (i32.const 8)) ;; key_len + (i32.const 172) ;; Pointer to the output buffer + (i32.const 4) ;; Pointer to the size of the buffer + ) + ) + + ;; Return the contents of the buffer + (call $seal_return + (i32.const 0) ;; flags + (i32.const 168) ;; output buffer ptr + (i32.add ;; length: storage size + 4 (retval) + (i32.load (i32.const 4)) + (i32.const 4) + ) + ) + ) + + (func (export "deploy")) +) +"#; + + let mut ext = MockExt::default(); + + ext.set_storage( + &Key::::try_from_var([1u8; 64].to_vec()).unwrap(), + Some(vec![42u8]), + false, + ) + .unwrap(); + + ext.set_storage( + &Key::::try_from_var([2u8; 19].to_vec()).unwrap(), + Some(vec![]), + false, + ) + .unwrap(); + + // value does not exist -> error returned + let input = (63, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::KeyNotFound as u32 + ); + + // value did exist -> value returned + let input = (64, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::Success as u32 + ); + assert_eq!(ext.storage.get(&[1u8; 64].to_vec()), None); + assert_eq!(&result.data[4..], &[42u8]); + + // value did exist -> length returned (test for 0 sized) + let input = (19, [2u8; 19]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::Success as u32 + ); + assert_eq!(ext.storage.get(&[2u8; 19].to_vec()), None); + assert_eq!(&result.data[4..], &[0u8; 0]); + } + + #[test] + fn set_transient_storage_works() { + const CODE: &str = r#" +(module + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "seal0" "set_transient_storage" (func $set_transient_storage (param i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0, 4) size of input buffer + ;; 4k in little endian + (data (i32.const 0) "\00\10") + + ;; [4, 4100) input buffer + + (func (export "call") + ;; Receive (key ++ value_to_write) + (call $seal_input + (i32.const 4) ;; Pointer to the input buffer + (i32.const 0) ;; Size of the input buffer + ) + ;; Store the passed value to the passed key and store result to memory + (i32.store (i32.const 168) + (call $set_transient_storage + (i32.const 8) ;; key_ptr + (i32.load (i32.const 4)) ;; key_len + (i32.add ;; value_ptr = 8 + key_len + (i32.const 8) + (i32.load (i32.const 4))) + (i32.sub ;; value_len (input_size - (key_len + key_len_len)) + (i32.load (i32.const 0)) + (i32.add + (i32.load (i32.const 4)) + (i32.const 4) + ) + ) + ) + ) + (call $seal_return + (i32.const 0) ;; flags + (i32.const 168) ;; ptr to returned value + (i32.const 4) ;; length of returned value + ) + ) + + (func (export "deploy")) +) +"#; + + let mut ext = MockExt::default(); + + // value did not exist before -> sentinel returned + let input = (32, [1u8; 32], [42u8, 48]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), crate::SENTINEL); + assert_eq!( + ext.get_transient_storage(&Key::::try_from_var([1u8; 32].to_vec()).unwrap()), + Some(vec![42, 48]) + ); + + // value do exist -> length of old value returned + let input = (32, [1u8; 32], [0u8; 0]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 2); + assert_eq!( + ext.get_transient_storage(&Key::::try_from_var([1u8; 32].to_vec()).unwrap()), + Some(vec![]) + ); + + // value do exist -> length of old value returned (test for zero sized val) + let input = (32, [1u8; 32], [99u8]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 0); + assert_eq!( + ext.get_transient_storage(&Key::::try_from_var([1u8; 32].to_vec()).unwrap()), + Some(vec![99]) + ); + } + + #[test] + fn get_transient_storage_works() { + const CODE: &str = r#" +(module + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "seal0" "get_transient_storage" (func $get_transient_storage (param i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0, 4) size of input buffer (160 bytes as we copy the key+len here) + (data (i32.const 0) "\A0") + + ;; [4, 8) size of output buffer + ;; 4k in little endian + (data (i32.const 4) "\00\10") + + ;; [8, 168) input buffer + ;; [168, 4264) output buffer + + (func (export "call") + ;; Receive (key ++ value_to_write) + (call $seal_input + (i32.const 8) ;; Pointer to the input buffer + (i32.const 0) ;; Size of the input buffer + ) + ;; Load a storage value and result of this call into the output buffer + (i32.store (i32.const 168) + (call $get_transient_storage + (i32.const 12) ;; key_ptr + (i32.load (i32.const 8)) ;; key_len + (i32.const 172) ;; Pointer to the output buffer + (i32.const 4) ;; Pointer to the size of the buffer + ) + ) + (call $seal_return + (i32.const 0) ;; flags + (i32.const 168) ;; output buffer ptr + (i32.add ;; length: output size + 4 (retval) + (i32.load (i32.const 4)) + (i32.const 4) + ) + ) + ) + + (func (export "deploy")) +) +"#; + + let mut ext = MockExt::default(); + + assert_ok!(ext.set_transient_storage( + &Key::::try_from_var([1u8; 64].to_vec()).unwrap(), + Some(vec![42u8]), + false + )); + assert_ok!(ext.set_transient_storage( + &Key::::try_from_var([2u8; 19].to_vec()).unwrap(), + Some(vec![]), + false + )); + + // value does not exist + let input = (63, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::KeyNotFound as u32 + ); + + // value exists + let input = (64, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::Success as u32 + ); + assert_eq!(&result.data[4..], &[42u8]); + + // value exists (test for 0 sized) + let input = (19, [2u8; 19]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::Success as u32 + ); + assert_eq!(&result.data[4..], &([] as [u8; 0])); + } + + #[test] + fn clear_transient_storage_works() { + const CODE: &str = r#" +(module + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "seal0" "clear_transient_storage" (func $clear_transient_storage (param i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + ;; size of input buffer + ;; [0, 4) size of input buffer (128+32 = 160 bytes = 0xA0) + (data (i32.const 0) "\A0") + + ;; [4, 164) input buffer + + (func (export "call") + ;; Receive key + (call $seal_input + (i32.const 4) ;; Where we take input and store it + (i32.const 0) ;; Where we take and store the length of thedata + ) + ;; Call seal_clear_storage and save what it returns at 0 + (i32.store (i32.const 0) + (call $clear_transient_storage + (i32.const 8) ;; key_ptr + (i32.load (i32.const 4)) ;; key_len + ) + ) + (call $seal_return + (i32.const 0) ;; flags + (i32.const 0) ;; returned value + (i32.const 4) ;; length of returned value + ) + ) + + (func (export "deploy")) +) +"#; + + let mut ext = MockExt::default(); + + assert_ok!(ext.set_transient_storage( + &Key::::try_from_var([1u8; 64].to_vec()).unwrap(), + Some(vec![42u8]), + false + )); + + // value did not exist + let input = (32, [3u8; 32]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + // sentinel returned + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), crate::SENTINEL); + + // value did exist + let input = (64, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + // length returned + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 1); + // value cleared + assert_eq!( + ext.get_transient_storage(&Key::::try_from_var([1u8; 64].to_vec()).unwrap()), + None + ); + } + + #[test] + fn take_transient_storage_works() { + const CODE: &str = r#" +(module + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "take_transient_storage" (func $take_transient_storage (param i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0, 4) size of input buffer (160 bytes as we copy the key+len here) + (data (i32.const 0) "\A0") + + ;; [4, 8) size of output buffer + ;; 4k in little endian + (data (i32.const 4) "\00\10") + + ;; [8, 168) input buffer + ;; [168, 4264) output buffer + + (func (export "call") + ;; Receive key + (call $seal_input + (i32.const 8) ;; Pointer to the input buffer + (i32.const 0) ;; Size of the length buffer + ) + + ;; Load a storage value and result of this call into the output buffer + (i32.store (i32.const 168) + (call $take_transient_storage + (i32.const 12) ;; key_ptr + (i32.load (i32.const 8)) ;; key_len + (i32.const 172) ;; Pointer to the output buffer + (i32.const 4) ;; Pointer to the size of the buffer + ) + ) + + ;; Return the contents of the buffer + (call $seal_return + (i32.const 0) ;; flags + (i32.const 168) ;; output buffer ptr + (i32.add ;; length: storage size + 4 (retval) + (i32.load (i32.const 4)) + (i32.const 4) + ) + ) + ) + + (func (export "deploy")) +) +"#; + + let mut ext = MockExt::default(); + + assert_ok!(ext.set_transient_storage( + &Key::::try_from_var([1u8; 64].to_vec()).unwrap(), + Some(vec![42u8]), + false + )); + assert_ok!(ext.set_transient_storage( + &Key::::try_from_var([2u8; 19].to_vec()).unwrap(), + Some(vec![]), + false + )); + + // value does not exist -> error returned + let input = (63, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::KeyNotFound as u32 + ); + + // value did exist -> value returned + let input = (64, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::Success as u32 + ); + assert_eq!( + ext.get_transient_storage(&Key::::try_from_var([1u8; 64].to_vec()).unwrap()), + None + ); + assert_eq!(&result.data[4..], &[42u8]); + + // value did exist -> length returned (test for 0 sized) + let input = (19, [2u8; 19]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::Success as u32 + ); + assert_eq!( + ext.get_transient_storage(&Key::::try_from_var([2u8; 19].to_vec()).unwrap()), + None + ); + assert_eq!(&result.data[4..], &[0u8; 0]); + } + + #[test] + fn is_contract_works() { + const CODE_IS_CONTRACT: &str = r#" +;; This runs `is_contract` check on zero account address +(module + (import "seal0" "seal_is_contract" (func $seal_is_contract (param i32) (result i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0, 32) zero-adress + (data (i32.const 0) + "\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00" + "\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00" + ) + + ;; [32, 36) here we store the return code of the `seal_is_contract` + + (func (export "deploy")) + + (func (export "call") + (i32.store + (i32.const 32) + (call $seal_is_contract + (i32.const 0) ;; ptr to destination address + ) + ) + ;; exit with success and take `seal_is_contract` return code to the output buffer + (call $seal_return (i32.const 0) (i32.const 32) (i32.const 4)) + ) +) +"#; + let output = execute(CODE_IS_CONTRACT, vec![], MockExt::default()).unwrap(); + + // The mock ext just always returns 1u32 (`true`). + assert_eq!(output, ExecReturnValue { flags: ReturnFlags::empty(), data: 1u32.encode() },); + } + + #[test] + fn code_hash_works() { + /// calls `seal_code_hash` and compares the result with the constant. + const CODE_CODE_HASH: &str = r#" +(module + (import "seal0" "seal_code_hash" (func $seal_code_hash (param i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + ;; size of our buffer is 32 bytes + (data (i32.const 32) "\20") + + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + + (func (export "call") + ;; fill the buffer with the code hash. + (call $seal_code_hash + (i32.const 0) ;; input: address_ptr (before call) + (i32.const 0) ;; output: code_hash_ptr (after call) + (i32.const 32) ;; same 32 bytes length for input and output + ) + + ;; assert size == 32 + (call $assert + (i32.eq + (i32.load (i32.const 32)) + (i32.const 32) + ) + ) + + ;; assert that the first 8 bytes are "1111111111111111" + (call $assert + (i64.eq + (i64.load (i32.const 0)) + (i64.const 0x1111111111111111) + ) + ) + drop + ) + + (func (export "deploy")) +) +"#; + assert_ok!(execute(CODE_CODE_HASH, vec![], MockExt::default())); + } + + #[test] + fn own_code_hash_works() { + /// calls `seal_own_code_hash` and compares the result with the constant. + const CODE_OWN_CODE_HASH: &str = r#" +(module + (import "seal0" "seal_own_code_hash" (func $seal_own_code_hash (param i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; size of our buffer is 32 bytes + (data (i32.const 32) "\20") + + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + + (func (export "call") + ;; fill the buffer with the code hash + (call $seal_own_code_hash + (i32.const 0) ;; output: code_hash_ptr + (i32.const 32) ;; 32 bytes length of code_hash output + ) + + ;; assert size == 32 + (call $assert + (i32.eq + (i32.load (i32.const 32)) + (i32.const 32) + ) + ) + + ;; assert that the first 8 bytes are "1010101010101010" + (call $assert + (i64.eq + (i64.load (i32.const 0)) + (i64.const 0x1010101010101010) + ) + ) + ) + + (func (export "deploy")) +) +"#; + assert_ok!(execute(CODE_OWN_CODE_HASH, vec![], MockExt::default())); + } + + #[test] + fn caller_is_origin_works() { + const CODE_CALLER_IS_ORIGIN: &str = r#" +;; This runs `caller_is_origin` check on zero account address +(module + (import "seal0" "seal_caller_is_origin" (func $seal_caller_is_origin (result i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0, 4) here the return code of the `seal_caller_is_origin` will be stored + ;; we initialize it with non-zero value to be sure that it's being overwritten below + (data (i32.const 0) "\10\10\10\10") + + (func (export "deploy")) + + (func (export "call") + (i32.store + (i32.const 0) + (call $seal_caller_is_origin) + ) + ;; exit with success and take `seal_caller_is_origin` return code to the output buffer + (call $seal_return (i32.const 0) (i32.const 0) (i32.const 4)) + ) +) +"#; + let output = execute(CODE_CALLER_IS_ORIGIN, vec![], MockExt::default()).unwrap(); + + // The mock ext just always returns 0u32 (`false`) + assert_eq!(output, ExecReturnValue { flags: ReturnFlags::empty(), data: 0u32.encode() },); + } + + #[test] + fn caller_is_root_works() { + const CODE_CALLER_IS_ROOT: &str = r#" +;; This runs `caller_is_root` check on zero account address +(module + (import "seal0" "caller_is_root" (func $caller_is_root (result i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0, 4) here the return code of the `caller_is_root` will be stored + ;; we initialize it with non-zero value to be sure that it's being overwritten below + (data (i32.const 0) "\10\10\10\10") + + (func (export "deploy")) + + (func (export "call") + (i32.store + (i32.const 0) + (call $caller_is_root) + ) + ;; exit with success and take `caller_is_root` return code to the output buffer + (call $seal_return (i32.const 0) (i32.const 0) (i32.const 4)) + ) +) +"#; + // The default `caller` is ALICE. Therefore not root. + let output = execute(CODE_CALLER_IS_ROOT, vec![], MockExt::default()).unwrap(); + assert_eq!(output, ExecReturnValue { flags: ReturnFlags::empty(), data: 0u32.encode() },); + + // The caller is forced to be root instead of using the default ALICE. + let output = execute( + CODE_CALLER_IS_ROOT, + vec![], + MockExt { caller: Origin::Root, ..MockExt::default() }, + ) + .unwrap(); + assert_eq!(output, ExecReturnValue { flags: ReturnFlags::empty(), data: 1u32.encode() },); + } + + #[test] + fn set_code_hash() { + const CODE: &str = r#" +(module + (import "seal0" "seal_set_code_hash" (func $seal_set_code_hash (param i32) (result i32))) + (import "env" "memory" (memory 1 1)) + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + (func (export "call") + (local $exit_code i32) + (local.set $exit_code + (call $seal_set_code_hash (i32.const 0)) + ) + (call $assert + (i32.eq (local.get $exit_code) (i32.const 0)) ;; ReturnCode::Success + ) + ) + + (func (export "deploy")) + + ;; Hash of code. + (data (i32.const 0) + "\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11" + "\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11" + ) +) +"#; + + let mut mock_ext = MockExt::default(); + execute(CODE, [0u8; 32].encode(), &mut mock_ext).unwrap(); + + assert_eq!(mock_ext.code_hashes.pop().unwrap(), H256::from_slice(&[17u8; 32])); + } + + #[test] + fn reentrance_count_works() { + const CODE: &str = r#" +(module + (import "seal0" "reentrance_count" (func $reentrance_count (result i32))) + (import "env" "memory" (memory 1 1)) + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + (func (export "call") + (local $return_val i32) + (local.set $return_val + (call $reentrance_count) + ) + (call $assert + (i32.eq (local.get $return_val) (i32.const 12)) + ) + ) + + (func (export "deploy")) +) +"#; + + let mut mock_ext = MockExt::default(); + execute(CODE, vec![], &mut mock_ext).unwrap(); + } + + #[test] + fn account_reentrance_count_works() { + const CODE: &str = r#" +(module + (import "seal0" "account_reentrance_count" (func $account_reentrance_count (param i32) (result i32))) + (import "env" "memory" (memory 1 1)) + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + (func (export "call") + (local $return_val i32) + (local.set $return_val + (call $account_reentrance_count (i32.const 0)) + ) + (call $assert + (i32.eq (local.get $return_val) (i32.const 12)) + ) + ) + + (func (export "deploy")) +) +"#; + + let mut mock_ext = MockExt::default(); + execute(CODE, vec![], &mut mock_ext).unwrap(); + } + + #[test] + fn instantiation_nonce_works() { + const CODE: &str = r#" +(module + (import "seal0" "instantiation_nonce" (func $nonce (result i64))) + (import "env" "memory" (memory 1 1)) + + (func $assert (param i32) + (block $ok + (br_if $ok + (local.get 0) + ) + (unreachable) + ) + ) + (func (export "call") + (call $assert + (i64.eq (call $nonce) (i64.const 995)) + ) + ) + (func (export "deploy")) +) +"#; + + let mut mock_ext = MockExt::default(); + execute(CODE, vec![], &mut mock_ext).unwrap(); + } + + /// This test check that an unstable interface cannot be deployed. In case of runtime + /// benchmarks we always allow unstable interfaces. This is why this test does not + /// work when this feature is enabled. + #[cfg(not(feature = "runtime-benchmarks"))] + #[test] + fn cannot_deploy_unstable() { + const CANNOT_DEPLOY_UNSTABLE: &str = r#" +(module + (import "seal0" "reentrance_count" (func $reentrance_count (result i32))) + (import "env" "memory" (memory 1 1)) + + (func (export "call")) + (func (export "deploy")) +) +"#; + assert_err!( + execute_no_unstable(CANNOT_DEPLOY_UNSTABLE, vec![], MockExt::default()), + >::CodeRejected, + ); + assert_ok!(execute(CANNOT_DEPLOY_UNSTABLE, vec![], MockExt::default())); + } + + /// The random interface is deprecated and hence new contracts using it should not be deployed. + /// In case of runtime benchmarks we always allow deprecated interfaces. This is why this + /// test doesn't work if this feature is enabled. + #[cfg(not(feature = "runtime-benchmarks"))] + #[test] + fn cannot_deploy_deprecated() { + const CODE_RANDOM_0: &str = r#" +(module + (import "seal0" "seal_random" (func $seal_random (param i32 i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + (func (export "call")) + (func (export "deploy")) +) + "#; + const CODE_RANDOM_1: &str = r#" +(module + (import "seal1" "seal_random" (func $seal_random (param i32 i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + (func (export "call")) + (func (export "deploy")) +) + "#; + const CODE_RANDOM_2: &str = r#" +(module + (import "seal0" "random" (func $seal_random (param i32 i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + (func (export "call")) + (func (export "deploy")) +) + "#; + const CODE_RANDOM_3: &str = r#" +(module + (import "seal1" "random" (func $seal_random (param i32 i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + (func (export "call")) + (func (export "deploy")) +) + "#; + + assert_ok!(execute_unvalidated(CODE_RANDOM_0, vec![], MockExt::default())); + assert_err!( + execute_instantiate_unvalidated(CODE_RANDOM_0, vec![], MockExt::default()), + >::CodeRejected, + ); + assert_err!( + execute(CODE_RANDOM_0, vec![], MockExt::default()), + >::CodeRejected, + ); + + assert_ok!(execute_unvalidated(CODE_RANDOM_1, vec![], MockExt::default())); + assert_err!( + execute_instantiate_unvalidated(CODE_RANDOM_1, vec![], MockExt::default()), + >::CodeRejected, + ); + assert_err!( + execute(CODE_RANDOM_1, vec![], MockExt::default()), + >::CodeRejected, + ); + + assert_ok!(execute_unvalidated(CODE_RANDOM_2, vec![], MockExt::default())); + assert_err!( + execute_instantiate_unvalidated(CODE_RANDOM_2, vec![], MockExt::default()), + >::CodeRejected, + ); + assert_err!( + execute(CODE_RANDOM_2, vec![], MockExt::default()), + >::CodeRejected, + ); + + assert_ok!(execute_unvalidated(CODE_RANDOM_3, vec![], MockExt::default())); + assert_err!( + execute_instantiate_unvalidated(CODE_RANDOM_3, vec![], MockExt::default()), + >::CodeRejected, + ); + assert_err!( + execute(CODE_RANDOM_3, vec![], MockExt::default()), + >::CodeRejected, + ); + } + + #[test] + fn lock_unlock_delegate_dependency() { + const CODE_LOCK_UNLOCK_DELEGATE_DEPENDENCY: &str = r#" +(module + (import "seal0" "lock_delegate_dependency" (func $lock_delegate_dependency (param i32))) + (import "seal0" "unlock_delegate_dependency" (func $unlock_delegate_dependency (param i32))) + (import "env" "memory" (memory 1 1)) + (func (export "call") + (call $lock_delegate_dependency (i32.const 0)) + (call $lock_delegate_dependency (i32.const 32)) + (call $unlock_delegate_dependency (i32.const 32)) + ) + (func (export "deploy")) + + ;; hash1 (32 bytes) + (data (i32.const 0) + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + "\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01" + ) + + ;; hash2 (32 bytes) + (data (i32.const 32) + "\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02" + "\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02" + ) +) +"#; + let mut mock_ext = MockExt::default(); + assert_ok!(execute(&CODE_LOCK_UNLOCK_DELEGATE_DEPENDENCY, vec![], &mut mock_ext)); + let delegate_dependencies: Vec<_> = + mock_ext.delegate_dependencies.into_inner().into_iter().collect(); + assert_eq!(delegate_dependencies.len(), 1); + assert_eq!(delegate_dependencies[0].as_bytes(), [1; 32]); + } + + // This test checks that [`Runtime::read_sandbox_memory_as`] works, when the decoded type has a + // max_len greater than the memory size, but the decoded data fits into the memory. + #[test] + fn read_sandbox_memory_as_works_with_max_len_out_of_bounds_but_fitting_actual_data() { + use frame_support::BoundedVec; + use sp_core::ConstU32; + + let mut ext = MockExt::default(); + let runtime = Runtime::new(&mut ext, vec![]); + let data = vec![1u8, 2, 3]; + let memory = data.encode(); + let decoded: BoundedVec> = + runtime.read_sandbox_memory_as(&memory, 0u32).unwrap(); + assert_eq!(decoded.into_inner(), data); + } + + #[test] + fn run_out_of_gas_in_start_fn() { + const CODE: &str = r#" +(module + (import "env" "memory" (memory 1 1)) + (start $start) + (func $start + (loop $inf (br $inf)) ;; just run out of gas + (unreachable) + ) + (func (export "call")) + (func (export "deploy")) +) +"#; + let mut mock_ext = MockExt::default(); + assert_err!(execute(&CODE, vec![], &mut mock_ext), >::OutOfGas); + } +} diff --git a/pallets/contracts/src/wasm/prepare.rs b/pallets/contracts/src/wasm/prepare.rs new file mode 100644 index 00000000..93fe3080 --- /dev/null +++ b/pallets/contracts/src/wasm/prepare.rs @@ -0,0 +1,873 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This module takes care of loading, checking and preprocessing of a +//! wasm module before execution. It also extracts some essential information +//! from a module. + +use crate::{ + chain_extension::ChainExtension, + storage::meter::Diff, + wasm::{ + runtime::AllowDeprecatedInterface, CodeInfo, Determinism, Environment, WasmBlob, + BYTES_PER_PAGE, + }, + AccountIdOf, CodeVec, Config, Error, Schedule, LOG_TARGET, +}; +#[cfg(any(test, feature = "runtime-benchmarks"))] +use alloc::vec::Vec; +use codec::MaxEncodedLen; +use sp_runtime::{traits::Hash, DispatchError}; +use wasmi::{ + core::ValType as WasmiValueType, CompilationMode, Config as WasmiConfig, Engine, ExternType, + Module, StackLimits, +}; + +/// Imported memory must be located inside this module. The reason for hardcoding is that current +/// compiler toolchains might not support specifying other modules than "env" for memory imports. +pub const IMPORT_MODULE_MEMORY: &str = "env"; + +/// The inner deserialized module is valid and contains only allowed WebAssembly features. +/// This is checked by loading it into wasmi interpreter `engine`. +pub struct LoadedModule { + pub module: Module, + pub engine: Engine, +} + +#[derive(PartialEq, Debug, Clone)] +pub enum LoadingMode { + Checked, + Unchecked, +} + +#[cfg(test)] +pub mod tracker { + use core::cell::RefCell; + thread_local! { + pub static LOADED_MODULE: RefCell> = RefCell::new(Vec::new()); + } +} + +impl LoadedModule { + /// Creates a new instance of `LoadedModule`. + /// + /// The inner Wasm module is checked not to have restricted WebAssembly proposals. + /// Returns `Err` if the `code` cannot be deserialized or if it contains an invalid module. + pub fn new( + code: &[u8], + determinism: Determinism, + stack_limits: Option, + loading_mode: LoadingMode, + compilation_mode: CompilationMode, + ) -> Result { + // NOTE: wasmi does not support unstable WebAssembly features. The module is implicitly + // checked for not having those ones when creating `wasmi::Module` below. + let mut config = WasmiConfig::default(); + config + .wasm_multi_value(false) + .wasm_mutable_global(false) + .wasm_sign_extension(true) + .wasm_bulk_memory(false) + .wasm_reference_types(false) + .wasm_tail_call(false) + .wasm_extended_const(false) + .wasm_saturating_float_to_int(false) + .floats(matches!(determinism, Determinism::Relaxed)) + .compilation_mode(compilation_mode) + .consume_fuel(true); + + if let Some(stack_limits) = stack_limits { + config.set_stack_limits(stack_limits); + } + + let engine = Engine::new(&config); + + let module = match loading_mode { + LoadingMode::Checked => Module::new(&engine, code), + // Safety: The code has been validated, Therefore we know that it's a valid binary. + LoadingMode::Unchecked => unsafe { Module::new_unchecked(&engine, code) }, + } + .map_err(|err| { + log::debug!(target: LOG_TARGET, "Module creation failed: {:?}", err); + "Can't load the module into wasmi!" + })?; + + #[cfg(test)] + tracker::LOADED_MODULE.with(|t| t.borrow_mut().push(loading_mode)); + + // Return a `LoadedModule` instance with + // __valid__ module. + Ok(LoadedModule { module, engine }) + } + + /// Check that the module has required exported functions. For now + /// these are just entrypoints: + /// + /// - 'call' + /// - 'deploy' + /// + /// Any other exports are not allowed. + fn scan_exports(&self) -> Result<(), &'static str> { + let mut deploy_found = false; + let mut call_found = false; + let module = &self.module; + let exports = module.exports(); + + for export in exports { + match export.ty() { + ExternType::Func(ft) => { + match export.name() { + "call" => call_found = true, + "deploy" => deploy_found = true, + _ => + return Err( + "unknown function export: expecting only deploy and call functions", + ), + } + // Check the signature. + // Both "call" and "deploy" have the () -> () function type. + // We still support () -> (i32) for backwards compatibility. + if !(ft.params().is_empty() && + (ft.results().is_empty() || ft.results() == [WasmiValueType::I32])) + { + return Err("entry point has wrong signature") + } + }, + ExternType::Memory(_) => return Err("memory export is forbidden"), + ExternType::Global(_) => return Err("global export is forbidden"), + ExternType::Table(_) => return Err("table export is forbidden"), + } + } + + if !deploy_found { + return Err("deploy function isn't exported") + } + if !call_found { + return Err("call function isn't exported") + } + + Ok(()) + } + + /// Scan an import section if any. + /// + /// This makes sure that: + /// - The import section looks as we expect it from a contract. + /// - The limits of the memory type declared by the contract comply with the Schedule. + /// + /// Returns the checked memory limits back to caller. + /// + /// This method fails if: + /// + /// - Memory import not found in the module. + /// - Tables or globals found among imports. + /// - `call_chain_extension` host function is imported, while chain extensions are disabled. + /// + /// NOTE that only single memory instance is allowed for contract modules, which is enforced by + /// this check combined with multi_memory proposal gets disabled in the engine. + pub fn scan_imports( + &self, + schedule: &Schedule, + ) -> Result<(u32, u32), &'static str> { + let module = &self.module; + let imports = module.imports(); + let mut memory_limits = None; + + for import in imports { + match *import.ty() { + ExternType::Table(_) => return Err("Cannot import tables"), + ExternType::Global(_) => return Err("Cannot import globals"), + ExternType::Func(_) => { + let _ = import.ty().func().ok_or("expected a function")?; + + if !::ChainExtension::enabled() && + (import.name().as_bytes() == b"seal_call_chain_extension" || + import.name().as_bytes() == b"call_chain_extension") + { + return Err("Module uses chain extensions but chain extensions are disabled") + } + }, + ExternType::Memory(mt) => { + if import.module().as_bytes() != IMPORT_MODULE_MEMORY.as_bytes() { + return Err("Invalid module for imported memory") + } + if import.name().as_bytes() != b"memory" { + return Err("Memory import must have the field name 'memory'") + } + if memory_limits.is_some() { + return Err("Multiple memory imports defined") + } + // Parse memory limits defaulting it to (0,0). + // Any access to it will then lead to out of bounds trap. + let (initial, maximum) = ( + mt.initial_pages().to_bytes().unwrap_or(0).saturating_div(BYTES_PER_PAGE) + as u32, + mt.maximum_pages().map_or(schedule.limits.memory_pages, |p| { + p.to_bytes().unwrap_or(0).saturating_div(BYTES_PER_PAGE) as u32 + }), + ); + if initial > maximum { + return Err( + "Requested initial number of memory pages should not exceed the requested maximum", + ) + } + if maximum > schedule.limits.memory_pages { + return Err("Maximum number of memory pages should not exceed the maximum configured in the Schedule") + } + + memory_limits = Some((initial, maximum)); + continue + }, + } + } + + memory_limits.ok_or("No memory import found in the module") + } +} + +/// Check that given `code` satisfies constraints required for the contract Wasm module. +/// This includes two groups of checks: +/// +/// 1. General engine-side validation makes sure the module is consistent and does not contain +/// forbidden WebAssembly features. +/// 2. Additional checks which are specific to smart contracts eligible for this pallet. +fn validate( + code: &[u8], + schedule: &Schedule, + determinism: &mut Determinism, +) -> Result<(), (DispatchError, &'static str)> +where + E: Environment<()>, + T: Config, +{ + let module = (|| { + // We don't actually ever execute this instance so we can get away with a minimal stack + // which reduces the amount of memory that needs to be zeroed. + let stack_limits = Some(StackLimits::new(1, 1, 0).expect("initial <= max; qed")); + + // We check that the module is generally valid, + // and does not have restricted WebAssembly features, here. + let contract_module = match *determinism { + Determinism::Relaxed => + if let Ok(module) = LoadedModule::new::( + code, + Determinism::Enforced, + stack_limits, + LoadingMode::Checked, + CompilationMode::Eager, + ) { + *determinism = Determinism::Enforced; + module + } else { + LoadedModule::new::( + code, + Determinism::Relaxed, + None, + LoadingMode::Checked, + CompilationMode::Eager, + )? + }, + Determinism::Enforced => LoadedModule::new::( + code, + Determinism::Enforced, + stack_limits, + LoadingMode::Checked, + CompilationMode::Eager, + )?, + }; + + // The we check that module satisfies constraints the pallet puts on contracts. + contract_module.scan_exports()?; + contract_module.scan_imports::(schedule)?; + Ok(contract_module) + })() + .map_err(|msg: &str| { + log::debug!(target: LOG_TARGET, "New code rejected on validation: {}", msg); + (Error::::CodeRejected.into(), msg) + })?; + + // This will make sure that the module can be actually run within wasmi: + // + // - It doesn't use any unknown imports. + // - It doesn't explode the wasmi bytecode generation. + WasmBlob::::instantiate::(module, (), schedule, AllowDeprecatedInterface::No) + .map_err(|err| { + log::debug!(target: LOG_TARGET, "{err}"); + (Error::::CodeRejected.into(), "New code rejected on wasmi instantiation!") + })?; + + Ok(()) +} + +/// Validates the given binary `code` is a valid Wasm module satisfying following constraints: +/// +/// - The module doesn't export any memory. +/// - The module does imports memory, which limits lay within the limits permitted by the +/// `schedule`. +/// - All imported functions from the external environment match defined by `env` module. +/// +/// Also constructs contract `code_info` by calculating the storage deposit. +pub fn prepare( + code: CodeVec, + schedule: &Schedule, + owner: AccountIdOf, + mut determinism: Determinism, +) -> Result, (DispatchError, &'static str)> +where + E: Environment<()>, + T: Config, +{ + validate::(code.as_ref(), schedule, &mut determinism)?; + + // Calculate deposit for storing contract code and `code_info` in two different storage items. + let code_len = code.len() as u32; + let bytes_added = code_len.saturating_add(>::max_encoded_len() as u32); + let deposit = Diff { bytes_added, items_added: 2, ..Default::default() } + .update_contract::(None) + .charge_or_zero(); + let code_info = CodeInfo { owner, deposit, determinism, refcount: 0, code_len }; + let code_hash = T::Hashing::hash(&code); + + Ok(WasmBlob { code, code_info, code_hash }) +} + +/// Alternate (possibly unsafe) preparation functions used only for benchmarking and testing. +/// +/// For benchmarking we need to construct special contracts that might not pass our +/// sanity checks. We hide functions allowing this behind a feature that is only set during +/// benchmarking or testing to prevent usage in production code. +#[cfg(any(test, feature = "runtime-benchmarks"))] +pub mod benchmarking { + use super::*; + + /// Prepare function that does not perform export section checks on the passed in code. + pub fn prepare( + code: Vec, + schedule: &Schedule, + owner: AccountIdOf, + ) -> Result, DispatchError> { + let determinism = Determinism::Enforced; + let contract_module = LoadedModule::new::( + &code, + determinism, + None, + LoadingMode::Checked, + CompilationMode::Eager, + )?; + let _ = contract_module.scan_imports::(schedule)?; + let code: CodeVec = code.try_into().map_err(|_| >::CodeTooLarge)?; + let code_info = CodeInfo { + owner, + // this is a helper function for benchmarking which skips deposit collection + deposit: Default::default(), + refcount: 0, + code_len: code.len() as u32, + determinism, + }; + let code_hash = T::Hashing::hash(&code); + + Ok(WasmBlob { code, code_info, code_hash }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + exec::Ext, + schedule::Limits, + tests::{Test, ALICE}, + }; + use pallet_contracts_proc_macro::define_env; + use std::fmt; + + impl fmt::Debug for WasmBlob { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "ContractCode {{ .. }}") + } + } + + /// Using unreachable statements triggers unreachable warnings in the generated code + #[allow(unreachable_code)] + mod env { + use super::*; + use crate::wasm::runtime::{AllowDeprecatedInterface, AllowUnstableInterface, TrapReason}; + + // Define test environment for tests. We need ImportSatisfyCheck + // implementation from it. So actual implementations doesn't matter. + #[define_env] + pub mod test_env { + fn panic(_ctx: _, _memory: _) -> Result<(), TrapReason> { + Ok(()) + } + + // gas is an implementation defined function and a contract can't import it. + fn gas(_ctx: _, _memory: _, _amount: u64) -> Result<(), TrapReason> { + Ok(()) + } + + fn nop(_ctx: _, _memory: _, _unused: u64) -> Result<(), TrapReason> { + Ok(()) + } + + // new version of nop with other data type for argument + #[version(1)] + fn nop(_ctx: _, _memory: _, _unused: i32) -> Result<(), TrapReason> { + Ok(()) + } + } + } + + macro_rules! prepare_test { + ($name:ident, $wat:expr, $($expected:tt)*) => { + #[test] + fn $name() { + let wasm = wat::parse_str($wat).unwrap().try_into().unwrap(); + let schedule = Schedule { + limits: Limits { + memory_pages: 16, + .. Default::default() + }, + .. Default::default() + }; + let r = prepare::( + wasm, + &schedule, + ALICE, + Determinism::Enforced, + ); + assert_matches::assert_matches!(r.map_err(|(_, msg)| msg), $($expected)*); + } + }; + } + + prepare_test!( + no_floats, + r#" + (module + (func (export "call") + (drop + (f32.add + (f32.const 0) + (f32.const 1) + ) + ) + ) + (func (export "deploy")) + )"#, + Err("Can't load the module into wasmi!") + ); + + mod memories { + use super::*; + + prepare_test!( + memory_with_one_page, + r#" + (module + (import "env" "memory" (memory 1 1)) + + (func (export "call")) + (func (export "deploy")) + ) + "#, + Ok(_) + ); + + prepare_test!( + internal_memory_declaration, + r#" + (module + (memory 1 1) + + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("No memory import found in the module") + ); + + prepare_test!( + no_memory_import, + r#" + (module + ;; no memory imported + + (func (export "call")) + (func (export "deploy")) + )"#, + Err("No memory import found in the module") + ); + + prepare_test!( + initial_exceeds_maximum, + r#" + (module + (import "env" "memory" (memory 16 1)) + + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("Can't load the module into wasmi!") + ); + + prepare_test!( + requested_maximum_valid, + r#" + (module + (import "env" "memory" (memory 1 16)) + + (func (export "call")) + (func (export "deploy")) + ) + "#, + Ok(_) + ); + + prepare_test!( + requested_maximum_exceeds_configured_maximum, + r#" + (module + (import "env" "memory" (memory 1 17)) + + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("Maximum number of memory pages should not exceed the maximum configured in the Schedule") + ); + + prepare_test!( + field_name_not_memory, + r#" + (module + (import "env" "forgetit" (memory 1 1)) + + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("Memory import must have the field name 'memory'") + ); + + prepare_test!( + multiple_memory_imports, + r#" + (module + (import "env" "memory" (memory 1 1)) + (import "env" "memory" (memory 1 1)) + + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("Can't load the module into wasmi!") + ); + + prepare_test!( + table_import, + r#" + (module + (import "seal0" "table" (table 1 anyfunc)) + + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("Cannot import tables") + ); + + prepare_test!( + global_import, + r#" + (module + (global $g (import "seal0" "global") i32) + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("Cannot import globals") + ); + } + + mod imports { + use super::*; + + prepare_test!( + can_import_legit_function, + r#" + (module + (import "seal0" "nop" (func (param i64))) + (import "env" "memory" (memory 1 1)) + + (func (export "call")) + (func (export "deploy")) + ) + "#, + Ok(_) + ); + + // memory is in "env" and not in "seal0" + prepare_test!( + memory_not_in_seal0, + r#" + (module + (import "seal0" "memory" (memory 1 1)) + + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("Invalid module for imported memory") + ); + + // Memory is in "env" and not in some arbitrary module + prepare_test!( + memory_not_in_arbitrary_module, + r#" + (module + (import "any_module" "memory" (memory 1 1)) + + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("Invalid module for imported memory") + ); + + prepare_test!( + function_in_other_module_works, + r#" + (module + (import "seal1" "nop" (func (param i32))) + (import "env" "memory" (memory 1 1)) + + + (func (export "call")) + (func (export "deploy")) + ) + "#, + Ok(_) + ); + + prepare_test!( + wrong_signature, + r#" + (module + (import "seal0" "input" (func (param i64))) + (import "env" "memory" (memory 1 1)) + + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("New code rejected on wasmi instantiation!") + ); + + prepare_test!( + unknown_func_name, + r#" + (module + (import "seal0" "unknown_func" (func)) + + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("No memory import found in the module") + ); + + // Try to import function from not a "seal*" module. + prepare_test!( + try_import_from_wrong_module, + r#" + (module + (import "env" "panic" (func)) + (import "env" "memory" (memory 1 1)) + + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("New code rejected on wasmi instantiation!") + ); + } + + mod entrypoints { + use super::*; + + prepare_test!( + it_works, + r#" + (module + (import "env" "memory" (memory 1 1)) + (func (export "call")) + (func (export "deploy")) + ) + "#, + Ok(_) + ); + + prepare_test!( + signed_extension_works, + r#" + (module + (import "env" "memory" (memory 1 1)) + (func (export "deploy")) + (func (export "call")) + (func (param i32) (result i32) + local.get 0 + i32.extend8_s + ) + ) + "#, + Ok(_) + ); + + prepare_test!( + omit_memory, + r#" + (module + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("No memory import found in the module") + ); + + prepare_test!( + omit_deploy, + r#" + (module + (func (export "call")) + ) + "#, + Err("deploy function isn't exported") + ); + + prepare_test!( + omit_call, + r#" + (module + (func (export "deploy")) + ) + "#, + Err("call function isn't exported") + ); + + // Try to use imported function as an entry point. + // This is allowed. + prepare_test!( + try_sneak_export_as_entrypoint, + r#" + (module + (import "seal0" "panic" (func)) + (import "env" "memory" (memory 1 1)) + + (func (export "deploy")) + + (export "call" (func 0)) + ) + "#, + Ok(_) + ); + + // Try to use global as an entry point. + prepare_test!( + try_sneak_export_as_global, + r#" + (module + (func (export "deploy")) + (global (export "call") i32 (i32.const 0)) + ) + "#, + Err("global export is forbidden") + ); + + prepare_test!( + wrong_signature, + r#" + (module + (func (export "deploy")) + (func (export "call") (param i32)) + ) + "#, + Err("entry point has wrong signature") + ); + + prepare_test!( + unknown_exports, + r#" + (module + (func (export "call")) + (func (export "deploy")) + (func (export "whatevs")) + ) + "#, + Err("unknown function export: expecting only deploy and call functions") + ); + + prepare_test!( + global_float, + r#" + (module + (global $x f32 (f32.const 0)) + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("Can't load the module into wasmi!") + ); + + prepare_test!( + local_float, + r#" + (module + (func $foo (local f32)) + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("Can't load the module into wasmi!") + ); + + prepare_test!( + param_float, + r#" + (module + (func $foo (param f32)) + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("Can't load the module into wasmi!") + ); + + prepare_test!( + result_float, + r#" + (module + (func $foo (result f32) (f32.const 0)) + (func (export "call")) + (func (export "deploy")) + ) + "#, + Err("Can't load the module into wasmi!") + ); + } +} diff --git a/pallets/contracts/src/wasm/runtime.rs b/pallets/contracts/src/wasm/runtime.rs new file mode 100644 index 00000000..984e5712 --- /dev/null +++ b/pallets/contracts/src/wasm/runtime.rs @@ -0,0 +1,2549 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Environment definition of the wasm smart-contract runtime. + +use crate::{ + exec::{ExecError, ExecResult, Ext, Key, TopicOf}, + gas::{ChargedAmount, Token}, + primitives::ExecReturnValue, + weights::WeightInfo, + BalanceOf, CodeHash, Config, DebugBufferVec, Error, SENTINEL, +}; +use alloc::{boxed::Box, vec, vec::Vec}; +use codec::{Decode, DecodeLimit, Encode, MaxEncodedLen}; +use core::fmt; +use frame_support::{ + dispatch::DispatchInfo, ensure, pallet_prelude::DispatchResultWithPostInfo, parameter_types, + traits::Get, weights::Weight, +}; +use pallet_contracts_proc_macro::define_env; +use pallet_contracts_uapi::{CallFlags, ReturnFlags}; +use sp_io::hashing::{blake2_128, blake2_256, keccak_256, sha2_256}; +use sp_runtime::{ + traits::{Bounded, Zero}, + DispatchError, RuntimeDebug, +}; +use wasmi::{core::HostError, errors::LinkerError, Linker, Memory, Store}; + +type CallOf = ::RuntimeCall; + +/// The maximum nesting depth a contract can use when encoding types. +const MAX_DECODE_NESTING: u32 = 256; + +/// Passed to [`Environment`] to determine whether it should expose deprecated interfaces. +pub enum AllowDeprecatedInterface { + /// No deprecated interfaces are exposed. + No, + /// Deprecated interfaces are exposed. + Yes, +} + +/// Passed to [`Environment`] to determine whether it should expose unstable interfaces. +pub enum AllowUnstableInterface { + /// No unstable interfaces are exposed. + No, + /// Unstable interfaces are exposed. + Yes, +} + +/// Trait implemented by the [`define_env`](pallet_contracts_proc_macro::define_env) macro for the +/// emitted `Env` struct. +pub trait Environment { + /// Adds all declared functions to the supplied [`Linker`](wasmi::Linker) and + /// [`Store`](wasmi::Store). + fn define( + store: &mut Store, + linker: &mut Linker, + allow_unstable: AllowUnstableInterface, + allow_deprecated: AllowDeprecatedInterface, + ) -> Result<(), LinkerError>; +} + +/// Type of a storage key. +enum KeyType { + /// Legacy fix sized key `[u8;32]`. + Fix, + /// Variable sized key used in transparent hashing, + /// cannot be larger than MaxStorageKeyLen. + Var(u32), +} + +pub use pallet_contracts_uapi::ReturnErrorCode; + +parameter_types! { + /// Getter types used by [`crate::api_doc::Current::call_runtime`] + const CallRuntimeFailed: ReturnErrorCode = ReturnErrorCode::CallRuntimeFailed; + /// Getter types used by [`crate::api_doc::Current::xcm_execute`] + const XcmExecutionFailed: ReturnErrorCode = ReturnErrorCode::XcmExecutionFailed; +} + +impl From for ReturnErrorCode { + fn from(from: ExecReturnValue) -> Self { + if from.flags.contains(ReturnFlags::REVERT) { + Self::CalleeReverted + } else { + Self::Success + } + } +} + +/// The data passed through when a contract uses `seal_return`. +#[derive(RuntimeDebug)] +pub struct ReturnData { + /// The flags as passed through by the contract. They are still unchecked and + /// will later be parsed into a `ReturnFlags` bitflags struct. + flags: u32, + /// The output buffer passed by the contract as return data. + data: Vec, +} + +/// Enumerates all possible reasons why a trap was generated. +/// +/// This is either used to supply the caller with more information about why an error +/// occurred (the SupervisorError variant). +/// The other case is where the trap does not constitute an error but rather was invoked +/// as a quick way to terminate the application (all other variants). +#[derive(RuntimeDebug)] +pub enum TrapReason { + /// The supervisor trapped the contract because of an error condition occurred during + /// execution in privileged code. + SupervisorError(DispatchError), + /// Signals that trap was generated in response to call `seal_return` host function. + Return(ReturnData), + /// Signals that a trap was generated in response to a successful call to the + /// `seal_terminate` host function. + Termination, +} + +impl> From for TrapReason { + fn from(from: T) -> Self { + Self::SupervisorError(from.into()) + } +} + +impl fmt::Display for TrapReason { + fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + Ok(()) + } +} + +impl HostError for TrapReason {} + +#[cfg_attr(test, derive(Debug, PartialEq, Eq))] +#[derive(Copy, Clone)] +pub enum RuntimeCosts { + /// Base Weight of calling a host function. + HostFn, + /// Weight charged for copying data from the sandbox. + CopyFromContract(u32), + /// Weight charged for copying data to the sandbox. + CopyToContract(u32), + /// Weight of calling `seal_caller`. + Caller, + /// Weight of calling `seal_is_contract`. + IsContract, + /// Weight of calling `seal_code_hash`. + CodeHash, + /// Weight of calling `seal_own_code_hash`. + OwnCodeHash, + /// Weight of calling `seal_caller_is_origin`. + CallerIsOrigin, + /// Weight of calling `caller_is_root`. + CallerIsRoot, + /// Weight of calling `seal_address`. + Address, + /// Weight of calling `seal_gas_left`. + GasLeft, + /// Weight of calling `seal_balance`. + Balance, + /// Weight of calling `seal_value_transferred`. + ValueTransferred, + /// Weight of calling `seal_minimum_balance`. + MinimumBalance, + /// Weight of calling `seal_block_number`. + BlockNumber, + /// Weight of calling `seal_now`. + Now, + /// Weight of calling `seal_weight_to_fee`. + WeightToFee, + /// Weight of calling `seal_terminate`, passing the number of locked dependencies. + Terminate(u32), + /// Weight of calling `seal_random`. It includes the weight for copying the subject. + Random, + /// Weight of calling `seal_deposit_event` with the given number of topics and event size. + DepositEvent { num_topic: u32, len: u32 }, + /// Weight of calling `seal_debug_message` per byte of passed message. + DebugMessage(u32), + /// Weight of calling `seal_set_storage` for the given storage item sizes. + SetStorage { old_bytes: u32, new_bytes: u32 }, + /// Weight of calling `seal_clear_storage` per cleared byte. + ClearStorage(u32), + /// Weight of calling `seal_contains_storage` per byte of the checked item. + ContainsStorage(u32), + /// Weight of calling `seal_get_storage` with the specified size in storage. + GetStorage(u32), + /// Weight of calling `seal_take_storage` for the given size. + TakeStorage(u32), + /// Weight of calling `seal_set_transient_storage` for the given storage item sizes. + SetTransientStorage { old_bytes: u32, new_bytes: u32 }, + /// Weight of calling `seal_clear_transient_storage` per cleared byte. + ClearTransientStorage(u32), + /// Weight of calling `seal_contains_transient_storage` per byte of the checked item. + ContainsTransientStorage(u32), + /// Weight of calling `seal_get_transient_storage` with the specified size in storage. + GetTransientStorage(u32), + /// Weight of calling `seal_take_transient_storage` for the given size. + TakeTransientStorage(u32), + /// Weight of calling `seal_transfer`. + Transfer, + /// Base weight of calling `seal_call`. + CallBase, + /// Weight of calling `seal_delegate_call` for the given input size. + DelegateCallBase, + /// Weight of the transfer performed during a call. + CallTransferSurcharge, + /// Weight per byte that is cloned by supplying the `CLONE_INPUT` flag. + CallInputCloned(u32), + /// Weight of calling `seal_instantiate` for the given input length and salt. + Instantiate { input_data_len: u32, salt_len: u32 }, + /// Weight of calling `seal_hash_sha_256` for the given input size. + HashSha256(u32), + /// Weight of calling `seal_hash_keccak_256` for the given input size. + HashKeccak256(u32), + /// Weight of calling `seal_hash_blake2_256` for the given input size. + HashBlake256(u32), + /// Weight of calling `seal_hash_blake2_128` for the given input size. + HashBlake128(u32), + /// Weight of calling `seal_ecdsa_recover`. + EcdsaRecovery, + /// Weight of calling `seal_sr25519_verify` for the given input size. + Sr25519Verify(u32), + /// Weight charged by a chain extension through `seal_call_chain_extension`. + ChainExtension(Weight), + /// Weight charged for calling into the runtime. + CallRuntime(Weight), + /// Weight charged for calling xcm_execute. + CallXcmExecute(Weight), + /// Weight of calling `seal_set_code_hash` + SetCodeHash, + /// Weight of calling `ecdsa_to_eth_address` + EcdsaToEthAddress, + /// Weight of calling `reentrance_count` + ReentranceCount, + /// Weight of calling `account_reentrance_count` + AccountReentranceCount, + /// Weight of calling `instantiation_nonce` + InstantiationNonce, + /// Weight of calling `lock_delegate_dependency` + LockDelegateDependency, + /// Weight of calling `unlock_delegate_dependency` + UnlockDelegateDependency, +} + +/// For functions that modify storage, benchmarks are performed with one item in the +/// storage. To account for the worst-case scenario, the weight of the overhead of +/// writing to or reading from full storage is included. For transient storage writes, +/// the rollback weight is added to reflect the worst-case scenario for this operation. +macro_rules! cost_storage { + (write_transient, $name:ident $(, $arg:expr )*) => { + T::WeightInfo::$name($( $arg ),*) + .saturating_add(T::WeightInfo::rollback_transient_storage()) + .saturating_add(T::WeightInfo::set_transient_storage_full() + .saturating_sub(T::WeightInfo::set_transient_storage_empty())) + }; + + (read_transient, $name:ident $(, $arg:expr )*) => { + T::WeightInfo::$name($( $arg ),*) + .saturating_add(T::WeightInfo::get_transient_storage_full() + .saturating_sub(T::WeightInfo::get_transient_storage_empty())) + }; + + (write, $name:ident $(, $arg:expr )*) => { + T::WeightInfo::$name($( $arg ),*) + .saturating_add(T::WeightInfo::set_storage_full() + .saturating_sub(T::WeightInfo::set_storage_empty())) + }; + + (read, $name:ident $(, $arg:expr )*) => { + T::WeightInfo::$name($( $arg ),*) + .saturating_add(T::WeightInfo::get_storage_full() + .saturating_sub(T::WeightInfo::get_storage_empty())) + }; +} + +macro_rules! cost_args { + // cost_args!(name, a, b, c) -> T::WeightInfo::name(a, b, c).saturating_sub(T::WeightInfo::name(0, 0, 0)) + ($name:ident, $( $arg: expr ),+) => { + (T::WeightInfo::$name($( $arg ),+).saturating_sub(cost_args!(@call_zero $name, $( $arg ),+))) + }; + // Transform T::WeightInfo::name(a, b, c) into T::WeightInfo::name(0, 0, 0) + (@call_zero $name:ident, $( $arg:expr ),*) => { + T::WeightInfo::$name($( cost_args!(@replace_token $arg) ),*) + }; + // Replace the token with 0. + (@replace_token $_in:tt) => { 0 }; +} + +impl Token for RuntimeCosts { + fn influence_lowest_gas_limit(&self) -> bool { + match self { + &Self::CallXcmExecute(_) => false, + _ => true, + } + } + + fn weight(&self) -> Weight { + use self::RuntimeCosts::*; + match *self { + HostFn => cost_args!(noop_host_fn, 1), + CopyToContract(len) => T::WeightInfo::seal_input(len), + CopyFromContract(len) => T::WeightInfo::seal_return(len), + Caller => T::WeightInfo::seal_caller(), + IsContract => T::WeightInfo::seal_is_contract(), + CodeHash => T::WeightInfo::seal_code_hash(), + OwnCodeHash => T::WeightInfo::seal_own_code_hash(), + CallerIsOrigin => T::WeightInfo::seal_caller_is_origin(), + CallerIsRoot => T::WeightInfo::seal_caller_is_root(), + Address => T::WeightInfo::seal_address(), + GasLeft => T::WeightInfo::seal_gas_left(), + Balance => T::WeightInfo::seal_balance(), + ValueTransferred => T::WeightInfo::seal_value_transferred(), + MinimumBalance => T::WeightInfo::seal_minimum_balance(), + BlockNumber => T::WeightInfo::seal_block_number(), + Now => T::WeightInfo::seal_now(), + WeightToFee => T::WeightInfo::seal_weight_to_fee(), + Terminate(locked_dependencies) => T::WeightInfo::seal_terminate(locked_dependencies), + Random => T::WeightInfo::seal_random(), + // Given a 2-second block time and hardcoding a `ref_time` of 60,000 picoseconds per + // byte (event_ref_time), the max allocation size is 32MB per block. + DepositEvent { num_topic, len } => T::WeightInfo::seal_deposit_event(num_topic, len) + .saturating_add(Weight::from_parts( + T::Schedule::get().limits.event_ref_time.saturating_mul(len.into()), + 0, + )), + DebugMessage(len) => T::WeightInfo::seal_debug_message(len), + SetStorage { new_bytes, old_bytes } => + cost_storage!(write, seal_set_storage, new_bytes, old_bytes), + ClearStorage(len) => cost_storage!(write, seal_clear_storage, len), + ContainsStorage(len) => cost_storage!(read, seal_contains_storage, len), + GetStorage(len) => cost_storage!(read, seal_get_storage, len), + TakeStorage(len) => cost_storage!(write, seal_take_storage, len), + SetTransientStorage { new_bytes, old_bytes } => + cost_storage!(write_transient, seal_set_transient_storage, new_bytes, old_bytes), + ClearTransientStorage(len) => + cost_storage!(write_transient, seal_clear_transient_storage, len), + ContainsTransientStorage(len) => + cost_storage!(read_transient, seal_contains_transient_storage, len), + GetTransientStorage(len) => + cost_storage!(read_transient, seal_get_transient_storage, len), + TakeTransientStorage(len) => + cost_storage!(write_transient, seal_take_transient_storage, len), + Transfer => T::WeightInfo::seal_transfer(), + CallBase => T::WeightInfo::seal_call(0, 0), + DelegateCallBase => T::WeightInfo::seal_delegate_call(), + CallTransferSurcharge => cost_args!(seal_call, 1, 0), + CallInputCloned(len) => cost_args!(seal_call, 0, len), + Instantiate { input_data_len, salt_len } => + T::WeightInfo::seal_instantiate(input_data_len, salt_len), + HashSha256(len) => T::WeightInfo::seal_hash_sha2_256(len), + HashKeccak256(len) => T::WeightInfo::seal_hash_keccak_256(len), + HashBlake256(len) => T::WeightInfo::seal_hash_blake2_256(len), + HashBlake128(len) => T::WeightInfo::seal_hash_blake2_128(len), + EcdsaRecovery => T::WeightInfo::seal_ecdsa_recover(), + Sr25519Verify(len) => T::WeightInfo::seal_sr25519_verify(len), + ChainExtension(weight) | CallRuntime(weight) | CallXcmExecute(weight) => weight, + SetCodeHash => T::WeightInfo::seal_set_code_hash(), + EcdsaToEthAddress => T::WeightInfo::seal_ecdsa_to_eth_address(), + ReentranceCount => T::WeightInfo::seal_reentrance_count(), + AccountReentranceCount => T::WeightInfo::seal_account_reentrance_count(), + InstantiationNonce => T::WeightInfo::seal_instantiation_nonce(), + LockDelegateDependency => T::WeightInfo::lock_delegate_dependency(), + UnlockDelegateDependency => T::WeightInfo::unlock_delegate_dependency(), + } + } +} + +/// Same as [`Runtime::charge_gas`]. +/// +/// We need this access as a macro because sometimes hiding the lifetimes behind +/// a function won't work out. +macro_rules! charge_gas { + ($runtime:expr, $costs:expr) => {{ + $runtime.ext.gas_meter_mut().charge($costs) + }}; +} + +/// The kind of call that should be performed. +enum CallType { + /// Execute another instantiated contract + Call { callee_ptr: u32, value_ptr: u32, deposit_ptr: u32, weight: Weight }, + /// Execute deployed code in the context (storage, account ID, value) of the caller contract + DelegateCall { code_hash_ptr: u32 }, +} + +impl CallType { + fn cost(&self) -> RuntimeCosts { + match self { + CallType::Call { .. } => RuntimeCosts::CallBase, + CallType::DelegateCall { .. } => RuntimeCosts::DelegateCallBase, + } + } +} + +/// This is only appropriate when writing out data of constant size that does not depend on user +/// input. In this case the costs for this copy was already charged as part of the token at +/// the beginning of the API entry point. +fn already_charged(_: u32) -> Option { + None +} + +/// Can only be used for one call. +pub struct Runtime<'a, E: Ext + 'a> { + ext: &'a mut E, + input_data: Option>, + memory: Option, + chain_extension: Option::ChainExtension>>, +} + +impl<'a, E: Ext + 'a> Runtime<'a, E> { + pub fn new(ext: &'a mut E, input_data: Vec) -> Self { + Runtime { + ext, + input_data: Some(input_data), + memory: None, + chain_extension: Some(Box::new(Default::default())), + } + } + + pub fn memory(&self) -> Option { + self.memory + } + + pub fn set_memory(&mut self, memory: Memory) { + self.memory = Some(memory); + } + + /// Converts the sandbox result and the runtime state into the execution outcome. + pub fn to_execution_result(self, sandbox_result: Result<(), wasmi::Error>) -> ExecResult { + use wasmi::{ + core::TrapCode, + errors::{ErrorKind, FuelError}, + }; + use TrapReason::*; + + let Err(error) = sandbox_result else { + // Contract returned from main function -> no data was returned. + return Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() }) + }; + if let ErrorKind::Fuel(FuelError::OutOfFuel) = error.kind() { + // `OutOfGas` when host asks engine to consume more than left in the _store_. + // We should never get this case, as gas meter is being charged (and hence raises error) + // first. + return Err(Error::::OutOfGas.into()) + } + match error.as_trap_code() { + Some(TrapCode::OutOfFuel) => { + // `OutOfGas` during engine execution. + return Err(Error::::OutOfGas.into()) + }, + Some(_trap_code) => { + // Otherwise the trap came from the contract itself. + return Err(Error::::ContractTrapped.into()) + }, + None => {}, + } + // If we encoded a reason then it is some abort generated by a host function. + if let Some(reason) = &error.downcast_ref::() { + match &reason { + Return(ReturnData { flags, data }) => { + let flags = + ReturnFlags::from_bits(*flags).ok_or(Error::::InvalidCallFlags)?; + return Ok(ExecReturnValue { flags, data: data.to_vec() }) + }, + Termination => + return Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() }), + SupervisorError(error) => return Err((*error).into()), + } + } + + // Any other error is returned only if instantiation or linking failed (i.e. + // wasm binary tried to import a function that is not provided by the host). + // This shouldn't happen because validation process ought to reject such binaries. + // + // Because panics are really undesirable in the runtime code, we treat this as + // a trap for now. Eventually, we might want to revisit this. + log::debug!("Code rejected: {:?}", error); + Err(Error::::CodeRejected.into()) + } + + /// Get a mutable reference to the inner `Ext`. + /// + /// This is mainly for the chain extension to have access to the environment the + /// contract is executing in. + pub fn ext(&mut self) -> &mut E { + self.ext + } + + /// Charge the gas meter with the specified token. + /// + /// Returns `Err(HostError)` if there is not enough gas. + pub fn charge_gas(&mut self, costs: RuntimeCosts) -> Result { + charge_gas!(self, costs) + } + + /// Adjust a previously charged amount down to its actual amount. + /// + /// This is when a maximum a priori amount was charged and then should be partially + /// refunded to match the actual amount. + pub fn adjust_gas(&mut self, charged: ChargedAmount, actual_costs: RuntimeCosts) { + self.ext.gas_meter_mut().adjust_gas(charged, actual_costs); + } + + /// Charge, Run and adjust gas, for executing the given dispatchable. + fn call_dispatchable>( + &mut self, + dispatch_info: DispatchInfo, + runtime_cost: impl Fn(Weight) -> RuntimeCosts, + run: impl FnOnce(&mut Self) -> DispatchResultWithPostInfo, + ) -> Result { + use frame_support::dispatch::extract_actual_weight; + let charged = self.charge_gas(runtime_cost(dispatch_info.weight))?; + let result = run(self); + let actual_weight = extract_actual_weight(&result, &dispatch_info); + self.adjust_gas(charged, runtime_cost(actual_weight)); + match result { + Ok(_) => Ok(ReturnErrorCode::Success), + Err(e) => { + if self.ext.debug_buffer_enabled() { + self.ext.append_debug_buffer("call failed with: "); + self.ext.append_debug_buffer(e.into()); + }; + Ok(ErrorReturnCode::get()) + }, + } + } + + /// Read designated chunk from the sandbox memory. + /// + /// Returns `Err` if one of the following conditions occurs: + /// + /// - requested buffer is not within the bounds of the sandbox memory. + pub fn read_sandbox_memory( + &self, + memory: &[u8], + ptr: u32, + len: u32, + ) -> Result, DispatchError> { + ensure!(len <= self.ext.schedule().limits.max_memory_size(), Error::::OutOfBounds); + let mut buf = vec![0u8; len as usize]; + self.read_sandbox_memory_into_buf(memory, ptr, buf.as_mut_slice())?; + Ok(buf) + } + + /// Read designated chunk from the sandbox memory into the supplied buffer. + /// + /// Returns `Err` if one of the following conditions occurs: + /// + /// - requested buffer is not within the bounds of the sandbox memory. + pub fn read_sandbox_memory_into_buf( + &self, + memory: &[u8], + ptr: u32, + buf: &mut [u8], + ) -> Result<(), DispatchError> { + let ptr = ptr as usize; + let bound_checked = + memory.get(ptr..ptr + buf.len()).ok_or_else(|| Error::::OutOfBounds)?; + buf.copy_from_slice(bound_checked); + Ok(()) + } + + /// Reads and decodes a type with a size fixed at compile time from contract memory. + /// + /// # Note + /// + /// The weight of reading a fixed value is included in the overall weight of any + /// contract callable function. + pub fn read_sandbox_memory_as( + &self, + memory: &[u8], + ptr: u32, + ) -> Result { + let ptr = ptr as usize; + let mut bound_checked = memory.get(ptr..).ok_or_else(|| Error::::OutOfBounds)?; + + let decoded = D::decode_with_depth_limit(MAX_DECODE_NESTING, &mut bound_checked) + .map_err(|_| DispatchError::from(Error::::DecodingFailed))?; + Ok(decoded) + } + + /// Read designated chunk from the sandbox memory and attempt to decode into the specified type. + /// + /// Returns `Err` if one of the following conditions occurs: + /// + /// - requested buffer is not within the bounds of the sandbox memory. + /// - the buffer contents cannot be decoded as the required type. + /// + /// # Note + /// + /// There must be an extra benchmark for determining the influence of `len` with + /// regard to the overall weight. + pub fn read_sandbox_memory_as_unbounded( + &self, + memory: &[u8], + ptr: u32, + len: u32, + ) -> Result { + let ptr = ptr as usize; + let mut bound_checked = + memory.get(ptr..ptr + len as usize).ok_or_else(|| Error::::OutOfBounds)?; + + let decoded = D::decode_all_with_depth_limit(MAX_DECODE_NESTING, &mut bound_checked) + .map_err(|_| DispatchError::from(Error::::DecodingFailed))?; + + Ok(decoded) + } + + /// Write the given buffer and its length to the designated locations in sandbox memory and + /// charge gas according to the token returned by `create_token`. + // + /// `out_ptr` is the location in sandbox memory where `buf` should be written to. + /// `out_len_ptr` is an in-out location in sandbox memory. It is read to determine the + /// length of the buffer located at `out_ptr`. If that buffer is large enough the actual + /// `buf.len()` is written to this location. + /// + /// If `out_ptr` is set to the sentinel value of `SENTINEL` and `allow_skip` is true the + /// operation is skipped and `Ok` is returned. This is supposed to help callers to make copying + /// output optional. For example to skip copying back the output buffer of an `seal_call` + /// when the caller is not interested in the result. + /// + /// `create_token` can optionally instruct this function to charge the gas meter with the token + /// it returns. `create_token` receives the variable amount of bytes that are about to be copied + /// by this function. + /// + /// In addition to the error conditions of `write_sandbox_memory` this functions returns + /// `Err` if the size of the buffer located at `out_ptr` is too small to fit `buf`. + pub fn write_sandbox_output( + &mut self, + memory: &mut [u8], + out_ptr: u32, + out_len_ptr: u32, + buf: &[u8], + allow_skip: bool, + create_token: impl FnOnce(u32) -> Option, + ) -> Result<(), DispatchError> { + if allow_skip && out_ptr == SENTINEL { + return Ok(()) + } + + let buf_len = buf.len() as u32; + let len: u32 = self.read_sandbox_memory_as(memory, out_len_ptr)?; + + if len < buf_len { + return Err(Error::::OutputBufferTooSmall.into()) + } + + if let Some(costs) = create_token(buf_len) { + self.charge_gas(costs)?; + } + + self.write_sandbox_memory(memory, out_ptr, buf)?; + self.write_sandbox_memory(memory, out_len_ptr, &buf_len.encode()) + } + + /// Write the given buffer to the designated location in the sandbox memory. + /// + /// Returns `Err` if one of the following conditions occurs: + /// + /// - designated area is not within the bounds of the sandbox memory. + fn write_sandbox_memory( + &self, + memory: &mut [u8], + ptr: u32, + buf: &[u8], + ) -> Result<(), DispatchError> { + let ptr = ptr as usize; + let bound_checked = + memory.get_mut(ptr..ptr + buf.len()).ok_or_else(|| Error::::OutOfBounds)?; + bound_checked.copy_from_slice(buf); + Ok(()) + } + + /// Computes the given hash function on the supplied input. + /// + /// Reads from the sandboxed input buffer into an intermediate buffer. + /// Returns the result directly to the output buffer of the sandboxed memory. + /// + /// It is the callers responsibility to provide an output buffer that + /// is large enough to hold the expected amount of bytes returned by the + /// chosen hash function. + /// + /// # Note + /// + /// The `input` and `output` buffers may overlap. + fn compute_hash_on_intermediate_buffer( + &self, + memory: &mut [u8], + hash_fn: F, + input_ptr: u32, + input_len: u32, + output_ptr: u32, + ) -> Result<(), DispatchError> + where + F: FnOnce(&[u8]) -> R, + R: AsRef<[u8]>, + { + // Copy input into supervisor memory. + let input = self.read_sandbox_memory(memory, input_ptr, input_len)?; + // Compute the hash on the input buffer using the given hash function. + let hash = hash_fn(&input); + // Write the resulting hash back into the sandboxed output buffer. + self.write_sandbox_memory(memory, output_ptr, hash.as_ref())?; + Ok(()) + } + + /// Fallible conversion of `DispatchError` to `ReturnErrorCode`. + fn err_into_return_code(from: DispatchError) -> Result { + use ReturnErrorCode::*; + + let transfer_failed = Error::::TransferFailed.into(); + let no_code = Error::::CodeNotFound.into(); + let not_found = Error::::ContractNotFound.into(); + + match from { + x if x == transfer_failed => Ok(TransferFailed), + x if x == no_code => Ok(CodeNotFound), + x if x == not_found => Ok(NotCallable), + err => Err(err), + } + } + + /// Fallible conversion of a `ExecResult` to `ReturnErrorCode`. + fn exec_into_return_code(from: ExecResult) -> Result { + use crate::exec::ErrorOrigin::Callee; + + let ExecError { error, origin } = match from { + Ok(retval) => return Ok(retval.into()), + Err(err) => err, + }; + + match (error, origin) { + (_, Callee) => Ok(ReturnErrorCode::CalleeTrapped), + (err, _) => Self::err_into_return_code(err), + } + } + fn decode_key( + &self, + memory: &[u8], + key_type: KeyType, + key_ptr: u32, + ) -> Result, TrapReason> { + let res = match key_type { + KeyType::Fix => { + let key = self.read_sandbox_memory(memory, key_ptr, 32u32)?; + Key::try_from_fix(key) + }, + KeyType::Var(len) => { + ensure!( + len <= <::T as Config>::MaxStorageKeyLen::get(), + Error::::DecodingFailed + ); + let key = self.read_sandbox_memory(memory, key_ptr, len)?; + Key::try_from_var(key) + }, + }; + + res.map_err(|_| Error::::DecodingFailed.into()) + } + + fn set_storage( + &mut self, + memory: &[u8], + key_type: KeyType, + key_ptr: u32, + value_ptr: u32, + value_len: u32, + ) -> Result { + let max_size = self.ext.max_value_size(); + let charged = self + .charge_gas(RuntimeCosts::SetStorage { new_bytes: value_len, old_bytes: max_size })?; + if value_len > max_size { + return Err(Error::::ValueTooLarge.into()) + } + let key = self.decode_key(memory, key_type, key_ptr)?; + let value = Some(self.read_sandbox_memory(memory, value_ptr, value_len)?); + let write_outcome = self.ext.set_storage(&key, value, false)?; + + self.adjust_gas( + charged, + RuntimeCosts::SetStorage { new_bytes: value_len, old_bytes: write_outcome.old_len() }, + ); + Ok(write_outcome.old_len_with_sentinel()) + } + + fn clear_storage( + &mut self, + memory: &[u8], + key_type: KeyType, + key_ptr: u32, + ) -> Result { + let charged = self.charge_gas(RuntimeCosts::ClearStorage(self.ext.max_value_size()))?; + let key = self.decode_key(memory, key_type, key_ptr)?; + let outcome = self.ext.set_storage(&key, None, false)?; + + self.adjust_gas(charged, RuntimeCosts::ClearStorage(outcome.old_len())); + Ok(outcome.old_len_with_sentinel()) + } + + fn get_storage( + &mut self, + memory: &mut [u8], + key_type: KeyType, + key_ptr: u32, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result { + let charged = self.charge_gas(RuntimeCosts::GetStorage(self.ext.max_value_size()))?; + let key = self.decode_key(memory, key_type, key_ptr)?; + let outcome = self.ext.get_storage(&key); + + if let Some(value) = outcome { + self.adjust_gas(charged, RuntimeCosts::GetStorage(value.len() as u32)); + self.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &value, + false, + already_charged, + )?; + Ok(ReturnErrorCode::Success) + } else { + self.adjust_gas(charged, RuntimeCosts::GetStorage(0)); + Ok(ReturnErrorCode::KeyNotFound) + } + } + + fn contains_storage( + &mut self, + memory: &[u8], + key_type: KeyType, + key_ptr: u32, + ) -> Result { + let charged = self.charge_gas(RuntimeCosts::ContainsStorage(self.ext.max_value_size()))?; + let key = self.decode_key(memory, key_type, key_ptr)?; + let outcome = self.ext.get_storage_size(&key); + + self.adjust_gas(charged, RuntimeCosts::ContainsStorage(outcome.unwrap_or(0))); + Ok(outcome.unwrap_or(SENTINEL)) + } + + fn set_transient_storage( + &mut self, + memory: &[u8], + key_type: KeyType, + key_ptr: u32, + value_ptr: u32, + value_len: u32, + ) -> Result { + let max_size = self.ext.max_value_size(); + let charged = self.charge_gas(RuntimeCosts::SetTransientStorage { + new_bytes: value_len, + old_bytes: max_size, + })?; + if value_len > max_size { + return Err(Error::::ValueTooLarge.into()) + } + let key = self.decode_key(memory, key_type, key_ptr)?; + let value = Some(self.read_sandbox_memory(memory, value_ptr, value_len)?); + let write_outcome = self.ext.set_transient_storage(&key, value, false)?; + self.adjust_gas( + charged, + RuntimeCosts::SetTransientStorage { + new_bytes: value_len, + old_bytes: write_outcome.old_len(), + }, + ); + Ok(write_outcome.old_len_with_sentinel()) + } + + fn clear_transient_storage( + &mut self, + memory: &[u8], + key_type: KeyType, + key_ptr: u32, + ) -> Result { + let charged = + self.charge_gas(RuntimeCosts::ClearTransientStorage(self.ext.max_value_size()))?; + let key = self.decode_key(memory, key_type, key_ptr)?; + let outcome = self.ext.set_transient_storage(&key, None, false)?; + + self.adjust_gas(charged, RuntimeCosts::ClearTransientStorage(outcome.old_len())); + Ok(outcome.old_len_with_sentinel()) + } + + fn get_transient_storage( + &mut self, + memory: &mut [u8], + key_type: KeyType, + key_ptr: u32, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result { + let charged = + self.charge_gas(RuntimeCosts::GetTransientStorage(self.ext.max_value_size()))?; + let key = self.decode_key(memory, key_type, key_ptr)?; + let outcome = self.ext.get_transient_storage(&key); + + if let Some(value) = outcome { + self.adjust_gas(charged, RuntimeCosts::GetTransientStorage(value.len() as u32)); + self.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &value, + false, + already_charged, + )?; + Ok(ReturnErrorCode::Success) + } else { + self.adjust_gas(charged, RuntimeCosts::GetTransientStorage(0)); + Ok(ReturnErrorCode::KeyNotFound) + } + } + + fn contains_transient_storage( + &mut self, + memory: &[u8], + key_type: KeyType, + key_ptr: u32, + ) -> Result { + let charged = + self.charge_gas(RuntimeCosts::ContainsTransientStorage(self.ext.max_value_size()))?; + let key = self.decode_key(memory, key_type, key_ptr)?; + let outcome = self.ext.get_transient_storage_size(&key); + + self.adjust_gas(charged, RuntimeCosts::ContainsTransientStorage(outcome.unwrap_or(0))); + Ok(outcome.unwrap_or(SENTINEL)) + } + + fn take_transient_storage( + &mut self, + memory: &mut [u8], + key_type: KeyType, + key_ptr: u32, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result { + let charged = + self.charge_gas(RuntimeCosts::TakeTransientStorage(self.ext.max_value_size()))?; + let key = self.decode_key(memory, key_type, key_ptr)?; + if let crate::storage::WriteOutcome::Taken(value) = + self.ext.set_transient_storage(&key, None, true)? + { + self.adjust_gas(charged, RuntimeCosts::TakeTransientStorage(value.len() as u32)); + self.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &value, + false, + already_charged, + )?; + Ok(ReturnErrorCode::Success) + } else { + self.adjust_gas(charged, RuntimeCosts::TakeTransientStorage(0)); + Ok(ReturnErrorCode::KeyNotFound) + } + } + + fn call( + &mut self, + memory: &mut [u8], + flags: CallFlags, + call_type: CallType, + input_data_ptr: u32, + input_data_len: u32, + output_ptr: u32, + output_len_ptr: u32, + ) -> Result { + self.charge_gas(call_type.cost())?; + + let input_data = if flags.contains(CallFlags::CLONE_INPUT) { + let input = self.input_data.as_ref().ok_or(Error::::InputForwarded)?; + charge_gas!(self, RuntimeCosts::CallInputCloned(input.len() as u32))?; + input.clone() + } else if flags.contains(CallFlags::FORWARD_INPUT) { + self.input_data.take().ok_or(Error::::InputForwarded)? + } else { + self.charge_gas(RuntimeCosts::CopyFromContract(input_data_len))?; + self.read_sandbox_memory(memory, input_data_ptr, input_data_len)? + }; + + let call_outcome = match call_type { + CallType::Call { callee_ptr, value_ptr, deposit_ptr, weight } => { + let callee: <::T as frame_system::Config>::AccountId = + self.read_sandbox_memory_as(memory, callee_ptr)?; + let deposit_limit: BalanceOf<::T> = if deposit_ptr == SENTINEL { + BalanceOf::<::T>::zero() + } else { + self.read_sandbox_memory_as(memory, deposit_ptr)? + }; + let read_only = flags.contains(CallFlags::READ_ONLY); + let value: BalanceOf<::T> = + self.read_sandbox_memory_as(memory, value_ptr)?; + if value > 0u32.into() { + // If the call value is non-zero and state change is not allowed, issue an + // error. + if read_only || self.ext.is_read_only() { + return Err(Error::::StateChangeDenied.into()); + } + self.charge_gas(RuntimeCosts::CallTransferSurcharge)?; + } + self.ext.call( + weight, + deposit_limit, + callee, + value, + input_data, + flags.contains(CallFlags::ALLOW_REENTRY), + read_only, + ) + }, + CallType::DelegateCall { code_hash_ptr } => { + if flags.intersects(CallFlags::ALLOW_REENTRY | CallFlags::READ_ONLY) { + return Err(Error::::InvalidCallFlags.into()) + } + let code_hash = self.read_sandbox_memory_as(memory, code_hash_ptr)?; + self.ext.delegate_call(code_hash, input_data) + }, + }; + + // `TAIL_CALL` only matters on an `OK` result. Otherwise the call stack comes to + // a halt anyways without anymore code being executed. + if flags.contains(CallFlags::TAIL_CALL) { + if let Ok(return_value) = call_outcome { + return Err(TrapReason::Return(ReturnData { + flags: return_value.flags.bits(), + data: return_value.data, + })) + } + } + + if let Ok(output) = &call_outcome { + self.write_sandbox_output( + memory, + output_ptr, + output_len_ptr, + &output.data, + true, + |len| Some(RuntimeCosts::CopyToContract(len)), + )?; + } + Ok(Runtime::::exec_into_return_code(call_outcome)?) + } + + fn instantiate( + &mut self, + memory: &mut [u8], + code_hash_ptr: u32, + weight: Weight, + deposit_ptr: u32, + value_ptr: u32, + input_data_ptr: u32, + input_data_len: u32, + address_ptr: u32, + address_len_ptr: u32, + output_ptr: u32, + output_len_ptr: u32, + salt_ptr: u32, + salt_len: u32, + ) -> Result { + self.charge_gas(RuntimeCosts::Instantiate { input_data_len, salt_len })?; + let deposit_limit: BalanceOf<::T> = if deposit_ptr == SENTINEL { + BalanceOf::<::T>::zero() + } else { + self.read_sandbox_memory_as(memory, deposit_ptr)? + }; + let value: BalanceOf<::T> = self.read_sandbox_memory_as(memory, value_ptr)?; + let code_hash: CodeHash<::T> = + self.read_sandbox_memory_as(memory, code_hash_ptr)?; + let input_data = self.read_sandbox_memory(memory, input_data_ptr, input_data_len)?; + let salt = self.read_sandbox_memory(memory, salt_ptr, salt_len)?; + let instantiate_outcome = + self.ext.instantiate(weight, deposit_limit, code_hash, value, input_data, &salt); + if let Ok((address, output)) = &instantiate_outcome { + if !output.flags.contains(ReturnFlags::REVERT) { + self.write_sandbox_output( + memory, + address_ptr, + address_len_ptr, + &address.encode(), + true, + already_charged, + )?; + } + self.write_sandbox_output( + memory, + output_ptr, + output_len_ptr, + &output.data, + true, + |len| Some(RuntimeCosts::CopyToContract(len)), + )?; + } + Ok(Runtime::::exec_into_return_code(instantiate_outcome.map(|(_, retval)| retval))?) + } + + fn terminate(&mut self, memory: &[u8], beneficiary_ptr: u32) -> Result<(), TrapReason> { + let count = self.ext.locked_delegate_dependencies_count() as _; + self.charge_gas(RuntimeCosts::Terminate(count))?; + + let beneficiary: <::T as frame_system::Config>::AccountId = + self.read_sandbox_memory_as(memory, beneficiary_ptr)?; + self.ext.terminate(&beneficiary)?; + Err(TrapReason::Termination) + } +} + +// This is the API exposed to contracts. +// +// # Note +// +// Any input that leads to a out of bound error (reading or writing) or failing to decode +// data passed to the supervisor will lead to a trap. This is not documented explicitly +// for every function. +#[define_env(doc)] +pub mod env { + + /// Noop function used to benchmark the time it takes to execute an empty function. + #[cfg(feature = "runtime-benchmarks")] + #[unstable] + fn noop(ctx: _, memory: _) -> Result<(), TrapReason> { + Ok(()) + } + + /// Set the value at the given key in the contract storage. + /// See [`pallet_contracts_uapi::HostFn::set_storage`] + #[prefixed_alias] + #[mutating] + fn set_storage( + ctx: _, + memory: _, + key_ptr: u32, + value_ptr: u32, + value_len: u32, + ) -> Result<(), TrapReason> { + ctx.set_storage(memory, KeyType::Fix, key_ptr, value_ptr, value_len).map(|_| ()) + } + + /// Set the value at the given key in the contract storage. + /// See [`pallet_contracts_uapi::HostFn::set_storage_v1`] + #[version(1)] + #[prefixed_alias] + #[mutating] + fn set_storage( + ctx: _, + memory: _, + key_ptr: u32, + value_ptr: u32, + value_len: u32, + ) -> Result { + ctx.set_storage(memory, KeyType::Fix, key_ptr, value_ptr, value_len) + } + + /// Set the value at the given key in the contract storage. + /// See [`pallet_contracts_uapi::HostFn::set_storage_v2`] + #[version(2)] + #[prefixed_alias] + #[mutating] + fn set_storage( + ctx: _, + memory: _, + key_ptr: u32, + key_len: u32, + value_ptr: u32, + value_len: u32, + ) -> Result { + ctx.set_storage(memory, KeyType::Var(key_len), key_ptr, value_ptr, value_len) + } + + /// Clear the value at the given key in the contract storage. + /// See [`pallet_contracts_uapi::HostFn::clear_storage`] + #[prefixed_alias] + #[mutating] + fn clear_storage(ctx: _, memory: _, key_ptr: u32) -> Result<(), TrapReason> { + ctx.clear_storage(memory, KeyType::Fix, key_ptr).map(|_| ()) + } + + /// Clear the value at the given key in the contract storage. + /// See [`pallet_contracts_uapi::HostFn::clear_storage_v1`] + #[version(1)] + #[prefixed_alias] + #[mutating] + fn clear_storage(ctx: _, memory: _, key_ptr: u32, key_len: u32) -> Result { + ctx.clear_storage(memory, KeyType::Var(key_len), key_ptr) + } + + /// Retrieve the value under the given key from storage. + /// See [`pallet_contracts_uapi::HostFn::get_storage`] + #[prefixed_alias] + fn get_storage( + ctx: _, + memory: _, + key_ptr: u32, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result { + ctx.get_storage(memory, KeyType::Fix, key_ptr, out_ptr, out_len_ptr) + } + + /// Retrieve the value under the given key from storage. + /// See [`pallet_contracts_uapi::HostFn::get_storage_v1`] + #[version(1)] + #[prefixed_alias] + fn get_storage( + ctx: _, + memory: _, + key_ptr: u32, + key_len: u32, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result { + ctx.get_storage(memory, KeyType::Var(key_len), key_ptr, out_ptr, out_len_ptr) + } + + /// Checks whether there is a value stored under the given key. + /// See [`pallet_contracts_uapi::HostFn::contains_storage`] + #[prefixed_alias] + fn contains_storage(ctx: _, memory: _, key_ptr: u32) -> Result { + ctx.contains_storage(memory, KeyType::Fix, key_ptr) + } + + /// Checks whether there is a value stored under the given key. + /// See [`pallet_contracts_uapi::HostFn::contains_storage_v1`] + #[version(1)] + #[prefixed_alias] + fn contains_storage(ctx: _, memory: _, key_ptr: u32, key_len: u32) -> Result { + ctx.contains_storage(memory, KeyType::Var(key_len), key_ptr) + } + + /// Retrieve and remove the value under the given key from storage. + /// See [`pallet_contracts_uapi::HostFn::take_storage`] + #[prefixed_alias] + #[mutating] + fn take_storage( + ctx: _, + memory: _, + key_ptr: u32, + key_len: u32, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result { + let charged = ctx.charge_gas(RuntimeCosts::TakeStorage(ctx.ext.max_value_size()))?; + ensure!( + key_len <= <::T as Config>::MaxStorageKeyLen::get(), + Error::::DecodingFailed + ); + let key = ctx.read_sandbox_memory(memory, key_ptr, key_len)?; + if let crate::storage::WriteOutcome::Taken(value) = ctx.ext.set_storage( + &Key::::try_from_var(key).map_err(|_| Error::::DecodingFailed)?, + None, + true, + )? { + ctx.adjust_gas(charged, RuntimeCosts::TakeStorage(value.len() as u32)); + ctx.write_sandbox_output(memory, out_ptr, out_len_ptr, &value, false, already_charged)?; + Ok(ReturnErrorCode::Success) + } else { + ctx.adjust_gas(charged, RuntimeCosts::TakeStorage(0)); + Ok(ReturnErrorCode::KeyNotFound) + } + } + + /// Set the value at the given key in the contract transient storage. + #[unstable] + fn set_transient_storage( + ctx: _, + memory: _, + key_ptr: u32, + key_len: u32, + value_ptr: u32, + value_len: u32, + ) -> Result { + ctx.set_transient_storage(memory, KeyType::Var(key_len), key_ptr, value_ptr, value_len) + } + + /// Clear the value at the given key in the contract storage. + #[unstable] + fn clear_transient_storage( + ctx: _, + memory: _, + key_ptr: u32, + key_len: u32, + ) -> Result { + ctx.clear_transient_storage(memory, KeyType::Var(key_len), key_ptr) + } + + /// Retrieve the value under the given key from transient storage. + #[unstable] + fn get_transient_storage( + ctx: _, + memory: _, + key_ptr: u32, + key_len: u32, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result { + ctx.get_transient_storage(memory, KeyType::Var(key_len), key_ptr, out_ptr, out_len_ptr) + } + + /// Checks whether there is a value stored under the given key in transient storage. + #[unstable] + fn contains_transient_storage( + ctx: _, + memory: _, + key_ptr: u32, + key_len: u32, + ) -> Result { + ctx.contains_transient_storage(memory, KeyType::Var(key_len), key_ptr) + } + + /// Retrieve and remove the value under the given key from transient storage. + #[unstable] + fn take_transient_storage( + ctx: _, + memory: _, + key_ptr: u32, + key_len: u32, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result { + ctx.take_transient_storage(memory, KeyType::Var(key_len), key_ptr, out_ptr, out_len_ptr) + } + + /// Transfer some value to another account. + /// See [`pallet_contracts_uapi::HostFn::transfer`]. + #[prefixed_alias] + #[mutating] + fn transfer( + ctx: _, + memory: _, + account_ptr: u32, + _account_len: u32, + value_ptr: u32, + _value_len: u32, + ) -> Result { + ctx.charge_gas(RuntimeCosts::Transfer)?; + let callee: <::T as frame_system::Config>::AccountId = + ctx.read_sandbox_memory_as(memory, account_ptr)?; + let value: BalanceOf<::T> = ctx.read_sandbox_memory_as(memory, value_ptr)?; + let result = ctx.ext.transfer(&callee, value); + match result { + Ok(()) => Ok(ReturnErrorCode::Success), + Err(err) => { + let code = Runtime::::err_into_return_code(err)?; + Ok(code) + }, + } + } + + /// Make a call to another contract. + /// + /// # Note + /// + /// The values `_callee_len` and `_value_len` are ignored because the encoded sizes of those + /// types are fixed through [`codec::MaxEncodedLen`]. The fields exist for backwards + /// compatibility. Consider switching to the newest version of this function. + #[prefixed_alias] + fn call( + ctx: _, + memory: _, + callee_ptr: u32, + _callee_len: u32, + gas: u64, + value_ptr: u32, + _value_len: u32, + input_data_ptr: u32, + input_data_len: u32, + output_ptr: u32, + output_len_ptr: u32, + ) -> Result { + ctx.call( + memory, + CallFlags::ALLOW_REENTRY, + CallType::Call { + callee_ptr, + value_ptr, + deposit_ptr: SENTINEL, + weight: Weight::from_parts(gas, 0), + }, + input_data_ptr, + input_data_len, + output_ptr, + output_len_ptr, + ) + } + + /// Make a call to another contract. + /// See [`pallet_contracts_uapi::HostFn::call_v1`]. + #[version(1)] + #[prefixed_alias] + fn call( + ctx: _, + memory: _, + flags: u32, + callee_ptr: u32, + gas: u64, + value_ptr: u32, + input_data_ptr: u32, + input_data_len: u32, + output_ptr: u32, + output_len_ptr: u32, + ) -> Result { + ctx.call( + memory, + CallFlags::from_bits(flags).ok_or(Error::::InvalidCallFlags)?, + CallType::Call { + callee_ptr, + value_ptr, + deposit_ptr: SENTINEL, + weight: Weight::from_parts(gas, 0), + }, + input_data_ptr, + input_data_len, + output_ptr, + output_len_ptr, + ) + } + + /// Make a call to another contract. + /// See [`pallet_contracts_uapi::HostFn::call_v2`]. + #[version(2)] + fn call( + ctx: _, + memory: _, + flags: u32, + callee_ptr: u32, + ref_time_limit: u64, + proof_size_limit: u64, + deposit_ptr: u32, + value_ptr: u32, + input_data_ptr: u32, + input_data_len: u32, + output_ptr: u32, + output_len_ptr: u32, + ) -> Result { + ctx.call( + memory, + CallFlags::from_bits(flags).ok_or(Error::::InvalidCallFlags)?, + CallType::Call { + callee_ptr, + value_ptr, + deposit_ptr, + weight: Weight::from_parts(ref_time_limit, proof_size_limit), + }, + input_data_ptr, + input_data_len, + output_ptr, + output_len_ptr, + ) + } + + /// Execute code in the context (storage, caller, value) of the current contract. + /// See [`pallet_contracts_uapi::HostFn::delegate_call`]. + #[prefixed_alias] + fn delegate_call( + ctx: _, + memory: _, + flags: u32, + code_hash_ptr: u32, + input_data_ptr: u32, + input_data_len: u32, + output_ptr: u32, + output_len_ptr: u32, + ) -> Result { + ctx.call( + memory, + CallFlags::from_bits(flags).ok_or(Error::::InvalidCallFlags)?, + CallType::DelegateCall { code_hash_ptr }, + input_data_ptr, + input_data_len, + output_ptr, + output_len_ptr, + ) + } + + /// Instantiate a contract with the specified code hash. + /// See [`pallet_contracts_uapi::HostFn::instantiate`]. + /// + /// # Note + /// + /// The values `_code_hash_len` and `_value_len` are ignored because the encoded sizes + /// of those types are fixed through [`codec::MaxEncodedLen`]. The fields exist + /// for backwards compatibility. Consider switching to the newest version of this function. + #[prefixed_alias] + #[mutating] + fn instantiate( + ctx: _, + memory: _, + code_hash_ptr: u32, + _code_hash_len: u32, + gas: u64, + value_ptr: u32, + _value_len: u32, + input_data_ptr: u32, + input_data_len: u32, + address_ptr: u32, + address_len_ptr: u32, + output_ptr: u32, + output_len_ptr: u32, + salt_ptr: u32, + salt_len: u32, + ) -> Result { + ctx.instantiate( + memory, + code_hash_ptr, + Weight::from_parts(gas, 0), + SENTINEL, + value_ptr, + input_data_ptr, + input_data_len, + address_ptr, + address_len_ptr, + output_ptr, + output_len_ptr, + salt_ptr, + salt_len, + ) + } + + /// Instantiate a contract with the specified code hash. + /// See [`pallet_contracts_uapi::HostFn::instantiate_v1`]. + #[version(1)] + #[prefixed_alias] + #[mutating] + fn instantiate( + ctx: _, + memory: _, + code_hash_ptr: u32, + gas: u64, + value_ptr: u32, + input_data_ptr: u32, + input_data_len: u32, + address_ptr: u32, + address_len_ptr: u32, + output_ptr: u32, + output_len_ptr: u32, + salt_ptr: u32, + salt_len: u32, + ) -> Result { + ctx.instantiate( + memory, + code_hash_ptr, + Weight::from_parts(gas, 0), + SENTINEL, + value_ptr, + input_data_ptr, + input_data_len, + address_ptr, + address_len_ptr, + output_ptr, + output_len_ptr, + salt_ptr, + salt_len, + ) + } + + /// Instantiate a contract with the specified code hash. + /// See [`pallet_contracts_uapi::HostFn::instantiate_v2`]. + #[version(2)] + #[mutating] + fn instantiate( + ctx: _, + memory: _, + code_hash_ptr: u32, + ref_time_limit: u64, + proof_size_limit: u64, + deposit_ptr: u32, + value_ptr: u32, + input_data_ptr: u32, + input_data_len: u32, + address_ptr: u32, + address_len_ptr: u32, + output_ptr: u32, + output_len_ptr: u32, + salt_ptr: u32, + salt_len: u32, + ) -> Result { + ctx.instantiate( + memory, + code_hash_ptr, + Weight::from_parts(ref_time_limit, proof_size_limit), + deposit_ptr, + value_ptr, + input_data_ptr, + input_data_len, + address_ptr, + address_len_ptr, + output_ptr, + output_len_ptr, + salt_ptr, + salt_len, + ) + } + + /// Remove the calling account and transfer remaining balance. + /// See [`pallet_contracts_uapi::HostFn::terminate`]. + /// + /// # Note + /// + /// The value `_beneficiary_len` is ignored because the encoded sizes + /// this type is fixed through `[`MaxEncodedLen`]. The field exist for backwards + /// compatibility. Consider switching to the newest version of this function. + #[prefixed_alias] + #[mutating] + fn terminate( + ctx: _, + memory: _, + beneficiary_ptr: u32, + _beneficiary_len: u32, + ) -> Result<(), TrapReason> { + ctx.terminate(memory, beneficiary_ptr) + } + + /// Remove the calling account and transfer remaining **free** balance. + /// See [`pallet_contracts_uapi::HostFn::terminate_v1`]. + #[version(1)] + #[prefixed_alias] + #[mutating] + fn terminate(ctx: _, memory: _, beneficiary_ptr: u32) -> Result<(), TrapReason> { + ctx.terminate(memory, beneficiary_ptr) + } + + /// Stores the input passed by the caller into the supplied buffer. + /// See [`pallet_contracts_uapi::HostFn::input`]. + #[prefixed_alias] + fn input(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { + if let Some(input) = ctx.input_data.take() { + ctx.write_sandbox_output(memory, out_ptr, out_len_ptr, &input, false, |len| { + Some(RuntimeCosts::CopyToContract(len)) + })?; + ctx.input_data = Some(input); + Ok(()) + } else { + Err(Error::::InputForwarded.into()) + } + } + + /// Cease contract execution and save a data buffer as a result of the execution. + /// See [`pallet_contracts_uapi::HostFn::return_value`]. + fn seal_return( + ctx: _, + memory: _, + flags: u32, + data_ptr: u32, + data_len: u32, + ) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::CopyFromContract(data_len))?; + Err(TrapReason::Return(ReturnData { + flags, + data: ctx.read_sandbox_memory(memory, data_ptr, data_len)?, + })) + } + + /// Stores the address of the caller into the supplied buffer. + /// See [`pallet_contracts_uapi::HostFn::caller`]. + #[prefixed_alias] + fn caller(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::Caller)?; + let caller = ctx.ext.caller().account_id()?.clone(); + Ok(ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &caller.encode(), + false, + already_charged, + )?) + } + + /// Checks whether a specified address belongs to a contract. + /// See [`pallet_contracts_uapi::HostFn::is_contract`]. + #[prefixed_alias] + fn is_contract(ctx: _, memory: _, account_ptr: u32) -> Result { + ctx.charge_gas(RuntimeCosts::IsContract)?; + let address: <::T as frame_system::Config>::AccountId = + ctx.read_sandbox_memory_as(memory, account_ptr)?; + + Ok(ctx.ext.is_contract(&address) as u32) + } + + /// Retrieve the code hash for a specified contract address. + /// See [`pallet_contracts_uapi::HostFn::code_hash`]. + #[prefixed_alias] + fn code_hash( + ctx: _, + memory: _, + account_ptr: u32, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result { + ctx.charge_gas(RuntimeCosts::CodeHash)?; + let address: <::T as frame_system::Config>::AccountId = + ctx.read_sandbox_memory_as(memory, account_ptr)?; + if let Some(value) = ctx.ext.code_hash(&address) { + ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &value.encode(), + false, + already_charged, + )?; + Ok(ReturnErrorCode::Success) + } else { + Ok(ReturnErrorCode::KeyNotFound) + } + } + + /// Retrieve the code hash of the currently executing contract. + /// See [`pallet_contracts_uapi::HostFn::own_code_hash`]. + #[prefixed_alias] + fn own_code_hash(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::OwnCodeHash)?; + let code_hash_encoded = &ctx.ext.own_code_hash().encode(); + Ok(ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + code_hash_encoded, + false, + already_charged, + )?) + } + + /// Checks whether the caller of the current contract is the origin of the whole call stack. + /// See [`pallet_contracts_uapi::HostFn::caller_is_origin`]. + #[prefixed_alias] + fn caller_is_origin(ctx: _, _memory: _) -> Result { + ctx.charge_gas(RuntimeCosts::CallerIsOrigin)?; + Ok(ctx.ext.caller_is_origin() as u32) + } + + /// Checks whether the caller of the current contract is root. + /// See [`pallet_contracts_uapi::HostFn::caller_is_root`]. + fn caller_is_root(ctx: _, _memory: _) -> Result { + ctx.charge_gas(RuntimeCosts::CallerIsRoot)?; + Ok(ctx.ext.caller_is_root() as u32) + } + + /// Stores the address of the current contract into the supplied buffer. + /// See [`pallet_contracts_uapi::HostFn::address`]. + #[prefixed_alias] + fn address(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::Address)?; + Ok(ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &ctx.ext.address().encode(), + false, + already_charged, + )?) + } + + /// Stores the price for the specified amount of gas into the supplied buffer. + /// See [`pallet_contracts_uapi::HostFn::weight_to_fee`]. + #[prefixed_alias] + fn weight_to_fee( + ctx: _, + memory: _, + gas: u64, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result<(), TrapReason> { + let gas = Weight::from_parts(gas, 0); + ctx.charge_gas(RuntimeCosts::WeightToFee)?; + Ok(ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &ctx.ext.get_weight_price(gas).encode(), + false, + already_charged, + )?) + } + + /// Stores the price for the specified amount of weight into the supplied buffer. + /// See [`pallet_contracts_uapi::HostFn::weight_to_fee_v1`]. + #[version(1)] + #[unstable] + fn weight_to_fee( + ctx: _, + memory: _, + ref_time_limit: u64, + proof_size_limit: u64, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result<(), TrapReason> { + let weight = Weight::from_parts(ref_time_limit, proof_size_limit); + ctx.charge_gas(RuntimeCosts::WeightToFee)?; + Ok(ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &ctx.ext.get_weight_price(weight).encode(), + false, + already_charged, + )?) + } + + /// Stores the weight left into the supplied buffer. + /// See [`pallet_contracts_uapi::HostFn::gas_left`]. + #[prefixed_alias] + fn gas_left(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::GasLeft)?; + let gas_left = &ctx.ext.gas_meter().gas_left().ref_time().encode(); + Ok(ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + gas_left, + false, + already_charged, + )?) + } + + /// Stores the amount of weight left into the supplied buffer. + /// See [`pallet_contracts_uapi::HostFn::gas_left_v1`]. + #[version(1)] + #[unstable] + fn gas_left(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::GasLeft)?; + let gas_left = &ctx.ext.gas_meter().gas_left().encode(); + Ok(ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + gas_left, + false, + already_charged, + )?) + } + + /// Stores the *free* balance of the current account into the supplied buffer. + /// See [`pallet_contracts_uapi::HostFn::balance`]. + #[prefixed_alias] + fn balance(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::Balance)?; + Ok(ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &ctx.ext.balance().encode(), + false, + already_charged, + )?) + } + + /// Stores the value transferred along with this call/instantiate into the supplied buffer. + /// See [`pallet_contracts_uapi::HostFn::value_transferred`]. + #[prefixed_alias] + fn value_transferred( + ctx: _, + memory: _, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::ValueTransferred)?; + Ok(ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &ctx.ext.value_transferred().encode(), + false, + already_charged, + )?) + } + + /// Stores a random number for the current block and the given subject into the supplied buffer. + /// + /// The value is stored to linear memory at the address pointed to by `out_ptr`. + /// `out_len_ptr` must point to a u32 value that describes the available space at + /// `out_ptr`. This call overwrites it with the size of the value. If the available + /// space at `out_ptr` is less than the size of the value a trap is triggered. + /// + /// The data is encoded as `T::Hash`. + #[prefixed_alias] + #[deprecated] + fn random( + ctx: _, + memory: _, + subject_ptr: u32, + subject_len: u32, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::Random)?; + if subject_len > ctx.ext.schedule().limits.subject_len { + return Err(Error::::RandomSubjectTooLong.into()) + } + let subject_buf = ctx.read_sandbox_memory(memory, subject_ptr, subject_len)?; + Ok(ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &ctx.ext.random(&subject_buf).0.encode(), + false, + already_charged, + )?) + } + + /// Stores a random number for the current block and the given subject into the supplied buffer. + /// + /// The value is stored to linear memory at the address pointed to by `out_ptr`. + /// `out_len_ptr` must point to a u32 value that describes the available space at + /// `out_ptr`. This call overwrites it with the size of the value. If the available + /// space at `out_ptr` is less than the size of the value a trap is triggered. + /// + /// The data is encoded as (T::Hash, frame_system::pallet_prelude::BlockNumberFor::). + /// + /// # Changes from v0 + /// + /// In addition to the seed it returns the block number since which it was determinable + /// by chain observers. + /// + /// # Note + /// + /// The returned seed should only be used to distinguish commitments made before + /// the returned block number. If the block number is too early (i.e. commitments were + /// made afterwards), then ensure no further commitments may be made and repeatedly + /// call this on later blocks until the block number returned is later than the latest + /// commitment. + #[version(1)] + #[prefixed_alias] + #[deprecated] + fn random( + ctx: _, + memory: _, + subject_ptr: u32, + subject_len: u32, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::Random)?; + if subject_len > ctx.ext.schedule().limits.subject_len { + return Err(Error::::RandomSubjectTooLong.into()) + } + let subject_buf = ctx.read_sandbox_memory(memory, subject_ptr, subject_len)?; + Ok(ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &ctx.ext.random(&subject_buf).encode(), + false, + already_charged, + )?) + } + + /// Load the latest block timestamp into the supplied buffer + /// See [`pallet_contracts_uapi::HostFn::now`]. + #[prefixed_alias] + fn now(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::Now)?; + Ok(ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &ctx.ext.now().encode(), + false, + already_charged, + )?) + } + + /// Stores the minimum balance (a.k.a. existential deposit) into the supplied buffer. + /// See [`pallet_contracts_uapi::HostFn::minimum_balance`]. + #[prefixed_alias] + fn minimum_balance( + ctx: _, + memory: _, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::MinimumBalance)?; + Ok(ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &ctx.ext.minimum_balance().encode(), + false, + already_charged, + )?) + } + + /// Stores the tombstone deposit into the supplied buffer. + /// + /// The value is stored to linear memory at the address pointed to by `out_ptr`. + /// `out_len_ptr` must point to a u32 value that describes the available space at + /// `out_ptr`. This call overwrites it with the size of the value. If the available + /// space at `out_ptr` is less than the size of the value a trap is triggered. + /// + /// # Note + /// + /// There is no longer a tombstone deposit. This function always returns `0`. + #[prefixed_alias] + #[deprecated] + fn tombstone_deposit( + ctx: _, + memory: _, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::Balance)?; + let deposit = >::zero().encode(); + Ok(ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &deposit, + false, + already_charged, + )?) + } + + /// Was used to restore the given destination contract sacrificing the caller. + /// + /// # Note + /// + /// The state rent functionality was removed. This is stub only exists for + /// backwards compatibility + #[prefixed_alias] + #[deprecated] + fn restore_to( + ctx: _, + memory: _, + _dest_ptr: u32, + _dest_len: u32, + _code_hash_ptr: u32, + _code_hash_len: u32, + _rent_allowance_ptr: u32, + _rent_allowance_len: u32, + _delta_ptr: u32, + _delta_count: u32, + ) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::DebugMessage(0))?; + Ok(()) + } + + /// Was used to restore the given destination contract sacrificing the caller. + /// + /// # Note + /// + /// The state rent functionality was removed. This is stub only exists for + /// backwards compatibility + #[version(1)] + #[prefixed_alias] + #[deprecated] + fn restore_to( + ctx: _, + memory: _, + _dest_ptr: u32, + _code_hash_ptr: u32, + _rent_allowance_ptr: u32, + _delta_ptr: u32, + _delta_count: u32, + ) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::DebugMessage(0))?; + Ok(()) + } + + /// Was used to set rent allowance of the contract. + /// + /// # Note + /// + /// The state rent functionality was removed. This is stub only exists for + /// backwards compatibility. + #[prefixed_alias] + #[deprecated] + fn set_rent_allowance( + ctx: _, + memory: _, + _value_ptr: u32, + _value_len: u32, + ) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::DebugMessage(0))?; + Ok(()) + } + + /// Was used to set rent allowance of the contract. + /// + /// # Note + /// + /// The state rent functionality was removed. This is stub only exists for + /// backwards compatibility. + #[version(1)] + #[prefixed_alias] + #[deprecated] + fn set_rent_allowance(ctx: _, _memory: _, _value_ptr: u32) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::DebugMessage(0))?; + Ok(()) + } + + /// Was used to store the rent allowance into the supplied buffer. + /// + /// # Note + /// + /// The state rent functionality was removed. This is stub only exists for + /// backwards compatibility. + #[prefixed_alias] + #[deprecated] + fn rent_allowance(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::Balance)?; + let rent_allowance = >::max_value().encode(); + Ok(ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &rent_allowance, + false, + already_charged, + )?) + } + + /// Deposit a contract event with the data buffer and optional list of topics. + /// See [pallet_contracts_uapi::HostFn::deposit_event] + #[prefixed_alias] + #[mutating] + fn deposit_event( + ctx: _, + memory: _, + topics_ptr: u32, + topics_len: u32, + data_ptr: u32, + data_len: u32, + ) -> Result<(), TrapReason> { + let num_topic = topics_len + .checked_div(core::mem::size_of::>() as u32) + .ok_or("Zero sized topics are not allowed")?; + ctx.charge_gas(RuntimeCosts::DepositEvent { num_topic, len: data_len })?; + if data_len > ctx.ext.max_value_size() { + return Err(Error::::ValueTooLarge.into()) + } + + let topics: Vec::T>> = match topics_len { + 0 => Vec::new(), + _ => ctx.read_sandbox_memory_as_unbounded(memory, topics_ptr, topics_len)?, + }; + + // If there are more than `event_topics`, then trap. + if topics.len() > ctx.ext.schedule().limits.event_topics as usize { + return Err(Error::::TooManyTopics.into()) + } + + let event_data = ctx.read_sandbox_memory(memory, data_ptr, data_len)?; + + ctx.ext.deposit_event(topics, event_data); + + Ok(()) + } + + /// Stores the current block number of the current contract into the supplied buffer. + /// See [`pallet_contracts_uapi::HostFn::block_number`]. + #[prefixed_alias] + fn block_number(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::BlockNumber)?; + Ok(ctx.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &ctx.ext.block_number().encode(), + false, + already_charged, + )?) + } + + /// Computes the SHA2 256-bit hash on the given input buffer. + /// See [`pallet_contracts_uapi::HostFn::hash_sha2_256`]. + #[prefixed_alias] + fn hash_sha2_256( + ctx: _, + memory: _, + input_ptr: u32, + input_len: u32, + output_ptr: u32, + ) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::HashSha256(input_len))?; + Ok(ctx.compute_hash_on_intermediate_buffer( + memory, sha2_256, input_ptr, input_len, output_ptr, + )?) + } + + /// Computes the KECCAK 256-bit hash on the given input buffer. + /// See [`pallet_contracts_uapi::HostFn::hash_keccak_256`]. + #[prefixed_alias] + fn hash_keccak_256( + ctx: _, + memory: _, + input_ptr: u32, + input_len: u32, + output_ptr: u32, + ) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::HashKeccak256(input_len))?; + Ok(ctx.compute_hash_on_intermediate_buffer( + memory, keccak_256, input_ptr, input_len, output_ptr, + )?) + } + + /// Computes the BLAKE2 256-bit hash on the given input buffer. + /// See [`pallet_contracts_uapi::HostFn::hash_blake2_256`]. + #[prefixed_alias] + fn hash_blake2_256( + ctx: _, + memory: _, + input_ptr: u32, + input_len: u32, + output_ptr: u32, + ) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::HashBlake256(input_len))?; + Ok(ctx.compute_hash_on_intermediate_buffer( + memory, blake2_256, input_ptr, input_len, output_ptr, + )?) + } + + /// Computes the BLAKE2 128-bit hash on the given input buffer. + /// See [`pallet_contracts_uapi::HostFn::hash_blake2_128`]. + #[prefixed_alias] + fn hash_blake2_128( + ctx: _, + memory: _, + input_ptr: u32, + input_len: u32, + output_ptr: u32, + ) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::HashBlake128(input_len))?; + Ok(ctx.compute_hash_on_intermediate_buffer( + memory, blake2_128, input_ptr, input_len, output_ptr, + )?) + } + + /// Call into the chain extension provided by the chain if any. + /// See [`pallet_contracts_uapi::HostFn::call_chain_extension`]. + #[prefixed_alias] + fn call_chain_extension( + ctx: _, + memory: _, + id: u32, + input_ptr: u32, + input_len: u32, + output_ptr: u32, + output_len_ptr: u32, + ) -> Result { + use crate::chain_extension::{ChainExtension, Environment, RetVal}; + if !::ChainExtension::enabled() { + return Err(Error::::NoChainExtension.into()) + } + let mut chain_extension = ctx.chain_extension.take().expect( + "Constructor initializes with `Some`. This is the only place where it is set to `None`.\ + It is always reset to `Some` afterwards. qed" + ); + let env = + Environment::new(ctx, memory, id, input_ptr, input_len, output_ptr, output_len_ptr); + let ret = match chain_extension.call(env)? { + RetVal::Converging(val) => Ok(val), + RetVal::Diverging { flags, data } => + Err(TrapReason::Return(ReturnData { flags: flags.bits(), data })), + }; + ctx.chain_extension = Some(chain_extension); + ret + } + + /// Emit a custom debug message. + /// + /// No newlines are added to the supplied message. + /// Specifying invalid UTF-8 just drops the message with no trap. + /// + /// This is a no-op if debug message recording is disabled which is always the case + /// when the code is executing on-chain. The message is interpreted as UTF-8 and + /// appended to the debug buffer which is then supplied to the calling RPC client. + /// + /// # Note + /// + /// Even though no action is taken when debug message recording is disabled there is still + /// a non trivial overhead (and weight cost) associated with calling this function. Contract + /// languages should remove calls to this function (either at runtime or compile time) when + /// not being executed as an RPC. For example, they could allow users to disable logging + /// through compile time flags (cargo features) for on-chain deployment. Additionally, the + /// return value of this function can be cached in order to prevent further calls at runtime. + #[prefixed_alias] + fn debug_message( + ctx: _, + memory: _, + str_ptr: u32, + str_len: u32, + ) -> Result { + let str_len = str_len.min(DebugBufferVec::::bound() as u32); + ctx.charge_gas(RuntimeCosts::DebugMessage(str_len))?; + if ctx.ext.append_debug_buffer("") { + let data = ctx.read_sandbox_memory(memory, str_ptr, str_len)?; + if let Some(msg) = core::str::from_utf8(&data).ok() { + ctx.ext.append_debug_buffer(msg); + } + } + Ok(ReturnErrorCode::Success) + } + + /// Call some dispatchable of the runtime. + /// See [`frame_support::traits::call_runtime`]. + #[mutating] + fn call_runtime( + ctx: _, + memory: _, + call_ptr: u32, + call_len: u32, + ) -> Result { + use frame_support::dispatch::GetDispatchInfo; + ctx.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; + let call: ::RuntimeCall = + ctx.read_sandbox_memory_as_unbounded(memory, call_ptr, call_len)?; + ctx.call_dispatchable::( + call.get_dispatch_info(), + RuntimeCosts::CallRuntime, + |ctx| ctx.ext.call_runtime(call), + ) + } + + /// Execute an XCM program locally, using the contract's address as the origin. + /// See [`pallet_contracts_uapi::HostFn::execute_xcm`]. + #[mutating] + fn xcm_execute( + ctx: _, + memory: _, + msg_ptr: u32, + msg_len: u32, + ) -> Result { + use frame_support::dispatch::DispatchInfo; + use xcm::VersionedXcm; + use xcm_builder::{ExecuteController, ExecuteControllerWeightInfo}; + + ctx.charge_gas(RuntimeCosts::CopyFromContract(msg_len))?; + let message: VersionedXcm> = + ctx.read_sandbox_memory_as_unbounded(memory, msg_ptr, msg_len)?; + + let execute_weight = + <::Xcm as ExecuteController<_, _>>::WeightInfo::execute(); + let weight = ctx.ext.gas_meter().gas_left().max(execute_weight); + let dispatch_info = DispatchInfo { weight, ..Default::default() }; + + ctx.call_dispatchable::( + dispatch_info, + RuntimeCosts::CallXcmExecute, + |ctx| { + let origin = crate::RawOrigin::Signed(ctx.ext.address().clone()).into(); + let weight_used = <::Xcm>::execute( + origin, + Box::new(message), + weight.saturating_sub(execute_weight), + )?; + + Ok(Some(weight_used.saturating_add(execute_weight)).into()) + }, + ) + } + + /// Send an XCM program from the contract to the specified destination. + /// See [`pallet_contracts_uapi::HostFn::send_xcm`]. + #[mutating] + fn xcm_send( + ctx: _, + memory: _, + dest_ptr: u32, + msg_ptr: u32, + msg_len: u32, + output_ptr: u32, + ) -> Result { + use xcm::{VersionedLocation, VersionedXcm}; + use xcm_builder::{SendController, SendControllerWeightInfo}; + + ctx.charge_gas(RuntimeCosts::CopyFromContract(msg_len))?; + let dest: VersionedLocation = ctx.read_sandbox_memory_as(memory, dest_ptr)?; + + let message: VersionedXcm<()> = + ctx.read_sandbox_memory_as_unbounded(memory, msg_ptr, msg_len)?; + let weight = <::Xcm as SendController<_>>::WeightInfo::send(); + ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; + let origin = crate::RawOrigin::Signed(ctx.ext.address().clone()).into(); + + match <::Xcm>::send(origin, dest.into(), message.into()) { + Ok(message_id) => { + ctx.write_sandbox_memory(memory, output_ptr, &message_id.encode())?; + Ok(ReturnErrorCode::Success) + }, + Err(e) => { + if ctx.ext.append_debug_buffer("") { + ctx.ext.append_debug_buffer("seal0::xcm_send failed with: "); + ctx.ext.append_debug_buffer(e.into()); + }; + Ok(ReturnErrorCode::XcmSendFailed) + }, + } + } + + /// Recovers the ECDSA public key from the given message hash and signature. + /// See [`pallet_contracts_uapi::HostFn::ecdsa_recover`]. + #[prefixed_alias] + fn ecdsa_recover( + ctx: _, + memory: _, + signature_ptr: u32, + message_hash_ptr: u32, + output_ptr: u32, + ) -> Result { + ctx.charge_gas(RuntimeCosts::EcdsaRecovery)?; + + let mut signature: [u8; 65] = [0; 65]; + ctx.read_sandbox_memory_into_buf(memory, signature_ptr, &mut signature)?; + let mut message_hash: [u8; 32] = [0; 32]; + ctx.read_sandbox_memory_into_buf(memory, message_hash_ptr, &mut message_hash)?; + + let result = ctx.ext.ecdsa_recover(&signature, &message_hash); + + match result { + Ok(pub_key) => { + // Write the recovered compressed ecdsa public key back into the sandboxed output + // buffer. + ctx.write_sandbox_memory(memory, output_ptr, pub_key.as_ref())?; + + Ok(ReturnErrorCode::Success) + }, + Err(_) => Ok(ReturnErrorCode::EcdsaRecoveryFailed), + } + } + + /// Verify a sr25519 signature + /// See [`pallet_contracts_uapi::HostFn::sr25519_verify`]. + fn sr25519_verify( + ctx: _, + memory: _, + signature_ptr: u32, + pub_key_ptr: u32, + message_len: u32, + message_ptr: u32, + ) -> Result { + ctx.charge_gas(RuntimeCosts::Sr25519Verify(message_len))?; + + let mut signature: [u8; 64] = [0; 64]; + ctx.read_sandbox_memory_into_buf(memory, signature_ptr, &mut signature)?; + + let mut pub_key: [u8; 32] = [0; 32]; + ctx.read_sandbox_memory_into_buf(memory, pub_key_ptr, &mut pub_key)?; + + let message: Vec = ctx.read_sandbox_memory(memory, message_ptr, message_len)?; + + if ctx.ext.sr25519_verify(&signature, &message, &pub_key) { + Ok(ReturnErrorCode::Success) + } else { + Ok(ReturnErrorCode::Sr25519VerifyFailed) + } + } + + /// Replace the contract code at the specified address with new code. + /// See [`pallet_contracts_uapi::HostFn::set_code_hash`]. + #[prefixed_alias] + #[mutating] + fn set_code_hash(ctx: _, memory: _, code_hash_ptr: u32) -> Result { + ctx.charge_gas(RuntimeCosts::SetCodeHash)?; + let code_hash: CodeHash<::T> = + ctx.read_sandbox_memory_as(memory, code_hash_ptr)?; + match ctx.ext.set_code_hash(code_hash) { + Err(err) => { + let code = Runtime::::err_into_return_code(err)?; + Ok(code) + }, + Ok(()) => Ok(ReturnErrorCode::Success), + } + } + + /// Calculates Ethereum address from the ECDSA compressed public key and stores + /// See [`pallet_contracts_uapi::HostFn::ecdsa_to_eth_address`]. + #[prefixed_alias] + fn ecdsa_to_eth_address( + ctx: _, + memory: _, + key_ptr: u32, + out_ptr: u32, + ) -> Result { + ctx.charge_gas(RuntimeCosts::EcdsaToEthAddress)?; + let mut compressed_key: [u8; 33] = [0; 33]; + ctx.read_sandbox_memory_into_buf(memory, key_ptr, &mut compressed_key)?; + let result = ctx.ext.ecdsa_to_eth_address(&compressed_key); + match result { + Ok(eth_address) => { + ctx.write_sandbox_memory(memory, out_ptr, eth_address.as_ref())?; + Ok(ReturnErrorCode::Success) + }, + Err(_) => Ok(ReturnErrorCode::EcdsaRecoveryFailed), + } + } + + /// Returns the number of times the currently executing contract exists on the call stack in + /// addition to the calling instance. + /// See [`pallet_contracts_uapi::HostFn::reentrance_count`]. + #[unstable] + fn reentrance_count(ctx: _, memory: _) -> Result { + ctx.charge_gas(RuntimeCosts::ReentranceCount)?; + Ok(ctx.ext.reentrance_count()) + } + + /// Returns the number of times specified contract exists on the call stack. Delegated calls are + /// not counted as separate calls. + /// See [`pallet_contracts_uapi::HostFn::account_reentrance_count`]. + #[unstable] + fn account_reentrance_count(ctx: _, memory: _, account_ptr: u32) -> Result { + ctx.charge_gas(RuntimeCosts::AccountReentranceCount)?; + let account_id: <::T as frame_system::Config>::AccountId = + ctx.read_sandbox_memory_as(memory, account_ptr)?; + Ok(ctx.ext.account_reentrance_count(&account_id)) + } + + /// Returns a nonce that is unique per contract instantiation. + /// See [`pallet_contracts_uapi::HostFn::instantiation_nonce`]. + fn instantiation_nonce(ctx: _, _memory: _) -> Result { + ctx.charge_gas(RuntimeCosts::InstantiationNonce)?; + Ok(ctx.ext.nonce()) + } + + /// Adds a new delegate dependency to the contract. + /// See [`pallet_contracts_uapi::HostFn::lock_delegate_dependency`]. + #[mutating] + fn lock_delegate_dependency(ctx: _, memory: _, code_hash_ptr: u32) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::LockDelegateDependency)?; + let code_hash = ctx.read_sandbox_memory_as(memory, code_hash_ptr)?; + ctx.ext.lock_delegate_dependency(code_hash)?; + Ok(()) + } + + /// Removes the delegate dependency from the contract. + /// see [`pallet_contracts_uapi::HostFn::unlock_delegate_dependency`]. + #[mutating] + fn unlock_delegate_dependency(ctx: _, memory: _, code_hash_ptr: u32) -> Result<(), TrapReason> { + ctx.charge_gas(RuntimeCosts::UnlockDelegateDependency)?; + let code_hash = ctx.read_sandbox_memory_as(memory, code_hash_ptr)?; + ctx.ext.unlock_delegate_dependency(&code_hash)?; + Ok(()) + } +} diff --git a/pallets/contracts/src/weights.rs b/pallets/contracts/src/weights.rs new file mode 100644 index 00000000..25b36fc4 --- /dev/null +++ b/pallets/contracts/src/weights.rs @@ -0,0 +1,2120 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Autogenerated weights for `pallet_contracts` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 +//! DATE: 2024-07-17, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-yaoqqom-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` + +// Executed Command: +// target/production/substrate-node +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=pallet_contracts +// --chain=dev +// --header=./substrate/HEADER-APACHE2 +// --output=./substrate/frame/contracts/src/weights.rs +// --template=./substrate/.maintain/frame-weight-template.hbs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use core::marker::PhantomData; + +/// Weight functions needed for `pallet_contracts`. +pub trait WeightInfo { + fn on_process_deletion_queue_batch() -> Weight; + fn on_initialize_per_trie_key(k: u32, ) -> Weight; + fn v9_migration_step(c: u32, ) -> Weight; + fn v10_migration_step() -> Weight; + fn v11_migration_step(k: u32, ) -> Weight; + fn v12_migration_step(c: u32, ) -> Weight; + fn v13_migration_step() -> Weight; + fn v14_migration_step() -> Weight; + fn v15_migration_step() -> Weight; + fn v16_migration_step() -> Weight; + fn migration_noop() -> Weight; + fn migrate() -> Weight; + fn on_runtime_upgrade_noop() -> Weight; + fn on_runtime_upgrade_in_progress() -> Weight; + fn on_runtime_upgrade() -> Weight; + fn call_with_code_per_byte(c: u32, ) -> Weight; + fn instantiate_with_code(c: u32, i: u32, s: u32, ) -> Weight; + fn instantiate(i: u32, s: u32, ) -> Weight; + fn call() -> Weight; + fn upload_code_determinism_enforced(c: u32, ) -> Weight; + fn upload_code_determinism_relaxed(c: u32, ) -> Weight; + fn remove_code() -> Weight; + fn set_code() -> Weight; + fn noop_host_fn(r: u32, ) -> Weight; + fn seal_caller() -> Weight; + fn seal_is_contract() -> Weight; + fn seal_code_hash() -> Weight; + fn seal_own_code_hash() -> Weight; + fn seal_caller_is_origin() -> Weight; + fn seal_caller_is_root() -> Weight; + fn seal_address() -> Weight; + fn seal_gas_left() -> Weight; + fn seal_balance() -> Weight; + fn seal_value_transferred() -> Weight; + fn seal_minimum_balance() -> Weight; + fn seal_block_number() -> Weight; + fn seal_now() -> Weight; + fn seal_weight_to_fee() -> Weight; + fn seal_input(n: u32, ) -> Weight; + fn seal_return(n: u32, ) -> Weight; + fn seal_terminate(n: u32, ) -> Weight; + fn seal_random() -> Weight; + fn seal_deposit_event(t: u32, n: u32, ) -> Weight; + fn seal_debug_message(i: u32, ) -> Weight; + fn get_storage_empty() -> Weight; + fn get_storage_full() -> Weight; + fn set_storage_empty() -> Weight; + fn set_storage_full() -> Weight; + fn seal_set_storage(n: u32, o: u32, ) -> Weight; + fn seal_clear_storage(n: u32, ) -> Weight; + fn seal_get_storage(n: u32, ) -> Weight; + fn seal_contains_storage(n: u32, ) -> Weight; + fn seal_take_storage(n: u32, ) -> Weight; + fn set_transient_storage_empty() -> Weight; + fn set_transient_storage_full() -> Weight; + fn get_transient_storage_empty() -> Weight; + fn get_transient_storage_full() -> Weight; + fn rollback_transient_storage() -> Weight; + fn seal_set_transient_storage(n: u32, o: u32, ) -> Weight; + fn seal_clear_transient_storage(n: u32, ) -> Weight; + fn seal_get_transient_storage(n: u32, ) -> Weight; + fn seal_contains_transient_storage(n: u32, ) -> Weight; + fn seal_take_transient_storage(n: u32, ) -> Weight; + fn seal_transfer() -> Weight; + fn seal_call(t: u32, i: u32, ) -> Weight; + fn seal_delegate_call() -> Weight; + fn seal_instantiate(i: u32, s: u32, ) -> Weight; + fn seal_hash_sha2_256(n: u32, ) -> Weight; + fn seal_hash_keccak_256(n: u32, ) -> Weight; + fn seal_hash_blake2_256(n: u32, ) -> Weight; + fn seal_hash_blake2_128(n: u32, ) -> Weight; + fn seal_sr25519_verify(n: u32, ) -> Weight; + fn seal_ecdsa_recover() -> Weight; + fn seal_ecdsa_to_eth_address() -> Weight; + fn seal_set_code_hash() -> Weight; + fn lock_delegate_dependency() -> Weight; + fn unlock_delegate_dependency() -> Weight; + fn seal_reentrance_count() -> Weight; + fn seal_account_reentrance_count() -> Weight; + fn seal_instantiation_nonce() -> Weight; + fn instr_i64_load_store(r: u32, ) -> Weight; +} + +/// Weights for `pallet_contracts` using the Substrate node and recommended hardware. +pub struct SubstrateWeight(PhantomData); +impl WeightInfo for SubstrateWeight { + /// Storage: `Contracts::DeletionQueueCounter` (r:1 w:0) + /// Proof: `Contracts::DeletionQueueCounter` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + fn on_process_deletion_queue_batch() -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `1627` + // Minimum execution time: 1_915_000 picoseconds. + Weight::from_parts(1_986_000, 1627) + .saturating_add(T::DbWeight::get().reads(1_u64)) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `k` is `[0, 1024]`. + fn on_initialize_per_trie_key(k: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `452 + k * (69 ±0)` + // Estimated: `442 + k * (70 ±0)` + // Minimum execution time: 11_103_000 picoseconds. + Weight::from_parts(11_326_000, 442) + // Standard Error: 2_291 + .saturating_add(Weight::from_parts(1_196_329, 0).saturating_mul(k.into())) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(k.into()))) + .saturating_add(T::DbWeight::get().writes(2_u64)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(k.into()))) + .saturating_add(Weight::from_parts(0, 70).saturating_mul(k.into())) + } + /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc553022fca90611ba8b7942f8bdb3b97f6580` (r:2 w:1) + /// Proof: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc553022fca90611ba8b7942f8bdb3b97f6580` (r:2 w:1) + /// The range of component `c` is `[0, 125952]`. + fn v9_migration_step(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `211 + c * (1 ±0)` + // Estimated: `6149 + c * (1 ±0)` + // Minimum execution time: 7_783_000 picoseconds. + Weight::from_parts(4_462_075, 6149) + // Standard Error: 5 + .saturating_add(Weight::from_parts(1_634, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) + } + /// Storage: `Contracts::ContractInfoOf` (r:2 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:0) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + fn v10_migration_step() -> Weight { + // Proof Size summary in bytes: + // Measured: `510` + // Estimated: `6450` + // Minimum execution time: 15_971_000 picoseconds. + Weight::from_parts(16_730_000, 6450) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `Contracts::DeletionQueue` (r:1 w:1025) + /// Proof: `Contracts::DeletionQueue` (`max_values`: None, `max_size`: Some(142), added: 2617, mode: `Measured`) + /// Storage: `Contracts::DeletionQueueCounter` (r:0 w:1) + /// Proof: `Contracts::DeletionQueueCounter` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// The range of component `k` is `[0, 1024]`. + fn v11_migration_step(k: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `171 + k * (1 ±0)` + // Estimated: `3635 + k * (1 ±0)` + // Minimum execution time: 3_149_000 picoseconds. + Weight::from_parts(3_264_000, 3635) + // Standard Error: 559 + .saturating_add(Weight::from_parts(1_111_209, 0).saturating_mul(k.into())) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(k.into()))) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(k.into())) + } + /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc553053f13fd319a03c211337c76e0fe776df` (r:2 w:0) + /// Proof: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc553053f13fd319a03c211337c76e0fe776df` (r:2 w:0) + /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc553022fca90611ba8b7942f8bdb3b97f6580` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc553022fca90611ba8b7942f8bdb3b97f6580` (r:1 w:1) + /// Storage: `System::Account` (r:1 w:0) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:0 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// The range of component `c` is `[0, 125952]`. + fn v12_migration_step(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `325 + c * (1 ±0)` + // Estimated: `6263 + c * (1 ±0)` + // Minimum execution time: 15_072_000 picoseconds. + Weight::from_parts(15_721_891, 6263) + // Standard Error: 2 + .saturating_add(Weight::from_parts(428, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(4_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) + } + /// Storage: `Contracts::ContractInfoOf` (r:2 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + fn v13_migration_step() -> Weight { + // Proof Size summary in bytes: + // Measured: `440` + // Estimated: `6380` + // Minimum execution time: 12_047_000 picoseconds. + Weight::from_parts(12_500_000, 6380) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `Contracts::CodeInfoOf` (r:2 w:0) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + /// Storage: `Balances::Holds` (r:1 w:0) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + fn v14_migration_step() -> Weight { + // Proof Size summary in bytes: + // Measured: `352` + // Estimated: `6292` + // Minimum execution time: 47_488_000 picoseconds. + Weight::from_parts(48_482_000, 6292) + .saturating_add(T::DbWeight::get().reads(4_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `Contracts::ContractInfoOf` (r:2 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `System::Account` (r:2 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + fn v15_migration_step() -> Weight { + // Proof Size summary in bytes: + // Measured: `594` + // Estimated: `6534` + // Minimum execution time: 52_801_000 picoseconds. + Weight::from_parts(54_230_000, 6534) + .saturating_add(T::DbWeight::get().reads(4_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) + } + /// Storage: `Contracts::ContractInfoOf` (r:2 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + fn v16_migration_step() -> Weight { + // Proof Size summary in bytes: + // Measured: `409` + // Estimated: `6349` + // Minimum execution time: 11_618_000 picoseconds. + Weight::from_parts(12_068_000, 6349) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:1) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + fn migration_noop() -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `1627` + // Minimum execution time: 2_131_000 picoseconds. + Weight::from_parts(2_255_000, 1627) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:1) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:1) + fn migrate() -> Weight { + // Proof Size summary in bytes: + // Measured: `166` + // Estimated: `3631` + // Minimum execution time: 10_773_000 picoseconds. + Weight::from_parts(11_118_000, 3631) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) + } + /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) + /// Proof: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) + fn on_runtime_upgrade_noop() -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `3607` + // Minimum execution time: 4_371_000 picoseconds. + Weight::from_parts(4_624_000, 3607) + .saturating_add(T::DbWeight::get().reads(1_u64)) + } + /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) + /// Proof: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + fn on_runtime_upgrade_in_progress() -> Weight { + // Proof Size summary in bytes: + // Measured: `167` + // Estimated: `3632` + // Minimum execution time: 5_612_000 picoseconds. + Weight::from_parts(5_838_000, 3632) + .saturating_add(T::DbWeight::get().reads(2_u64)) + } + /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) + /// Proof: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) + /// Storage: `Contracts::MigrationInProgress` (r:1 w:1) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + fn on_runtime_upgrade() -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `3607` + // Minimum execution time: 5_487_000 picoseconds. + Weight::from_parts(5_693_000, 3607) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:1 w:0) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:1 w:0) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + /// Storage: `Timestamp::Now` (r:1 w:0) + /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + /// The range of component `c` is `[0, 125952]`. + fn call_with_code_per_byte(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `800 + c * (1 ±0)` + // Estimated: `4266 + c * (1 ±0)` + // Minimum execution time: 247_545_000 picoseconds. + Weight::from_parts(268_016_699, 4266) + // Standard Error: 4 + .saturating_add(Weight::from_parts(700, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(6_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Balances::Holds` (r:2 w:2) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Storage: `Contracts::Nonce` (r:1 w:1) + /// Proof: `Contracts::Nonce` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `Timestamp::Now` (r:1 w:0) + /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:0 w:1) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + /// The range of component `c` is `[0, 125952]`. + /// The range of component `i` is `[0, 1048576]`. + /// The range of component `s` is `[0, 1048576]`. + fn instantiate_with_code(c: u32, i: u32, s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `323` + // Estimated: `6262` + // Minimum execution time: 4_396_772_000 picoseconds. + Weight::from_parts(235_107_907, 6262) + // Standard Error: 185 + .saturating_add(Weight::from_parts(53_843, 0).saturating_mul(c.into())) + // Standard Error: 22 + .saturating_add(Weight::from_parts(2_143, 0).saturating_mul(i.into())) + // Standard Error: 22 + .saturating_add(Weight::from_parts(2_210, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(8_u64)) + .saturating_add(T::DbWeight::get().writes(7_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:1 w:0) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + /// Storage: `Contracts::Nonce` (r:1 w:1) + /// Proof: `Contracts::Nonce` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `Timestamp::Now` (r:1 w:0) + /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + /// Storage: `Balances::Holds` (r:1 w:1) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// The range of component `i` is `[0, 1048576]`. + /// The range of component `s` is `[0, 1048576]`. + fn instantiate(i: u32, s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `560` + // Estimated: `4017` + // Minimum execution time: 2_240_868_000 picoseconds. + Weight::from_parts(2_273_668_000, 4017) + // Standard Error: 32 + .saturating_add(Weight::from_parts(934, 0).saturating_mul(i.into())) + // Standard Error: 32 + .saturating_add(Weight::from_parts(920, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(8_u64)) + .saturating_add(T::DbWeight::get().writes(5_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:1 w:0) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:1 w:0) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + /// Storage: `Timestamp::Now` (r:1 w:0) + /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + fn call() -> Weight { + // Proof Size summary in bytes: + // Measured: `826` + // Estimated: `4291` + // Minimum execution time: 165_067_000 picoseconds. + Weight::from_parts(168_582_000, 4291) + .saturating_add(T::DbWeight::get().reads(6_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Balances::Holds` (r:1 w:1) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:0 w:1) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + /// The range of component `c` is `[0, 125952]`. + fn upload_code_determinism_enforced(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `3607` + // Minimum execution time: 229_454_000 picoseconds. + Weight::from_parts(251_495_551, 3607) + // Standard Error: 71 + .saturating_add(Weight::from_parts(51_428, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().writes(3_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Balances::Holds` (r:1 w:1) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:0 w:1) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + /// The range of component `c` is `[0, 125952]`. + fn upload_code_determinism_relaxed(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `3607` + // Minimum execution time: 240_390_000 picoseconds. + Weight::from_parts(273_854_266, 3607) + // Standard Error: 243 + .saturating_add(Weight::from_parts(51_836, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().writes(3_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Balances::Holds` (r:1 w:1) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:0 w:1) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + fn remove_code() -> Weight { + // Proof Size summary in bytes: + // Measured: `315` + // Estimated: `3780` + // Minimum execution time: 39_374_000 picoseconds. + Weight::from_parts(40_247_000, 3780) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().writes(3_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:2 w:2) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + fn set_code() -> Weight { + // Proof Size summary in bytes: + // Measured: `552` + // Estimated: `6492` + // Minimum execution time: 24_473_000 picoseconds. + Weight::from_parts(25_890_000, 6492) + .saturating_add(T::DbWeight::get().reads(4_u64)) + .saturating_add(T::DbWeight::get().writes(3_u64)) + } + /// The range of component `r` is `[0, 1600]`. + fn noop_host_fn(r: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 8_528_000 picoseconds. + Weight::from_parts(9_301_010, 0) + // Standard Error: 98 + .saturating_add(Weight::from_parts(53_173, 0).saturating_mul(r.into())) + } + fn seal_caller() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 643_000 picoseconds. + Weight::from_parts(678_000, 0) + } + /// Storage: `Contracts::ContractInfoOf` (r:1 w:0) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + fn seal_is_contract() -> Weight { + // Proof Size summary in bytes: + // Measured: `354` + // Estimated: `3819` + // Minimum execution time: 6_107_000 picoseconds. + Weight::from_parts(6_235_000, 3819) + .saturating_add(T::DbWeight::get().reads(1_u64)) + } + /// Storage: `Contracts::ContractInfoOf` (r:1 w:0) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + fn seal_code_hash() -> Weight { + // Proof Size summary in bytes: + // Measured: `447` + // Estimated: `3912` + // Minimum execution time: 7_316_000 picoseconds. + Weight::from_parts(7_653_000, 3912) + .saturating_add(T::DbWeight::get().reads(1_u64)) + } + fn seal_own_code_hash() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 721_000 picoseconds. + Weight::from_parts(764_000, 0) + } + fn seal_caller_is_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 369_000 picoseconds. + Weight::from_parts(417_000, 0) + } + fn seal_caller_is_root() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 318_000 picoseconds. + Weight::from_parts(349_000, 0) + } + fn seal_address() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 590_000 picoseconds. + Weight::from_parts(628_000, 0) + } + fn seal_gas_left() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 660_000 picoseconds. + Weight::from_parts(730_000, 0) + } + fn seal_balance() -> Weight { + // Proof Size summary in bytes: + // Measured: `140` + // Estimated: `0` + // Minimum execution time: 4_361_000 picoseconds. + Weight::from_parts(4_577_000, 0) + } + fn seal_value_transferred() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 560_000 picoseconds. + Weight::from_parts(603_000, 0) + } + fn seal_minimum_balance() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 561_000 picoseconds. + Weight::from_parts(610_000, 0) + } + fn seal_block_number() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 557_000 picoseconds. + Weight::from_parts(583_000, 0) + } + fn seal_now() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 550_000 picoseconds. + Weight::from_parts(602_000, 0) + } + /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) + /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `Measured`) + fn seal_weight_to_fee() -> Weight { + // Proof Size summary in bytes: + // Measured: `67` + // Estimated: `1552` + // Minimum execution time: 4_065_000 picoseconds. + Weight::from_parts(4_291_000, 1552) + .saturating_add(T::DbWeight::get().reads(1_u64)) + } + /// The range of component `n` is `[0, 1048572]`. + fn seal_input(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 487_000 picoseconds. + Weight::from_parts(517_000, 0) + // Standard Error: 3 + .saturating_add(Weight::from_parts(301, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 1048572]`. + fn seal_return(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 318_000 picoseconds. + Weight::from_parts(372_000, 0) + // Standard Error: 10 + .saturating_add(Weight::from_parts(411, 0).saturating_mul(n.into())) + } + /// Storage: `Contracts::DeletionQueueCounter` (r:1 w:1) + /// Proof: `Contracts::DeletionQueueCounter` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:33 w:33) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Contracts::DeletionQueue` (r:0 w:1) + /// Proof: `Contracts::DeletionQueue` (`max_values`: None, `max_size`: Some(142), added: 2617, mode: `Measured`) + /// The range of component `n` is `[0, 32]`. + fn seal_terminate(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `319 + n * (78 ±0)` + // Estimated: `3784 + n * (2553 ±0)` + // Minimum execution time: 13_251_000 picoseconds. + Weight::from_parts(15_257_892, 3784) + // Standard Error: 7_089 + .saturating_add(Weight::from_parts(3_443_907, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) + .saturating_add(T::DbWeight::get().writes(3_u64)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(n.into()))) + .saturating_add(Weight::from_parts(0, 2553).saturating_mul(n.into())) + } + /// Storage: `RandomnessCollectiveFlip::RandomMaterial` (r:1 w:0) + /// Proof: `RandomnessCollectiveFlip::RandomMaterial` (`max_values`: Some(1), `max_size`: Some(2594), added: 3089, mode: `Measured`) + fn seal_random() -> Weight { + // Proof Size summary in bytes: + // Measured: `76` + // Estimated: `1561` + // Minimum execution time: 3_434_000 picoseconds. + Weight::from_parts(3_605_000, 1561) + .saturating_add(T::DbWeight::get().reads(1_u64)) + } + /// Storage: `System::EventTopics` (r:4 w:4) + /// Proof: `System::EventTopics` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `t` is `[0, 4]`. + /// The range of component `n` is `[0, 16384]`. + fn seal_deposit_event(t: u32, n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `990 + t * (2475 ±0)` + // Minimum execution time: 3_668_000 picoseconds. + Weight::from_parts(3_999_591, 990) + // Standard Error: 5_767 + .saturating_add(Weight::from_parts(2_011_090, 0).saturating_mul(t.into())) + // Standard Error: 1 + .saturating_add(Weight::from_parts(12, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(t.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(t.into()))) + .saturating_add(Weight::from_parts(0, 2475).saturating_mul(t.into())) + } + /// The range of component `i` is `[0, 1048576]`. + fn seal_debug_message(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 443_000 picoseconds. + Weight::from_parts(472_000, 0) + // Standard Error: 10 + .saturating_add(Weight::from_parts(1_207, 0).saturating_mul(i.into())) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn get_storage_empty() -> Weight { + // Proof Size summary in bytes: + // Measured: `16618` + // Estimated: `16618` + // Minimum execution time: 13_752_000 picoseconds. + Weight::from_parts(14_356_000, 16618) + .saturating_add(T::DbWeight::get().reads(1_u64)) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn get_storage_full() -> Weight { + // Proof Size summary in bytes: + // Measured: `26628` + // Estimated: `26628` + // Minimum execution time: 43_444_000 picoseconds. + Weight::from_parts(45_087_000, 26628) + .saturating_add(T::DbWeight::get().reads(1_u64)) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn set_storage_empty() -> Weight { + // Proof Size summary in bytes: + // Measured: `16618` + // Estimated: `16618` + // Minimum execution time: 15_616_000 picoseconds. + Weight::from_parts(16_010_000, 16618) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn set_storage_full() -> Weight { + // Proof Size summary in bytes: + // Measured: `26628` + // Estimated: `26628` + // Minimum execution time: 47_020_000 picoseconds. + Weight::from_parts(50_152_000, 26628) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `n` is `[0, 16384]`. + /// The range of component `o` is `[0, 16384]`. + fn seal_set_storage(n: u32, o: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `250 + o * (1 ±0)` + // Estimated: `249 + o * (1 ±0)` + // Minimum execution time: 8_824_000 picoseconds. + Weight::from_parts(8_915_233, 249) + // Standard Error: 1 + .saturating_add(Weight::from_parts(255, 0).saturating_mul(n.into())) + // Standard Error: 1 + .saturating_add(Weight::from_parts(39, 0).saturating_mul(o.into())) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(o.into())) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `n` is `[0, 16384]`. + fn seal_clear_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `248 + n * (1 ±0)` + // Estimated: `248 + n * (1 ±0)` + // Minimum execution time: 7_133_000 picoseconds. + Weight::from_parts(7_912_778, 248) + // Standard Error: 1 + .saturating_add(Weight::from_parts(88, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `n` is `[0, 16384]`. + fn seal_get_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `248 + n * (1 ±0)` + // Estimated: `248 + n * (1 ±0)` + // Minimum execution time: 6_746_000 picoseconds. + Weight::from_parts(7_647_236, 248) + // Standard Error: 2 + .saturating_add(Weight::from_parts(603, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `n` is `[0, 16384]`. + fn seal_contains_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `248 + n * (1 ±0)` + // Estimated: `248 + n * (1 ±0)` + // Minimum execution time: 6_247_000 picoseconds. + Weight::from_parts(6_952_661, 248) + // Standard Error: 1 + .saturating_add(Weight::from_parts(77, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `n` is `[0, 16384]`. + fn seal_take_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `248 + n * (1 ±0)` + // Estimated: `248 + n * (1 ±0)` + // Minimum execution time: 7_428_000 picoseconds. + Weight::from_parts(8_384_015, 248) + // Standard Error: 2 + .saturating_add(Weight::from_parts(625, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) + } + fn set_transient_storage_empty() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_478_000 picoseconds. + Weight::from_parts(1_533_000, 0) + } + fn set_transient_storage_full() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_485_000 picoseconds. + Weight::from_parts(2_728_000, 0) + } + fn get_transient_storage_empty() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_195_000 picoseconds. + Weight::from_parts(3_811_000, 0) + } + fn get_transient_storage_full() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_902_000 picoseconds. + Weight::from_parts(4_118_000, 0) + } + fn rollback_transient_storage() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_571_000 picoseconds. + Weight::from_parts(1_662_000, 0) + } + /// The range of component `n` is `[0, 16384]`. + /// The range of component `o` is `[0, 16384]`. + fn seal_set_transient_storage(n: u32, o: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 5_250_000 picoseconds. + Weight::from_parts(2_465_568, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(201, 0).saturating_mul(n.into())) + // Standard Error: 0 + .saturating_add(Weight::from_parts(223, 0).saturating_mul(o.into())) + } + /// The range of component `n` is `[0, 16384]`. + fn seal_clear_transient_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_012_000 picoseconds. + Weight::from_parts(2_288_004, 0) + // Standard Error: 3 + .saturating_add(Weight::from_parts(239, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 16384]`. + fn seal_get_transient_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_906_000 picoseconds. + Weight::from_parts(2_121_040, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(225, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 16384]`. + fn seal_contains_transient_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_736_000 picoseconds. + Weight::from_parts(1_954_728, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(111, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 16384]`. + fn seal_take_transient_storage(_n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_872_000 picoseconds. + Weight::from_parts(8_125_644, 0) + } + fn seal_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `140` + // Estimated: `0` + // Minimum execution time: 8_489_000 picoseconds. + Weight::from_parts(8_791_000, 0) + } + /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:1 w:0) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:1 w:0) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + /// The range of component `t` is `[0, 1]`. + /// The range of component `i` is `[0, 1048576]`. + fn seal_call(t: u32, i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `620 + t * (280 ±0)` + // Estimated: `4085 + t * (2182 ±0)` + // Minimum execution time: 122_759_000 picoseconds. + Weight::from_parts(120_016_020, 4085) + // Standard Error: 173_118 + .saturating_add(Weight::from_parts(42_848_338, 0).saturating_mul(t.into())) + // Standard Error: 0 + .saturating_add(Weight::from_parts(6, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(t.into()))) + .saturating_add(T::DbWeight::get().writes(1_u64)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(t.into()))) + .saturating_add(Weight::from_parts(0, 2182).saturating_mul(t.into())) + } + /// Storage: `Contracts::CodeInfoOf` (r:1 w:0) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:1 w:0) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + fn seal_delegate_call() -> Weight { + // Proof Size summary in bytes: + // Measured: `430` + // Estimated: `3895` + // Minimum execution time: 111_566_000 picoseconds. + Weight::from_parts(115_083_000, 3895) + .saturating_add(T::DbWeight::get().reads(2_u64)) + } + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:1 w:0) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + /// Storage: `Contracts::Nonce` (r:1 w:0) + /// Proof: `Contracts::Nonce` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + /// The range of component `i` is `[0, 983040]`. + /// The range of component `s` is `[0, 983040]`. + fn seal_instantiate(i: u32, s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `676` + // Estimated: `4132` + // Minimum execution time: 1_871_402_000 picoseconds. + Weight::from_parts(1_890_038_000, 4132) + // Standard Error: 24 + .saturating_add(Weight::from_parts(581, 0).saturating_mul(i.into())) + // Standard Error: 24 + .saturating_add(Weight::from_parts(915, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(5_u64)) + .saturating_add(T::DbWeight::get().writes(3_u64)) + } + /// The range of component `n` is `[0, 1048576]`. + fn seal_hash_sha2_256(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 966_000 picoseconds. + Weight::from_parts(9_599_151, 0) + // Standard Error: 1 + .saturating_add(Weight::from_parts(1_336, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 1048576]`. + fn seal_hash_keccak_256(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_416_000 picoseconds. + Weight::from_parts(10_964_255, 0) + // Standard Error: 1 + .saturating_add(Weight::from_parts(3_593, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 1048576]`. + fn seal_hash_blake2_256(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 821_000 picoseconds. + Weight::from_parts(6_579_283, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(1_466, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 1048576]`. + fn seal_hash_blake2_128(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 773_000 picoseconds. + Weight::from_parts(10_990_209, 0) + // Standard Error: 1 + .saturating_add(Weight::from_parts(1_457, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 125697]`. + fn seal_sr25519_verify(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 43_195_000 picoseconds. + Weight::from_parts(41_864_855, 0) + // Standard Error: 9 + .saturating_add(Weight::from_parts(5_154, 0).saturating_mul(n.into())) + } + fn seal_ecdsa_recover() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 47_747_000 picoseconds. + Weight::from_parts(49_219_000, 0) + } + fn seal_ecdsa_to_eth_address() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 12_854_000 picoseconds. + Weight::from_parts(12_962_000, 0) + } + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:1 w:0) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + fn seal_set_code_hash() -> Weight { + // Proof Size summary in bytes: + // Measured: `430` + // Estimated: `3895` + // Minimum execution time: 17_868_000 picoseconds. + Weight::from_parts(18_486_000, 3895) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + fn lock_delegate_dependency() -> Weight { + // Proof Size summary in bytes: + // Measured: `355` + // Estimated: `3820` + // Minimum execution time: 8_393_000 picoseconds. + Weight::from_parts(8_640_000, 3820) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `MaxEncodedLen`) + fn unlock_delegate_dependency() -> Weight { + // Proof Size summary in bytes: + // Measured: `355` + // Estimated: `3558` + // Minimum execution time: 7_489_000 picoseconds. + Weight::from_parts(7_815_000, 3558) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + fn seal_reentrance_count() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 299_000 picoseconds. + Weight::from_parts(339_000, 0) + } + fn seal_account_reentrance_count() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 324_000 picoseconds. + Weight::from_parts(380_000, 0) + } + /// Storage: `Contracts::Nonce` (r:1 w:0) + /// Proof: `Contracts::Nonce` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + fn seal_instantiation_nonce() -> Weight { + // Proof Size summary in bytes: + // Measured: `219` + // Estimated: `1704` + // Minimum execution time: 2_768_000 picoseconds. + Weight::from_parts(3_025_000, 1704) + .saturating_add(T::DbWeight::get().reads(1_u64)) + } + /// The range of component `r` is `[0, 5000]`. + fn instr_i64_load_store(r: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 766_000 picoseconds. + Weight::from_parts(722_169, 0) + // Standard Error: 10 + .saturating_add(Weight::from_parts(7_191, 0).saturating_mul(r.into())) + } +} + +// For backwards compatibility and tests. +impl WeightInfo for () { + /// Storage: `Contracts::DeletionQueueCounter` (r:1 w:0) + /// Proof: `Contracts::DeletionQueueCounter` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + fn on_process_deletion_queue_batch() -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `1627` + // Minimum execution time: 1_915_000 picoseconds. + Weight::from_parts(1_986_000, 1627) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `k` is `[0, 1024]`. + fn on_initialize_per_trie_key(k: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `452 + k * (69 ±0)` + // Estimated: `442 + k * (70 ±0)` + // Minimum execution time: 11_103_000 picoseconds. + Weight::from_parts(11_326_000, 442) + // Standard Error: 2_291 + .saturating_add(Weight::from_parts(1_196_329, 0).saturating_mul(k.into())) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(k.into()))) + .saturating_add(RocksDbWeight::get().writes(2_u64)) + .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(k.into()))) + .saturating_add(Weight::from_parts(0, 70).saturating_mul(k.into())) + } + /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc553022fca90611ba8b7942f8bdb3b97f6580` (r:2 w:1) + /// Proof: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc553022fca90611ba8b7942f8bdb3b97f6580` (r:2 w:1) + /// The range of component `c` is `[0, 125952]`. + fn v9_migration_step(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `211 + c * (1 ±0)` + // Estimated: `6149 + c * (1 ±0)` + // Minimum execution time: 7_783_000 picoseconds. + Weight::from_parts(4_462_075, 6149) + // Standard Error: 5 + .saturating_add(Weight::from_parts(1_634, 0).saturating_mul(c.into())) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) + } + /// Storage: `Contracts::ContractInfoOf` (r:2 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:0) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + fn v10_migration_step() -> Weight { + // Proof Size summary in bytes: + // Measured: `510` + // Estimated: `6450` + // Minimum execution time: 15_971_000 picoseconds. + Weight::from_parts(16_730_000, 6450) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `Contracts::DeletionQueue` (r:1 w:1025) + /// Proof: `Contracts::DeletionQueue` (`max_values`: None, `max_size`: Some(142), added: 2617, mode: `Measured`) + /// Storage: `Contracts::DeletionQueueCounter` (r:0 w:1) + /// Proof: `Contracts::DeletionQueueCounter` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// The range of component `k` is `[0, 1024]`. + fn v11_migration_step(k: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `171 + k * (1 ±0)` + // Estimated: `3635 + k * (1 ±0)` + // Minimum execution time: 3_149_000 picoseconds. + Weight::from_parts(3_264_000, 3635) + // Standard Error: 559 + .saturating_add(Weight::from_parts(1_111_209, 0).saturating_mul(k.into())) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) + .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(k.into()))) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(k.into())) + } + /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc553053f13fd319a03c211337c76e0fe776df` (r:2 w:0) + /// Proof: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc553053f13fd319a03c211337c76e0fe776df` (r:2 w:0) + /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc553022fca90611ba8b7942f8bdb3b97f6580` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc553022fca90611ba8b7942f8bdb3b97f6580` (r:1 w:1) + /// Storage: `System::Account` (r:1 w:0) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:0 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// The range of component `c` is `[0, 125952]`. + fn v12_migration_step(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `325 + c * (1 ±0)` + // Estimated: `6263 + c * (1 ±0)` + // Minimum execution time: 15_072_000 picoseconds. + Weight::from_parts(15_721_891, 6263) + // Standard Error: 2 + .saturating_add(Weight::from_parts(428, 0).saturating_mul(c.into())) + .saturating_add(RocksDbWeight::get().reads(4_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) + } + /// Storage: `Contracts::ContractInfoOf` (r:2 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + fn v13_migration_step() -> Weight { + // Proof Size summary in bytes: + // Measured: `440` + // Estimated: `6380` + // Minimum execution time: 12_047_000 picoseconds. + Weight::from_parts(12_500_000, 6380) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `Contracts::CodeInfoOf` (r:2 w:0) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + /// Storage: `Balances::Holds` (r:1 w:0) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + fn v14_migration_step() -> Weight { + // Proof Size summary in bytes: + // Measured: `352` + // Estimated: `6292` + // Minimum execution time: 47_488_000 picoseconds. + Weight::from_parts(48_482_000, 6292) + .saturating_add(RocksDbWeight::get().reads(4_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `Contracts::ContractInfoOf` (r:2 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `System::Account` (r:2 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + fn v15_migration_step() -> Weight { + // Proof Size summary in bytes: + // Measured: `594` + // Estimated: `6534` + // Minimum execution time: 52_801_000 picoseconds. + Weight::from_parts(54_230_000, 6534) + .saturating_add(RocksDbWeight::get().reads(4_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) + } + /// Storage: `Contracts::ContractInfoOf` (r:2 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + fn v16_migration_step() -> Weight { + // Proof Size summary in bytes: + // Measured: `409` + // Estimated: `6349` + // Minimum execution time: 11_618_000 picoseconds. + Weight::from_parts(12_068_000, 6349) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:1) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + fn migration_noop() -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `1627` + // Minimum execution time: 2_131_000 picoseconds. + Weight::from_parts(2_255_000, 1627) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:1) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:1) + fn migrate() -> Weight { + // Proof Size summary in bytes: + // Measured: `166` + // Estimated: `3631` + // Minimum execution time: 10_773_000 picoseconds. + Weight::from_parts(11_118_000, 3631) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) + } + /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) + /// Proof: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) + fn on_runtime_upgrade_noop() -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `3607` + // Minimum execution time: 4_371_000 picoseconds. + Weight::from_parts(4_624_000, 3607) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + } + /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) + /// Proof: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + fn on_runtime_upgrade_in_progress() -> Weight { + // Proof Size summary in bytes: + // Measured: `167` + // Estimated: `3632` + // Minimum execution time: 5_612_000 picoseconds. + Weight::from_parts(5_838_000, 3632) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + } + /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) + /// Proof: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) + /// Storage: `Contracts::MigrationInProgress` (r:1 w:1) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + fn on_runtime_upgrade() -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `3607` + // Minimum execution time: 5_487_000 picoseconds. + Weight::from_parts(5_693_000, 3607) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:1 w:0) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:1 w:0) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + /// Storage: `Timestamp::Now` (r:1 w:0) + /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + /// The range of component `c` is `[0, 125952]`. + fn call_with_code_per_byte(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `800 + c * (1 ±0)` + // Estimated: `4266 + c * (1 ±0)` + // Minimum execution time: 247_545_000 picoseconds. + Weight::from_parts(268_016_699, 4266) + // Standard Error: 4 + .saturating_add(Weight::from_parts(700, 0).saturating_mul(c.into())) + .saturating_add(RocksDbWeight::get().reads(6_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Balances::Holds` (r:2 w:2) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Storage: `Contracts::Nonce` (r:1 w:1) + /// Proof: `Contracts::Nonce` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `Timestamp::Now` (r:1 w:0) + /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:0 w:1) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + /// The range of component `c` is `[0, 125952]`. + /// The range of component `i` is `[0, 1048576]`. + /// The range of component `s` is `[0, 1048576]`. + fn instantiate_with_code(c: u32, i: u32, s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `323` + // Estimated: `6262` + // Minimum execution time: 4_396_772_000 picoseconds. + Weight::from_parts(235_107_907, 6262) + // Standard Error: 185 + .saturating_add(Weight::from_parts(53_843, 0).saturating_mul(c.into())) + // Standard Error: 22 + .saturating_add(Weight::from_parts(2_143, 0).saturating_mul(i.into())) + // Standard Error: 22 + .saturating_add(Weight::from_parts(2_210, 0).saturating_mul(s.into())) + .saturating_add(RocksDbWeight::get().reads(8_u64)) + .saturating_add(RocksDbWeight::get().writes(7_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:1 w:0) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + /// Storage: `Contracts::Nonce` (r:1 w:1) + /// Proof: `Contracts::Nonce` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `Timestamp::Now` (r:1 w:0) + /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + /// Storage: `Balances::Holds` (r:1 w:1) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// The range of component `i` is `[0, 1048576]`. + /// The range of component `s` is `[0, 1048576]`. + fn instantiate(i: u32, s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `560` + // Estimated: `4017` + // Minimum execution time: 2_240_868_000 picoseconds. + Weight::from_parts(2_273_668_000, 4017) + // Standard Error: 32 + .saturating_add(Weight::from_parts(934, 0).saturating_mul(i.into())) + // Standard Error: 32 + .saturating_add(Weight::from_parts(920, 0).saturating_mul(s.into())) + .saturating_add(RocksDbWeight::get().reads(8_u64)) + .saturating_add(RocksDbWeight::get().writes(5_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:1 w:0) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:1 w:0) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + /// Storage: `Timestamp::Now` (r:1 w:0) + /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + fn call() -> Weight { + // Proof Size summary in bytes: + // Measured: `826` + // Estimated: `4291` + // Minimum execution time: 165_067_000 picoseconds. + Weight::from_parts(168_582_000, 4291) + .saturating_add(RocksDbWeight::get().reads(6_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Balances::Holds` (r:1 w:1) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:0 w:1) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + /// The range of component `c` is `[0, 125952]`. + fn upload_code_determinism_enforced(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `3607` + // Minimum execution time: 229_454_000 picoseconds. + Weight::from_parts(251_495_551, 3607) + // Standard Error: 71 + .saturating_add(Weight::from_parts(51_428, 0).saturating_mul(c.into())) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Balances::Holds` (r:1 w:1) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:0 w:1) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + /// The range of component `c` is `[0, 125952]`. + fn upload_code_determinism_relaxed(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `3607` + // Minimum execution time: 240_390_000 picoseconds. + Weight::from_parts(273_854_266, 3607) + // Standard Error: 243 + .saturating_add(Weight::from_parts(51_836, 0).saturating_mul(c.into())) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Balances::Holds` (r:1 w:1) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:0 w:1) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + fn remove_code() -> Weight { + // Proof Size summary in bytes: + // Measured: `315` + // Estimated: `3780` + // Minimum execution time: 39_374_000 picoseconds. + Weight::from_parts(40_247_000, 3780) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) + } + /// Storage: `Contracts::MigrationInProgress` (r:1 w:0) + /// Proof: `Contracts::MigrationInProgress` (`max_values`: Some(1), `max_size`: Some(1026), added: 1521, mode: `Measured`) + /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:2 w:2) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + fn set_code() -> Weight { + // Proof Size summary in bytes: + // Measured: `552` + // Estimated: `6492` + // Minimum execution time: 24_473_000 picoseconds. + Weight::from_parts(25_890_000, 6492) + .saturating_add(RocksDbWeight::get().reads(4_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) + } + /// The range of component `r` is `[0, 1600]`. + fn noop_host_fn(r: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 8_528_000 picoseconds. + Weight::from_parts(9_301_010, 0) + // Standard Error: 98 + .saturating_add(Weight::from_parts(53_173, 0).saturating_mul(r.into())) + } + fn seal_caller() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 643_000 picoseconds. + Weight::from_parts(678_000, 0) + } + /// Storage: `Contracts::ContractInfoOf` (r:1 w:0) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + fn seal_is_contract() -> Weight { + // Proof Size summary in bytes: + // Measured: `354` + // Estimated: `3819` + // Minimum execution time: 6_107_000 picoseconds. + Weight::from_parts(6_235_000, 3819) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + } + /// Storage: `Contracts::ContractInfoOf` (r:1 w:0) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + fn seal_code_hash() -> Weight { + // Proof Size summary in bytes: + // Measured: `447` + // Estimated: `3912` + // Minimum execution time: 7_316_000 picoseconds. + Weight::from_parts(7_653_000, 3912) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + } + fn seal_own_code_hash() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 721_000 picoseconds. + Weight::from_parts(764_000, 0) + } + fn seal_caller_is_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 369_000 picoseconds. + Weight::from_parts(417_000, 0) + } + fn seal_caller_is_root() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 318_000 picoseconds. + Weight::from_parts(349_000, 0) + } + fn seal_address() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 590_000 picoseconds. + Weight::from_parts(628_000, 0) + } + fn seal_gas_left() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 660_000 picoseconds. + Weight::from_parts(730_000, 0) + } + fn seal_balance() -> Weight { + // Proof Size summary in bytes: + // Measured: `140` + // Estimated: `0` + // Minimum execution time: 4_361_000 picoseconds. + Weight::from_parts(4_577_000, 0) + } + fn seal_value_transferred() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 560_000 picoseconds. + Weight::from_parts(603_000, 0) + } + fn seal_minimum_balance() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 561_000 picoseconds. + Weight::from_parts(610_000, 0) + } + fn seal_block_number() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 557_000 picoseconds. + Weight::from_parts(583_000, 0) + } + fn seal_now() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 550_000 picoseconds. + Weight::from_parts(602_000, 0) + } + /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) + /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `Measured`) + fn seal_weight_to_fee() -> Weight { + // Proof Size summary in bytes: + // Measured: `67` + // Estimated: `1552` + // Minimum execution time: 4_065_000 picoseconds. + Weight::from_parts(4_291_000, 1552) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + } + /// The range of component `n` is `[0, 1048572]`. + fn seal_input(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 487_000 picoseconds. + Weight::from_parts(517_000, 0) + // Standard Error: 3 + .saturating_add(Weight::from_parts(301, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 1048572]`. + fn seal_return(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 318_000 picoseconds. + Weight::from_parts(372_000, 0) + // Standard Error: 10 + .saturating_add(Weight::from_parts(411, 0).saturating_mul(n.into())) + } + /// Storage: `Contracts::DeletionQueueCounter` (r:1 w:1) + /// Proof: `Contracts::DeletionQueueCounter` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:33 w:33) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Contracts::DeletionQueue` (r:0 w:1) + /// Proof: `Contracts::DeletionQueue` (`max_values`: None, `max_size`: Some(142), added: 2617, mode: `Measured`) + /// The range of component `n` is `[0, 32]`. + fn seal_terminate(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `319 + n * (78 ±0)` + // Estimated: `3784 + n * (2553 ±0)` + // Minimum execution time: 13_251_000 picoseconds. + Weight::from_parts(15_257_892, 3784) + // Standard Error: 7_089 + .saturating_add(Weight::from_parts(3_443_907, 0).saturating_mul(n.into())) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(n.into()))) + .saturating_add(RocksDbWeight::get().writes(3_u64)) + .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(n.into()))) + .saturating_add(Weight::from_parts(0, 2553).saturating_mul(n.into())) + } + /// Storage: `RandomnessCollectiveFlip::RandomMaterial` (r:1 w:0) + /// Proof: `RandomnessCollectiveFlip::RandomMaterial` (`max_values`: Some(1), `max_size`: Some(2594), added: 3089, mode: `Measured`) + fn seal_random() -> Weight { + // Proof Size summary in bytes: + // Measured: `76` + // Estimated: `1561` + // Minimum execution time: 3_434_000 picoseconds. + Weight::from_parts(3_605_000, 1561) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + } + /// Storage: `System::EventTopics` (r:4 w:4) + /// Proof: `System::EventTopics` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `t` is `[0, 4]`. + /// The range of component `n` is `[0, 16384]`. + fn seal_deposit_event(t: u32, n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `990 + t * (2475 ±0)` + // Minimum execution time: 3_668_000 picoseconds. + Weight::from_parts(3_999_591, 990) + // Standard Error: 5_767 + .saturating_add(Weight::from_parts(2_011_090, 0).saturating_mul(t.into())) + // Standard Error: 1 + .saturating_add(Weight::from_parts(12, 0).saturating_mul(n.into())) + .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(t.into()))) + .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(t.into()))) + .saturating_add(Weight::from_parts(0, 2475).saturating_mul(t.into())) + } + /// The range of component `i` is `[0, 1048576]`. + fn seal_debug_message(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 443_000 picoseconds. + Weight::from_parts(472_000, 0) + // Standard Error: 10 + .saturating_add(Weight::from_parts(1_207, 0).saturating_mul(i.into())) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn get_storage_empty() -> Weight { + // Proof Size summary in bytes: + // Measured: `16618` + // Estimated: `16618` + // Minimum execution time: 13_752_000 picoseconds. + Weight::from_parts(14_356_000, 16618) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn get_storage_full() -> Weight { + // Proof Size summary in bytes: + // Measured: `26628` + // Estimated: `26628` + // Minimum execution time: 43_444_000 picoseconds. + Weight::from_parts(45_087_000, 26628) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn set_storage_empty() -> Weight { + // Proof Size summary in bytes: + // Measured: `16618` + // Estimated: `16618` + // Minimum execution time: 15_616_000 picoseconds. + Weight::from_parts(16_010_000, 16618) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn set_storage_full() -> Weight { + // Proof Size summary in bytes: + // Measured: `26628` + // Estimated: `26628` + // Minimum execution time: 47_020_000 picoseconds. + Weight::from_parts(50_152_000, 26628) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `n` is `[0, 16384]`. + /// The range of component `o` is `[0, 16384]`. + fn seal_set_storage(n: u32, o: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `250 + o * (1 ±0)` + // Estimated: `249 + o * (1 ±0)` + // Minimum execution time: 8_824_000 picoseconds. + Weight::from_parts(8_915_233, 249) + // Standard Error: 1 + .saturating_add(Weight::from_parts(255, 0).saturating_mul(n.into())) + // Standard Error: 1 + .saturating_add(Weight::from_parts(39, 0).saturating_mul(o.into())) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(o.into())) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `n` is `[0, 16384]`. + fn seal_clear_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `248 + n * (1 ±0)` + // Estimated: `248 + n * (1 ±0)` + // Minimum execution time: 7_133_000 picoseconds. + Weight::from_parts(7_912_778, 248) + // Standard Error: 1 + .saturating_add(Weight::from_parts(88, 0).saturating_mul(n.into())) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `n` is `[0, 16384]`. + fn seal_get_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `248 + n * (1 ±0)` + // Estimated: `248 + n * (1 ±0)` + // Minimum execution time: 6_746_000 picoseconds. + Weight::from_parts(7_647_236, 248) + // Standard Error: 2 + .saturating_add(Weight::from_parts(603, 0).saturating_mul(n.into())) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `n` is `[0, 16384]`. + fn seal_contains_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `248 + n * (1 ±0)` + // Estimated: `248 + n * (1 ±0)` + // Minimum execution time: 6_247_000 picoseconds. + Weight::from_parts(6_952_661, 248) + // Standard Error: 1 + .saturating_add(Weight::from_parts(77, 0).saturating_mul(n.into())) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `n` is `[0, 16384]`. + fn seal_take_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `248 + n * (1 ±0)` + // Estimated: `248 + n * (1 ±0)` + // Minimum execution time: 7_428_000 picoseconds. + Weight::from_parts(8_384_015, 248) + // Standard Error: 2 + .saturating_add(Weight::from_parts(625, 0).saturating_mul(n.into())) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) + } + fn set_transient_storage_empty() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_478_000 picoseconds. + Weight::from_parts(1_533_000, 0) + } + fn set_transient_storage_full() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_485_000 picoseconds. + Weight::from_parts(2_728_000, 0) + } + fn get_transient_storage_empty() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_195_000 picoseconds. + Weight::from_parts(3_811_000, 0) + } + fn get_transient_storage_full() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_902_000 picoseconds. + Weight::from_parts(4_118_000, 0) + } + fn rollback_transient_storage() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_571_000 picoseconds. + Weight::from_parts(1_662_000, 0) + } + /// The range of component `n` is `[0, 16384]`. + /// The range of component `o` is `[0, 16384]`. + fn seal_set_transient_storage(n: u32, o: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 5_250_000 picoseconds. + Weight::from_parts(2_465_568, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(201, 0).saturating_mul(n.into())) + // Standard Error: 0 + .saturating_add(Weight::from_parts(223, 0).saturating_mul(o.into())) + } + /// The range of component `n` is `[0, 16384]`. + fn seal_clear_transient_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_012_000 picoseconds. + Weight::from_parts(2_288_004, 0) + // Standard Error: 3 + .saturating_add(Weight::from_parts(239, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 16384]`. + fn seal_get_transient_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_906_000 picoseconds. + Weight::from_parts(2_121_040, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(225, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 16384]`. + fn seal_contains_transient_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_736_000 picoseconds. + Weight::from_parts(1_954_728, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(111, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 16384]`. + fn seal_take_transient_storage(_n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_872_000 picoseconds. + Weight::from_parts(8_125_644, 0) + } + fn seal_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `140` + // Estimated: `0` + // Minimum execution time: 8_489_000 picoseconds. + Weight::from_parts(8_791_000, 0) + } + /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `Contracts::CodeInfoOf` (r:1 w:0) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:1 w:0) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + /// The range of component `t` is `[0, 1]`. + /// The range of component `i` is `[0, 1048576]`. + fn seal_call(t: u32, i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `620 + t * (280 ±0)` + // Estimated: `4085 + t * (2182 ±0)` + // Minimum execution time: 122_759_000 picoseconds. + Weight::from_parts(120_016_020, 4085) + // Standard Error: 173_118 + .saturating_add(Weight::from_parts(42_848_338, 0).saturating_mul(t.into())) + // Standard Error: 0 + .saturating_add(Weight::from_parts(6, 0).saturating_mul(i.into())) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(t.into()))) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(t.into()))) + .saturating_add(Weight::from_parts(0, 2182).saturating_mul(t.into())) + } + /// Storage: `Contracts::CodeInfoOf` (r:1 w:0) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:1 w:0) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + fn seal_delegate_call() -> Weight { + // Proof Size summary in bytes: + // Measured: `430` + // Estimated: `3895` + // Minimum execution time: 111_566_000 picoseconds. + Weight::from_parts(115_083_000, 3895) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + } + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:1 w:0) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + /// Storage: `Contracts::Nonce` (r:1 w:0) + /// Proof: `Contracts::Nonce` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) + /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) + /// The range of component `i` is `[0, 983040]`. + /// The range of component `s` is `[0, 983040]`. + fn seal_instantiate(i: u32, s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `676` + // Estimated: `4132` + // Minimum execution time: 1_871_402_000 picoseconds. + Weight::from_parts(1_890_038_000, 4132) + // Standard Error: 24 + .saturating_add(Weight::from_parts(581, 0).saturating_mul(i.into())) + // Standard Error: 24 + .saturating_add(Weight::from_parts(915, 0).saturating_mul(s.into())) + .saturating_add(RocksDbWeight::get().reads(5_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) + } + /// The range of component `n` is `[0, 1048576]`. + fn seal_hash_sha2_256(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 966_000 picoseconds. + Weight::from_parts(9_599_151, 0) + // Standard Error: 1 + .saturating_add(Weight::from_parts(1_336, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 1048576]`. + fn seal_hash_keccak_256(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_416_000 picoseconds. + Weight::from_parts(10_964_255, 0) + // Standard Error: 1 + .saturating_add(Weight::from_parts(3_593, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 1048576]`. + fn seal_hash_blake2_256(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 821_000 picoseconds. + Weight::from_parts(6_579_283, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(1_466, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 1048576]`. + fn seal_hash_blake2_128(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 773_000 picoseconds. + Weight::from_parts(10_990_209, 0) + // Standard Error: 1 + .saturating_add(Weight::from_parts(1_457, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 125697]`. + fn seal_sr25519_verify(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 43_195_000 picoseconds. + Weight::from_parts(41_864_855, 0) + // Standard Error: 9 + .saturating_add(Weight::from_parts(5_154, 0).saturating_mul(n.into())) + } + fn seal_ecdsa_recover() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 47_747_000 picoseconds. + Weight::from_parts(49_219_000, 0) + } + fn seal_ecdsa_to_eth_address() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 12_854_000 picoseconds. + Weight::from_parts(12_962_000, 0) + } + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + /// Storage: `Contracts::PristineCode` (r:1 w:0) + /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) + fn seal_set_code_hash() -> Weight { + // Proof Size summary in bytes: + // Measured: `430` + // Estimated: `3895` + // Minimum execution time: 17_868_000 picoseconds. + Weight::from_parts(18_486_000, 3895) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) + fn lock_delegate_dependency() -> Weight { + // Proof Size summary in bytes: + // Measured: `355` + // Estimated: `3820` + // Minimum execution time: 8_393_000 picoseconds. + Weight::from_parts(8_640_000, 3820) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) + /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `MaxEncodedLen`) + fn unlock_delegate_dependency() -> Weight { + // Proof Size summary in bytes: + // Measured: `355` + // Estimated: `3558` + // Minimum execution time: 7_489_000 picoseconds. + Weight::from_parts(7_815_000, 3558) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + fn seal_reentrance_count() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 299_000 picoseconds. + Weight::from_parts(339_000, 0) + } + fn seal_account_reentrance_count() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 324_000 picoseconds. + Weight::from_parts(380_000, 0) + } + /// Storage: `Contracts::Nonce` (r:1 w:0) + /// Proof: `Contracts::Nonce` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) + fn seal_instantiation_nonce() -> Weight { + // Proof Size summary in bytes: + // Measured: `219` + // Estimated: `1704` + // Minimum execution time: 2_768_000 picoseconds. + Weight::from_parts(3_025_000, 1704) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + } + /// The range of component `r` is `[0, 5000]`. + fn instr_i64_load_store(r: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 766_000 picoseconds. + Weight::from_parts(722_169, 0) + // Standard Error: 10 + .saturating_add(Weight::from_parts(7_191, 0).saturating_mul(r.into())) + } +} diff --git a/pallets/contracts/uapi/Cargo.toml b/pallets/contracts/uapi/Cargo.toml new file mode 100644 index 00000000..6744532d --- /dev/null +++ b/pallets/contracts/uapi/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "pallet-contracts-uapi" +version = "5.0.0" +authors.workspace = true +edition.workspace = true +license = "Apache-2.0" +homepage.workspace = true +repository.workspace = true +description = "Exposes all the host functions that a contract can import." + +[dependencies] +paste = { workspace = true } +bitflags = { workspace = true } +scale-info = { features = ["derive"], optional = true, workspace = true } +codec = { features = [ + "derive", + "max-encoded-len", +], optional = true, workspace = true } + +[target.'cfg(target_arch = "riscv32")'.dependencies] +polkavm-derive = { workspace = true } + +[package.metadata.docs.rs] +default-target = ["wasm32-unknown-unknown"] + +[features] +default = ["scale"] +scale = ["dep:codec", "scale-info"] diff --git a/pallets/contracts/uapi/src/flags.rs b/pallets/contracts/uapi/src/flags.rs new file mode 100644 index 00000000..9ad105b8 --- /dev/null +++ b/pallets/contracts/uapi/src/flags.rs @@ -0,0 +1,81 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use bitflags::bitflags; + +bitflags! { + /// Flags used by a contract to customize exit behaviour. + #[cfg_attr(feature = "scale", derive(codec::Encode, codec::Decode, scale_info::TypeInfo))] + pub struct ReturnFlags: u32 { + /// If this bit is set all changes made by the contract execution are rolled back. + const REVERT = 0x0000_0001; + } +} + +bitflags! { + /// Flags used to change the behaviour of `seal_call` and `seal_delegate_call`. + pub struct CallFlags: u32 { + /// Forward the input of current function to the callee. + /// + /// Supplied input pointers are ignored when set. + /// + /// # Note + /// + /// A forwarding call will consume the current contracts input. Any attempt to + /// access the input after this call returns will lead to [`Error::InputForwarded`]. + /// It does not matter if this is due to calling `seal_input` or trying another + /// forwarding call. Consider using [`Self::CLONE_INPUT`] in order to preserve + /// the input. + const FORWARD_INPUT = 0b0000_0001; + /// Identical to [`Self::FORWARD_INPUT`] but without consuming the input. + /// + /// This adds some additional weight costs to the call. + /// + /// # Note + /// + /// This implies [`Self::FORWARD_INPUT`] and takes precedence when both are set. + const CLONE_INPUT = 0b0000_0010; + /// Do not return from the call but rather return the result of the callee to the + /// callers caller. + /// + /// # Note + /// + /// This makes the current contract completely transparent to its caller by replacing + /// this contracts potential output by the callee ones. Any code after `seal_call` + /// can be safely considered unreachable. + const TAIL_CALL = 0b0000_0100; + /// Allow the callee to reenter into the current contract. + /// + /// Without this flag any reentrancy into the current contract that originates from + /// the callee (or any of its callees) is denied. This includes the first callee: + /// You cannot call into yourself with this flag set. + /// + /// # Note + /// + /// For `seal_delegate_call` should be always unset, otherwise + /// [`Error::InvalidCallFlags`] is returned. + const ALLOW_REENTRY = 0b0000_1000; + /// Indicates that the callee is restricted from modifying the state during call execution, + /// equivalent to Ethereum's STATICCALL. + /// + /// # Note + /// + /// For `seal_delegate_call` should be always unset, otherwise + /// [`Error::InvalidCallFlags`] is returned. + const READ_ONLY = 0b0001_0000; + } +} diff --git a/pallets/contracts/uapi/src/host.rs b/pallets/contracts/uapi/src/host.rs new file mode 100644 index 00000000..51f0cd7e --- /dev/null +++ b/pallets/contracts/uapi/src/host.rs @@ -0,0 +1,888 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// +// 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::{CallFlags, Result, ReturnFlags}; +use paste::paste; + +#[cfg(target_arch = "wasm32")] +mod wasm32; + +#[cfg(target_arch = "riscv32")] +mod riscv32; + +macro_rules! hash_fn { + ( $name:ident, $bytes:literal ) => { + paste! { + #[doc = "Computes the " $name " " $bytes "-bit hash on the given input buffer."] + #[doc = "\n# Notes\n"] + #[doc = "- The `input` and `output` buffer may overlap."] + #[doc = "- The output buffer is expected to hold at least " $bytes " bits."] + #[doc = "- It is the callers responsibility to provide an output buffer that is large enough to hold the expected amount of bytes returned by the hash function."] + #[doc = "\n# Parameters\n"] + #[doc = "- `input`: The input data buffer."] + #[doc = "- `output`: The output buffer to write the hash result to."] + fn [](input: &[u8], output: &mut [u8; $bytes]); + } + }; +} + +// TODO remove cfg once used by all targets +#[cfg(target_arch = "wasm32")] +#[inline(always)] +fn extract_from_slice(output: &mut &mut [u8], new_len: usize) { + debug_assert!(new_len <= output.len()); + let tmp = core::mem::take(output); + *output = &mut tmp[..new_len]; +} + +#[cfg(target_arch = "wasm32")] +#[inline(always)] +fn ptr_len_or_sentinel(data: &mut Option<&mut &mut [u8]>) -> (*mut u8, u32) { + match data { + Some(ref mut data) => (data.as_mut_ptr(), data.len() as _), + None => (crate::SENTINEL as _, 0), + } +} + +#[cfg(target_arch = "wasm32")] +#[inline(always)] +fn ptr_or_sentinel(data: &Option<&[u8]>) -> *const u8 { + match data { + Some(ref data) => data.as_ptr(), + None => crate::SENTINEL as _, + } +} + +/// Implements [`HostFn`] for each supported target architecture. +pub enum HostFnImpl {} + +/// Defines all the host apis implemented by both wasm and RISC-V vms. +pub trait HostFn: private::Sealed { + /// Returns the number of times specified contract exists on the call stack. Delegated calls are + /// not counted as separate calls. + /// + /// # Parameters + /// + /// - `account`: The contract address. Should be decodable as an `T::AccountId`. Traps + /// otherwise. + /// + /// # Return + /// + /// Returns the number of times specified contract exists on the call stack. + #[deprecated( + note = "Unstable function. Behaviour can change without further notice. Use only for testing." + )] + fn account_reentrance_count(account: &[u8]) -> u32; + + /// Stores the address of the current contract into the supplied buffer. + /// + /// If the available space in `output` is less than the size of the value a trap is triggered. + /// + /// # Parameters + /// + /// - `output`: A reference to the output data buffer to write the address. + fn address(output: &mut &mut [u8]); + + /// Lock a new delegate dependency to the contract. + /// + /// Traps if the maximum number of delegate_dependencies is reached or if + /// the delegate dependency already exists. + /// + /// # Parameters + /// + /// - `code_hash`: The code hash of the dependency. Should be decodable as an `T::Hash`. Traps + /// otherwise. + fn lock_delegate_dependency(code_hash: &[u8]); + + /// Stores the *free* balance of the current account into the supplied buffer. + /// + /// If the available space in `output` is less than the size of the value a trap is triggered. + /// + /// # Parameters + /// + /// - `output`: A reference to the output data buffer to write the balance. + fn balance(output: &mut &mut [u8]); + + /// Stores the current block number of the current contract into the supplied buffer. + /// + /// If the available space in `output` is less than the size of the value a trap is triggered. + /// + /// # Parameters + /// + /// - `output`: A reference to the output data buffer to write the block number. + fn block_number(output: &mut &mut [u8]); + + /// Make a call to another contract. + /// + /// This is equivalent to calling the newer version of this function with + /// `flags` set to [`CallFlags::ALLOW_REENTRY`]. See the newer version for documentation. + #[deprecated(note = "Deprecated, use newer version instead")] + fn call( + callee: &[u8], + gas: u64, + value: &[u8], + input_data: &[u8], + output: Option<&mut &mut [u8]>, + ) -> Result; + + /// Make a call to another contract. + /// + /// Equivalent to the newer [`Self::call_v2`] version but works with + /// *ref_time* Weight only + #[deprecated(note = "Deprecated, use newer version instead")] + fn call_v1( + flags: CallFlags, + callee: &[u8], + gas: u64, + value: &[u8], + input_data: &[u8], + output: Option<&mut &mut [u8]>, + ) -> Result; + + /// Call (possibly transferring some amount of funds) into the specified account. + /// + /// # Parameters + /// + /// - `flags`: See [`CallFlags`] for a documentation of the supported flags. + /// - `callee`: The address of the callee. Should be decodable as an `T::AccountId`. Traps + /// otherwise. + /// - `ref_time_limit`: how much *ref_time* Weight to devote to the execution. + /// - `proof_size_limit`: how much *proof_size* Weight to devote to the execution. + /// - `deposit`: The storage deposit limit for instantiation. Should be decodable as a + /// `Option`. Traps otherwise. Passing `None` means setting no specific limit for + /// the call, which implies storage usage up to the limit of the parent call. + /// - `value`: The value to transfer into the contract. Should be decodable as a `T::Balance`. + /// Traps otherwise. + /// - `input`: The input data buffer used to call the contract. + /// - `output`: A reference to the output data buffer to write the call output buffer. If `None` + /// is provided then the output buffer is not copied. + /// + /// # Errors + /// + /// An error means that the call wasn't successful output buffer is returned unless + /// stated otherwise. + /// + /// - [CalleeReverted][`crate::ReturnErrorCode::CalleeReverted]: Output buffer is returned. + /// - [CalleeTrapped][`crate::ReturnErrorCode::CalleeTrapped] + /// - [TransferFailed][`crate::ReturnErrorCode::TransferFailed] + /// - [NotCallable][`crate::ReturnErrorCode::NotCallable] + fn call_v2( + flags: CallFlags, + callee: &[u8], + ref_time_limit: u64, + proof_size_limit: u64, + deposit: Option<&[u8]>, + value: &[u8], + input_data: &[u8], + output: Option<&mut &mut [u8]>, + ) -> Result; + + /// Call into the chain extension provided by the chain if any. + /// + /// Handling of the input values is up to the specific chain extension and so is the + /// return value. The extension can decide to use the inputs as primitive inputs or as + /// in/out arguments by interpreting them as pointers. Any caller of this function + /// must therefore coordinate with the chain that it targets. + /// + /// # Note + /// + /// If no chain extension exists the contract will trap with the `NoChainExtension` + /// module error. + /// + /// # Parameters + /// + /// - `func_id`: The function id of the chain extension. + /// - `input`: The input data buffer. + /// - `output`: A reference to the output data buffer to write the call output buffer. If `None` + /// is provided then the output buffer is not copied. + /// + /// # Return + /// + /// The chain extension returned value, if executed successfully. + fn call_chain_extension(func_id: u32, input: &[u8], output: Option<&mut &mut [u8]>) -> u32; + + /// Call some dispatchable of the runtime. + /// + /// # Parameters + /// + /// - `call`: The call data. + /// + /// # Return + /// + /// Returns `Error::Success` when the dispatchable was successfully executed and + /// returned `Ok`. When the dispatchable was executed but returned an error + /// `Error::CallRuntimeFailed` is returned. The full error is not + /// provided because it is not guaranteed to be stable. + /// + /// # Comparison with `ChainExtension` + /// + /// Just as a chain extension this API allows the runtime to extend the functionality + /// of contracts. While making use of this function is generally easier it cannot be + /// used in all cases. Consider writing a chain extension if you need to do perform + /// one of the following tasks: + /// + /// - Return data. + /// - Provide functionality **exclusively** to contracts. + /// - Provide custom weights. + /// - Avoid the need to keep the `Call` data structure stable. + fn call_runtime(call: &[u8]) -> Result; + + /// Stores the address of the caller into the supplied buffer. + /// + /// If the available space in `output` is less than the size of the value a trap is triggered. + /// + /// If this is a top-level call (i.e. initiated by an extrinsic) the origin address of the + /// extrinsic will be returned. Otherwise, if this call is initiated by another contract then + /// the address of the contract will be returned. + /// + /// If there is no address associated with the caller (e.g. because the caller is root) then + /// it traps with `BadOrigin`. + /// + /// # Parameters + /// + /// - `output`: A reference to the output data buffer to write the caller address. + fn caller(output: &mut &mut [u8]); + + /// Checks whether the caller of the current contract is the origin of the whole call stack. + /// + /// Prefer this over [`is_contract()`][`Self::is_contract`] when checking whether your contract + /// is being called by a contract or a plain account. The reason is that it performs better + /// since it does not need to do any storage lookups. + /// + /// # Return + /// + /// A return value of `true` indicates that this contract is being called by a plain account + /// and `false` indicates that the caller is another contract. + fn caller_is_origin() -> bool; + + /// Checks whether the caller of the current contract is root. + /// + /// Note that only the origin of the call stack can be root. Hence this function returning + /// `true` implies that the contract is being called by the origin. + /// + /// A return value of `true` indicates that this contract is being called by a root origin, + /// and `false` indicates that the caller is a signed origin. + fn caller_is_root() -> u32; + + /// Clear the value at the given key in the contract storage. + /// + /// Equivalent to the newer [`Self::clear_storage_v1`] version with + /// the exception of the return type. Still a valid thing to call when not interested in the + /// return value. + fn clear_storage(key: &[u8]); + + /// Clear the value at the given key in the contract storage. + /// + /// # Parameters + /// + /// - `key`: The storage key. + /// + /// # Return + /// + /// Returns the size of the pre-existing value at the specified key if any. + fn clear_storage_v1(key: &[u8]) -> Option; + + /// Clear the value at the given key in the contract transient storage. + /// + /// # Parameters + /// + /// - `key`: The storage key. + /// + /// # Return + /// + /// Returns the size of the pre-existing value at the specified key if any. + #[deprecated( + note = "Unstable function. Behaviour can change without further notice. Use only for testing." + )] + fn clear_transient_storage(key: &[u8]) -> Option; + + /// Retrieve the code hash for a specified contract address. + /// + /// # Parameters + /// + /// - `account_id`: The address of the contract.Should be decodable as an `T::AccountId`. Traps + /// otherwise. + /// - `output`: A reference to the output data buffer to write the code hash. + /// + /// + /// # Errors + /// + /// - [CodeNotFound][`crate::ReturnErrorCode::CodeNotFound] + fn code_hash(account_id: &[u8], output: &mut [u8]) -> Result; + + /// Checks whether there is a value stored under the given key. + /// + /// This version is to be used with a fixed sized storage key. For runtimes supporting + /// transparent hashing, please use the newer version of this function. + fn contains_storage(key: &[u8]) -> Option; + + /// Checks whether there is a value stored under the given key. + /// + /// The key length must not exceed the maximum defined by the contracts module parameter. + /// + /// # Parameters + /// - `key`: The storage key. + /// + /// # Return + /// + /// Returns the size of the pre-existing value at the specified key if any. + fn contains_storage_v1(key: &[u8]) -> Option; + + /// Checks whether there is a value stored under the given key in transient storage. + /// + /// The key length must not exceed the maximum defined by the contracts module parameter. + /// + /// # Parameters + /// - `key`: The storage key. + /// + /// # Return + /// + /// Returns the size of the pre-existing value at the specified key if any. + #[deprecated( + note = "Unstable function. Behaviour can change without further notice. Use only for testing." + )] + fn contains_transient_storage(key: &[u8]) -> Option; + + /// Emit a custom debug message. + /// + /// No newlines are added to the supplied message. + /// Specifying invalid UTF-8 just drops the message with no trap. + /// + /// This is a no-op if debug message recording is disabled which is always the case + /// when the code is executing on-chain. The message is interpreted as UTF-8 and + /// appended to the debug buffer which is then supplied to the calling RPC client. + /// + /// # Note + /// + /// Even though no action is taken when debug message recording is disabled there is still + /// a non trivial overhead (and weight cost) associated with calling this function. Contract + /// languages should remove calls to this function (either at runtime or compile time) when + /// not being executed as an RPC. For example, they could allow users to disable logging + /// through compile time flags (cargo features) for on-chain deployment. Additionally, the + /// return value of this function can be cached in order to prevent further calls at runtime. + fn debug_message(str: &[u8]) -> Result; + + /// Execute code in the context (storage, caller, value) of the current contract. + /// + /// Reentrancy protection is always disabled since the callee is allowed + /// to modify the callers storage. This makes going through a reentrancy attack + /// unnecessary for the callee when it wants to exploit the caller. + /// + /// # Parameters + /// + /// - `flags`: See [`CallFlags`] for a documentation of the supported flags. + /// - `code_hash`: The hash of the code to be executed. + /// - `input`: The input data buffer used to call the contract. + /// - `output`: A reference to the output data buffer to write the call output buffer. If `None` + /// is provided then the output buffer is not copied. + /// + /// # Errors + /// + /// An error means that the call wasn't successful and no output buffer is returned unless + /// stated otherwise. + /// + /// - [CalleeReverted][`crate::ReturnErrorCode::CalleeReverted]: Output buffer is returned. + /// - [CalleeTrapped][`crate::ReturnErrorCode::CalleeTrapped] + /// - [CodeNotFound][`crate::ReturnErrorCode::CodeNotFound] + fn delegate_call( + flags: CallFlags, + code_hash: &[u8], + input_data: &[u8], + output: Option<&mut &mut [u8]>, + ) -> Result; + + /// Deposit a contract event with the data buffer and optional list of topics. There is a limit + /// on the maximum number of topics specified by `event_topics`. + /// + /// There should not be any duplicates in `topics`. + /// + /// # Parameters + /// + /// - `topics`: The topics list encoded as `Vec`. It can't contain duplicates. + fn deposit_event(topics: &[u8], data: &[u8]); + + /// Recovers the ECDSA public key from the given message hash and signature. + /// + /// Writes the public key into the given output buffer. + /// Assumes the secp256k1 curve. + /// + /// # Parameters + /// + /// - `signature`: The signature bytes. + /// - `message_hash`: The message hash bytes. + /// - `output`: A reference to the output data buffer to write the public key. + /// + /// # Errors + /// + /// - [EcdsaRecoveryFailed][`crate::ReturnErrorCode::EcdsaRecoveryFailed] + fn ecdsa_recover( + signature: &[u8; 65], + message_hash: &[u8; 32], + output: &mut [u8; 33], + ) -> Result; + + /// Calculates Ethereum address from the ECDSA compressed public key and stores + /// it into the supplied buffer. + /// + /// # Parameters + /// + /// - `pubkey`: The public key bytes. + /// - `output`: A reference to the output data buffer to write the address. + /// + /// # Errors + /// + /// - [EcdsaRecoveryFailed][`crate::ReturnErrorCode::EcdsaRecoveryFailed] + fn ecdsa_to_eth_address(pubkey: &[u8; 33], output: &mut [u8; 20]) -> Result; + + /// Stores the weight left into the supplied buffer. + /// + /// Equivalent to the newer [`Self::gas_left_v1`] version but + /// works with *ref_time* Weight only. + fn gas_left(out: &mut &mut [u8]); + + /// Stores the amount of weight left into the supplied buffer. + /// The data is encoded as Weight. + /// + /// If the available space in `output` is less than the size of the value a trap is triggered. + /// + /// # Parameters + /// + /// - `output`: A reference to the output data buffer to write the weight left. + #[deprecated( + note = "Unstable function. Behaviour can change without further notice. Use only for testing." + )] + fn gas_left_v1(output: &mut &mut [u8]); + + /// Retrieve the value under the given key from storage. + /// + /// This version is to be used with a fixed sized storage key. For runtimes supporting + /// transparent hashing, please use the newer version of this function. + fn get_storage(key: &[u8], output: &mut &mut [u8]) -> Result; + + /// Retrieve the value under the given key from storage. + /// + /// The key length must not exceed the maximum defined by the contracts module parameter. + /// + /// # Parameters + /// - `key`: The storage key. + /// - `output`: A reference to the output data buffer to write the storage entry. + /// + /// # Errors + /// + /// [KeyNotFound][`crate::ReturnErrorCode::KeyNotFound] + fn get_storage_v1(key: &[u8], output: &mut &mut [u8]) -> Result; + + /// Retrieve the value under the given key from transient storage. + /// + /// The key length must not exceed the maximum defined by the contracts module parameter. + /// + /// # Parameters + /// - `key`: The storage key. + /// - `output`: A reference to the output data buffer to write the storage entry. + /// + /// # Errors + /// + /// [KeyNotFound][`crate::ReturnErrorCode::KeyNotFound] + #[deprecated( + note = "Unstable function. Behaviour can change without further notice. Use only for testing." + )] + fn get_transient_storage(key: &[u8], output: &mut &mut [u8]) -> Result; + + hash_fn!(sha2_256, 32); + hash_fn!(keccak_256, 32); + hash_fn!(blake2_256, 32); + hash_fn!(blake2_128, 16); + + /// Stores the input passed by the caller into the supplied buffer. + /// + /// # Note + /// + /// This function traps if: + /// - the input is larger than the available space. + /// - the input was previously forwarded by a [`call()`][`Self::call()`]. + /// + /// # Parameters + /// + /// - `output`: A reference to the output data buffer to write the input data. + fn input(output: &mut &mut [u8]); + + /// Instantiate a contract with the specified code hash. + /// + /// Equivalent to the newer [`Self::instantiate_v2`] version but works + /// with *ref_time* Weight only. + #[deprecated(note = "Deprecated, use newer version instead")] + fn instantiate_v1( + code_hash: &[u8], + gas: u64, + value: &[u8], + input: &[u8], + address: Option<&mut &mut [u8]>, + output: Option<&mut &mut [u8]>, + salt: &[u8], + ) -> Result; + + /// Instantiate a contract with the specified code hash. + /// + /// This function creates an account and executes the constructor defined in the code specified + /// by the code hash. + /// + /// # Parameters + /// + /// - `code_hash`: The hash of the code to be instantiated. + /// - `ref_time_limit`: how much *ref_time* Weight to devote to the execution. + /// - `proof_size_limit`: how much *proof_size* Weight to devote to the execution. + /// - `deposit`: The storage deposit limit for instantiation. Should be decodable as a + /// `Option`. Traps otherwise. Passing `None` means setting no specific limit for + /// the call, which implies storage usage up to the limit of the parent call. + /// - `value`: The value to transfer into the contract. Should be decodable as a `T::Balance`. + /// Traps otherwise. + /// - `input`: The input data buffer. + /// - `address`: A reference to the address buffer to write the address of the contract. If + /// `None` is provided then the output buffer is not copied. + /// - `output`: A reference to the return value buffer to write the constructor output buffer. + /// If `None` is provided then the output buffer is not copied. + /// - `salt`: The salt bytes to use for this instantiation. + /// + /// # Errors + /// + /// Please consult the [ReturnErrorCode][`crate::ReturnErrorCode`] enum declaration for more + /// information on those errors. Here we only note things specific to this function. + /// + /// An error means that the account wasn't created and no address or output buffer + /// is returned unless stated otherwise. + /// + /// - [CalleeReverted][`crate::ReturnErrorCode::CalleeReverted]: Output buffer is returned. + /// - [CalleeTrapped][`crate::ReturnErrorCode::CalleeTrapped] + /// - [TransferFailed][`crate::ReturnErrorCode::TransferFailed] + /// - [CodeNotFound][`crate::ReturnErrorCode::CodeNotFound] + fn instantiate_v2( + code_hash: &[u8], + ref_time_limit: u64, + proof_size_limit: u64, + deposit: Option<&[u8]>, + value: &[u8], + input: &[u8], + address: Option<&mut &mut [u8]>, + output: Option<&mut &mut [u8]>, + salt: &[u8], + ) -> Result; + + /// Returns a nonce that is unique per contract instantiation. + /// + /// The nonce is incremented for each successful contract instantiation. This is a + /// sensible default salt for contract instantiations. + fn instantiation_nonce() -> u64; + + /// Checks whether a specified address belongs to a contract. + /// + /// # Parameters + /// + /// - `account_id`: The address to check. Should be decodable as an `T::AccountId`. Traps + /// otherwise. + /// + /// # Return + /// + /// Returns `true` if the address belongs to a contract. + fn is_contract(account_id: &[u8]) -> bool; + + /// Stores the minimum balance (a.k.a. existential deposit) into the supplied buffer. + /// The data is encoded as `T::Balance`. + /// + /// If the available space in `output` is less than the size of the value a trap is triggered. + /// + /// # Parameters + /// + /// - `output`: A reference to the output data buffer to write the minimum balance. + fn minimum_balance(output: &mut &mut [u8]); + + /// Retrieve the code hash of the currently executing contract. + /// + /// # Parameters + /// + /// - `output`: A reference to the output data buffer to write the code hash. + fn own_code_hash(output: &mut [u8]); + + /// Load the latest block timestamp into the supplied buffer + /// + /// If the available space in `output` is less than the size of the value a trap is triggered. + /// + /// # Parameters + /// + /// - `output`: A reference to the output data buffer to write the timestamp. + fn now(output: &mut &mut [u8]); + + /// Returns the number of times the currently executing contract exists on the call stack in + /// addition to the calling instance. + /// + /// # Return + /// + /// Returns `0` when there is no reentrancy. + #[deprecated( + note = "Unstable function. Behaviour can change without further notice. Use only for testing." + )] + fn reentrance_count() -> u32; + + /// Removes the delegate dependency from the contract. + /// + /// Traps if the delegate dependency does not exist. + /// + /// # Parameters + /// + /// - `code_hash`: The code hash of the dependency. Should be decodable as an `T::Hash`. Traps + /// otherwise. + fn unlock_delegate_dependency(code_hash: &[u8]); + + /// Cease contract execution and save a data buffer as a result of the execution. + /// + /// This function never returns as it stops execution of the caller. + /// This is the only way to return a data buffer to the caller. Returning from + /// execution without calling this function is equivalent to calling: + /// ```nocompile + /// return_value(ReturnFlags::empty(), &[]) + /// ``` + /// + /// Using an unnamed non empty `ReturnFlags` triggers a trap. + /// + /// # Parameters + /// + /// - `flags`: Flag used to signal special return conditions to the supervisor. See + /// [`ReturnFlags`] for a documentation of the supported flags. + /// - `return_value`: The return value buffer. + fn return_value(flags: ReturnFlags, return_value: &[u8]) -> !; + + /// Replace the contract code at the specified address with new code. + /// + /// # Note + /// + /// There are a couple of important considerations which must be taken into account when + /// using this API: + /// + /// 1. The storage at the code address will remain untouched. This means that contract + /// developers must ensure that the storage layout of the new code is compatible with that of + /// the old code. + /// + /// 2. Contracts using this API can't be assumed as having deterministic addresses. Said another + /// way, when using this API you lose the guarantee that an address always identifies a specific + /// code hash. + /// + /// 3. If a contract calls into itself after changing its code the new call would use + /// the new code. However, if the original caller panics after returning from the sub call it + /// would revert the changes made by [`set_code_hash()`][`Self::set_code_hash`] and the next + /// caller would use the old code. + /// + /// # Parameters + /// + /// - `code_hash`: The hash of the new code. Should be decodable as an `T::Hash`. Traps + /// otherwise. + /// + /// # Errors + /// + /// - [CodeNotFound][`crate::ReturnErrorCode::CodeNotFound] + fn set_code_hash(code_hash: &[u8]) -> Result; + + /// Set the value at the given key in the contract storage. + /// + /// Equivalent to [`Self::set_storage_v1`] version with the + /// exception of the return type. Still a valid thing to call for fixed sized storage key, when + /// not interested in the return value. + fn set_storage(key: &[u8], value: &[u8]); + + /// Set the value at the given key in the contract storage. + /// + /// This version is to be used with a fixed sized storage key. For runtimes supporting + /// transparent hashing, please use the newer version of this function. + fn set_storage_v1(key: &[u8], value: &[u8]) -> Option; + + /// Set the value at the given key in the contract storage. + /// + /// The key and value lengths must not exceed the maximums defined by the contracts module + /// parameters. + /// + /// # Parameters + /// + /// - `key`: The storage key. + /// - `encoded_value`: The storage value. + /// + /// # Return + /// + /// Returns the size of the pre-existing value at the specified key if any. + fn set_storage_v2(key: &[u8], value: &[u8]) -> Option; + + /// Set the value at the given key in the contract transient storage. + /// + /// The key and value lengths must not exceed the maximums defined by the contracts module + /// parameters. + /// + /// # Parameters + /// + /// - `key`: The storage key. + /// - `encoded_value`: The storage value. + /// + /// # Return + /// + /// Returns the size of the pre-existing value at the specified key if any. + #[deprecated( + note = "Unstable function. Behaviour can change without further notice. Use only for testing." + )] + fn set_transient_storage(key: &[u8], value: &[u8]) -> Option; + + /// Verify a sr25519 signature + /// + /// # Parameters + /// + /// - `signature`: The signature bytes. + /// - `message`: The message bytes. + /// + /// # Errors + /// + /// - [Sr25519VerifyFailed][`crate::ReturnErrorCode::Sr25519VerifyFailed] + fn sr25519_verify(signature: &[u8; 64], message: &[u8], pub_key: &[u8; 32]) -> Result; + + /// Retrieve and remove the value under the given key from storage. + /// + /// # Parameters + /// - `key`: The storage key. + /// - `output`: A reference to the output data buffer to write the storage entry. + /// + /// # Errors + /// + /// [KeyNotFound][`crate::ReturnErrorCode::KeyNotFound] + fn take_storage(key: &[u8], output: &mut &mut [u8]) -> Result; + + /// Retrieve and remove the value under the given key from transient storage. + /// + /// # Parameters + /// - `key`: The storage key. + /// - `output`: A reference to the output data buffer to write the storage entry. + /// + /// # Errors + /// + /// [KeyNotFound][`crate::ReturnErrorCode::KeyNotFound] + #[deprecated( + note = "Unstable function. Behaviour can change without further notice. Use only for testing." + )] + fn take_transient_storage(key: &[u8], output: &mut &mut [u8]) -> Result; + + /// Transfer some amount of funds into the specified account. + /// + /// # Parameters + /// + /// - `account_id`: The address of the account to transfer funds to. Should be decodable as an + /// `T::AccountId`. Traps otherwise. + /// - `value`: The value to transfer. Should be decodable as a `T::Balance`. Traps otherwise. + /// + /// # Errors + /// + /// - [TransferFailed][`crate::ReturnErrorCode::TransferFailed] + fn transfer(account_id: &[u8], value: &[u8]) -> Result; + + /// Remove the calling account and transfer remaining balance. + /// + /// This is equivalent to calling the newer version of this function + #[deprecated(note = "Deprecated, use newer version instead")] + fn terminate(beneficiary: &[u8]) -> !; + + /// Remove the calling account and transfer remaining **free** balance. + /// + /// This function never returns. Either the termination was successful and the + /// execution of the destroyed contract is halted. Or it failed during the termination + /// which is considered fatal and results in a trap + rollback. + /// + /// # Parameters + /// + /// - `beneficiary`: The address of the beneficiary account, Should be decodable as an + /// `T::AccountId`. + /// + /// # Traps + /// + /// - The contract is live i.e is already on the call stack. + /// - Failed to send the balance to the beneficiary. + /// - The deletion queue is full. + fn terminate_v1(beneficiary: &[u8]) -> !; + + /// Stores the value transferred along with this call/instantiate into the supplied buffer. + /// The data is encoded as `T::Balance`. + /// + /// If the available space in `output` is less than the size of the value a trap is triggered. + /// + /// # Parameters + /// + /// - `output`: A reference to the output data buffer to write the transferred value. + fn value_transferred(output: &mut &mut [u8]); + + /// Stores the price for the specified amount of gas into the supplied buffer. + /// + /// Equivalent to the newer [`Self::weight_to_fee_v1`] version but + /// works with *ref_time* Weight only. It is recommended to switch to the latest version, once + /// it's stabilized. + fn weight_to_fee(gas: u64, output: &mut &mut [u8]); + + /// Stores the price for the specified amount of gas into the supplied buffer. + /// The data is encoded as `T::Balance`. + /// + /// If the available space in `output` is less than the size of the value a trap is triggered. + /// + /// # Parameters + /// + /// - `ref_time_limit`: The *ref_time* Weight limit to query the price for. + /// - `proof_size_limit`: The *proof_size* Weight limit to query the price for. + /// - `output`: A reference to the output data buffer to write the price. + #[deprecated( + note = "Unstable function. Behaviour can change without further notice. Use only for testing." + )] + fn weight_to_fee_v1(ref_time_limit: u64, proof_size_limit: u64, output: &mut &mut [u8]); + + /// Execute an XCM program locally, using the contract's address as the origin. + /// This is equivalent to dispatching `pallet_xcm::execute` through call_runtime, except that + /// the function is called directly instead of being dispatched. + /// + /// # Parameters + /// + /// - `msg`: The message, should be decodable as a [VersionedXcm](https://paritytech.github.io/polkadot-sdk/master/staging_xcm/enum.VersionedXcm.html), + /// traps otherwise. + /// - `output`: A reference to the output data buffer to write the [Outcome](https://paritytech.github.io/polkadot-sdk/master/staging_xcm/v3/enum.Outcome.html) + /// + /// # Return + /// + /// Returns `Error::Success` when the XCM execution attempt is successful. When the XCM + /// execution fails, `ReturnCode::XcmExecutionFailed` is returned + #[deprecated( + note = "Unstable function. Behaviour can change without further notice. Use only for testing." + )] + fn xcm_execute(msg: &[u8]) -> Result; + + /// Send an XCM program from the contract to the specified destination. + /// This is equivalent to dispatching `pallet_xcm::send` through `call_runtime`, except that + /// the function is called directly instead of being dispatched. + /// + /// # Parameters + /// + /// - `dest`: The XCM destination, should be decodable as [VersionedLocation](https://paritytech.github.io/polkadot-sdk/master/staging_xcm/enum.VersionedLocation.html), + /// traps otherwise. + /// - `msg`: The message, should be decodable as a [VersionedXcm](https://paritytech.github.io/polkadot-sdk/master/staging_xcm/enum.VersionedXcm.html), + /// traps otherwise. + /// + /// # Return + /// + /// Returns `ReturnCode::Success` when the message was successfully sent. When the XCM + /// execution fails, `ReturnErrorCode::XcmSendFailed` is returned. + #[deprecated( + note = "Unstable function. Behaviour can change without further notice. Use only for testing." + )] + fn xcm_send(dest: &[u8], msg: &[u8], output: &mut [u8; 32]) -> Result; +} + +mod private { + pub trait Sealed {} + impl Sealed for super::HostFnImpl {} +} diff --git a/pallets/contracts/uapi/src/host/riscv32.rs b/pallets/contracts/uapi/src/host/riscv32.rs new file mode 100644 index 00000000..35552023 --- /dev/null +++ b/pallets/contracts/uapi/src/host/riscv32.rs @@ -0,0 +1,327 @@ +#![allow(unused_variables, unused_mut)] +// Copyright (C) Parity Technologies (UK) Ltd. +// +// 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. +// TODO: bring up to date with wasm32.rs + +use super::{CallFlags, HostFn, HostFnImpl, Result}; +use crate::ReturnFlags; + +/// A macro to implement all Host functions with a signature of `fn(&mut &mut [u8])`. +/// +/// Example: +/// ```nocompile +// impl_wrapper_for! { +// () => [gas_left], +// (v1) => [gas_left], +// } +// ``` +// +// Expands to: +// ```nocompile +// fn gas_left(output: &mut &mut [u8]) { +// unsafe { sys::gas_left(...); } +// } +// fn gas_left_v1(output: &mut &mut [u8]) { +// unsafe { sys::v1::gas_left(...); } +// } +// ``` +macro_rules! impl_wrapper_for { + (@impl_fn $( $mod:ident )::*, $suffix_sep: literal, $suffix:tt, $name:ident) => { + paste::paste! { + fn [<$name $suffix_sep $suffix>](output: &mut &mut [u8]) { + todo!() + } + } + }; + + () => {}; + + (($mod:ident) => [$( $name:ident),*], $($tail:tt)*) => { + $(impl_wrapper_for!(@impl_fn sys::$mod, "_", $mod, $name);)* + impl_wrapper_for!($($tail)*); + }; + + (() => [$( $name:ident),*], $($tail:tt)*) => { + $(impl_wrapper_for!(@impl_fn sys, "", "", $name);)* + impl_wrapper_for!($($tail)*); + }; +} + +/// A macro to implement all the hash functions Apis. +macro_rules! impl_hash_fn { + ( $name:ident, $bytes_result:literal ) => { + paste::item! { + fn [](input: &[u8], output: &mut [u8; $bytes_result]) { + todo!() + } + } + }; +} + +/// A macro to implement the get_storage functions. +macro_rules! impl_get_storage { + ($fn_name:ident, $sys_get_storage:path) => { + fn $fn_name(key: &[u8], output: &mut &mut [u8]) -> Result { + todo!() + } + }; +} + +impl HostFn for HostFnImpl { + fn instantiate_v1( + code_hash: &[u8], + gas: u64, + value: &[u8], + input: &[u8], + mut address: Option<&mut &mut [u8]>, + mut output: Option<&mut &mut [u8]>, + salt: &[u8], + ) -> Result { + todo!() + } + + fn instantiate_v2( + code_hash: &[u8], + ref_time_limit: u64, + proof_size_limit: u64, + deposit: Option<&[u8]>, + value: &[u8], + input: &[u8], + mut address: Option<&mut &mut [u8]>, + mut output: Option<&mut &mut [u8]>, + salt: &[u8], + ) -> Result { + todo!() + } + + fn call( + callee: &[u8], + gas: u64, + value: &[u8], + input_data: &[u8], + mut output: Option<&mut &mut [u8]>, + ) -> Result { + todo!() + } + + fn call_v1( + flags: CallFlags, + callee: &[u8], + gas: u64, + value: &[u8], + input_data: &[u8], + mut output: Option<&mut &mut [u8]>, + ) -> Result { + todo!() + } + + fn call_v2( + flags: CallFlags, + callee: &[u8], + ref_time_limit: u64, + proof_size_limit: u64, + deposit: Option<&[u8]>, + value: &[u8], + input_data: &[u8], + mut output: Option<&mut &mut [u8]>, + ) -> Result { + todo!() + } + + fn caller_is_root() -> u32 { + todo!() + } + + fn delegate_call( + flags: CallFlags, + code_hash: &[u8], + input: &[u8], + mut output: Option<&mut &mut [u8]>, + ) -> Result { + todo!() + } + + fn transfer(account_id: &[u8], value: &[u8]) -> Result { + todo!() + } + + fn deposit_event(topics: &[u8], data: &[u8]) { + todo!() + } + + fn set_storage(key: &[u8], value: &[u8]) { + todo!() + } + + fn set_storage_v1(key: &[u8], encoded_value: &[u8]) -> Option { + todo!() + } + + fn set_storage_v2(key: &[u8], encoded_value: &[u8]) -> Option { + todo!() + } + + fn set_transient_storage(key: &[u8], encoded_value: &[u8]) -> Option { + todo!() + } + + fn clear_storage(key: &[u8]) { + todo!() + } + + fn clear_storage_v1(key: &[u8]) -> Option { + todo!() + } + + fn clear_transient_storage(key: &[u8]) -> Option { + todo!() + } + + impl_get_storage!(get_storage, sys::get_storage); + impl_get_storage!(get_storage_v1, sys::v1::get_storage); + + fn get_transient_storage(key: &[u8], output: &mut &mut [u8]) -> Result { + todo!() + } + + fn take_storage(key: &[u8], output: &mut &mut [u8]) -> Result { + todo!() + } + + fn take_transient_storage(key: &[u8], output: &mut &mut [u8]) -> Result { + todo!() + } + + fn contains_storage(key: &[u8]) -> Option { + todo!() + } + + fn contains_storage_v1(key: &[u8]) -> Option { + todo!() + } + + fn contains_transient_storage(key: &[u8]) -> Option { + todo!() + } + + fn terminate(beneficiary: &[u8]) -> ! { + todo!() + } + + fn terminate_v1(beneficiary: &[u8]) -> ! { + todo!() + } + + fn call_chain_extension(func_id: u32, input: &[u8], output: Option<&mut &mut [u8]>) -> u32 { + todo!() + } + + fn input(output: &mut &mut [u8]) { + todo!() + } + + fn return_value(flags: ReturnFlags, return_value: &[u8]) -> ! { + todo!() + } + + fn call_runtime(call: &[u8]) -> Result { + todo!() + } + + fn debug_message(str: &[u8]) -> Result { + todo!() + } + + impl_wrapper_for! { + () => [caller, block_number, address, balance, gas_left, value_transferred, now, minimum_balance], + (v1) => [gas_left], + } + + fn weight_to_fee(gas: u64, output: &mut &mut [u8]) { + todo!() + } + + fn weight_to_fee_v1(ref_time_limit: u64, proof_size_limit: u64, output: &mut &mut [u8]) { + todo!() + } + + impl_hash_fn!(sha2_256, 32); + impl_hash_fn!(keccak_256, 32); + impl_hash_fn!(blake2_256, 32); + impl_hash_fn!(blake2_128, 16); + + fn ecdsa_recover( + signature: &[u8; 65], + message_hash: &[u8; 32], + output: &mut [u8; 33], + ) -> Result { + todo!() + } + + fn ecdsa_to_eth_address(pubkey: &[u8; 33], output: &mut [u8; 20]) -> Result { + todo!() + } + + fn sr25519_verify(signature: &[u8; 64], message: &[u8], pub_key: &[u8; 32]) -> Result { + todo!() + } + + fn is_contract(account_id: &[u8]) -> bool { + todo!() + } + + fn caller_is_origin() -> bool { + todo!() + } + + fn set_code_hash(code_hash: &[u8]) -> Result { + todo!() + } + + fn code_hash(account_id: &[u8], output: &mut [u8]) -> Result { + todo!() + } + + fn own_code_hash(output: &mut [u8]) { + todo!() + } + + fn account_reentrance_count(account: &[u8]) -> u32 { + todo!() + } + + fn lock_delegate_dependency(code_hash: &[u8]) { + todo!() + } + + fn unlock_delegate_dependency(code_hash: &[u8]) { + todo!() + } + + fn instantiation_nonce() -> u64 { + todo!() + } + + fn reentrance_count() -> u32 { + todo!() + } + + fn xcm_execute(msg: &[u8]) -> Result { + todo!() + } + + fn xcm_send(dest: &[u8], msg: &[u8], output: &mut [u8; 32]) -> Result { + todo!() + } +} diff --git a/pallets/contracts/uapi/src/host/wasm32.rs b/pallets/contracts/uapi/src/host/wasm32.rs new file mode 100644 index 00000000..55600bc3 --- /dev/null +++ b/pallets/contracts/uapi/src/host/wasm32.rs @@ -0,0 +1,915 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// +// 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 super::{ + extract_from_slice, ptr_len_or_sentinel, ptr_or_sentinel, CallFlags, HostFn, HostFnImpl, Result, +}; +use crate::{ReturnCode, ReturnFlags}; + +mod sys { + use super::ReturnCode; + + #[link(wasm_import_module = "seal0")] + extern "C" { + pub fn account_reentrance_count(account_ptr: *const u8) -> u32; + + pub fn lock_delegate_dependency(code_hash_ptr: *const u8); + + pub fn address(output_ptr: *mut u8, output_len_ptr: *mut u32); + + pub fn balance(output_ptr: *mut u8, output_len_ptr: *mut u32); + + pub fn block_number(output_ptr: *mut u8, output_len_ptr: *mut u32); + + pub fn call( + callee_ptr: *const u8, + callee_len: u32, + gas: u64, + value_ptr: *const u8, + value_len: u32, + input_data_ptr: *const u8, + input_data_len: u32, + output_ptr: *mut u8, + output_len_ptr: *mut u32, + ) -> ReturnCode; + + pub fn call_chain_extension( + func_id: u32, + input_ptr: *const u8, + input_len: u32, + output_ptr: *mut u8, + output_len_ptr: *mut u32, + ) -> ReturnCode; + + pub fn call_runtime(call_ptr: *const u8, call_len: u32) -> ReturnCode; + + pub fn caller(output_ptr: *mut u8, output_len_ptr: *mut u32); + + pub fn caller_is_origin() -> ReturnCode; + + pub fn caller_is_root() -> ReturnCode; + + pub fn clear_storage(key_ptr: *const u8); + + pub fn clear_transient_storage(key_ptr: *const u8, key_len: u32) -> ReturnCode; + + pub fn code_hash( + account_id_ptr: *const u8, + output_ptr: *mut u8, + output_len_ptr: *mut u32, + ) -> ReturnCode; + + pub fn contains_storage(key_ptr: *const u8) -> ReturnCode; + + pub fn contains_transient_storage(key_ptr: *const u8, key_len: u32) -> ReturnCode; + + pub fn debug_message(str_ptr: *const u8, str_len: u32) -> ReturnCode; + + pub fn delegate_call( + flags: u32, + code_hash_ptr: *const u8, + input_data_ptr: *const u8, + input_data_len: u32, + output_ptr: *mut u8, + output_len_ptr: *mut u32, + ) -> ReturnCode; + + pub fn deposit_event( + topics_ptr: *const u8, + topics_len: u32, + data_ptr: *const u8, + data_len: u32, + ); + + pub fn ecdsa_recover( + signature_ptr: *const u8, + message_hash_ptr: *const u8, + output_ptr: *mut u8, + ) -> ReturnCode; + + pub fn ecdsa_to_eth_address(public_key_ptr: *const u8, output_ptr: *mut u8) -> ReturnCode; + + pub fn gas_left(output_ptr: *mut u8, output_len_ptr: *mut u32); + + pub fn get_storage( + key_ptr: *const u8, + out_ptr: *mut u8, + out_len_ptr: *mut u32, + ) -> ReturnCode; + + pub fn get_transient_storage( + key_ptr: *const u8, + key_len: u32, + out_ptr: *mut u8, + out_len_ptr: *mut u32, + ) -> ReturnCode; + + pub fn hash_blake2_128(input_ptr: *const u8, input_len: u32, output_ptr: *mut u8); + + pub fn hash_blake2_256(input_ptr: *const u8, input_len: u32, output_ptr: *mut u8); + + pub fn hash_keccak_256(input_ptr: *const u8, input_len: u32, output_ptr: *mut u8); + + pub fn hash_sha2_256(input_ptr: *const u8, input_len: u32, output_ptr: *mut u8); + + pub fn input(buf_ptr: *mut u8, buf_len_ptr: *mut u32); + + pub fn instantiation_nonce() -> u64; + + pub fn is_contract(account_id_ptr: *const u8) -> ReturnCode; + + pub fn minimum_balance(output_ptr: *mut u8, output_len_ptr: *mut u32); + + pub fn now(output_ptr: *mut u8, output_len_ptr: *mut u32); + + pub fn own_code_hash(output_ptr: *mut u8, output_len_ptr: *mut u32); + + pub fn reentrance_count() -> u32; + + pub fn unlock_delegate_dependency(code_hash_ptr: *const u8); + + pub fn seal_return(flags: u32, data_ptr: *const u8, data_len: u32) -> !; + + pub fn set_code_hash(code_hash_ptr: *const u8) -> ReturnCode; + + pub fn set_storage(key_ptr: *const u8, value_ptr: *const u8, value_len: u32); + + pub fn set_transient_storage( + key_ptr: *const u8, + key_len: u32, + value_ptr: *const u8, + value_len: u32, + ) -> ReturnCode; + + pub fn sr25519_verify( + signature_ptr: *const u8, + public_key_ptr: *const u8, + message_len: u32, + message_ptr: *const u8, + ) -> ReturnCode; + + pub fn take_storage( + key_ptr: *const u8, + key_len: u32, + out_ptr: *mut u8, + out_len_ptr: *mut u32, + ) -> ReturnCode; + + pub fn take_transient_storage( + key_ptr: *const u8, + key_len: u32, + out_ptr: *mut u8, + out_len_ptr: *mut u32, + ) -> ReturnCode; + + pub fn terminate(beneficiary_ptr: *const u8) -> !; + + pub fn transfer( + account_id_ptr: *const u8, + account_id_len: u32, + transferred_value_ptr: *const u8, + transferred_value_len: u32, + ) -> ReturnCode; + + pub fn value_transferred(output_ptr: *mut u8, output_len_ptr: *mut u32); + + pub fn weight_to_fee(gas: u64, output_ptr: *mut u8, output_len_ptr: *mut u32); + + pub fn xcm_execute(msg_ptr: *const u8, msg_len: u32) -> ReturnCode; + + pub fn xcm_send( + dest_ptr: *const u8, + msg_ptr: *const u8, + msg_len: u32, + output_ptr: *mut u8, + ) -> ReturnCode; + } + + pub mod v1 { + use crate::ReturnCode; + + #[link(wasm_import_module = "seal1")] + extern "C" { + pub fn call( + flags: u32, + callee_ptr: *const u8, + gas: u64, + transferred_value_ptr: *const u8, + input_data_ptr: *const u8, + input_data_len: u32, + output_ptr: *mut u8, + output_len_ptr: *mut u32, + ) -> ReturnCode; + + pub fn clear_storage(key_ptr: *const u8, key_len: u32) -> ReturnCode; + + pub fn contains_storage(key_ptr: *const u8, key_len: u32) -> ReturnCode; + + pub fn gas_left(output_ptr: *mut u8, output_len_ptr: *mut u32); + + pub fn get_storage( + key_ptr: *const u8, + key_len: u32, + out_ptr: *mut u8, + out_len_ptr: *mut u32, + ) -> ReturnCode; + + pub fn instantiate( + code_hash_ptr: *const u8, + gas: u64, + value_ptr: *const u8, + input_ptr: *const u8, + input_len: u32, + address_ptr: *mut u8, + address_len_ptr: *mut u32, + output_ptr: *mut u8, + output_len_ptr: *mut u32, + salt_ptr: *const u8, + salt_len: u32, + ) -> ReturnCode; + + pub fn set_storage( + key_ptr: *const u8, + value_ptr: *const u8, + value_len: u32, + ) -> ReturnCode; + + pub fn terminate(beneficiary_ptr: *const u8) -> !; + + pub fn weight_to_fee( + ref_time_limit: u64, + proof_size_limit: u64, + output_ptr: *mut u8, + output_len_ptr: *mut u32, + ); + } + } + + pub mod v2 { + use crate::ReturnCode; + + #[link(wasm_import_module = "seal2")] + extern "C" { + pub fn call( + flags: u32, + callee_ptr: *const u8, + ref_time_limit: u64, + proof_size_limit: u64, + deposit_ptr: *const u8, + transferred_value_ptr: *const u8, + input_data_ptr: *const u8, + input_data_len: u32, + output_ptr: *mut u8, + output_len_ptr: *mut u32, + ) -> ReturnCode; + + pub fn instantiate( + code_hash_ptr: *const u8, + ref_time_limit: u64, + proof_size_limit: u64, + deposit_ptr: *const u8, + value_ptr: *const u8, + input_ptr: *const u8, + input_len: u32, + address_ptr: *mut u8, + address_len_ptr: *mut u32, + output_ptr: *mut u8, + output_len_ptr: *mut u32, + salt_ptr: *const u8, + salt_len: u32, + ) -> ReturnCode; + + pub fn set_storage( + key_ptr: *const u8, + key_len: u32, + value_ptr: *const u8, + value_len: u32, + ) -> ReturnCode; + } + } +} + +/// A macro to implement all Host functions with a signature of `fn(&mut &mut [u8])`. +/// +/// Example: +/// ```nocompile +// impl_wrapper_for! { +// () => [gas_left], +// (v1) => [gas_left], +// } +// ``` +// +// Expands to: +// ```nocompile +// fn gas_left(output: &mut &mut [u8]) { +// unsafe { sys::gas_left(...); } +// } +// fn gas_left_v1(output: &mut &mut [u8]) { +// unsafe { sys::v1::gas_left(...); } +// } +// ``` +macro_rules! impl_wrapper_for { + (@impl_fn $( $mod:ident )::*, $suffix_sep: literal, $suffix:tt, $name:ident) => { + paste::paste! { + fn [<$name $suffix_sep $suffix>](output: &mut &mut [u8]) { + let mut output_len = output.len() as u32; + unsafe { + $( $mod )::*::$name(output.as_mut_ptr(), &mut output_len); + } + extract_from_slice(output, output_len as usize) + } + } + }; + + () => {}; + + (($mod:ident) => [$( $name:ident),*], $($tail:tt)*) => { + $(impl_wrapper_for!(@impl_fn sys::$mod, "_", $mod, $name);)* + impl_wrapper_for!($($tail)*); + }; + + (() => [$( $name:ident),*], $($tail:tt)*) => { + $(impl_wrapper_for!(@impl_fn sys, "", "", $name);)* + impl_wrapper_for!($($tail)*); + }; +} + +/// A macro to implement all the hash functions Apis. +macro_rules! impl_hash_fn { + ( $name:ident, $bytes_result:literal ) => { + paste::item! { + fn [](input: &[u8], output: &mut [u8; $bytes_result]) { + unsafe { + sys::[]( + input.as_ptr(), + input.len() as u32, + output.as_mut_ptr(), + ) + } + } + } + }; +} + +impl HostFn for HostFnImpl { + #[inline(always)] + fn instantiate_v1( + code_hash: &[u8], + gas: u64, + value: &[u8], + input: &[u8], + mut address: Option<&mut &mut [u8]>, + mut output: Option<&mut &mut [u8]>, + salt: &[u8], + ) -> Result { + let (address_ptr, mut address_len) = ptr_len_or_sentinel(&mut address); + let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); + let ret_code = unsafe { + sys::v1::instantiate( + code_hash.as_ptr(), + gas, + value.as_ptr(), + input.as_ptr(), + input.len() as u32, + address_ptr, + &mut address_len, + output_ptr, + &mut output_len, + salt.as_ptr(), + salt.len() as u32, + ) + }; + + if let Some(ref mut address) = address { + extract_from_slice(address, address_len as usize); + } + if let Some(ref mut output) = output { + extract_from_slice(output, output_len as usize); + } + ret_code.into() + } + + fn instantiate_v2( + code_hash: &[u8], + ref_time_limit: u64, + proof_size_limit: u64, + deposit: Option<&[u8]>, + value: &[u8], + input: &[u8], + mut address: Option<&mut &mut [u8]>, + mut output: Option<&mut &mut [u8]>, + salt: &[u8], + ) -> Result { + let (address_ptr, mut address_len) = ptr_len_or_sentinel(&mut address); + let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); + let deposit_ptr = ptr_or_sentinel(&deposit); + + let ret_code = { + unsafe { + sys::v2::instantiate( + code_hash.as_ptr(), + ref_time_limit, + proof_size_limit, + deposit_ptr, + value.as_ptr(), + input.as_ptr(), + input.len() as u32, + address_ptr, + &mut address_len, + output_ptr, + &mut output_len, + salt.as_ptr(), + salt.len() as u32, + ) + } + }; + + if let Some(ref mut address) = address { + extract_from_slice(address, address_len as usize); + } + + if let Some(ref mut output) = output { + extract_from_slice(output, output_len as usize); + } + + ret_code.into() + } + + #[inline(always)] + fn call( + callee: &[u8], + gas: u64, + value: &[u8], + input_data: &[u8], + mut output: Option<&mut &mut [u8]>, + ) -> Result { + let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); + let ret_code = { + unsafe { + sys::call( + callee.as_ptr(), + callee.len() as u32, + gas, + value.as_ptr(), + value.len() as u32, + input_data.as_ptr(), + input_data.len() as u32, + output_ptr, + &mut output_len, + ) + } + }; + + if let Some(ref mut output) = output { + extract_from_slice(output, output_len as usize); + } + + ret_code.into() + } + + #[inline(always)] + fn call_v1( + flags: CallFlags, + callee: &[u8], + gas: u64, + value: &[u8], + input_data: &[u8], + mut output: Option<&mut &mut [u8]>, + ) -> Result { + let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); + let ret_code = { + unsafe { + sys::v1::call( + flags.bits(), + callee.as_ptr(), + gas, + value.as_ptr(), + input_data.as_ptr(), + input_data.len() as u32, + output_ptr, + &mut output_len, + ) + } + }; + + if let Some(ref mut output) = output { + extract_from_slice(output, output_len as usize); + } + + ret_code.into() + } + + fn call_v2( + flags: CallFlags, + callee: &[u8], + ref_time_limit: u64, + proof_size_limit: u64, + deposit: Option<&[u8]>, + value: &[u8], + input_data: &[u8], + mut output: Option<&mut &mut [u8]>, + ) -> Result { + let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); + let deposit_ptr = ptr_or_sentinel(&deposit); + let ret_code = { + unsafe { + sys::v2::call( + flags.bits(), + callee.as_ptr(), + ref_time_limit, + proof_size_limit, + deposit_ptr, + value.as_ptr(), + input_data.as_ptr(), + input_data.len() as u32, + output_ptr, + &mut output_len, + ) + } + }; + + if let Some(ref mut output) = output { + extract_from_slice(output, output_len as usize); + } + + ret_code.into() + } + + fn caller_is_root() -> u32 { + unsafe { sys::caller_is_root() }.into_u32() + } + + #[inline(always)] + fn delegate_call( + flags: CallFlags, + code_hash: &[u8], + input: &[u8], + mut output: Option<&mut &mut [u8]>, + ) -> Result { + let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); + let ret_code = { + unsafe { + sys::delegate_call( + flags.bits(), + code_hash.as_ptr(), + input.as_ptr(), + input.len() as u32, + output_ptr, + &mut output_len, + ) + } + }; + + if let Some(ref mut output) = output { + extract_from_slice(output, output_len as usize); + } + + ret_code.into() + } + + fn transfer(account_id: &[u8], value: &[u8]) -> Result { + let ret_code = unsafe { + sys::transfer( + account_id.as_ptr(), + account_id.len() as u32, + value.as_ptr(), + value.len() as u32, + ) + }; + ret_code.into() + } + + fn deposit_event(topics: &[u8], data: &[u8]) { + unsafe { + sys::deposit_event( + topics.as_ptr(), + topics.len() as u32, + data.as_ptr(), + data.len() as u32, + ) + } + } + + fn set_storage(key: &[u8], value: &[u8]) { + unsafe { sys::set_storage(key.as_ptr(), value.as_ptr(), value.len() as u32) }; + } + + fn set_storage_v1(key: &[u8], encoded_value: &[u8]) -> Option { + let ret_code = unsafe { + sys::v1::set_storage(key.as_ptr(), encoded_value.as_ptr(), encoded_value.len() as u32) + }; + ret_code.into() + } + + fn set_storage_v2(key: &[u8], encoded_value: &[u8]) -> Option { + let ret_code = unsafe { + sys::v2::set_storage( + key.as_ptr(), + key.len() as u32, + encoded_value.as_ptr(), + encoded_value.len() as u32, + ) + }; + ret_code.into() + } + + fn set_transient_storage(key: &[u8], encoded_value: &[u8]) -> Option { + let ret_code = unsafe { + sys::set_transient_storage( + key.as_ptr(), + key.len() as u32, + encoded_value.as_ptr(), + encoded_value.len() as u32, + ) + }; + ret_code.into() + } + + fn clear_storage(key: &[u8]) { + unsafe { sys::clear_storage(key.as_ptr()) }; + } + + fn clear_storage_v1(key: &[u8]) -> Option { + let ret_code = unsafe { sys::v1::clear_storage(key.as_ptr(), key.len() as u32) }; + ret_code.into() + } + + fn clear_transient_storage(key: &[u8]) -> Option { + let ret_code = unsafe { sys::clear_transient_storage(key.as_ptr(), key.len() as u32) }; + ret_code.into() + } + + #[inline(always)] + fn get_storage(key: &[u8], output: &mut &mut [u8]) -> Result { + let mut output_len = output.len() as u32; + let ret_code = + { unsafe { sys::get_storage(key.as_ptr(), output.as_mut_ptr(), &mut output_len) } }; + extract_from_slice(output, output_len as usize); + ret_code.into() + } + + #[inline(always)] + fn get_storage_v1(key: &[u8], output: &mut &mut [u8]) -> Result { + let mut output_len = output.len() as u32; + let ret_code = { + unsafe { + sys::v1::get_storage( + key.as_ptr(), + key.len() as u32, + output.as_mut_ptr(), + &mut output_len, + ) + } + }; + extract_from_slice(output, output_len as usize); + ret_code.into() + } + + #[inline(always)] + fn get_transient_storage(key: &[u8], output: &mut &mut [u8]) -> Result { + let mut output_len = output.len() as u32; + let ret_code = { + unsafe { + sys::get_transient_storage( + key.as_ptr(), + key.len() as u32, + output.as_mut_ptr(), + &mut output_len, + ) + } + }; + extract_from_slice(output, output_len as usize); + ret_code.into() + } + + #[inline(always)] + fn take_storage(key: &[u8], output: &mut &mut [u8]) -> Result { + let mut output_len = output.len() as u32; + let ret_code = { + unsafe { + sys::take_storage( + key.as_ptr(), + key.len() as u32, + output.as_mut_ptr(), + &mut output_len, + ) + } + }; + extract_from_slice(output, output_len as usize); + ret_code.into() + } + + #[inline(always)] + fn take_transient_storage(key: &[u8], output: &mut &mut [u8]) -> Result { + let mut output_len = output.len() as u32; + let ret_code = { + unsafe { + sys::take_transient_storage( + key.as_ptr(), + key.len() as u32, + output.as_mut_ptr(), + &mut output_len, + ) + } + }; + extract_from_slice(output, output_len as usize); + ret_code.into() + } + + fn debug_message(str: &[u8]) -> Result { + let ret_code = unsafe { sys::debug_message(str.as_ptr(), str.len() as u32) }; + ret_code.into() + } + + fn contains_storage(key: &[u8]) -> Option { + let ret_code = unsafe { sys::contains_storage(key.as_ptr()) }; + ret_code.into() + } + + fn contains_storage_v1(key: &[u8]) -> Option { + let ret_code = unsafe { sys::v1::contains_storage(key.as_ptr(), key.len() as u32) }; + ret_code.into() + } + + fn contains_transient_storage(key: &[u8]) -> Option { + let ret_code = unsafe { sys::contains_transient_storage(key.as_ptr(), key.len() as u32) }; + ret_code.into() + } + + fn terminate(beneficiary: &[u8]) -> ! { + unsafe { sys::terminate(beneficiary.as_ptr()) } + } + + fn terminate_v1(beneficiary: &[u8]) -> ! { + unsafe { sys::v1::terminate(beneficiary.as_ptr()) } + } + + fn call_chain_extension(func_id: u32, input: &[u8], mut output: Option<&mut &mut [u8]>) -> u32 { + let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); + let ret_code = { + unsafe { + sys::call_chain_extension( + func_id, + input.as_ptr(), + input.len() as u32, + output_ptr, + &mut output_len, + ) + } + }; + + if let Some(ref mut output) = output { + extract_from_slice(output, output_len as usize); + } + ret_code.into_u32() + } + + #[inline(always)] + fn input(output: &mut &mut [u8]) { + let mut output_len = output.len() as u32; + { + unsafe { sys::input(output.as_mut_ptr(), &mut output_len) }; + } + extract_from_slice(output, output_len as usize); + } + + fn return_value(flags: ReturnFlags, return_value: &[u8]) -> ! { + unsafe { sys::seal_return(flags.bits(), return_value.as_ptr(), return_value.len() as u32) } + } + + fn call_runtime(call: &[u8]) -> Result { + let ret_code = unsafe { sys::call_runtime(call.as_ptr(), call.len() as u32) }; + ret_code.into() + } + + impl_wrapper_for! { + () => [caller, block_number, address, balance, gas_left, value_transferred, now, minimum_balance], + (v1) => [gas_left], + } + + #[inline(always)] + fn weight_to_fee(gas: u64, output: &mut &mut [u8]) { + let mut output_len = output.len() as u32; + { + unsafe { sys::weight_to_fee(gas, output.as_mut_ptr(), &mut output_len) }; + } + extract_from_slice(output, output_len as usize); + } + + fn weight_to_fee_v1(ref_time_limit: u64, proof_size_limit: u64, output: &mut &mut [u8]) { + let mut output_len = output.len() as u32; + { + unsafe { + sys::v1::weight_to_fee( + ref_time_limit, + proof_size_limit, + output.as_mut_ptr(), + &mut output_len, + ) + }; + } + extract_from_slice(output, output_len as usize); + } + + impl_hash_fn!(sha2_256, 32); + impl_hash_fn!(keccak_256, 32); + impl_hash_fn!(blake2_256, 32); + impl_hash_fn!(blake2_128, 16); + + fn ecdsa_recover( + signature: &[u8; 65], + message_hash: &[u8; 32], + output: &mut [u8; 33], + ) -> Result { + let ret_code = unsafe { + sys::ecdsa_recover(signature.as_ptr(), message_hash.as_ptr(), output.as_mut_ptr()) + }; + ret_code.into() + } + + fn ecdsa_to_eth_address(pubkey: &[u8; 33], output: &mut [u8; 20]) -> Result { + let ret_code = unsafe { sys::ecdsa_to_eth_address(pubkey.as_ptr(), output.as_mut_ptr()) }; + ret_code.into() + } + + fn sr25519_verify(signature: &[u8; 64], message: &[u8], pub_key: &[u8; 32]) -> Result { + let ret_code = unsafe { + sys::sr25519_verify( + signature.as_ptr(), + pub_key.as_ptr(), + message.len() as u32, + message.as_ptr(), + ) + }; + ret_code.into() + } + + fn is_contract(account_id: &[u8]) -> bool { + let ret_val = unsafe { sys::is_contract(account_id.as_ptr()) }; + ret_val.into_bool() + } + + fn caller_is_origin() -> bool { + let ret_val = unsafe { sys::caller_is_origin() }; + ret_val.into_bool() + } + + fn set_code_hash(code_hash: &[u8]) -> Result { + let ret_val = unsafe { sys::set_code_hash(code_hash.as_ptr()) }; + ret_val.into() + } + + fn code_hash(account_id: &[u8], output: &mut [u8]) -> Result { + let mut output_len = output.len() as u32; + let ret_val = + unsafe { sys::code_hash(account_id.as_ptr(), output.as_mut_ptr(), &mut output_len) }; + ret_val.into() + } + + fn own_code_hash(output: &mut [u8]) { + let mut output_len = output.len() as u32; + unsafe { sys::own_code_hash(output.as_mut_ptr(), &mut output_len) } + } + + fn account_reentrance_count(account: &[u8]) -> u32 { + unsafe { sys::account_reentrance_count(account.as_ptr()) } + } + + fn lock_delegate_dependency(code_hash: &[u8]) { + unsafe { sys::lock_delegate_dependency(code_hash.as_ptr()) } + } + + fn unlock_delegate_dependency(code_hash: &[u8]) { + unsafe { sys::unlock_delegate_dependency(code_hash.as_ptr()) } + } + + fn instantiation_nonce() -> u64 { + unsafe { sys::instantiation_nonce() } + } + + fn reentrance_count() -> u32 { + unsafe { sys::reentrance_count() } + } + + fn xcm_execute(msg: &[u8]) -> Result { + let ret_code = unsafe { sys::xcm_execute(msg.as_ptr(), msg.len() as _) }; + ret_code.into() + } + + fn xcm_send(dest: &[u8], msg: &[u8], output: &mut [u8; 32]) -> Result { + let ret_code = unsafe { + sys::xcm_send(dest.as_ptr(), msg.as_ptr(), msg.len() as _, output.as_mut_ptr()) + }; + ret_code.into() + } +} diff --git a/pallets/contracts/uapi/src/lib.rs b/pallets/contracts/uapi/src/lib.rs new file mode 100644 index 00000000..83877c6e --- /dev/null +++ b/pallets/contracts/uapi/src/lib.rs @@ -0,0 +1,138 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// +// 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. + +//! External C API to communicate with substrate contracts runtime module. +//! +//! Refer to substrate FRAME contract module for more documentation. + +#![no_std] + +mod flags; +pub use flags::*; + +#[cfg(any(target_arch = "wasm32", target_arch = "riscv32"))] +mod host; + +#[cfg(any(target_arch = "wasm32", target_arch = "riscv32"))] +pub use host::*; + +macro_rules! define_error_codes { + ( + $( + $( #[$attr:meta] )* + $name:ident = $discr:literal, + )* + ) => { + /// Every error that can be returned to a contract when it calls any of the host functions. + #[derive(Debug, PartialEq, Eq)] + #[repr(u8)] + pub enum ReturnErrorCode { + /// API call successful. + Success = 0, + $( + $( #[$attr] )* + $name = $discr, + )* + /// Returns if an unknown error was received from the host module. + Unknown, + } + + impl From for Result { + fn from(return_code: ReturnCode) -> Self { + match return_code.0 { + 0 => Ok(()), + $( + $discr => Err(ReturnErrorCode::$name), + )* + _ => Err(ReturnErrorCode::Unknown), + } + } + } + }; +} + +impl From for u32 { + fn from(code: ReturnErrorCode) -> u32 { + code as u32 + } +} + +define_error_codes! { + /// The called function trapped and has its state changes reverted. + /// In this case no output buffer is returned. + /// Can only be returned from `call` and `instantiate`. + CalleeTrapped = 1, + /// The called function ran to completion but decided to revert its state. + /// An output buffer is returned when one was supplied. + /// Can only be returned from `call` and `instantiate`. + CalleeReverted = 2, + /// The passed key does not exist in storage. + KeyNotFound = 3, + /// Deprecated and no longer returned: There is only the minimum balance. + _BelowSubsistenceThreshold = 4, + /// Transfer failed for other not further specified reason. Most probably + /// reserved or locked balance of the sender that was preventing the transfer. + TransferFailed = 5, + /// Deprecated and no longer returned: Endowment is no longer required. + _EndowmentTooLow = 6, + /// No code could be found at the supplied code hash. + CodeNotFound = 7, + /// The account that was called is no contract. + NotCallable = 8, + /// The call to `debug_message` had no effect because debug message + /// recording was disabled. + LoggingDisabled = 9, + /// The call dispatched by `call_runtime` was executed but returned an error. + CallRuntimeFailed = 10, + /// ECDSA public key recovery failed. Most probably wrong recovery id or signature. + EcdsaRecoveryFailed = 11, + /// sr25519 signature verification failed. + Sr25519VerifyFailed = 12, + /// The `xcm_execute` call failed. + XcmExecutionFailed = 13, + /// The `xcm_send` call failed. + XcmSendFailed = 14, +} + +/// The raw return code returned by the host side. +#[repr(transparent)] +pub struct ReturnCode(u32); + +/// Used as a sentinel value when reading and writing contract memory. +/// +/// We use this value to signal `None` to a contract when only a primitive is +/// allowed and we don't want to go through encoding a full Rust type. +/// Using `u32::Max` is a safe sentinel because contracts are never +/// allowed to use such a large amount of resources. So this value doesn't +/// make sense for a memory location or length. +const SENTINEL: u32 = u32::MAX; + +impl From for Option { + fn from(code: ReturnCode) -> Self { + (code.0 < SENTINEL).then_some(code.0) + } +} + +impl ReturnCode { + /// Returns the raw underlying `u32` representation. + pub fn into_u32(self) -> u32 { + self.0 + } + /// Returns the underlying `u32` converted into `bool`. + pub fn into_bool(self) -> bool { + self.0.ne(&0) + } +} + +type Result = core::result::Result<(), ReturnErrorCode>; diff --git a/polkadot-launch/config.json b/polkadot-launch/config.json deleted file mode 100644 index f03f983a..00000000 --- a/polkadot-launch/config.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "relaychain": { - "bin": "../../polkadot/target/release/polkadot", - "chain": "rococo-local", - "nodes": [ - { - "name": "alice", - "wsPort": 9944, - "port": 30444 - }, - { - "name": "bob", - "wsPort": 9955, - "port": 30555 - } - ] - }, - "parachains": [ - { - "bin": "../target/release/polkadot-parachain", - "id": "200", - "balance": "1000000000000000000000", - "nodes": [ - { - "wsPort": 9988, - "name": "alice", - "port": 31200, - "flags": [ - "--force-authoring", - "--", - "--execution=wasm" - ] - } - ] - } - ], - "types": { - } -} diff --git a/pop-api/Cargo.toml b/pop-api/Cargo.toml index 0fa1119c..9946abf7 100644 --- a/pop-api/Cargo.toml +++ b/pop-api/Cargo.toml @@ -1,17 +1,13 @@ [package] name = "pop-api" -description = "Easily access the power of Polkadot via the Pop Network" +description = "Enabling smart(er) contracts with the power of Polkadot" license = "GPL-3.0-only" version = "0.0.0" edition = "2021" [dependencies] -enumflags2 = { version = "0.7.7" } ink = { version = "5.0.0", default-features = false } -scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] } -scale-info = { version = "2.6", default-features = false, features = ["derive"] } -sp-io = { version = "23.0.0", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } -sp-runtime = { version = "24.0", default-features = false } +sp-io = { version = "31.0.0", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } pop-primitives = { path = "../primitives", default-features = false } @@ -23,11 +19,9 @@ crate-type = ["rlib"] [features] default = ["std"] std = [ - "enumflags2/std", "ink/std", "pop-primitives/std", - "scale/std", - "scale-info/std", "sp-io/std", - "sp-runtime/std", ] +assets = [] +fungibles = ["assets"] diff --git a/pop-api/examples/read-runtime-state/.gitignore b/pop-api/examples/.gitignore similarity index 91% rename from pop-api/examples/read-runtime-state/.gitignore rename to pop-api/examples/.gitignore index 8de8f877..d60800c8 100755 --- a/pop-api/examples/read-runtime-state/.gitignore +++ b/pop-api/examples/.gitignore @@ -1,9 +1,9 @@ # Ignore build artifacts from the local tests sub-crate. -/target/ +**/target/ # Ignore backup files creates by cargo fmt. **/*.rs.bk # Remove Cargo.lock when creating an executable, leave it for libraries # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock -Cargo.lock +**/Cargo.lock diff --git a/pop-api/examples/balance-transfer/lib.rs b/pop-api/examples/balance-transfer/lib.rs index 328a818b..e75c15b9 100755 --- a/pop-api/examples/balance-transfer/lib.rs +++ b/pop-api/examples/balance-transfer/lib.rs @@ -1,3 +1,4 @@ +// DEPRECATED #![cfg_attr(not(feature = "std"), no_std, no_main)] use pop_api::balances::*; @@ -14,7 +15,7 @@ impl From for ContractError { } } -#[ink::contract(env = pop_api::Environment)] +#[ink::contract] mod balance_transfer { use super::*; @@ -131,4 +132,4 @@ mod balance_transfer { Ok(()) } } -} \ No newline at end of file +} diff --git a/pop-api/examples/fungibles/Cargo.toml b/pop-api/examples/fungibles/Cargo.toml new file mode 100755 index 00000000..19d9ce12 --- /dev/null +++ b/pop-api/examples/fungibles/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "fungibles" +version = "0.1.0" +authors = ["[your_name] <[your_email]>"] +edition = "2021" + +[dependencies] +ink = { version = "5.0.0", default-features = false } +pop-api = { path = "../../../pop-api", default-features = false, features = ["fungibles"] } + +[lib] +path = "lib.rs" + +[features] +default = ["std"] +std = [ + "ink/std", + "pop-api/std", +] +ink-as-dependency = [] +e2e-tests = [] diff --git a/pop-api/examples/fungibles/lib.rs b/pop-api/examples/fungibles/lib.rs new file mode 100755 index 00000000..1b42fec4 --- /dev/null +++ b/pop-api/examples/fungibles/lib.rs @@ -0,0 +1,185 @@ +#![cfg_attr(not(feature = "std"), no_std, no_main)] + +/// Local Fungibles: +/// 1. PSP-22 Interface +/// 2. PSP-22 Metadata Interface +/// 3. Asset Management +/// +use ink::prelude::vec::Vec; +use pop_api::{ + assets::fungibles::{self as api}, + primitives::AssetId, + StatusCode, +}; + +pub type Result = core::result::Result; + +#[ink::contract] +mod fungibles { + use super::*; + + #[ink(storage)] + #[derive(Default)] + pub struct Fungibles; + + impl Fungibles { + #[ink(constructor, payable)] + pub fn new() -> Self { + ink::env::debug_println!("PopApiFungiblesExample::new"); + Default::default() + } + + /// 1. PSP-22 Interface: + /// - total_supply + /// - balance_of + /// - allowance + /// - transfer + /// - transfer_from + /// - approve + /// - increase_allowance + /// - decrease_allowance + + #[ink(message)] + pub fn total_supply(&self, id: AssetId) -> Result { + api::total_supply(id) + } + + #[ink(message)] + pub fn balance_of(&self, id: AssetId, owner: AccountId) -> Result { + api::balance_of(id, owner) + } + + #[ink(message)] + pub fn allowance( + &self, + id: AssetId, + owner: AccountId, + spender: AccountId, + ) -> Result { + api::allowance(id, owner, spender) + } + + #[ink(message)] + pub fn transfer(&self, id: AssetId, to: AccountId, value: Balance) -> Result<()> { + api::transfer(id, to, value) + } + + #[ink(message)] + pub fn transfer_from( + &self, + id: AssetId, + from: AccountId, + to: AccountId, + value: Balance, + // In the PSP-22 standard a `[u8]`, but the size needs to be known at compile time. + _data: Vec, + ) -> Result<()> { + api::transfer_from(id, from, to, value) + } + + #[ink(message)] + pub fn approve(&self, id: AssetId, spender: AccountId, value: Balance) -> Result<()> { + api::approve(id, spender, value) + } + + #[ink(message)] + pub fn increase_allowance( + &self, + id: AssetId, + spender: AccountId, + value: Balance, + ) -> Result<()> { + api::increase_allowance(id, spender, value) + } + + #[ink(message)] + pub fn decrease_allowance( + &self, + id: AssetId, + spender: AccountId, + value: Balance, + ) -> Result<()> { + api::decrease_allowance(id, spender, value) + } + + /// 2. PSP-22 Metadata Interface: + /// - token_name + /// - token_symbol + /// - token_decimals + + #[ink(message)] + pub fn token_name(&self, id: AssetId) -> Result> { + api::token_name(id) + } + + #[ink(message)] + pub fn token_symbol(&self, id: AssetId) -> Result> { + api::token_symbol(id) + } + + #[ink(message)] + pub fn token_decimals(&self, id: AssetId) -> Result { + api::token_decimals(id) + } + + // 3. Asset Management: + // - create + // - start_destroy + // - destroy_accounts + // - destroy_approvals + // - finish_destroy + // - set_metadata + // - clear_metadata + + // #[ink(message)] + // pub fn create(&self, id: AssetId, admin: AccountId, min_balance: Balance) -> Result<()> { + // ink::env::debug_println!( + // "PopApiFungiblesExample::create: id: {:?} admin: {:?} min_balance: {:?}", + // id, + // admin, + // min_balance, + // ); + // let result = api::create(id, admin, min_balance); + // ink::env::debug_println!("Result: {:?}", result); + // result.map_err(|e| e.into()) + // result + // } + + // #[ink(message)] + // pub fn set_metadata( + // &self, + // id: AssetId, + // name: Vec, + // symbol: Vec, + // decimals: u8, + // ) -> Result<()> { + // ink::env::debug_println!( + // "PopApiFungiblesExample::set_metadata: id: {:?} name: {:?} symbol: {:?}, decimals: {:?}", + // id, + // name, + // symbol, + // decimals, + // ); + // let result = api::set_metadata(id, name, symbol, decimals); + // ink::env::debug_println!("Result: {:?}", result); + // // result.map_err(|e| e.into()) + // result + // } + // + // #[ink(message)] + // pub fn asset_exists(&self, id: AssetId) -> Result { + // // api::asset_exists(id).map_err(|e| e.into()) + // api::asset_exists(id) + // } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[ink::test] + fn default_works() { + PopApiFungiblesExample::new(); + } + } +} diff --git a/pop-api/examples/nfts/.gitignore b/pop-api/examples/nfts/.gitignore deleted file mode 100755 index 8de8f877..00000000 --- a/pop-api/examples/nfts/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -# Ignore build artifacts from the local tests sub-crate. -/target/ - -# Ignore backup files creates by cargo fmt. -**/*.rs.bk - -# Remove Cargo.lock when creating an executable, leave it for libraries -# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock -Cargo.lock diff --git a/pop-api/examples/nfts/lib.rs b/pop-api/examples/nfts/lib.rs index d47140e7..0cd0f313 100755 --- a/pop-api/examples/nfts/lib.rs +++ b/pop-api/examples/nfts/lib.rs @@ -1,3 +1,4 @@ +// DEPRECATED #![cfg_attr(not(feature = "std"), no_std, no_main)] use pop_api::nfts::*; @@ -17,7 +18,7 @@ impl From for ContractError { } } -#[ink::contract(env = pop_api::Environment)] +#[ink::contract] mod nfts { use super::*; @@ -33,27 +34,29 @@ mod nfts { } #[ink(message)] - pub fn create_nft_collection( &self ) -> Result<(), ContractError>{ + pub fn create_nft_collection(&self) -> Result<(), ContractError> { ink::env::debug_println!("Nfts::create_nft_collection: collection creation started."); - let admin = Self::env().caller(); - let item_settings = ItemSettings(BitFlags::from(ItemSetting::Transferable)); - - let mint_settings = MintSettings { - mint_type: MintType::Issuer, - price: Some(0), - start_block: Some(0), - end_block: Some(0), - default_item_settings: item_settings, - }; - - let config = CollectionConfig { - settings: CollectionSettings(BitFlags::from(CollectionSetting::TransferableItems)), - max_supply: None, - mint_settings, - }; - pop_api::nfts::create(admin, config)?; - ink::env::debug_println!("Nfts::create_nft_collection: collection created successfully."); - Ok(()) + let admin = Self::env().caller(); + let item_settings = ItemSettings(BitFlags::from(ItemSetting::Transferable)); + + let mint_settings = MintSettings { + mint_type: MintType::Issuer, + price: Some(0), + start_block: Some(0), + end_block: Some(0), + default_item_settings: item_settings, + }; + + let config = CollectionConfig { + settings: CollectionSettings(BitFlags::from(CollectionSetting::TransferableItems)), + max_supply: None, + mint_settings, + }; + pop_api::nfts::create(admin, config)?; + ink::env::debug_println!( + "Nfts::create_nft_collection: collection created successfully." + ); + Ok(()) } #[ink(message)] @@ -82,9 +85,7 @@ mod nfts { // check owner match owner(collection_id, item_id)? { Some(owner) if owner == receiver => { - ink::env::debug_println!( - "Nfts::mint success: minted item belongs to receiver" - ); + ink::env::debug_println!("Nfts::mint success: minted item belongs to receiver"); }, _ => { return Err(ContractError::NotOwner); @@ -113,4 +114,4 @@ mod nfts { Nfts::new(); } } -} \ No newline at end of file +} diff --git a/pop-api/examples/place-spot-order/.gitignore b/pop-api/examples/place-spot-order/.gitignore deleted file mode 100755 index 8de8f877..00000000 --- a/pop-api/examples/place-spot-order/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -# Ignore build artifacts from the local tests sub-crate. -/target/ - -# Ignore backup files creates by cargo fmt. -**/*.rs.bk - -# Remove Cargo.lock when creating an executable, leave it for libraries -# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock -Cargo.lock diff --git a/pop-api/examples/place-spot-order/lib.rs b/pop-api/examples/place-spot-order/lib.rs index f5e34f7f..965917d1 100755 --- a/pop-api/examples/place-spot-order/lib.rs +++ b/pop-api/examples/place-spot-order/lib.rs @@ -1,6 +1,7 @@ +// DEPRECATED #![cfg_attr(not(feature = "std"), no_std, no_main)] -#[ink::contract(env = pop_api::Environment)] +#[ink::contract] mod spot_order { #[ink(storage)] @@ -15,11 +16,7 @@ mod spot_order { } #[ink(message)] - pub fn place_spot_order( - &mut self, - max_amount: Balance, - para_id: u32, - ) { + pub fn place_spot_order(&mut self, max_amount: Balance, para_id: u32) { ink::env::debug_println!( "SpotOrder::place_spot_order: max_amount {:?} para_id: {:?} ", max_amount, @@ -28,10 +25,7 @@ mod spot_order { #[allow(unused_variables)] let res = pop_api::cross_chain::coretime::place_spot_order(max_amount, para_id); - ink::env::debug_println!( - "SpotOrder::place_spot_order: res {:?} ", - res, - ); + ink::env::debug_println!("SpotOrder::place_spot_order: res {:?} ", res,); ink::env::debug_println!("SpotOrder::place_spot_order end"); } @@ -46,4 +40,4 @@ mod spot_order { SpotOrder::new(); } } -} \ No newline at end of file +} diff --git a/pop-api/examples/read-runtime-state/lib.rs b/pop-api/examples/read-runtime-state/lib.rs index 05a44108..092e9f2f 100755 --- a/pop-api/examples/read-runtime-state/lib.rs +++ b/pop-api/examples/read-runtime-state/lib.rs @@ -1,35 +1,36 @@ +// DEPRECATED #![cfg_attr(not(feature = "std"), no_std, no_main)] -#[ink::contract(env = pop_api::Environment)] +#[ink::contract] mod read_relay_blocknumber { - use pop_api::primitives::storage_keys::{ - ParachainSystemKeys::LastRelayChainBlockNumber, RuntimeStateKeys::ParachainSystem, - }; + use pop_api::primitives::storage_keys::{ + ParachainSystemKeys::LastRelayChainBlockNumber, RuntimeStateKeys::ParachainSystem, + }; - #[ink(event)] - pub struct RelayBlockNumberRead { - value: BlockNumber, - } + #[ink(event)] + pub struct RelayBlockNumberRead { + value: BlockNumber, + } - #[ink(storage)] - #[derive(Default)] - pub struct ReadRelayBlockNumber; + #[ink(storage)] + #[derive(Default)] + pub struct ReadRelayBlockNumber; - impl ReadRelayBlockNumber { - #[ink(constructor, payable)] - pub fn new() -> Self { - ink::env::debug_println!("ReadRelayBlockNumber::new"); - Default::default() - } + impl ReadRelayBlockNumber { + #[ink(constructor, payable)] + pub fn new() -> Self { + ink::env::debug_println!("ReadRelayBlockNumber::new"); + Default::default() + } - #[ink(message)] - pub fn read_relay_block_number(&self) { - let result = - pop_api::state::read::(ParachainSystem(LastRelayChainBlockNumber)); - ink::env::debug_println!("Last relay block number read by contract: {:?}", result); - self.env().emit_event(RelayBlockNumberRead { - value: result.expect("Failed to read relay block number."), - }); - } - } -} \ No newline at end of file + #[ink(message)] + pub fn read_relay_block_number(&self) { + let result = + pop_api::state::read::(ParachainSystem(LastRelayChainBlockNumber)); + ink::env::debug_println!("Last relay block number read by contract: {:?}", result); + self.env().emit_event(RelayBlockNumberRead { + value: result.expect("Failed to read relay block number."), + }); + } + } +} diff --git a/pop-api/integration-tests/Cargo.toml b/pop-api/integration-tests/Cargo.toml new file mode 100644 index 00000000..cc56630a --- /dev/null +++ b/pop-api/integration-tests/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "integration-tests" +version = "0.1.0" +edition = "2021" + +[dev-dependencies] +env_logger = "0.11.2" +scale = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } +frame-support = { version = "29.0.0", default-features = false } +frame-system = { version = "29.0.0", default-features = false } +pallet-balances = { version = "29.0.2", default-features = false } +pallet-assets = { version = "30.0.0", default-features = false } +pallet-contracts = { version = "28.0.0", default-features = false } +pop-primitives = { path = "../../primitives", default-features = false } +pop-runtime-devnet = { path = "../../runtime/devnet", default-features = false } +sp-io = { version = "31.0.0", default-features = false } +sp-runtime = { version = "32.0.0", default-features = false } + + +[features] +default = ["std"] +std = [ + "frame-support/std", + "frame-system/std", + "pallet-balances/std", + "pallet-assets/std", + "pallet-contracts/std", + "pop-primitives/std", + "pop-runtime-devnet/std", + "scale/std", + "sp-io/std", + "sp-runtime/std", +] \ No newline at end of file diff --git a/pop-api/examples/balance-transfer/.gitignore b/pop-api/integration-tests/contracts/.gitignore similarity index 91% rename from pop-api/examples/balance-transfer/.gitignore rename to pop-api/integration-tests/contracts/.gitignore index 8de8f877..d60800c8 100755 --- a/pop-api/examples/balance-transfer/.gitignore +++ b/pop-api/integration-tests/contracts/.gitignore @@ -1,9 +1,9 @@ # Ignore build artifacts from the local tests sub-crate. -/target/ +**/target/ # Ignore backup files creates by cargo fmt. **/*.rs.bk # Remove Cargo.lock when creating an executable, leave it for libraries # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock -Cargo.lock +**/Cargo.lock diff --git a/pop-api/integration-tests/contracts/create_token_in_constructor/Cargo.toml b/pop-api/integration-tests/contracts/create_token_in_constructor/Cargo.toml new file mode 100755 index 00000000..2c202715 --- /dev/null +++ b/pop-api/integration-tests/contracts/create_token_in_constructor/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "create_token_in_constructor" +version = "0.1.0" +authors = ["[your_name] <[your_email]>"] +edition = "2021" + +[dependencies] +ink = { version = "5.0.0", default-features = false } +pop-api = { path = "../../..", default-features = false, features = ["fungibles"] } + +[lib] +path = "lib.rs" + +[features] +default = ["std"] +std = [ + "ink/std", + "pop-api/std", +] +ink-as-dependency = [] +e2e-tests = [] diff --git a/pop-api/integration-tests/contracts/create_token_in_constructor/lib.rs b/pop-api/integration-tests/contracts/create_token_in_constructor/lib.rs new file mode 100755 index 00000000..e9e5d127 --- /dev/null +++ b/pop-api/integration-tests/contracts/create_token_in_constructor/lib.rs @@ -0,0 +1,46 @@ +#![cfg_attr(not(feature = "std"), no_std, no_main)] + +use ink::prelude::vec::Vec; +use pop_api::{ + assets::fungibles::{self as api}, + primitives::AssetId, + StatusCode, +}; + +pub type Result = core::result::Result; + +#[ink::contract] +mod create_token_in_constructor { + use super::*; + + #[ink(storage)] + pub struct Fungible { + id: AssetId, + } + + impl Fungible { + #[ink(constructor, payable)] + pub fn new(id: AssetId, min_balance: Balance) -> Result { + let contract = Self { id }; + // AccountId of the contract which will be set to the owner of the fungible token. + let owner = contract.env().account_id(); + api::create(id, owner, min_balance)?; + Ok(contract) + } + + #[ink(message)] + pub fn asset_exists(&self) -> Result { + api::asset_exists(self.id) + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[ink::test] + fn default_works() { + PopApiFungiblesExample::new(); + } + } +} diff --git a/pop-api/integration-tests/contracts/fungibles/Cargo.toml b/pop-api/integration-tests/contracts/fungibles/Cargo.toml new file mode 100755 index 00000000..7c322004 --- /dev/null +++ b/pop-api/integration-tests/contracts/fungibles/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "fungibles" +version = "0.1.0" +authors = ["[your_name] <[your_email]>"] +edition = "2021" + +[dependencies] +ink = { version = "5.0.0", default-features = false } +pop-api = { path = "../../../../pop-api", default-features = false, features = ["fungibles"] } + +[lib] +path = "lib.rs" + +[features] +default = ["std"] +std = [ + "ink/std", + "pop-api/std", +] +ink-as-dependency = [] +e2e-tests = [] diff --git a/pop-api/integration-tests/contracts/fungibles/lib.rs b/pop-api/integration-tests/contracts/fungibles/lib.rs new file mode 100755 index 00000000..239d3a2d --- /dev/null +++ b/pop-api/integration-tests/contracts/fungibles/lib.rs @@ -0,0 +1,187 @@ +#![cfg_attr(not(feature = "std"), no_std, no_main)] + +/// Local Fungibles: +/// 1. PSP-22 Interface +/// 2. PSP-22 Metadata Interface +/// 3. Asset Management +/// +use ink::prelude::vec::Vec; +use pop_api::{ + assets::fungibles::{self as api}, + primitives::AssetId, + StatusCode, +}; + +pub type Result = core::result::Result; + +#[ink::contract] +mod fungibles { + use super::*; + + #[ink(storage)] + #[derive(Default)] + pub struct Fungibles; + + impl Fungibles { + #[ink(constructor, payable)] + pub fn new() -> Self { + ink::env::debug_println!("PopApiFungiblesExample::new"); + Default::default() + } + + /// 1. PSP-22 Interface: + /// - total_supply + /// - balance_of + /// - allowance + /// - transfer + /// - transfer_from + /// - approve + /// - increase_allowance + /// - decrease_allowance + + #[ink(message)] + pub fn total_supply(&self, id: AssetId) -> Result { + api::total_supply(id) + } + + #[ink(message)] + pub fn balance_of(&self, id: AssetId, owner: AccountId) -> Result { + api::balance_of(id, owner) + } + + #[ink(message)] + pub fn allowance( + &self, + id: AssetId, + owner: AccountId, + spender: AccountId, + ) -> Result { + api::allowance(id, owner, spender) + } + + #[ink(message)] + pub fn transfer(&self, id: AssetId, to: AccountId, value: Balance) -> Result<()> { + api::transfer(id, to, value) + } + + #[ink(message)] + pub fn transfer_from( + &self, + id: AssetId, + from: AccountId, + to: AccountId, + value: Balance, + // In the PSP-22 standard a `[u8]`, but the size needs to be known at compile time. + _data: Vec, + ) -> Result<()> { + api::transfer_from(id, from, to, value) + } + + #[ink(message)] + pub fn approve(&self, id: AssetId, spender: AccountId, value: Balance) -> Result<()> { + api::approve(id, spender, value) + } + + #[ink(message)] + pub fn increase_allowance( + &self, + id: AssetId, + spender: AccountId, + value: Balance, + ) -> Result<()> { + api::increase_allowance(id, spender, value) + } + + #[ink(message)] + pub fn decrease_allowance( + &self, + id: AssetId, + spender: AccountId, + value: Balance, + ) -> Result<()> { + api::decrease_allowance(id, spender, value) + } + + /// 2. PSP-22 Metadata Interface: + /// - token_name + /// - token_symbol + /// - token_decimals + + #[ink(message)] + pub fn token_name(&self, id: AssetId) -> Result> { + api::token_name(id) + } + + #[ink(message)] + pub fn token_symbol(&self, id: AssetId) -> Result> { + api::token_symbol(id) + } + + #[ink(message)] + pub fn token_decimals(&self, id: AssetId) -> Result { + api::token_decimals(id) + } + + /// 3. Asset Management: + /// - create + /// - start_destroy + /// - set_metadata + /// - clear_metadata + /// - asset_exists + + #[ink(message)] + pub fn create(&self, id: AssetId, admin: AccountId, min_balance: Balance) -> Result<()> { + api::create(id, admin, min_balance) + } + + #[ink(message)] + pub fn start_destroy(&self, id: AssetId) -> Result<()> { + api::start_destroy(id) + } + + #[ink(message)] + pub fn set_metadata( + &self, + id: AssetId, + name: Vec, + symbol: Vec, + decimals: u8, + ) -> Result<()> { + api::set_metadata(id, name, symbol, decimals) + } + + #[ink(message)] + pub fn clear_metadata(&self, id: AssetId) -> Result<()> { + api::clear_metadata(id) + } + + #[ink(message)] + pub fn asset_exists(&self, id: AssetId) -> Result { + api::asset_exists(id) + } + + /// 4. PSP-22 Mintable & Burnable Interface: + /// - mint + /// - burn + + #[ink(message)] + pub fn mint(&self, id: AssetId, account: AccountId, amount: Balance) -> Result<()> { + api::mint(id, account, amount) + } + + #[ink(message)] + pub fn burn(&self, id: AssetId, account: AccountId, amount: Balance) -> Result<()> { + api::burn(id, account, amount) + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[ink::test] + fn default_works() { + PopApiFungiblesExample::new(); + } + } +} diff --git a/pop-api/integration-tests/src/fungibles/mod.rs b/pop-api/integration-tests/src/fungibles/mod.rs new file mode 100644 index 00000000..d1c0e2ae --- /dev/null +++ b/pop-api/integration-tests/src/fungibles/mod.rs @@ -0,0 +1,575 @@ +use super::*; +use pop_primitives::{ArithmeticError::*, AssetId, Error::*, TokenError::*, *}; +use utils::*; + +mod utils; + +const ASSET_ID: AssetId = 1; +const CONTRACT: &str = "contracts/fungibles/target/ink/fungibles.wasm"; + +/// 1. PSP-22 Interface: +/// - total_supply +/// - balance_of +/// - allowance +/// - transfer +/// - transfer_from +/// - approve +/// - increase_allowance +/// - decrease_allowance + +#[test] +fn total_supply_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = instantiate(CONTRACT, INIT_VALUE, vec![]); + + // No tokens in circulation. + assert_eq!(total_supply(addr.clone(), ASSET_ID), Ok(Assets::total_supply(ASSET_ID))); + assert_eq!(total_supply(addr.clone(), ASSET_ID), Ok(0)); + + // Tokens in circulation. + create_asset_and_mint_to(addr.clone(), ASSET_ID, BOB, 100); + assert_eq!(total_supply(addr.clone(), ASSET_ID), Ok(Assets::total_supply(ASSET_ID))); + assert_eq!(total_supply(addr, ASSET_ID), Ok(100)); + }); +} + +#[test] +fn balance_of_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = instantiate(CONTRACT, INIT_VALUE, vec![]); + + // No tokens in circulation. + assert_eq!(balance_of(addr.clone(), ASSET_ID, BOB), Ok(Assets::balance(ASSET_ID, BOB))); + assert_eq!(balance_of(addr.clone(), ASSET_ID, BOB), Ok(0)); + + // Tokens in circulation. + create_asset_and_mint_to(addr.clone(), ASSET_ID, BOB, 100); + assert_eq!(balance_of(addr.clone(), ASSET_ID, BOB), Ok(Assets::balance(ASSET_ID, BOB))); + assert_eq!(balance_of(addr, ASSET_ID, BOB), Ok(100)); + }); +} + +#[test] +fn allowance_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = instantiate(CONTRACT, INIT_VALUE, vec![]); + + // No tokens in circulation. + assert_eq!( + allowance(addr.clone(), ASSET_ID, BOB, ALICE), + Ok(Assets::allowance(ASSET_ID, &BOB, &ALICE)) + ); + assert_eq!(allowance(addr.clone(), ASSET_ID, BOB, ALICE), Ok(0)); + + // Tokens in circulation. + create_asset_mint_and_approve(addr.clone(), ASSET_ID, BOB, 100, ALICE, 50); + assert_eq!( + allowance(addr.clone(), ASSET_ID, BOB, ALICE), + Ok(Assets::allowance(ASSET_ID, &BOB, &ALICE)) + ); + assert_eq!(allowance(addr, ASSET_ID, BOB, ALICE), Ok(50)); + }); +} + +#[test] +fn transfer_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = instantiate(CONTRACT, INIT_VALUE, vec![]); + let amount: Balance = 100 * UNIT; + + // Asset does not exist. + assert_eq!( + transfer(addr.clone(), 1, BOB, amount), + Err(Module { index: 52, error: [3, 0] }) + ); + // Create asset with Alice as owner and mint `amount` to contract address. + let asset = create_asset_and_mint_to(ALICE, 1, addr.clone(), amount); + // Asset is not live, i.e. frozen or being destroyed. + freeze_asset(ALICE, asset); + assert_eq!( + transfer(addr.clone(), asset, BOB, amount), + Err(Module { index: 52, error: [16, 0] }) + ); + thaw_asset(ALICE, asset); + // Not enough balance. + assert_eq!( + transfer(addr.clone(), asset, BOB, amount + 1 * UNIT), + Err(Module { index: 52, error: [0, 0] }) + ); + // Not enough balance due to ED. + assert_eq!( + transfer(addr.clone(), asset, BOB, amount), + Err(Module { index: 52, error: [0, 0] }) + ); + // Successful transfer. + let balance_before_transfer = Assets::balance(asset, &BOB); + assert_ok!(transfer(addr.clone(), asset, BOB, amount / 2)); + let balance_after_transfer = Assets::balance(asset, &BOB); + assert_eq!(balance_after_transfer, balance_before_transfer + amount / 2); + // Transfer asset to account that does not exist. + assert_eq!(transfer(addr.clone(), asset, FERDIE, amount / 4), Err(Token(CannotCreate))); + // Asset is not live, i.e. frozen or being destroyed. + start_destroy_asset(ALICE, asset); + assert_eq!( + transfer(addr.clone(), asset, BOB, amount / 4), + Err(Module { index: 52, error: [16, 0] }) + ); + }); +} + +#[test] +fn transfer_from_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = instantiate(CONTRACT, INIT_VALUE, vec![]); + let amount: Balance = 100 * UNIT; + + // Asset does not exist. + assert_eq!( + transfer_from(addr.clone(), 1, ALICE, BOB, amount / 2), + Err(Module { index: 52, error: [3, 0] }), + ); + // Create asset with Alice as owner and mint `amount` to contract address. + let asset = create_asset_and_mint_to(ALICE, 1, ALICE, amount); + // Unapproved transfer. + assert_eq!( + transfer_from(addr.clone(), asset, ALICE, BOB, amount / 2), + Err(Module { index: 52, error: [10, 0] }) + ); + assert_ok!(Assets::approve_transfer( + RuntimeOrigin::signed(ALICE.into()), + asset.into(), + addr.clone().into(), + amount + 1 * UNIT, + )); + // Asset is not live, i.e. frozen or being destroyed. + freeze_asset(ALICE, asset); + assert_eq!( + transfer_from(addr.clone(), asset, ALICE, BOB, amount), + Err(Module { index: 52, error: [16, 0] }), + ); + thaw_asset(ALICE, asset); + // Not enough balance. + assert_eq!( + transfer_from(addr.clone(), asset, ALICE, BOB, amount + 1 * UNIT), + Err(Module { index: 52, error: [0, 0] }), + ); + // Successful transfer. + let balance_before_transfer = Assets::balance(asset, &BOB); + assert_ok!(transfer_from(addr.clone(), asset, ALICE, BOB, amount / 2)); + let balance_after_transfer = Assets::balance(asset, &BOB); + assert_eq!(balance_after_transfer, balance_before_transfer + amount / 2); + }); +} + +#[test] +fn approve_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = instantiate(CONTRACT, 0, vec![]); + let amount: Balance = 100 * UNIT; + + // Asset does not exist. + assert_eq!(approve(addr.clone(), 0, BOB, amount), Err(Module { index: 52, error: [3, 0] })); + let asset = create_asset_and_mint_to(ALICE, 0, addr.clone(), amount); + assert_eq!(approve(addr.clone(), asset, BOB, amount), Err(ConsumerRemaining)); + let addr = instantiate(CONTRACT, INIT_VALUE, vec![1]); + // Create asset with Alice as owner and mint `amount` to contract address. + let asset = create_asset_and_mint_to(ALICE, 1, addr.clone(), amount); + // Asset is not live, i.e. frozen or being destroyed. + freeze_asset(ALICE, asset); + assert_eq!( + approve(addr.clone(), asset, BOB, amount), + Err(Module { index: 52, error: [16, 0] }) + ); + thaw_asset(ALICE, asset); + // Successful approvals: + assert_eq!(0, Assets::allowance(asset, &addr, &BOB)); + assert_ok!(approve(addr.clone(), asset, BOB, amount)); + assert_eq!(Assets::allowance(asset, &addr, &BOB), amount); + // Non-additive, sets new value. + assert_ok!(approve(addr.clone(), asset, BOB, amount / 2)); + assert_eq!(Assets::allowance(asset, &addr, &BOB), amount / 2); + // Asset is not live, i.e. frozen or being destroyed. + start_destroy_asset(ALICE, asset); + assert_eq!( + approve(addr.clone(), asset, BOB, amount), + Err(Module { index: 52, error: [16, 0] }) + ); + }); +} + +#[test] +fn increase_allowance_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let amount: Balance = 100 * UNIT; + // Instantiate a contract without balance - test `ConsumerRemaining. + let addr = instantiate(CONTRACT, 0, vec![]); + // Asset does not exist. + assert_eq!( + increase_allowance(addr.clone(), 0, BOB, amount), + Err(Module { index: 52, error: [3, 0] }) + ); + let asset = create_asset_and_mint_to(ALICE, 0, addr.clone(), amount); + assert_eq!(increase_allowance(addr.clone(), asset, BOB, amount), Err(ConsumerRemaining)); + + // Instantiate a contract with balance. + let addr = instantiate(CONTRACT, INIT_VALUE, vec![1]); + // Create asset with Alice as owner and mint `amount` to contract address. + let asset = create_asset_and_mint_to(ALICE, 1, addr.clone(), amount); + // Asset is not live, i.e. frozen or being destroyed. + freeze_asset(ALICE, asset); + assert_eq!( + increase_allowance(addr.clone(), asset, BOB, amount), + Err(Module { index: 52, error: [16, 0] }) + ); + thaw_asset(ALICE, asset); + // Successful approvals: + assert_eq!(0, Assets::allowance(asset, &addr, &BOB)); + assert_ok!(increase_allowance(addr.clone(), asset, BOB, amount)); + assert_eq!(Assets::allowance(asset, &addr, &BOB), amount); + // Additive. + assert_ok!(increase_allowance(addr.clone(), asset, BOB, amount)); + assert_eq!(Assets::allowance(asset, &addr, &BOB), amount * 2); + // Asset is not live, i.e. frozen or being destroyed. + start_destroy_asset(ALICE, asset); + assert_eq!( + increase_allowance(addr.clone(), asset, BOB, amount), + Err(Module { index: 52, error: [16, 0] }) + ); + }); +} + +#[test] +fn decrease_allowance_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = instantiate(CONTRACT, INIT_VALUE, vec![]); + let amount: Balance = 100 * UNIT; + + // Asset does not exist. + assert_eq!( + decrease_allowance(addr.clone(), 0, BOB, amount), + Err(Module { index: 52, error: [3, 0] }), + ); + // Create asset and mint `amount` to contract address, then approve Bob to spend `amount`. + let asset = + create_asset_mint_and_approve(addr.clone(), 0, addr.clone(), amount, BOB, amount); + // Asset is not live, i.e. frozen or being destroyed. + freeze_asset(addr.clone(), asset); + assert_eq!( + decrease_allowance(addr.clone(), asset, BOB, amount), + Err(Module { index: 52, error: [16, 0] }), + ); + thaw_asset(addr.clone(), asset); + // Successfully decrease allowance. + let allowance_before = Assets::allowance(asset, &addr, &BOB); + assert_ok!(decrease_allowance(addr.clone(), 0, BOB, amount / 2 - 1 * UNIT)); + let allowance_after = Assets::allowance(asset, &addr, &BOB); + assert_eq!(allowance_before - allowance_after, amount / 2 - 1 * UNIT); + // Asset is not live, i.e. frozen or being destroyed. + start_destroy_asset(addr.clone(), asset); + assert_eq!( + decrease_allowance(addr.clone(), asset, BOB, amount), + Err(Module { index: 52, error: [16, 0] }), + ); + }); +} + +/// 2. PSP-22 Metadata Interface: +/// - token_name +/// - token_symbol +/// - token_decimals + +#[test] +fn token_metadata_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = instantiate(CONTRACT, INIT_VALUE, vec![]); + let name: Vec = vec![11, 12, 13]; + let symbol: Vec = vec![21, 22, 23]; + let decimals: u8 = 69; + + // Token does not exist. + assert_eq!(token_name(addr.clone(), ASSET_ID), Ok(token_name_asset(ASSET_ID))); + assert_eq!(token_name(addr.clone(), ASSET_ID), Ok(Vec::::new())); + assert_eq!(token_symbol(addr.clone(), ASSET_ID), Ok(token_symbol_asset(ASSET_ID))); + assert_eq!(token_symbol(addr.clone(), ASSET_ID), Ok(Vec::::new())); + assert_eq!(token_decimals(addr.clone(), ASSET_ID), Ok(token_decimals_asset(ASSET_ID))); + assert_eq!(token_decimals(addr.clone(), ASSET_ID), Ok(0)); + // Create Token. + create_asset_and_set_metadata( + addr.clone(), + ASSET_ID, + name.clone(), + symbol.clone(), + decimals, + ); + assert_eq!(token_name(addr.clone(), ASSET_ID), Ok(token_name_asset(ASSET_ID))); + assert_eq!(token_name(addr.clone(), ASSET_ID), Ok(name)); + assert_eq!(token_symbol(addr.clone(), ASSET_ID), Ok(token_symbol_asset(ASSET_ID))); + assert_eq!(token_symbol(addr.clone(), ASSET_ID), Ok(symbol)); + assert_eq!(token_decimals(addr.clone(), ASSET_ID), Ok(token_decimals_asset(ASSET_ID))); + assert_eq!(token_decimals(addr.clone(), ASSET_ID), Ok(decimals)); + }); +} + +/// 3. Asset Management: +/// - create +/// - start_destroy +/// - set_metadata +/// - clear_metadata +/// - asset_exists + +#[test] +fn create_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + // Instantiate a contract without balance for fees. + let addr = instantiate(CONTRACT, 0, vec![0]); + // No balance to pay for fees. + assert_eq!( + create(addr.clone(), ASSET_ID, addr.clone(), 1), + Err(Module { index: 10, error: [2, 0] }), + ); + + // Instantiate a contract without balance for deposit. + let addr = instantiate(CONTRACT, 100, vec![1]); + // No balance to pay the deposit. + assert_eq!( + create(addr.clone(), ASSET_ID, addr.clone(), 1), + Err(Module { index: 10, error: [2, 0] }), + ); + + // Instantiate a contract with enough balance. + let addr = instantiate(CONTRACT, INIT_VALUE, vec![2]); + assert_eq!( + create(addr.clone(), ASSET_ID, BOB, 0), + Err(Module { index: 52, error: [7, 0] }), + ); + // The minimal balance for an asset must be non zero. + assert_eq!( + create(addr.clone(), ASSET_ID, BOB, 0), + Err(Module { index: 52, error: [7, 0] }), + ); + // Create asset successfully. + assert_ok!(create(addr.clone(), ASSET_ID, BOB, 1)); + // Asset ID is already taken. + assert_eq!( + create(addr.clone(), ASSET_ID, BOB, 1), + Err(Module { index: 52, error: [5, 0] }), + ); + }); +} + +// Testing a contract that creates an asset in the constructor. +#[test] +fn instantiate_and_create_fungible_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let contract = + "contracts/create_token_in_constructor/target/ink/create_token_in_constructor.wasm"; + // Asset already exists. + create_asset(ALICE, 0, 1); + assert_eq!( + instantiate_and_create_fungible(contract, 0, 1), + Err(Module { index: 52, error: [5, 0] }) + ); + // Successfully create an asset when instantiating the contract. + assert_ok!(instantiate_and_create_fungible(contract, ASSET_ID, 1)); + assert!(Assets::asset_exists(ASSET_ID)); + }); +} + +#[test] +fn start_destroy_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = instantiate(CONTRACT, INIT_VALUE, vec![2]); + + // Asset does not exist. + assert_eq!(start_destroy(addr.clone(), ASSET_ID), Err(Module { index: 52, error: [3, 0] }),); + // Create assets where contract is not the owner. + let asset = create_asset(ALICE, 0, 1); + // No Permission. + assert_eq!(start_destroy(addr.clone(), asset), Err(Module { index: 52, error: [2, 0] }),); + let asset = create_asset(addr.clone(), ASSET_ID, 1); + assert_ok!(start_destroy(addr.clone(), asset)); + }); +} + +#[test] +fn set_metadata_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let name = vec![42]; + let symbol = vec![42]; + let decimals = 42u8; + let addr = instantiate(CONTRACT, INIT_VALUE, vec![]); + + // Asset does not exist. + assert_eq!( + set_metadata(addr.clone(), ASSET_ID, vec![0], vec![0], 0u8), + Err(Module { index: 52, error: [3, 0] }), + ); + // Create assets where contract is not the owner. + let asset = create_asset(ALICE, 0, 1); + // No Permission. + assert_eq!( + set_metadata(addr.clone(), asset, vec![0], vec![0], 0u8), + Err(Module { index: 52, error: [2, 0] }), + ); + let asset = create_asset(addr.clone(), ASSET_ID, 1); + // Asset is not live, i.e. frozen or being destroyed. + freeze_asset(addr.clone(), asset); + assert_eq!( + set_metadata(addr.clone(), ASSET_ID, vec![0], vec![0], 0u8), + Err(Module { index: 52, error: [16, 0] }), + ); + thaw_asset(addr.clone(), asset); + // TODO: calling the below with a vector of length `100_000` errors in pallet contracts + // `OutputBufferTooSmall. Added to security analysis issue #131 to revisit. + // Set bad metadata - too large values. + assert_eq!( + set_metadata(addr.clone(), ASSET_ID, vec![0; 1000], vec![0; 1000], 0u8), + Err(Module { index: 52, error: [9, 0] }), + ); + // Set metadata successfully. + assert_ok!(set_metadata(addr.clone(), ASSET_ID, name, symbol, decimals)); + // Asset is not live, i.e. frozen or being destroyed. + start_destroy_asset(addr.clone(), asset); + assert_eq!( + set_metadata(addr.clone(), ASSET_ID, vec![0], vec![0], 0), + Err(Module { index: 52, error: [16, 0] }), + ); + }); +} + +#[test] +fn clear_metadata_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let name = vec![42]; + let symbol = vec![42]; + let decimals = 42u8; + let addr = instantiate(CONTRACT, INIT_VALUE, vec![]); + + // Asset does not exist. + assert_eq!(clear_metadata(addr.clone(), 0), Err(Module { index: 52, error: [3, 0] }),); + // Create assets where contract is not the owner. + let asset = create_asset_and_set_metadata(ALICE, 0, vec![0], vec![0], 0); + // No Permission. + assert_eq!(clear_metadata(addr.clone(), asset), Err(Module { index: 52, error: [2, 0] }),); + let asset = create_asset(addr.clone(), ASSET_ID, 1); + // Asset is not live, i.e. frozen or being destroyed. + freeze_asset(addr.clone(), asset); + assert_eq!(clear_metadata(addr.clone(), asset), Err(Module { index: 52, error: [16, 0] }),); + thaw_asset(addr.clone(), asset); + // No metadata set. + assert_eq!(clear_metadata(addr.clone(), asset), Err(Module { index: 52, error: [3, 0] }),); + set_metadata_asset(addr.clone(), asset, name, symbol, decimals); + // Clear metadata successfully. + assert_ok!(clear_metadata(addr.clone(), ASSET_ID)); + // Asset is not live, i.e. frozen or being destroyed. + start_destroy_asset(addr.clone(), asset); + assert_eq!( + set_metadata(addr.clone(), ASSET_ID, vec![0], vec![0], decimals), + Err(Module { index: 52, error: [16, 0] }), + ); + }); +} + +#[test] +fn asset_exists_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = instantiate(CONTRACT, INIT_VALUE, vec![]); + + // No tokens in circulation. + assert_eq!(asset_exists(addr.clone(), ASSET_ID), Ok(Assets::asset_exists(ASSET_ID))); + + // Tokens in circulation. + create_asset(addr.clone(), ASSET_ID, 1); + assert_eq!(asset_exists(addr.clone(), ASSET_ID), Ok(Assets::asset_exists(ASSET_ID))); + }); +} + +#[test] +fn mint_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = instantiate(CONTRACT, INIT_VALUE, vec![]); + let amount: Balance = 100 * UNIT; + + // Asset does not exist. + assert_eq!(mint(addr.clone(), 1, BOB, amount), Err(Token(UnknownAsset))); + let asset = create_asset(ALICE, 1, 1); + // Minting can only be done by the owner. + assert_eq!(mint(addr.clone(), asset, BOB, 1), Err(Module { index: 52, error: [2, 0] })); + let asset = create_asset(addr.clone(), 2, 2); + // Minimum balance of an asset can not be zero. + assert_eq!(mint(addr.clone(), asset, BOB, 1), Err(Token(BelowMinimum))); + // Asset is not live, i.e. frozen or being destroyed. + freeze_asset(addr.clone(), asset); + assert_eq!( + mint(addr.clone(), asset, BOB, amount), + Err(Module { index: 52, error: [16, 0] }) + ); + thaw_asset(addr.clone(), asset); + // Successful mint. + let balance_before_mint = Assets::balance(asset, &BOB); + assert_ok!(mint(addr.clone(), asset, BOB, amount)); + let balance_after_mint = Assets::balance(asset, &BOB); + assert_eq!(balance_after_mint, balance_before_mint + amount); + // Account can not hold more tokens than Balance::MAX. + assert_eq!(mint(addr.clone(), asset, BOB, Balance::MAX,), Err(Arithmetic(Overflow))); + // Asset is not live, i.e. frozen or being destroyed. + start_destroy_asset(addr.clone(), asset); + assert_eq!( + mint(addr.clone(), asset, BOB, amount), + Err(Module { index: 52, error: [16, 0] }) + ); + }); +} + +#[test] +fn burn_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = instantiate(CONTRACT, INIT_VALUE, vec![]); + let amount: Balance = 100 * UNIT; + + // Asset does not exist. + assert_eq!(burn(addr.clone(), 1, BOB, amount), Err(Module { index: 52, error: [3, 0] })); + let asset = create_asset(ALICE, 1, 1); + // Bob has no tokens and thus pallet assets doesn't know the account. + assert_eq!(burn(addr.clone(), asset, BOB, 1), Err(Module { index: 52, error: [1, 0] })); + // Burning can only be done by the manager. + mint_asset(ALICE, asset, BOB, amount); + assert_eq!(burn(addr.clone(), asset, BOB, 1), Err(Module { index: 52, error: [2, 0] })); + let asset = create_asset_and_mint_to(addr.clone(), 2, BOB, amount); + // Asset is not live, i.e. frozen or being destroyed. + freeze_asset(addr.clone(), asset); + assert_eq!( + burn(addr.clone(), asset, BOB, amount), + Err(Module { index: 52, error: [16, 0] }) + ); + thaw_asset(addr.clone(), asset); + // Successful mint. + let balance_before_burn = Assets::balance(asset, &BOB); + assert_ok!(burn(addr.clone(), asset, BOB, amount)); + let balance_after_burn = Assets::balance(asset, &BOB); + assert_eq!(balance_after_burn, balance_before_burn - amount); + // Asset is not live, i.e. frozen or being destroyed. + start_destroy_asset(addr.clone(), asset); + assert_eq!( + burn(addr.clone(), asset, BOB, amount), + Err(Module { index: 52, error: [16, 0] }) + ); + }); +} diff --git a/pop-api/integration-tests/src/fungibles/utils.rs b/pop-api/integration-tests/src/fungibles/utils.rs new file mode 100644 index 00000000..33a25f7a --- /dev/null +++ b/pop-api/integration-tests/src/fungibles/utils.rs @@ -0,0 +1,339 @@ +use super::*; + +fn do_bare_call(function: &str, addr: AccountId32, params: Vec) -> ExecReturnValue { + let function = function_selector(function); + let params = [function, params].concat(); + bare_call(addr, params, 0).expect("should work") +} + +pub(super) fn decoded(result: ExecReturnValue) -> Result { + ::decode(&mut &result.data[1..]).map_err(|_| result) +} + +pub(super) fn total_supply(addr: AccountId32, asset_id: AssetId) -> Result { + let result = do_bare_call("total_supply", addr, asset_id.encode()); + decoded::>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn balance_of( + addr: AccountId32, + asset_id: AssetId, + owner: AccountId32, +) -> Result { + let params = [asset_id.encode(), owner.encode()].concat(); + let result = do_bare_call("balance_of", addr, params); + decoded::>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn allowance( + addr: AccountId32, + asset_id: AssetId, + owner: AccountId32, + spender: AccountId32, +) -> Result { + let params = [asset_id.encode(), owner.encode(), spender.encode()].concat(); + let result = do_bare_call("allowance", addr, params); + decoded::>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn token_name(addr: AccountId32, asset_id: AssetId) -> Result, Error> { + let result = do_bare_call("token_name", addr, asset_id.encode()); + decoded::, Error>>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn token_symbol(addr: AccountId32, asset_id: AssetId) -> Result, Error> { + let result = do_bare_call("token_symbol", addr, asset_id.encode()); + decoded::, Error>>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn token_decimals(addr: AccountId32, asset_id: AssetId) -> Result { + let result = do_bare_call("token_decimals", addr, asset_id.encode()); + decoded::>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn asset_exists(addr: AccountId32, asset_id: AssetId) -> Result { + let result = do_bare_call("asset_exists", addr, asset_id.encode()); + decoded::>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn transfer( + addr: AccountId32, + asset_id: AssetId, + to: AccountId32, + value: Balance, +) -> Result<(), Error> { + let params = [asset_id.encode(), to.encode(), value.encode()].concat(); + let result = do_bare_call("transfer", addr, params); + decoded::>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn transfer_from( + addr: AccountId32, + asset_id: AssetId, + from: AccountId32, + to: AccountId32, + value: Balance, +) -> Result<(), Error> { + let data: Vec = vec![]; + let params = + [asset_id.encode(), from.encode(), to.encode(), value.encode(), data.encode()].concat(); + let result = do_bare_call("transfer_from", addr, params); + decoded::>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn approve( + addr: AccountId32, + asset_id: AssetId, + spender: AccountId32, + value: Balance, +) -> Result<(), Error> { + let params = [asset_id.encode(), spender.encode(), value.encode()].concat(); + let result = do_bare_call("approve", addr, params); + decoded::>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn increase_allowance( + addr: AccountId32, + asset_id: AssetId, + spender: AccountId32, + value: Balance, +) -> Result<(), Error> { + let params = [asset_id.encode(), spender.encode(), value.encode()].concat(); + let result = do_bare_call("increase_allowance", addr, params); + decoded::>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn decrease_allowance( + addr: AccountId32, + asset_id: AssetId, + spender: AccountId32, + value: Balance, +) -> Result<(), Error> { + let params = [asset_id.encode(), spender.encode(), value.encode()].concat(); + let result = do_bare_call("decrease_allowance", addr, params); + decoded::>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn create( + addr: AccountId32, + asset_id: AssetId, + admin: AccountId32, + min_balance: Balance, +) -> Result<(), Error> { + let params = [asset_id.encode(), admin.encode(), min_balance.encode()].concat(); + let result = do_bare_call("create", addr, params); + decoded::>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn start_destroy(addr: AccountId32, asset_id: AssetId) -> Result<(), Error> { + let result = do_bare_call("start_destroy", addr, asset_id.encode()); + match decoded::>(result) { + Ok(x) => x, + Err(result) => panic!("Contract reverted: {:?}", result), + } +} + +pub(super) fn set_metadata( + addr: AccountId32, + asset_id: AssetId, + name: Vec, + symbol: Vec, + decimals: u8, +) -> Result<(), Error> { + let params = [asset_id.encode(), name.encode(), symbol.encode(), decimals.encode()].concat(); + let result = do_bare_call("set_metadata", addr, params); + decoded::>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn clear_metadata(addr: AccountId32, asset_id: AssetId) -> Result<(), Error> { + let result = do_bare_call("clear_metadata", addr, asset_id.encode()); + decoded::>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn mint( + addr: AccountId32, + asset_id: AssetId, + account: AccountId32, + amount: Balance, +) -> Result<(), Error> { + let params = [asset_id.encode(), account.encode(), amount.encode()].concat(); + let result = do_bare_call("mint", addr, params); + decoded::>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn burn( + addr: AccountId32, + asset_id: AssetId, + account: AccountId32, + amount: Balance, +) -> Result<(), Error> { + let params = [asset_id.encode(), account.encode(), amount.encode()].concat(); + let result = do_bare_call("burn", addr, params); + decoded::>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} + +pub(super) fn create_asset(owner: AccountId32, asset_id: AssetId, min_balance: Balance) -> AssetId { + assert_ok!(Assets::create( + RuntimeOrigin::signed(owner.clone()), + asset_id.into(), + owner.into(), + min_balance + )); + asset_id +} + +pub(super) fn mint_asset( + owner: AccountId32, + asset_id: AssetId, + to: AccountId32, + value: Balance, +) -> AssetId { + assert_ok!(Assets::mint( + RuntimeOrigin::signed(owner.clone()), + asset_id.into(), + to.into(), + value + )); + asset_id +} + +pub(super) fn create_asset_and_mint_to( + owner: AccountId32, + asset_id: AssetId, + to: AccountId32, + value: Balance, +) -> AssetId { + create_asset(owner.clone(), asset_id, 1); + mint_asset(owner, asset_id, to, value) +} + +// Create an asset, mints to, and approves spender. +pub(super) fn create_asset_mint_and_approve( + owner: AccountId32, + asset_id: AssetId, + to: AccountId32, + mint: Balance, + spender: AccountId32, + approve: Balance, +) -> AssetId { + create_asset_and_mint_to(owner.clone(), asset_id, to.clone(), mint); + assert_ok!(Assets::approve_transfer( + RuntimeOrigin::signed(to.into()), + asset_id.into(), + spender.into(), + approve, + )); + asset_id +} + +// Freeze an asset. +pub(super) fn freeze_asset(owner: AccountId32, asset_id: AssetId) { + assert_ok!(Assets::freeze_asset(RuntimeOrigin::signed(owner.into()), asset_id.into())); +} + +// Thaw an asset. +pub(super) fn thaw_asset(owner: AccountId32, asset_id: AssetId) { + assert_ok!(Assets::thaw_asset(RuntimeOrigin::signed(owner.into()), asset_id.into())); +} + +// Start destroying an asset. +pub(super) fn start_destroy_asset(owner: AccountId32, asset_id: AssetId) { + assert_ok!(Assets::start_destroy(RuntimeOrigin::signed(owner.into()), asset_id.into())); +} + +// Create an asset and set metadata. +pub(super) fn create_asset_and_set_metadata( + owner: AccountId32, + asset_id: AssetId, + name: Vec, + symbol: Vec, + decimals: u8, +) -> AssetId { + assert_ok!(Assets::create( + RuntimeOrigin::signed(owner.clone()), + asset_id.into(), + owner.clone().into(), + 100 + )); + set_metadata_asset(owner, asset_id, name, symbol, decimals); + asset_id +} + +// Set metadata of an asset. +pub(super) fn set_metadata_asset( + owner: AccountId32, + asset_id: AssetId, + name: Vec, + symbol: Vec, + decimals: u8, +) { + assert_ok!(Assets::set_metadata( + RuntimeOrigin::signed(owner.into()), + asset_id.into(), + name, + symbol, + decimals + )); +} + +pub(super) fn token_name_asset(asset_id: AssetId) -> Vec { + as MetadataInspect>::name( + asset_id, + ) +} + +pub(super) fn token_symbol_asset(asset_id: AssetId) -> Vec { + as MetadataInspect>::symbol( + asset_id, + ) +} + +pub(super) fn token_decimals_asset(asset_id: AssetId) -> u8 { + as MetadataInspect>::decimals( + asset_id, + ) +} + +pub(super) fn instantiate_and_create_fungible( + contract: &str, + asset_id: AssetId, + min_balance: Balance, +) -> Result<(), Error> { + let function = function_selector("new"); + let input = [function, asset_id.encode(), min_balance.encode()].concat(); + let (wasm_binary, _) = + load_wasm_module::(contract).expect("could not read .wasm file"); + let result = Contracts::bare_instantiate( + ALICE, + INIT_VALUE, + GAS_LIMIT, + None, + Code::Upload(wasm_binary), + input, + vec![], + DEBUG_OUTPUT, + CollectEvents::Skip, + ) + .result + .expect("should work") + .result; + decoded::>(result.clone()) + .unwrap_or_else(|_| panic!("Contract reverted: {:?}", result)) +} diff --git a/pop-api/integration-tests/src/lib.rs b/pop-api/integration-tests/src/lib.rs new file mode 100644 index 00000000..b728fca6 --- /dev/null +++ b/pop-api/integration-tests/src/lib.rs @@ -0,0 +1,101 @@ +#![cfg(test)] + +use frame_support::{ + assert_ok, + traits::fungibles::{ + approvals::Inspect as ApprovalInspect, metadata::Inspect as MetadataInspect, Inspect, + }, + weights::Weight, +}; +use pallet_contracts::{Code, CollectEvents, Determinism, ExecReturnValue}; +use scale::{Decode, Encode}; +use sp_runtime::{traits::Hash, AccountId32, BuildStorage, DispatchError}; + +use pop_runtime_devnet::{ + config::assets::TrustBackedAssetsInstance, Assets, Contracts, Runtime, RuntimeOrigin, System, + UNIT, +}; + +mod fungibles; + +type AssetId = u32; +type Balance = u128; + +const ALICE: AccountId32 = AccountId32::new([1_u8; 32]); +const BOB: AccountId32 = AccountId32::new([2_u8; 32]); +const DEBUG_OUTPUT: pallet_contracts::DebugInfo = pallet_contracts::DebugInfo::UnsafeDebug; +// FERDIE has no initial balance. +const FERDIE: AccountId32 = AccountId32::new([3_u8; 32]); +const GAS_LIMIT: Weight = Weight::from_parts(100_000_000_000, 3 * 1024 * 1024); +const INIT_AMOUNT: Balance = 100_000_000 * UNIT; +const INIT_VALUE: Balance = 100 * UNIT; + +fn new_test_ext() -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .expect("Frame system builds valid default genesis config"); + + pallet_balances::GenesisConfig:: { + balances: vec![(ALICE, INIT_AMOUNT), (BOB, INIT_AMOUNT)], + } + .assimilate_storage(&mut t) + .expect("Pallet balances storage can be assimilated"); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext +} + +fn load_wasm_module(path: &str) -> std::io::Result<(Vec, ::Output)> +where + T: frame_system::Config, +{ + let wasm_binary = std::fs::read(path)?; + let code_hash = T::Hashing::hash(&wasm_binary); + Ok((wasm_binary, code_hash)) +} + +fn function_selector(name: &str) -> Vec { + let hash = sp_io::hashing::blake2_256(name.as_bytes()); + [hash[0..4].to_vec()].concat() +} + +fn bare_call( + addr: AccountId32, + input: Vec, + value: u128, +) -> Result { + let result = Contracts::bare_call( + ALICE, + addr.into(), + value.into(), + GAS_LIMIT, + None, + input, + DEBUG_OUTPUT, + CollectEvents::Skip, + Determinism::Enforced, + ); + result.result +} + +// Deploy, instantiate and return contract address. +fn instantiate(contract: &str, init_value: u128, salt: Vec) -> AccountId32 { + let (wasm_binary, _) = + load_wasm_module::(contract).expect("could not read .wasm file"); + let result = Contracts::bare_instantiate( + ALICE, + init_value, + GAS_LIMIT, + None, + Code::Upload(wasm_binary), + function_selector("new"), + salt, + DEBUG_OUTPUT, + CollectEvents::Skip, + ) + .result + .unwrap(); + assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); + result.account_id +} diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index e4590c89..cc785c14 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -1,101 +1,93 @@ +//! The `pop-api` crate provides an API for smart contracts to interact with the Pop Network runtime. +//! +//! This crate abstracts away complexities to deliver a streamlined developer experience while supporting +//! multiple API versions to ensure backward compatibility. It is designed with a focus on stability, +//! future-proofing, and storage efficiency, allowing developers to easily integrate powerful runtime +//! features into their contracts without unnecessary overhead. + #![cfg_attr(not(feature = "std"), no_std, no_main)] +use constants::DECODING_FAILED; +use ink::env::chain_extension::{ChainExtensionMethod, FromStatusCode}; +#[cfg(feature = "assets")] +pub use v0::assets; + +/// Module providing primitives types. pub mod primitives; +/// The first version of the API. pub mod v0; -use crate::PopApiError::{Balances, Nfts, UnknownStatusCode}; -use ink::{prelude::vec::Vec, ChainExtensionInstance}; -use primitives::{cross_chain::*, storage_keys::*}; -pub use sp_runtime::{BoundedVec, MultiAddress, MultiSignature}; -use v0::RuntimeCall; -pub use v0::{balances, cross_chain, nfts, relay_chain_block_number, state}; +/// A result type used by the API, with the `StatusCode` as the error type. +pub type Result = core::result::Result; -type AccountId = ::AccountId; -type Balance = ::Balance; -type BlockNumber = ::BlockNumber; -type StringLimit = u32; -type MaxTips = u32; +mod constants { + // Errors: + pub(crate) const DECODING_FAILED: u32 = 255; + // TODO: will be used in the future when the remaining fungibles features will be implemented. + pub(crate) const _MODULE_ERROR: u8 = 3; -pub type Result = core::result::Result; + // Function IDs: + pub(crate) const DISPATCH: u8 = 0; + pub(crate) const READ_STATE: u8 = 1; -#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum PopApiError { - UnknownStatusCode(u32), - DecodingFailed, - SystemCallFiltered, - Balances(balances::Error), - Nfts(nfts::Error), - Xcm(cross_chain::Error), + // Modules: + pub(crate) const ASSETS: u8 = 52; + pub(crate) const BALANCES: u8 = 10; + pub(crate) const FUNGIBLES: u8 = 150; } -impl ink::env::chain_extension::FromStatusCode for PopApiError { - fn from_status_code(status_code: u32) -> core::result::Result<(), Self> { - match status_code { - 0 => Ok(()), - // CallFiltered originates from `frame_system` with pallet-index 0. The CallFiltered error is at index 5 - 5 => Err(PopApiError::SystemCallFiltered), - 10_000..=10_999 => Err(Balances((status_code - 10_000).try_into()?)), - 50_000..=50_999 => Err(Nfts((status_code - 50_000).try_into()?)), - _ => Err(UnknownStatusCode(status_code)), - } - } +// Helper method to build a dispatch call or a call to read state. +// +// Parameters: +// - 'version': The version of the chain extension. +// - 'function': The ID of the function. +// - 'module': The index of the runtime module. +// - 'dispatchable': The index of the module dispatchable functions. +fn build_extension_method( + version: u8, + function: u8, + module: u8, + dispatchable: u8, +) -> ChainExtensionMethod<(), (), (), false> { + ChainExtensionMethod::build(u32::from_le_bytes([version, function, module, dispatchable])) } -impl From for PopApiError { - fn from(_: scale::Error) -> Self { - panic!("encountered unexpected invalid SCALE encoding") +/// Represents a status code returned by the runtime. +/// +/// `StatusCode` encapsulates a `u32` value that indicates the status of an operation performed by +/// the runtime. It helps to communicate the success or failure of a Pop API call to the contract, +/// providing a standardized way to handle errors. +/// +/// This status code can be used to determine if an operation succeeded or if it encountered an +/// error. A `StatusCode` of `0` typically indicates success, while any other value represents an +/// error. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[ink::scale_derive(Encode, Decode, TypeInfo)] +pub struct StatusCode(pub u32); + +impl From for StatusCode { + /// Converts a `u32` into a `StatusCode`. + fn from(value: u32) -> Self { + StatusCode(value) } } -#[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum Environment {} - -impl ink::env::Environment for Environment { - const MAX_EVENT_TOPICS: usize = - ::MAX_EVENT_TOPICS; - - type AccountId = ::AccountId; - type Balance = ::Balance; - type Hash = ::Hash; - type BlockNumber = ::BlockNumber; - type Timestamp = ::Timestamp; - - type ChainExtension = PopApi; -} - -#[ink::chain_extension(extension = 909)] -pub trait PopApi { - type ErrorCode = PopApiError; - - #[ink(function = 0)] - #[allow(private_interfaces)] - fn dispatch(call: RuntimeCall) -> Result<()>; - - #[ink(function = 1)] - #[allow(private_interfaces)] - fn read_state(key: RuntimeStateKeys) -> Result>; - - #[ink(function = 2)] - #[allow(private_interfaces)] - fn send_xcm(xcm: CrossChainMessage) -> Result<()>; -} - -fn dispatch(call: RuntimeCall) -> Result<()> { - <::ChainExtension as ChainExtensionInstance>::instantiate( - ) - .dispatch(call) -} - -fn read_state(key: RuntimeStateKeys) -> Result> { - <::ChainExtension as ChainExtensionInstance>::instantiate( - ) - .read_state(key) +impl FromStatusCode for StatusCode { + /// Converts a `u32` status code to a `Result`. + /// + /// `Ok(())` if the status code is `0` and `Err(StatusCode(status_code))` for any other status + /// code. + fn from_status_code(status_code: u32) -> Result<()> { + match status_code { + 0 => Ok(()), + _ => Err(StatusCode(status_code)), + } + } } -fn send_xcm(xcm: CrossChainMessage) -> Result<()> { - <::ChainExtension as ChainExtensionInstance>::instantiate( - ) - .send_xcm(xcm) +impl From for StatusCode { + /// Converts a scale decoding error into a `StatusCode` indicating a decoding failure. + fn from(_: ink::scale::Error) -> Self { + StatusCode(DECODING_FAILED) + } } diff --git a/pop-api/src/primitives.rs b/pop-api/src/primitives.rs index e8098f69..a3d596a5 100644 --- a/pop-api/src/primitives.rs +++ b/pop-api/src/primitives.rs @@ -1,2 +1,5 @@ +use ink::env::{DefaultEnvironment, Environment}; pub use pop_primitives::*; -pub use sp_runtime::{BoundedVec, MultiAddress}; + +pub(crate) type AccountId = ::AccountId; +pub(crate) type Balance = ::Balance; diff --git a/pop-api/src/v0/assets/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs new file mode 100644 index 00000000..4f270e6b --- /dev/null +++ b/pop-api/src/v0/assets/fungibles.rs @@ -0,0 +1,581 @@ +//! The `fungibles` module provides an API for interacting and managing fungible assets on Pop Network. +//! +//! The API includes the following interfaces: +//! 1. PSP-22 +//! 2. PSP-22 Metadata +//! 3. Asset Management +//! 4. PSP-22 Mintable & Burnable + +use crate::{ + constants::{ASSETS, BALANCES, FUNGIBLES}, + primitives::{AccountId, AssetId, Balance}, + Result, StatusCode, +}; +use constants::*; +use ink::{env::chain_extension::ChainExtensionMethod, prelude::vec::Vec}; +pub use management::*; +pub use metadata::*; + +// Helper method to build a dispatch call. +// +// Parameters: +// - 'dispatchable': The index of the dispatchable function within the module. +fn build_dispatch(dispatchable: u8) -> ChainExtensionMethod<(), (), (), false> { + crate::v0::build_dispatch(FUNGIBLES, dispatchable) +} + +// Helper method to build a call to read state. +// +// Parameters: +// - 'state_query': The index of the runtime state query. +fn build_read_state(state_query: u8) -> ChainExtensionMethod<(), (), (), false> { + crate::v0::build_read_state(FUNGIBLES, state_query) +} + +mod constants { + /// 1. PSP-22 Interface: + pub(super) const TOTAL_SUPPLY: u8 = 0; + pub(super) const BALANCE_OF: u8 = 1; + pub(super) const ALLOWANCE: u8 = 2; + pub(super) const TRANSFER: u8 = 3; + pub(super) const TRANSFER_FROM: u8 = 4; + pub(super) const APPROVE: u8 = 5; + pub(super) const INCREASE_ALLOWANCE: u8 = 6; + pub(super) const DECREASE_ALLOWANCE: u8 = 7; + + /// 2. PSP-22 Metadata Interface: + pub(super) const TOKEN_NAME: u8 = 8; + pub(super) const TOKEN_SYMBOL: u8 = 9; + pub(super) const TOKEN_DECIMALS: u8 = 10; + + /// 3. Asset Management: + pub(super) const CREATE: u8 = 11; + pub(super) const START_DESTROY: u8 = 12; + pub(super) const SET_METADATA: u8 = 16; + pub(super) const CLEAR_METADATA: u8 = 17; + pub(super) const ASSET_EXISTS: u8 = 18; + + /// 4. PSP-22 Mintable & Burnable interface: + pub(super) const MINT: u8 = 19; + pub(super) const BURN: u8 = 20; +} + +/// A set of events for use in smart contracts interacting with the fungibles API. +/// +/// The `Transfer` and `Approval` events conform to the PSP-22 standard. The other events +/// (`Create`, `StartDestroy`, `SetMetadata`, `ClearMetadata`) are provided for convenience. +/// +/// These events are not emitted by the API itself but can be used in your contracts to +/// track asset operations. Be mindful of the costs associated with emitting events. +/// +/// For more details, refer to [ink! events](https://use.ink/basics/events). +pub mod events { + use super::*; + + /// Event emitted when allowance by `owner` to `spender` changes. + #[ink::event] + pub struct Approval { + /// Account providing allowance. + #[ink(topic)] + pub owner: AccountId, + /// Allowance beneficiary. + #[ink(topic)] + pub spender: AccountId, + /// New allowance amount. + pub value: u128, + } + + /// Event emitted when transfer of tokens occurs. + #[ink::event] + pub struct Transfer { + /// Transfer sender. `None` in case of minting new tokens. + #[ink(topic)] + pub from: Option, + /// Transfer recipient. `None` in case of burning tokens. + #[ink(topic)] + pub to: Option, + /// Amount of tokens transferred (or minted/burned). + pub value: u128, + } + + /// Event emitted when a token class is created. + #[ink::event] + pub struct Create { + /// The ID of the asset. + #[ink(topic)] + pub id: AssetId, + /// Creator of the asset. + #[ink(topic)] + pub creator: AccountId, + /// Admin of the asset. + #[ink(topic)] + pub admin: AccountId, + } + + /// Event emitted when a asset is in the process of being destroyed. + #[ink::event] + pub struct StartDestroy { + /// The ID of the asset. + #[ink(topic)] + pub id: AssetId, + } + + /// Event emitted when new metadata is set for an asset. + #[ink::event] + pub struct SetMetadata { + /// The ID of the asset created. + #[ink(topic)] + pub id: AssetId, + /// The name of the asset. + #[ink(topic)] + pub name: Vec, + /// The symbol of the asset. + #[ink(topic)] + pub symbol: Vec, + /// The decimals of the asset. + pub decimals: u8, + } + + /// Event emitted when metadata is cleared for a token. + #[ink::event] + pub struct ClearMetadata { + /// The ID of the asset. + #[ink(topic)] + pub id: AssetId, + } +} + +/// Returns the total token supply for a given asset ID. +/// +/// # Parameters +/// - `id` - The ID of the asset. +#[inline] +pub fn total_supply(id: AssetId) -> Result { + build_read_state(TOTAL_SUPPLY) + .input::() + .output::, true>() + .handle_error_code::() + .call(&(id)) +} + +/// Returns the account balance for the specified `owner` for a given asset ID. Returns `0` if +/// the account is non-existent. +/// +/// # Parameters +/// - `id` - The ID of the asset. +/// - `owner` - The account whose balance is being queried. +#[inline] +pub fn balance_of(id: AssetId, owner: AccountId) -> Result { + build_read_state(BALANCE_OF) + .input::<(AssetId, AccountId)>() + .output::, true>() + .handle_error_code::() + .call(&(id, owner)) +} + +/// Returns the amount which `spender` is still allowed to withdraw from `owner` for a given +/// asset ID. Returns `0` if no allowance has been set. +/// +/// # Parameters +/// - `id` - The ID of the asset. +/// - `owner` - The account that owns the tokens. +/// - `spender` - The account that is allowed to spend the tokens. +#[inline] +pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { + build_read_state(ALLOWANCE) + .input::<(AssetId, AccountId, AccountId)>() + .output::, true>() + .handle_error_code::() + .call(&(id, owner, spender)) +} + +/// Transfers `value` amount of tokens from the caller's account to account `to`, with additional +/// `data` in unspecified format. +/// +/// # Parameters +/// - `id` - The ID of the asset. +/// - `to` - The recipient account. +/// - `value` - The number of tokens to transfer. +#[inline] +pub fn transfer(id: AssetId, to: AccountId, value: Balance) -> Result<()> { + build_dispatch(TRANSFER) + .input::<(AssetId, AccountId, Balance)>() + .output::, true>() + .handle_error_code::() + .call(&(id, to, value)) +} + +/// Transfers `value` amount tokens on behalf of `from` to account `to` with additional `data` +/// in unspecified format. +/// +/// # Parameters +/// - `id` - The ID of the asset. +/// - `from` - The account from which the tokens are transferred. +/// - `to` - The recipient account. +/// - `value` - The number of tokens to transfer. +#[inline] +pub fn transfer_from(id: AssetId, from: AccountId, to: AccountId, value: Balance) -> Result<()> { + build_dispatch(TRANSFER_FROM) + .input::<(AssetId, AccountId, AccountId, Balance)>() + .output::, true>() + .handle_error_code::() + .call(&(id, from, to, value)) +} + +/// Approves an account to spend a specified number of tokens on behalf of the caller. +/// +/// # Parameters +/// - `id` - The ID of the asset. +/// - `spender` - The account that is allowed to spend the tokens. +/// - `value` - The number of tokens to approve. +#[inline] +pub fn approve(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { + build_dispatch(APPROVE) + .input::<(AssetId, AccountId, Balance)>() + .output::, true>() + .handle_error_code::() + .call(&(id, spender, value)) +} + +/// Increases the allowance of a spender. +/// +/// # Parameters +/// - `id` - The ID of the asset. +/// - `spender` - The account that is allowed to spend the tokens. +/// - `value` - The number of tokens to increase the allowance by. +#[inline] +pub fn increase_allowance(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { + build_dispatch(INCREASE_ALLOWANCE) + .input::<(AssetId, AccountId, Balance)>() + .output::, true>() + .handle_error_code::() + .call(&(id, spender, value)) +} + +/// Decreases the allowance of a spender. +/// +/// # Parameters +/// - `id` - The ID of the asset. +/// - `spender` - The account that is allowed to spend the tokens. +/// - `value` - The number of tokens to decrease the allowance by. +#[inline] +pub fn decrease_allowance(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { + build_dispatch(DECREASE_ALLOWANCE) + .input::<(AssetId, AccountId, Balance)>() + .output::, true>() + .handle_error_code::() + .call(&(id, spender, value)) +} + +/// Creates `value` amount tokens and assigns them to `account`, increasing the total supply. +/// +/// # Parameters +/// - `id` - The ID of the asset. +/// - `account` - The account to be credited with the created tokens. +/// - `value` - The number of tokens to mint. +#[inline] +pub fn mint(id: AssetId, account: AccountId, value: Balance) -> Result<()> { + build_dispatch(MINT) + .input::<(AssetId, AccountId, Balance)>() + .output::, true>() + .handle_error_code::() + .call(&(id, account, value)) +} + +/// Destroys `value` amount tokens from `account`, reducing the total supply. +/// +/// # Parameters +/// - `id` - The ID of the asset. +/// - `account` - The account from which the tokens will be destroyed. +/// - `value` - The number of tokens to destroy. +#[inline] +pub fn burn(id: AssetId, account: AccountId, value: Balance) -> Result<()> { + build_dispatch(BURN) + .input::<(AssetId, AccountId, Balance)>() + .output::, true>() + .handle_error_code::() + .call(&(id, account, value)) +} + +/// The PSP-22 Metadata interface for querying metadata. +pub mod metadata { + use super::*; + + /// Returns the token name for a given asset ID. + /// + /// # Parameters + /// - `id` - The ID of the asset. + #[inline] + pub fn token_name(id: AssetId) -> Result> { + build_read_state(TOKEN_NAME) + .input::() + .output::>, true>() + .handle_error_code::() + .call(&(id)) + } + + /// Returns the token symbol for a given asset ID. + /// + /// # Parameters + /// - `id` - The ID of the asset. + #[inline] + pub fn token_symbol(id: AssetId) -> Result> { + build_read_state(TOKEN_SYMBOL) + .input::() + .output::>, true>() + .handle_error_code::() + .call(&(id)) + } + + /// Returns the token decimals for a given asset ID. + /// + /// # Parameters + /// - `id` - The ID of the asset. + #[inline] + pub fn token_decimals(id: AssetId) -> Result { + build_read_state(TOKEN_DECIMALS) + .input::() + .output::, true>() + .handle_error_code::() + .call(&(id)) + } +} + +/// The interface for creating, managing and destroying fungible assets. +pub mod management { + use super::*; + + /// Create a new token with a given asset ID. + /// + /// # Parameters + /// - `id` - The ID of the asset. + /// - `admin` - The account that will administer the asset. + /// - `min_balance` - The minimum balance required for accounts holding this asset. + #[inline] + pub fn create(id: AssetId, admin: AccountId, min_balance: Balance) -> Result<()> { + build_dispatch(CREATE) + .input::<(AssetId, AccountId, Balance)>() + .output::, true>() + .handle_error_code::() + .call(&(id, admin, min_balance)) + } + + /// Start the process of destroying a token with a given asset ID. + /// + /// # Parameters + /// - `id` - The ID of the asset. + #[inline] + pub fn start_destroy(id: AssetId) -> Result<()> { + build_dispatch(START_DESTROY) + .input::() + .output::, true>() + .handle_error_code::() + .call(&(id)) + } + + /// Set the metadata for a token with a given asset ID. + /// + /// # Parameters + /// - `id`: The identifier of the asset to update. + /// - `name`: The user friendly name of this asset. Limited in length by `StringLimit`. + /// - `symbol`: The exchange symbol for this asset. Limited in length by `StringLimit`. + /// - `decimals`: The number of decimals this asset uses to represent one unit. + #[inline] + pub fn set_metadata(id: AssetId, name: Vec, symbol: Vec, decimals: u8) -> Result<()> { + build_dispatch(SET_METADATA) + .input::<(AssetId, Vec, Vec, u8)>() + .output::, true>() + .handle_error_code::() + .call(&(id, name, symbol, decimals)) + } + + /// Clear the metadata for a token with a given asset ID. + /// + /// # Parameters + /// - `id` - The ID of the asset. + #[inline] + pub fn clear_metadata(id: AssetId) -> Result<()> { + build_dispatch(CLEAR_METADATA) + .input::() + .output::, true>() + .handle_error_code::() + .call(&(id)) + } + + /// Checks if token with a given asset ID exists. + /// + /// # Parameters + /// - `id` - The ID of the asset. + #[inline] + pub fn asset_exists(id: AssetId) -> Result { + build_read_state(ASSET_EXISTS) + .input::() + .output::, true>() + .handle_error_code::() + .call(&(id)) + } +} + +/// Represents various errors related to local fungible assets in the Pop API. +/// +/// The `FungiblesError` provides a detailed and specific set of error types that can occur when +/// interacting with fungible assets through the Pop API. Each variant signifies a particular error +/// condition, facilitating precise error handling and debugging. +/// +/// It is designed to be lightweight, including only the essential errors relevant to fungible asset +/// operations. The `Other` variant serves as a catch-all for any unexpected errors. For more +/// detailed debugging, the `Other` variant can be converted into the richer `Error` type defined in +/// the primitives crate. +#[derive(Debug, PartialEq, Eq)] +#[ink::scale_derive(Encode, Decode, TypeInfo)] +pub enum FungiblesError { + /// An unspecified or unknown error occurred. + Other(StatusCode), + /// The asset is not live; either frozen or being destroyed. + AssetNotLive, + /// Not enough allowance to fulfill a request is available. + InsufficientAllowance, + /// Not enough balance to fulfill a request is available. + InsufficientBalance, + /// The asset ID is already taken. + InUse, + /// Minimum balance should be non-zero. + MinBalanceZero, + /// The account to alter does not exist. + NoAccount, + /// The signing account has no permission to do the operation. + NoPermission, + /// The given asset ID is unknown. + Unknown, + /// No balance for creation of assets or fees. + // TODO: Originally `pallet_balances::Error::InsufficientBalance` but collides with the + // `InsufficientBalance` error that is used for `pallet_assets::Error::BalanceLow` to adhere to + // standard. This deserves a second look. + NoBalance, +} + +impl From for FungiblesError { + /// Converts a `StatusCode` to a `FungiblesError`. + /// + /// This conversion maps a `StatusCode`, returned by the runtime, to a more descriptive + /// `FungiblesError`. This provides better context and understanding of the error, allowing + /// developers to handle the most important errors effectively. + fn from(value: StatusCode) -> Self { + let encoded = value.0.to_le_bytes(); + match encoded { + // Balances. + [_, BALANCES, 2, _] => FungiblesError::NoBalance, + // Assets. + [_, ASSETS, 0, _] => FungiblesError::NoAccount, + [_, ASSETS, 1, _] => FungiblesError::NoPermission, + [_, ASSETS, 2, _] => FungiblesError::Unknown, + [_, ASSETS, 3, _] => FungiblesError::InUse, + [_, ASSETS, 5, _] => FungiblesError::MinBalanceZero, + [_, ASSETS, 7, _] => FungiblesError::InsufficientAllowance, + [_, ASSETS, 10, _] => FungiblesError::AssetNotLive, + _ => FungiblesError::Other(value), + } + } +} + +#[cfg(test)] +mod tests { + use ink::scale::{Decode, Encode}; + + use super::FungiblesError; + use crate::{ + constants::{ASSETS, BALANCES}, + primitives::error::{ + ArithmeticError::*, + Error::{self, *}, + TokenError::*, + TransactionalError::*, + }, + StatusCode, + }; + + fn error_into_status_code(error: Error) -> StatusCode { + let mut encoded_error = error.encode(); + encoded_error.resize(4, 0); + let value = u32::from_le_bytes( + encoded_error.try_into().expect("qed, resized to 4 bytes line above"), + ); + value.into() + } + + fn into_fungibles_error(error: Error) -> FungiblesError { + let status_code: StatusCode = error_into_status_code(error); + status_code.into() + } + + // If we ever want to change the conversion from bytes to `u32`. + #[test] + fn status_code_vs_encoded() { + assert_eq!(u32::decode(&mut &[3u8, 10, 2, 0][..]).unwrap(), 133635u32); + assert_eq!(u32::decode(&mut &[3u8, 52, 0, 0][..]).unwrap(), 13315u32); + assert_eq!(u32::decode(&mut &[3u8, 52, 1, 0][..]).unwrap(), 78851u32); + assert_eq!(u32::decode(&mut &[3u8, 52, 2, 0][..]).unwrap(), 144387u32); + assert_eq!(u32::decode(&mut &[3u8, 52, 3, 0][..]).unwrap(), 209923u32); + assert_eq!(u32::decode(&mut &[3u8, 52, 5, 0][..]).unwrap(), 340995u32); + assert_eq!(u32::decode(&mut &[3u8, 52, 7, 0][..]).unwrap(), 472067u32); + assert_eq!(u32::decode(&mut &[3u8, 52, 10, 0][..]).unwrap(), 668675u32); + } + + #[test] + fn conversion_status_code_into_fungibles_error_works() { + let other_errors = vec![ + Other { dispatch_error_index: 5, error_index: 5, error: 1 }, + CannotLookup, + BadOrigin, + // `ModuleError` other than assets module. + Module { index: 2, error: 5 }, + ConsumerRemaining, + NoProviders, + TooManyConsumers, + Token(OnlyProvider), + Arithmetic(Overflow), + Transactional(NoLayer), + Exhausted, + Corruption, + Unavailable, + RootNotAllowed, + UnknownCall, + DecodingFailed, + ]; + for error in other_errors { + let status_code: StatusCode = error_into_status_code(error); + let fungibles_error: FungiblesError = status_code.into(); + assert_eq!(fungibles_error, FungiblesError::Other(status_code)) + } + + assert_eq!( + into_fungibles_error(Module { index: BALANCES, error: 2 }), + FungiblesError::NoBalance + ); + assert_eq!( + into_fungibles_error(Module { index: ASSETS, error: 0 }), + FungiblesError::NoAccount + ); + assert_eq!( + into_fungibles_error(Module { index: ASSETS, error: 1 }), + FungiblesError::NoPermission + ); + assert_eq!( + into_fungibles_error(Module { index: ASSETS, error: 2 }), + FungiblesError::Unknown + ); + assert_eq!(into_fungibles_error(Module { index: ASSETS, error: 3 }), FungiblesError::InUse); + assert_eq!( + into_fungibles_error(Module { index: ASSETS, error: 5 }), + FungiblesError::MinBalanceZero + ); + assert_eq!( + into_fungibles_error(Module { index: ASSETS, error: 7 }), + FungiblesError::InsufficientAllowance + ); + assert_eq!( + into_fungibles_error(Module { index: ASSETS, error: 10 }), + FungiblesError::AssetNotLive + ); + } +} diff --git a/pop-api/src/v0/assets/mod.rs b/pop-api/src/v0/assets/mod.rs new file mode 100644 index 00000000..2d5ae236 --- /dev/null +++ b/pop-api/src/v0/assets/mod.rs @@ -0,0 +1,3 @@ +/// APIs for fungible assets. +#[cfg(feature = "fungibles")] +pub mod fungibles; diff --git a/pop-api/src/v0/balances.rs b/pop-api/src/v0/balances.rs deleted file mode 100644 index bf029178..00000000 --- a/pop-api/src/v0/balances.rs +++ /dev/null @@ -1,88 +0,0 @@ -use crate::{ - dispatch, primitives::MultiAddress, v0::RuntimeCall, AccountId, PopApiError, - PopApiError::UnknownStatusCode, -}; - -type Result = core::result::Result; - -pub fn transfer_keep_alive( - dest: impl Into>, - value: u128, -) -> Result<()> { - Ok(dispatch(RuntimeCall::Balances(BalancesCall::TransferKeepAlive { - dest: dest.into(), - value, - }))?) -} - -#[derive(scale::Encode)] -#[allow(dead_code)] -pub(crate) enum BalancesCall { - #[codec(index = 3)] - TransferKeepAlive { - dest: MultiAddress, - #[codec(compact)] - value: u128, - }, -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum Error { - /// Vesting balance too high to send value. - VestingBalance, - /// Account liquidity restrictions prevent withdrawal. - LiquidityRestrictions, - /// Balance too low to send value. - InsufficientBalance, - /// Value too low to create account due to existential deposit. - ExistentialDeposit, - /// Transfer/payment would kill account. - Expendability, - /// A vesting schedule already exists for this account. - ExistingVestingSchedule, - /// Beneficiary account must pre-exist. - DeadAccount, - /// Number of named reserves exceed `MaxReserves`. - TooManyReserves, - /// Number of holds exceed `VariantCountOf`. - TooManyHolds, - /// Number of freezes exceed `MaxFreezes`. - TooManyFreezes, - /// The issuance cannot be modified since it is already deactivated. - IssuanceDeactivated, - /// The delta cannot be zero. - DeltaZero, -} - -impl TryFrom for Error { - type Error = PopApiError; - - fn try_from(status_code: u32) -> core::result::Result { - use Error::*; - match status_code { - 0 => Ok(VestingBalance), - 1 => Ok(LiquidityRestrictions), - 2 => Ok(InsufficientBalance), - 3 => Ok(ExistentialDeposit), - 4 => Ok(Expendability), - 5 => Ok(ExistingVestingSchedule), - 6 => Ok(DeadAccount), - 7 => Ok(TooManyReserves), - 8 => Ok(TooManyHolds), - 9 => Ok(TooManyFreezes), - 10 => Ok(IssuanceDeactivated), - 11 => Ok(DeltaZero), - _ => Err(UnknownStatusCode(status_code)), - } - } -} - -impl From for Error { - fn from(error: PopApiError) -> Self { - match error { - PopApiError::Balances(e) => e, - _ => panic!("expected balances error"), - } - } -} diff --git a/pop-api/src/v0/cross_chain/coretime.rs b/pop-api/src/v0/cross_chain/coretime.rs deleted file mode 100644 index 0039ed20..00000000 --- a/pop-api/src/v0/cross_chain/coretime.rs +++ /dev/null @@ -1,11 +0,0 @@ -use crate::{ - primitives::cross_chain::{CrossChainMessage, OnDemand, RelayChainMessage}, - send_xcm, -}; - -/// Send a cross-chain message to place a sport order for instantaneous coretime. -pub fn place_spot_order(max_amount: u128, para_id: u32) -> crate::cross_chain::Result<()> { - Ok(send_xcm(CrossChainMessage::Relay(RelayChainMessage::OnDemand( - OnDemand::PlaceOrderKeepAlive { max_amount, para_id }, - )))?) -} diff --git a/pop-api/src/v0/cross_chain/mod.rs b/pop-api/src/v0/cross_chain/mod.rs deleted file mode 100644 index 6732c119..00000000 --- a/pop-api/src/v0/cross_chain/mod.rs +++ /dev/null @@ -1,107 +0,0 @@ -pub mod coretime; - -use crate::{PopApiError::UnknownStatusCode, *}; - -type Result = core::result::Result; - -#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum Error { - /// The desired destination was unreachable, generally because there is a no way of routing - /// to it. - Unreachable, - /// There was some other issue (i.e. not to do with routing) in sending the message. - /// Perhaps a lack of space for buffering the message. - SendFailure, - /// The message execution fails the filter. - Filtered, - /// The message's weight could not be determined. - UnweighableMessage, - /// The destination `Location` provided cannot be inverted. - DestinationNotInvertible, - /// The assets to be sent are empty. - Empty, - /// Could not re-anchor the assets to declare the fees for the destination chain. - CannotReanchor, - /// Too many assets have been attempted for transfer. - TooManyAssets, - /// Origin is invalid for sending. - InvalidOrigin, - /// The version of the `Versioned` value used is not able to be interpreted. - BadVersion, - /// The given location could not be used (e.g. because it cannot be expressed in the - /// desired version of XCM). - BadLocation, - /// The referenced subscription could not be found. - NoSubscription, - /// The location is invalid since it already has a subscription from us. - AlreadySubscribed, - /// Could not check-out the assets for teleportation to the destination chain. - CannotCheckOutTeleport, - /// The owner does not own (all) of the asset that they wish to do the operation on. - LowBalance, - /// The asset owner has too many locks on the asset. - TooManyLocks, - /// The given account is not an identifiable sovereign account for any location. - AccountNotSovereign, - /// The operation required fees to be paid which the initiator could not meet. - FeesNotMet, - /// A remote lock with the corresponding data could not be found. - LockNotFound, - /// The unlock operation cannot succeed because there are still consumers of the lock. - InUse, - /// Invalid non-concrete asset. - InvalidAssetNotConcrete, - /// Invalid asset, reserve chain could not be determined for it. - InvalidAssetUnknownReserve, - /// Invalid asset, do not support remote asset reserves with different fees reserves. - InvalidAssetUnsupportedReserve, - /// Too many assets with different reserve locations have been attempted for transfer. - TooManyReserves, - /// Local XCM execution incomplete. - LocalExecutionIncomplete, -} - -impl TryFrom for Error { - type Error = PopApiError; - - fn try_from(status_code: u32) -> core::result::Result { - use Error::*; - match status_code { - 0 => Ok(Unreachable), - 1 => Ok(SendFailure), - 2 => Ok(Filtered), - 3 => Ok(UnweighableMessage), - 4 => Ok(DestinationNotInvertible), - 5 => Ok(Empty), - 6 => Ok(CannotReanchor), - 7 => Ok(TooManyAssets), - 8 => Ok(InvalidOrigin), - 9 => Ok(BadVersion), - 10 => Ok(BadLocation), - 11 => Ok(NoSubscription), - 12 => Ok(AlreadySubscribed), - 13 => Ok(CannotCheckOutTeleport), - 14 => Ok(LowBalance), - 15 => Ok(TooManyLocks), - 16 => Ok(AccountNotSovereign), - 17 => Ok(FeesNotMet), - 18 => Ok(LockNotFound), - 19 => Ok(InUse), - 20 => Ok(InvalidAssetNotConcrete), - 21 => Ok(InvalidAssetUnknownReserve), - 22 => Ok(InvalidAssetUnsupportedReserve), - 23 => Ok(TooManyReserves), - _ => Err(UnknownStatusCode(status_code)), - } - } -} - -impl From for Error { - fn from(error: PopApiError) -> Self { - match error { - PopApiError::Xcm(e) => e, - _ => panic!("expected xcm error"), - } - } -} diff --git a/pop-api/src/v0/mod.rs b/pop-api/src/v0/mod.rs index 2ae0b821..55732e2d 100644 --- a/pop-api/src/v0/mod.rs +++ b/pop-api/src/v0/mod.rs @@ -1,21 +1,37 @@ use crate::{ - primitives::storage_keys::{ParachainSystemKeys, RuntimeStateKeys}, - BlockNumber, PopApiError, + build_extension_method, + constants::{DISPATCH, READ_STATE}, + primitives::Error, + StatusCode, }; +use ink::env::chain_extension::ChainExtensionMethod; -pub mod balances; -pub mod cross_chain; -pub mod nfts; -pub mod state; +/// APIs for asset-related use cases. +#[cfg(feature = "assets")] +pub mod assets; -pub fn relay_chain_block_number() -> Result { - state::read(RuntimeStateKeys::ParachainSystem(ParachainSystemKeys::LastRelayChainBlockNumber)) +pub(crate) const V0: u8 = 0; + +impl From for Error { + fn from(value: StatusCode) -> Self { + value.0.into() + } +} + +// Helper method to build a dispatch call. +// +// Parameters: +// - 'module': The index of the runtime module. +// - 'dispatchable': The index of the module dispatchable functions. +fn build_dispatch(module: u8, dispatchable: u8) -> ChainExtensionMethod<(), (), (), false> { + build_extension_method(V0, DISPATCH, module, dispatchable) } -#[derive(scale::Encode)] -pub(crate) enum RuntimeCall { - #[codec(index = 10)] - Balances(balances::BalancesCall), - #[codec(index = 50)] - Nfts(nfts::NftCalls), +// Helper method to build a call to read state. +// +// Parameters: +// - 'module': The index of the runtime module. +// - 'state_query': The index of the runtime state query. +fn build_read_state(module: u8, state_query: u8) -> ChainExtensionMethod<(), (), (), false> { + build_extension_method(V0, READ_STATE, module, state_query) } diff --git a/pop-api/src/v0/nfts.rs b/pop-api/src/v0/nfts.rs deleted file mode 100644 index 3db08cd1..00000000 --- a/pop-api/src/v0/nfts.rs +++ /dev/null @@ -1,882 +0,0 @@ -use super::RuntimeCall; -use crate::{PopApiError::UnknownStatusCode, *}; -use ink::prelude::vec::Vec; -use primitives::{ApprovalsLimit, BoundedBTreeMap, KeyLimit, MultiAddress}; -pub use primitives::{CollectionId, ItemId}; -use scale::Encode; -pub use types::*; - -type Result = core::result::Result; - -/// Issue a new collection of non-fungible items -pub fn create( - admin: impl Into>, - config: CollectionConfig, -) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::Create { admin: admin.into(), config }))?) -} - -/// Destroy a collection of fungible items. -pub fn destroy(collection: CollectionId) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::Destroy { collection }))?) -} - -/// Mint an item of a particular collection. -pub fn mint( - collection: CollectionId, - item: ItemId, - mint_to: impl Into>, -) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::Mint { - collection, - item, - mint_to: mint_to.into(), - witness_data: None, - }))?) -} - -/// Destroy a single item. -pub fn burn(collection: CollectionId, item: ItemId) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::Burn { collection, item }))?) -} - -/// Move an item from the sender account to another. -pub fn transfer( - collection: CollectionId, - item: ItemId, - dest: impl Into>, -) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::Transfer { collection, item, dest: dest.into() }))?) -} - -/// Re-evaluate the deposits on some items. -pub fn redeposit(collection: CollectionId, items: Vec) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::Redeposit { collection, items }))?) -} - -/// Change the Owner of a collection. -pub fn transfer_ownership( - collection: CollectionId, - new_owner: impl Into>, -) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::TransferOwnership { - collection, - new_owner: new_owner.into(), - }))?) -} - -/// Set (or reset) the acceptance of ownership for a particular account. -pub fn set_accept_ownership( - collection: CollectionId, - maybe_collection: Option, -) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::SetAcceptOwnership { collection, maybe_collection }))?) -} - -/// Set the maximum number of items a collection could have. -pub fn set_collection_max_supply(collection: CollectionId, max_supply: u32) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::SetCollectionMaxSupply { collection, max_supply }))?) -} - -/// Update mint settings. -pub fn update_mint_settings(collection: CollectionId, mint_settings: MintSettings) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::UpdateMintSettings { collection, mint_settings }))?) -} - -/// Get the owner of the item, if the item exists. -pub fn owner(collection: CollectionId, item: ItemId) -> Result> { - Ok(state::read(RuntimeStateKeys::Nfts(NftsKeys::Owner(collection, item)))?) -} - -/// Get the owner of the collection, if the collection exists. -pub fn collection_owner(collection: CollectionId) -> Result> { - Ok(state::read(RuntimeStateKeys::Nfts(NftsKeys::CollectionOwner(collection)))?) -} - -/// Get the details of a collection. -pub fn collection(collection: CollectionId) -> Result> { - Ok(state::read(RuntimeStateKeys::Nfts(NftsKeys::Collection(collection)))?) -} - -/// Get the details of an item. -pub fn item(collection: CollectionId, item: ItemId) -> Result> { - Ok(state::read(RuntimeStateKeys::Nfts(NftsKeys::Item(collection, item)))?) -} - -pub mod approvals { - use super::*; - - /// Approve an item to be transferred by a delegated third-party account. - pub fn approve_transfer( - collection: CollectionId, - item: ItemId, - delegate: impl Into>, - maybe_deadline: Option, - ) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::ApproveTransfer { - collection, - item, - delegate: delegate.into(), - maybe_deadline, - }))?) - } - - /// Cancel one of the transfer approvals for a specific item. - pub fn cancel_approval( - collection: CollectionId, - item: ItemId, - delegate: impl Into>, - ) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::CancelApproval { - collection, - item, - delegate: delegate.into(), - }))?) - } - - /// Cancel all the approvals of a specific item. - pub fn clear_all_transfer_approvals(collection: CollectionId, item: ItemId) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::ClearAllTransferApprovals { collection, item }))?) - } -} - -pub mod attributes { - use super::*; - - /// Approve item's attributes to be changed by a delegated third-party account. - pub fn approve_item_attribute( - collection: CollectionId, - item: ItemId, - delegate: impl Into>, - ) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::ApproveItemAttributes { - collection, - item, - delegate: delegate.into(), - }))?) - } - - /// Cancel the previously provided approval to change item's attributes. - pub fn cancel_item_attributes_approval( - collection: CollectionId, - item: ItemId, - delegate: impl Into>, - ) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::CancelItemAttributesApproval { - collection, - item, - delegate: delegate.into(), - }))?) - } - - /// Set an attribute for a collection or item. - pub fn set_attribute( - collection: CollectionId, - maybe_item: Option, - namespace: AttributeNamespace, - key: BoundedVec, - value: BoundedVec, - ) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::SetAttribute { - collection, - maybe_item, - namespace, - key, - value, - }))?) - } - - /// Clear an attribute for a collection or item. - pub fn clear_attribute( - collection: CollectionId, - maybe_item: Option, - namespace: AttributeNamespace, - key: BoundedVec, - ) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::ClearAttribute { - collection, - maybe_item, - namespace, - key, - }))?) - } - - /// Get the attribute value of `item` of `collection` corresponding to `key`. - pub fn attribute( - collection: CollectionId, - item: ItemId, - key: BoundedVec, - ) -> Result>> { - Ok(state::read(RuntimeStateKeys::Nfts(NftsKeys::Attribute(collection, item, key)))?) - } - - // /// Get the custom attribute value of `item` of `collection` corresponding to `key`. - // pub fn custom_attribute( - // account: AccountId, - // collection: CollectionId, - // item: ItemId, - // key: BoundedVec, - // ) -> Result>> { - // Ok(state::read(RuntimeStateKeys::Nfts(NftsKeys::CustomAttribute( - // account, collection, item, key, - // )))?) - // } - - /// Get the system attribute value of `item` of `collection` corresponding to `key` if - /// `item` is `Some`. Otherwise, returns the system attribute value of `collection` - /// corresponding to `key`. - pub fn system_attribute( - collection: CollectionId, - item: Option, - key: BoundedVec, - ) -> Result>> { - Ok(state::read(RuntimeStateKeys::Nfts(NftsKeys::SystemAttribute(collection, item, key)))?) - } - - /// Get the attribute value of `item` of `collection` corresponding to `key`. - pub fn collection_attribute( - collection: CollectionId, - key: BoundedVec, - ) -> Result>> { - Ok(state::read(RuntimeStateKeys::Nfts(NftsKeys::CollectionAttribute(collection, key)))?) - } -} - -pub mod locking { - use super::*; - - /// Disallows changing the metadata or attributes of the item. - pub fn lock_item_properties( - collection: CollectionId, - item: ItemId, - lock_metadata: bool, - lock_attributes: bool, - ) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::LockItemProperties { - collection, - item, - lock_metadata, - lock_attributes, - }))?) - } - - /// Disallow further unprivileged transfer of an item. - pub fn lock_item_transfer(collection: CollectionId, item: ItemId) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::LockItemTransfer { collection, item }))?) - } - - /// Re-allow unprivileged transfer of an item. - pub fn unlock_item_transfer(collection: CollectionId, item: ItemId) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::UnlockItemTransfer { collection, item }))?) - } - - /// Disallows specified settings for the whole collection. - pub fn lock_collection( - collection: CollectionId, - lock_settings: CollectionSettings, - ) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::LockCollection { collection, lock_settings }))?) - } -} - -pub mod metadata { - use super::*; - - /// Set the metadata for an item. - pub fn set_metadata( - collection: CollectionId, - item: ItemId, - data: BoundedVec, - ) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::SetMetadata { collection, item, data }))?) - } - - /// Clear the metadata for an item. - pub fn clear_metadata(collection: CollectionId, item: ItemId) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::ClearMetadata { collection, item }))?) - } - - /// Set the metadata for a collection. - pub fn set_collection_metadata( - collection: CollectionId, - data: BoundedVec, - ) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::SetCollectionMetadata { collection, data }))?) - } - - /// Clear the metadata for a collection. - pub fn clear_collection_metadata(collection: CollectionId) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::ClearCollectionMetadata { collection }))?) - } -} - -pub mod roles { - use super::*; - - /// Change the Issuer, Admin and Freezer of a collection. - pub fn set_team( - collection: CollectionId, - issuer: Option>>, - admin: Option>>, - freezer: Option>>, - ) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::SetTeam { - collection, - issuer: issuer.map(|i| i.into()), - admin: admin.map(|i| i.into()), - freezer: freezer.map(|i| i.into()), - }))?) - } -} - -pub mod trading { - use super::*; - - /// Allows to pay the tips. - pub fn pay_tips(tips: BoundedVec) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::PayTips { tips }))?) - } - - /// Set (or reset) the price for an item. - pub fn price(collection: CollectionId, item: ItemId, price: Option) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::SetPrice { collection, item, price }))?) - } - - /// Allows to buy an item if it's up for sale. - pub fn buy_item(collection: CollectionId, item: ItemId, bid_price: Balance) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::BuyItem { collection, item, bid_price }))?) - } - - pub mod swaps { - use super::*; - - /// Register a new atomic swap, declaring an intention to send an `item` in exchange for - /// `desired_item` from origin to target on the current chain. - pub fn create_swap( - offered_collection: CollectionId, - offered_item: ItemId, - desired_collection: CollectionId, - maybe_desired_item: Option, - maybe_price: Option, - duration: BlockNumber, - ) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::CreateSwap { - offered_collection, - offered_item, - desired_collection, - maybe_desired_item, - maybe_price, - duration, - }))?) - } - - /// Cancel an atomic swap. - pub fn cancel_swap(offered_collection: CollectionId, offered_item: ItemId) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::CancelSwap { - offered_collection, - offered_item, - }))?) - } - - /// Claim an atomic swap. - pub fn claim_swap( - send_collection: CollectionId, - send_item: ItemId, - receive_collection: CollectionId, - receive_item: ItemId, - ) -> Result<()> { - Ok(dispatch(RuntimeCall::Nfts(NftCalls::ClaimSwap { - send_collection, - send_item, - receive_collection, - receive_item, - }))?) - } - } -} - -#[derive(Encode)] -pub(crate) enum NftCalls { - #[codec(index = 0)] - Create { admin: MultiAddress, config: CollectionConfig }, - #[codec(index = 2)] - Destroy { collection: CollectionId }, - #[codec(index = 3)] - Mint { - collection: CollectionId, - item: ItemId, - mint_to: MultiAddress, - witness_data: Option<()>, - }, - #[codec(index = 5)] - Burn { collection: CollectionId, item: ItemId }, - #[codec(index = 6)] - Transfer { collection: CollectionId, item: ItemId, dest: MultiAddress }, - #[codec(index = 7)] - Redeposit { collection: CollectionId, items: Vec }, - #[codec(index = 8)] - LockItemTransfer { collection: CollectionId, item: ItemId }, - #[codec(index = 9)] - UnlockItemTransfer { collection: CollectionId, item: ItemId }, - #[codec(index = 10)] - LockCollection { collection: CollectionId, lock_settings: CollectionSettings }, - #[codec(index = 11)] - TransferOwnership { collection: CollectionId, new_owner: MultiAddress }, - #[codec(index = 12)] - SetTeam { - collection: CollectionId, - issuer: Option>, - admin: Option>, - freezer: Option>, - }, - #[codec(index = 15)] - ApproveTransfer { - collection: CollectionId, - item: ItemId, - delegate: MultiAddress, - maybe_deadline: Option, - }, - #[codec(index = 16)] - CancelApproval { collection: CollectionId, item: ItemId, delegate: MultiAddress }, - #[codec(index = 17)] - ClearAllTransferApprovals { collection: CollectionId, item: ItemId }, - #[codec(index = 18)] - LockItemProperties { - collection: CollectionId, - item: ItemId, - lock_metadata: bool, - lock_attributes: bool, - }, - #[codec(index = 19)] - SetAttribute { - collection: CollectionId, - maybe_item: Option, - namespace: AttributeNamespace, - key: BoundedVec, - value: BoundedVec, - }, - #[codec(index = 21)] - ClearAttribute { - collection: CollectionId, - maybe_item: Option, - namespace: AttributeNamespace, - key: BoundedVec, - }, - #[codec(index = 22)] - ApproveItemAttributes { - collection: CollectionId, - item: ItemId, - delegate: MultiAddress, - }, - #[codec(index = 23)] - CancelItemAttributesApproval { - collection: CollectionId, - item: ItemId, - delegate: MultiAddress, - }, - #[codec(index = 24)] - SetMetadata { collection: CollectionId, item: ItemId, data: BoundedVec }, - #[codec(index = 25)] - ClearMetadata { collection: CollectionId, item: ItemId }, - #[codec(index = 26)] - SetCollectionMetadata { collection: CollectionId, data: BoundedVec }, - #[codec(index = 27)] - ClearCollectionMetadata { collection: CollectionId }, - #[codec(index = 28)] - SetAcceptOwnership { collection: CollectionId, maybe_collection: Option }, - #[codec(index = 29)] - SetCollectionMaxSupply { collection: CollectionId, max_supply: u32 }, - #[codec(index = 30)] - UpdateMintSettings { collection: CollectionId, mint_settings: MintSettings }, - #[codec(index = 31)] - SetPrice { collection: CollectionId, item: ItemId, price: Option }, - #[codec(index = 32)] - BuyItem { collection: CollectionId, item: ItemId, bid_price: Balance }, - #[codec(index = 33)] - PayTips { tips: BoundedVec }, - #[codec(index = 34)] - CreateSwap { - offered_collection: CollectionId, - offered_item: ItemId, - desired_collection: CollectionId, - maybe_desired_item: Option, - maybe_price: Option, - duration: BlockNumber, - }, - #[codec(index = 35)] - CancelSwap { offered_collection: CollectionId, offered_item: ItemId }, - #[codec(index = 36)] - ClaimSwap { - send_collection: CollectionId, - send_item: ItemId, - receive_collection: CollectionId, - receive_item: ItemId, - }, -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum Error { - /// The signing account has no permission to do the operation. - NoPermission, - /// The given item ID is unknown. - UnknownCollection, - /// The item ID has already been used for an item. - AlreadyExists, - /// The approval had a deadline that expired, so the approval isn't valid anymore. - ApprovalExpired, - /// The owner turned out to be different to what was expected. - WrongOwner, - /// The witness data given does not match the current state of the chain. - BadWitness, - /// Collection ID is already taken. - CollectionIdInUse, - /// Items within that collection are non-transferable. - ItemsNonTransferable, - /// The provided account is not a delegate. - NotDelegate, - /// The delegate turned out to be different to what was expected. - WrongDelegate, - /// No approval exists that would allow the transfer. - Unapproved, - /// The named owner has not signed ownership acceptance of the collection. - Unaccepted, - /// The item is locked (non-transferable). - ItemLocked, - /// Item's attributes are locked. - LockedItemAttributes, - /// Collection's attributes are locked. - LockedCollectionAttributes, - /// Item's metadata is locked. - LockedItemMetadata, - /// Collection's metadata is locked. - LockedCollectionMetadata, - /// All items have been minted. - MaxSupplyReached, - /// The max supply is locked and can't be changed. - MaxSupplyLocked, - /// The provided max supply is less than the number of items a collection already has. - MaxSupplyTooSmall, - /// The given item ID is unknown. - UnknownItem, - /// Swap doesn't exist. - UnknownSwap, - /// The given item has no metadata set. - MetadataNotFound, - /// The provided attribute can't be found. - AttributeNotFound, - /// Item is not for sale. - NotForSale, - /// The provided bid is too low. - BidTooLow, - /// The item has reached its approval limit. - ReachedApprovalLimit, - /// The deadline has already expired. - DeadlineExpired, - /// The duration provided should be less than or equal to `MaxDeadlineDuration`. - WrongDuration, - /// The method is disabled by system settings. - MethodDisabled, - /// The provided setting can't be set. - WrongSetting, - /// Item's config already exists and should be equal to the provided one. - InconsistentItemConfig, - /// Config for a collection or an item can't be found. - NoConfig, - /// Some roles were not cleared. - RolesNotCleared, - /// Mint has not started yet. - MintNotStarted, - /// Mint has already ended. - MintEnded, - /// The provided Item was already used for claiming. - AlreadyClaimed, - /// The provided data is incorrect. - IncorrectData, - /// The extrinsic was sent by the wrong origin. - WrongOrigin, - /// The provided signature is incorrect. - WrongSignature, - /// The provided metadata might be too long. - IncorrectMetadata, - /// Can't set more attributes per one call. - MaxAttributesLimitReached, - /// The provided namespace isn't supported in this call. - WrongNamespace, - /// Can't delete non-empty collections. - CollectionNotEmpty, - /// The witness data should be provided. - WitnessRequired, -} - -impl TryFrom for Error { - type Error = PopApiError; - - fn try_from(status_code: u32) -> core::result::Result { - use Error::*; - match status_code { - 0 => Ok(NoPermission), - 1 => Ok(UnknownCollection), - 2 => Ok(AlreadyExists), - 3 => Ok(ApprovalExpired), - 4 => Ok(WrongOwner), - 5 => Ok(BadWitness), - 6 => Ok(CollectionIdInUse), - 7 => Ok(ItemsNonTransferable), - 8 => Ok(NotDelegate), - 9 => Ok(WrongDelegate), - 10 => Ok(Unapproved), - 11 => Ok(Unaccepted), - 12 => Ok(ItemLocked), - 13 => Ok(LockedItemAttributes), - 14 => Ok(LockedCollectionAttributes), - 15 => Ok(LockedItemMetadata), - 16 => Ok(LockedCollectionMetadata), - 17 => Ok(MaxSupplyReached), - 18 => Ok(MaxSupplyLocked), - 19 => Ok(MaxSupplyTooSmall), - 20 => Ok(UnknownItem), - 21 => Ok(UnknownSwap), - 22 => Ok(MetadataNotFound), - 23 => Ok(AttributeNotFound), - 24 => Ok(NotForSale), - 25 => Ok(BidTooLow), - 26 => Ok(ReachedApprovalLimit), - 27 => Ok(DeadlineExpired), - 28 => Ok(WrongDuration), - 29 => Ok(MethodDisabled), - 30 => Ok(WrongSetting), - 31 => Ok(InconsistentItemConfig), - 32 => Ok(NoConfig), - 33 => Ok(RolesNotCleared), - 34 => Ok(MintNotStarted), - 35 => Ok(MintEnded), - 36 => Ok(AlreadyClaimed), - 37 => Ok(IncorrectData), - 38 => Ok(WrongOrigin), - 39 => Ok(WrongSignature), - 40 => Ok(IncorrectMetadata), - 41 => Ok(MaxAttributesLimitReached), - 42 => Ok(WrongNamespace), - 43 => Ok(CollectionNotEmpty), - 44 => Ok(WitnessRequired), - _ => Err(UnknownStatusCode(status_code)), - } - } -} - -impl From for Error { - fn from(error: PopApiError) -> Self { - match error { - PopApiError::Nfts(e) => e, - _ => panic!("expected nfts error"), - } - } -} - -// Local implementations of pallet-nfts types -mod types { - use super::*; - use crate::{ - primitives::{CollectionId, ItemId}, - Balance, BlockNumber, - }; - pub use enumflags2::{bitflags, BitFlags}; - use scale::{Decode, EncodeLike, MaxEncodedLen}; - use scale_info::{build::Fields, meta_type, prelude::vec, Path, Type, TypeInfo, TypeParameter}; - - /// Attribute namespaces for non-fungible tokens. - #[derive(Encode)] - pub enum AttributeNamespace { - /// An attribute was set by the pallet. - Pallet, - /// An attribute was set by collection's owner. - CollectionOwner, - /// An attribute was set by item's owner. - ItemOwner, - /// An attribute was set by pre-approved account. - Account(AccountId), - } - - /// Collection's configuration. - #[derive(Encode)] - pub struct CollectionConfig { - /// Collection's settings. - pub settings: CollectionSettings, - /// Collection's max supply. - pub max_supply: Option, - /// Default settings each item will get during the mint. - pub mint_settings: MintSettings, - } - - /// Information about a collection. - #[derive(Decode, Debug, Encode, Eq, PartialEq)] - pub struct CollectionDetails { - /// Collection's owner. - pub owner: AccountId, - /// The total balance deposited by the owner for all the storage data associated with this - /// collection. Used by `destroy`. - pub owner_deposit: Balance, - /// The total number of outstanding items of this collection. - pub items: u32, - /// The total number of outstanding item metadata of this collection. - pub item_metadatas: u32, - /// The total number of outstanding item configs of this collection. - pub item_configs: u32, - /// The total number of attributes for this collection. - pub attributes: u32, - } - - /// Wrapper type for `BitFlags` that implements `Codec`. - pub struct CollectionSettings(pub BitFlags); - - impl_codec_bitflags!(CollectionSettings, u64, CollectionSetting); - - /// Support for up to 64 user-enabled features on a collection. - #[bitflags] - #[repr(u64)] - #[derive(Copy, Clone, Encode, TypeInfo)] - pub enum CollectionSetting { - /// Items in this collection are transferable. - TransferableItems, - /// The metadata of this collection can be modified. - UnlockedMetadata, - /// Attributes of this collection can be modified. - UnlockedAttributes, - /// The supply of this collection can be modified. - UnlockedMaxSupply, - /// When this isn't set then the deposit is required to hold the items of this collection. - DepositRequired, - } - - /// Information concerning the ownership of a single unique item. - #[derive(Decode, Debug, Encode, Eq, PartialEq)] - pub struct ItemDetails { - /// The owner of this item. - pub owner: AccountId, - /// The approved transferrer of this item, if one is set. - pub approvals: BoundedBTreeMap, ApprovalsLimit>, - /// The amount held in the pallet's default account for this item. Free-hold items will - /// have this as zero. - pub deposit: Balance, - } - - /// Support for up to 64 user-enabled features on an item. - #[bitflags] - #[repr(u64)] - #[derive(Copy, Clone, Encode, TypeInfo)] - pub enum ItemSetting { - /// This item is transferable. - Transferable, - /// The metadata of this item can be modified. - UnlockedMetadata, - /// Attributes of this item can be modified. - UnlockedAttributes, - } - - /// Wrapper type for `BitFlags` that implements `Codec`. - pub struct ItemSettings(pub BitFlags); - - impl_codec_bitflags!(ItemSettings, u64, ItemSetting); - - /// Information about the tip. - #[derive(Encode)] - pub struct ItemTip { - /// The collection of the item. - pub(super) collection: CollectionId, - /// An item of which the tip is sent for. - pub(super) item: ItemId, - /// A sender of the tip. - pub(super) receiver: AccountId, - /// An amount the sender is willing to tip. - pub(super) amount: Balance, - } - - /// Holds the information about minting. - #[derive(Encode)] - pub struct MintSettings { - /// Whether anyone can mint or if minters are restricted to some subset. - pub mint_type: MintType, - /// An optional price per mint. - pub price: Option, - /// When the mint starts. - pub start_block: Option, - /// When the mint ends. - pub end_block: Option, - /// Default settings each item will get during the mint. - pub default_item_settings: ItemSettings, - } - - /// Mint type. Can the NFT be created by anyone, or only the creator of the collection, - /// or only by wallets that already hold an NFT from a certain collection? - /// The ownership of a privately minted NFT is still publicly visible. - #[derive(Encode)] - pub enum MintType { - /// Only an `Issuer` could mint items. - Issuer, - /// Anyone could mint items. - Public, - /// Only holders of items in specified collection could mint new items. - HolderOf(CollectionId), - } - - /// Holds the details about the price. - #[derive(Encode)] - pub struct PriceWithDirection { - /// An amount. - pub(super) amount: Balance, - /// A direction (send or receive). - pub(super) direction: PriceDirection, - } - - /// Specifies whether the tokens will be sent or received. - #[derive(Encode)] - pub enum PriceDirection { - /// Tokens will be sent. - Send, - /// Tokens will be received. - Receive, - } - - macro_rules! impl_codec_bitflags { - ($wrapper:ty, $size:ty, $bitflag_enum:ty) => { - impl MaxEncodedLen for $wrapper { - fn max_encoded_len() -> usize { - <$size>::max_encoded_len() - } - } - impl Encode for $wrapper { - fn using_encoded R>(&self, f: F) -> R { - self.0.bits().using_encoded(f) - } - } - impl EncodeLike for $wrapper {} - impl Decode for $wrapper { - fn decode( - input: &mut I, - ) -> core::result::Result { - let field = <$size>::decode(input)?; - Ok(Self(BitFlags::from_bits(field as $size).map_err(|_| "invalid value")?)) - } - } - - impl TypeInfo for $wrapper { - type Identity = Self; - - fn type_info() -> Type { - Type::builder() - .path(Path::new("BitFlags", module_path!())) - .type_params(vec![TypeParameter::new( - "T", - Some(meta_type::<$bitflag_enum>()), - )]) - .composite( - Fields::unnamed() - .field(|f| f.ty::<$size>().type_name(stringify!($bitflag_enum))), - ) - } - } - }; - } - pub(crate) use impl_codec_bitflags; -} diff --git a/pop-api/src/v0/state.rs b/pop-api/src/v0/state.rs deleted file mode 100644 index 9f5e4c0c..00000000 --- a/pop-api/src/v0/state.rs +++ /dev/null @@ -1,6 +0,0 @@ -use crate::{primitives::storage_keys::RuntimeStateKeys, read_state, PopApiError}; -use scale::Decode; - -pub fn read(key: RuntimeStateKeys) -> crate::Result { - read_state(key).and_then(|v| T::decode(&mut &v[..]).map_err(|_e| PopApiError::DecodingFailed)) -} diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index b6f9adaa..e7d55ffe 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -1,18 +1,17 @@ [package] name = "pop-primitives" +description = "Primitives crate for Pop" license = "GPL-3.0-only" version = "0.0.0" edition = "2021" [dependencies] -bounded-collections = { version = "0.1", default-features = false } -scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] } -scale-info = { version = "2.6", default-features = false, features = ["derive"], optional = true } +codec.workspace = true +scale-info.workspace = true [features] default = ["std"] std = [ - "bounded-collections/std", - "scale/std", + "codec/std", "scale-info/std", -] +] \ No newline at end of file diff --git a/primitives/README.md b/primitives/README.md new file mode 100644 index 00000000..ded7918a --- /dev/null +++ b/primitives/README.md @@ -0,0 +1 @@ +Reserved crate for pop-primitives. \ No newline at end of file diff --git a/primitives/src/cross_chain.rs b/primitives/src/cross_chain.rs deleted file mode 100644 index 381e6a61..00000000 --- a/primitives/src/cross_chain.rs +++ /dev/null @@ -1,19 +0,0 @@ -use scale::{Decode, Encode, MaxEncodedLen}; - -#[derive(Encode, Decode, Debug, MaxEncodedLen)] -pub enum CrossChainMessage { - Relay(RelayChainMessage), -} - -#[derive(Encode, Decode, Debug, MaxEncodedLen)] -pub enum RelayChainMessage { - // Rococo index: https://github.com/paritytech/polkadot-sdk/blob/629506ce061db76d31d4f7a81f4a497752b27259/polkadot/runtime/rococo/src/lib.rs#L1423 - #[codec(index = 66)] - OnDemand(OnDemand), -} - -#[derive(Encode, Decode, Debug, MaxEncodedLen)] -pub enum OnDemand { - #[codec(index = 1)] - PlaceOrderKeepAlive { max_amount: u128, para_id: u32 }, -} diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 8ad74ade..30187d8e 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -1,19 +1,146 @@ #![cfg_attr(not(feature = "std"), no_std, no_main)] -pub use bounded_collections::{BoundedBTreeMap, BoundedBTreeSet, BoundedVec, ConstU32}; -//use scale::{Decode, Encode, MaxEncodedLen}; - -pub mod cross_chain; -pub mod storage_keys; - -// /// Some way of identifying an account on the chain. -// #[derive(Encode, Decode, Debug, MaxEncodedLen)] -// pub struct AccountId([u8; 32]); -// Id used for identifying non-fungible collections. -pub type CollectionId = u32; -// Id used for identifying non-fungible items. -pub type ItemId = u32; -/// The maximum length of an attribute key. -pub type KeyLimit = ConstU32<64>; -/// The maximum approvals an item could have. -pub type ApprovalsLimit = ConstU32<20>; +use codec::{Decode, Encode}; +#[cfg(feature = "std")] +use scale_info::TypeInfo; +pub use v0::*; + +/// Identifier for the class of asset. +pub type AssetId = u32; + +pub mod v0 { + use super::*; + pub use error::*; + + mod error { + use super::*; + + /// Reason why a Pop API call failed. + #[derive(Encode, Decode, Debug, Eq, PartialEq)] + #[cfg_attr(feature = "std", derive(TypeInfo))] + #[repr(u8)] + #[allow(clippy::unnecessary_cast)] + pub enum Error { + /// Some error occurred. + Other = 0, + /// Failed to look up some data. + CannotLookup = 1, + /// A bad origin. + BadOrigin = 2, + /// A custom error in a module. + Module { + /// The pallet index. + index: u8, + /// The error within the pallet. + // Supports a single level of nested error only, due to status code type size constraints. + error: [u8; 2], + } = 3, + /// At least one consumer is remaining so the account cannot be destroyed. + ConsumerRemaining = 4, + /// There are no providers so the account cannot be created. + NoProviders = 5, + /// There are too many consumers so the account cannot be created. + TooManyConsumers = 6, + /// An error to do with tokens. + Token(TokenError) = 7, + /// An arithmetic error. + Arithmetic(ArithmeticError) = 8, + /// The number of transactional layers has been reached, or we are not in a transactional + /// layer. + Transactional(TransactionalError) = 9, + /// Resources exhausted, e.g. attempt to read/write data which is too large to manipulate. + Exhausted = 10, + /// The state is corrupt; this is generally not going to fix itself. + Corruption = 11, + /// Some resource (e.g. a preimage) is unavailable right now. This might fix itself later. + Unavailable = 12, + /// Root origin is not allowed. + RootNotAllowed = 13, + /// Decoding failed. + DecodingFailed = 254, + /// An unknown error occurred. This variant captures any unexpected errors that the + /// contract cannot specifically handle. It is useful for cases where there are breaking + /// changes in the runtime or when an error falls outside the predefined categories. + Unknown { + /// The index within the `DispatchError`. + dispatch_error_index: u8, + /// The index within the `DispatchError` variant (e.g. a `TokenError`). + error_index: u8, + /// The specific error code or sub-index, providing additional context (e.g. `error` in `ModuleError`). + error: u8, + } = 255, + } + + impl From for Error { + /// Converts a `u32` status code into an `Error`. + /// + /// This conversion maps a raw status code returned by the runtime into the more + /// descriptive `Error` enum variant, providing better context and understanding of the + /// error. + fn from(value: u32) -> Self { + let encoded = value.to_le_bytes(); + Error::decode(&mut &encoded[..]).unwrap_or(Error::DecodingFailed) + } + } + + impl From for u32 { + fn from(value: Error) -> Self { + let mut encoded_error = value.encode(); + // Resize the encoded value to 4 bytes in order to decode the value into a u32 (4 bytes). + encoded_error.resize(4, 0); + u32::from_le_bytes( + encoded_error.try_into().expect("qed, resized to 4 bytes line above"), + ) + } + } + + /// Description of what went wrong when trying to complete an operation on a token. + #[derive(Encode, Decode, Debug, Eq, PartialEq)] + #[cfg_attr(feature = "std", derive(TypeInfo))] + pub enum TokenError { + /// Funds are unavailable. + FundsUnavailable, + /// Some part of the balance gives the only provider reference to the account and thus cannot + /// be (re)moved. + OnlyProvider, + /// Account cannot exist with the funds that would be given. + BelowMinimum, + /// Account cannot be created. + CannotCreate, + /// The asset in question is unknown. + UnknownAsset, + /// Funds exist but are frozen. + Frozen, + /// Operation is not supported by the asset. + Unsupported, + /// Account cannot be created for a held balance. + CannotCreateHold, + /// Withdrawal would cause unwanted loss of account. + NotExpendable, + /// Account cannot receive the assets. + Blocked, + } + + /// Arithmetic errors. + #[derive(Encode, Decode, Debug, Eq, PartialEq)] + #[cfg_attr(feature = "std", derive(TypeInfo))] + pub enum ArithmeticError { + /// Underflow. + Underflow, + /// Overflow. + Overflow, + /// Division by zero. + DivisionByZero, + } + + /// Errors related to transactional storage layers. + #[derive(Encode, Decode, Debug, Eq, PartialEq)] + #[cfg_attr(feature = "std", derive(TypeInfo))] + pub enum TransactionalError { + /// Too many transactional layers have been spawned. + LimitReached, + /// A transactional layer was expected, but does not exist. + NoLayer, + } + } +} diff --git a/primitives/src/storage_keys.rs b/primitives/src/storage_keys.rs deleted file mode 100644 index 2bcb41ec..00000000 --- a/primitives/src/storage_keys.rs +++ /dev/null @@ -1,35 +0,0 @@ -use super::*; -use scale::{Decode, Encode, MaxEncodedLen}; - -#[derive(Encode, Decode, Debug, MaxEncodedLen)] -pub enum RuntimeStateKeys { - Nfts(NftsKeys), - ParachainSystem(ParachainSystemKeys), -} - -#[derive(Encode, Decode, Debug, MaxEncodedLen)] -pub enum ParachainSystemKeys { - /// Get the last relay chain block number seen by the parachain. - LastRelayChainBlockNumber, -} - -// https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/nfts/src/impl_nonfungibles.rs -#[derive(Encode, Decode, Debug, MaxEncodedLen)] -pub enum NftsKeys { - // Get the details of a collection. - Collection(CollectionId), - /// Get the owner of the collection, if the collection exists. - CollectionOwner(CollectionId), - // Get the details of an item. - Item(CollectionId, ItemId), - /// Get the owner of the item, if the item exists. - Owner(CollectionId, ItemId), - /// Get the attribute value of `item` of `collection` corresponding to `key`. - Attribute(CollectionId, ItemId, BoundedVec), - // /// Get the custom attribute value of `item` of `collection` corresponding to `key`. - // CustomAttribute(AccountId, CollectionId, ItemId, BoundedVec), - /// Get the system attribute value of `item` of `collection` corresponding to `key` - SystemAttribute(CollectionId, Option, BoundedVec), - /// Get the attribute value of `item` of `collection` corresponding to `key`. - CollectionAttribute(CollectionId, BoundedVec), -} diff --git a/runtime/devnet/Cargo.toml b/runtime/devnet/Cargo.toml index da2c1852..8f41b2fc 100644 --- a/runtime/devnet/Cargo.toml +++ b/runtime/devnet/Cargo.toml @@ -22,8 +22,10 @@ scale-info.workspace = true smallvec.workspace = true # Local +pop-chain-extension.workspace = true pop-primitives.workspace = true -pop-runtime-common = { workspace = true, default-features = false } +pop-runtime-common.workspace = true +pallet-api.workspace = true # Substrate frame-benchmarking.workspace = true @@ -92,7 +94,6 @@ parachain-info.workspace = true [dev-dependencies] env_logger = "0.11.2" hex = "0.4.3" -enumflags2 = "0.7.9" [features] default = ["std"] @@ -122,6 +123,7 @@ std = [ "pallet-balances/std", "pallet-collator-selection/std", "pallet-contracts/std", + "pallet-api/std", "pallet-message-queue/std", "pallet-multisig/std", "pallet-nft-fractionalization/std", @@ -141,6 +143,7 @@ std = [ "parachains-common/std", "polkadot-parachain-primitives/std", "polkadot-runtime-common/std", + "pop-chain-extension/std", "pop-primitives/std", "scale-info/std", "sp-api/std", @@ -172,6 +175,7 @@ runtime-benchmarks = [ "frame-system-benchmarking/runtime-benchmarks", "frame-system/runtime-benchmarks", "pallet-assets/runtime-benchmarks", + "pallet-api/runtime-benchmarks", "pallet-balances/runtime-benchmarks", "pallet-collator-selection/runtime-benchmarks", "pallet-contracts/runtime-benchmarks", @@ -203,6 +207,7 @@ try-runtime = [ "frame-support/try-runtime", "frame-system/try-runtime", "frame-try-runtime/try-runtime", + "pallet-api/try-runtime", "pallet-aura/try-runtime", "pallet-authorship/try-runtime", "pallet-assets/try-runtime", @@ -238,4 +243,4 @@ metadata-hash = ["substrate-wasm-builder/metadata-hash"] # A convenience feature for enabling things when doing a build # for an on-chain release. -on-chain-release-build = ["metadata-hash"] \ No newline at end of file +on-chain-release-build = ["metadata-hash"] diff --git a/runtime/devnet/src/config/api/mod.rs b/runtime/devnet/src/config/api/mod.rs new file mode 100644 index 00000000..e244f656 --- /dev/null +++ b/runtime/devnet/src/config/api/mod.rs @@ -0,0 +1,145 @@ +use crate::{ + config::assets::TrustBackedAssetsInstance, fungibles, Runtime, RuntimeCall, RuntimeEvent, +}; +use codec::Decode; +use cumulus_primitives_core::Weight; +use frame_support::traits::Contains; +use pallet_api::extension::*; +pub(crate) use pallet_api::Extension; +use pallet_api::Read; +use sp_core::ConstU8; +use sp_runtime::DispatchError; +use sp_std::vec::Vec; +use versioning::*; + +mod versioning; + +type DecodingFailedError = DecodingFailed; +type DecodesAs = + pallet_api::extension::DecodesAs; + +/// A query of runtime state. +#[derive(Decode, Debug)] +#[repr(u8)] +pub enum RuntimeRead { + /// Fungible token queries. + #[codec(index = 150)] + Fungibles(fungibles::Read), +} + +impl Readable for RuntimeRead { + /// The corresponding type carrying the result of the query for runtime state. + type Result = RuntimeResult; + + /// Determines the weight of the read, used to charge the appropriate weight before the read is performed. + fn weight(&self) -> Weight { + match self { + RuntimeRead::Fungibles(key) => fungibles::Pallet::weight(key), + } + } + + /// Performs the read and returns the result. + fn read(self) -> Self::Result { + match self { + RuntimeRead::Fungibles(key) => RuntimeResult::Fungibles(fungibles::Pallet::read(key)), + } + } +} + +/// The result of a runtime state read. +#[derive(Debug)] +pub enum RuntimeResult { + /// Fungible token read results. + Fungibles(fungibles::ReadResult), +} + +impl RuntimeResult { + /// Encodes the result. + fn encode(&self) -> Vec { + match self { + RuntimeResult::Fungibles(result) => result.encode(), + } + } +} + +impl fungibles::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type AssetsInstance = TrustBackedAssetsInstance; + type WeightInfo = fungibles::weights::SubstrateWeight; +} + +#[derive(Default)] +pub struct Config; +impl pallet_api::extension::Config for Config { + /// Functions used by the Pop API. + /// + /// Each function corresponds to specific functionality provided by the API, facilitating the + /// interaction between smart contracts and the runtime. + type Functions = ( + // Dispatching calls + DispatchCall< + Runtime, + // Decode as a versioned runtime call + DecodesAs, + // Function 0 + IdentifiedByFirstByteOfFunctionId>, + Filter, + DispatchCallLogTarget, + >, + // Reading state + ReadState< + Runtime, + RuntimeRead, + // Decode as a versioned runtime read + DecodesAs, + // Function 1 + IdentifiedByFirstByteOfFunctionId>, + Filter, + // Convert the result of a read into the expected versioned result + VersionedResultConverter, + ReadStateLogTarget, + >, + ); + /// Ensure errors are versioned. + type Error = VersionedErrorConverter; + + /// The log target. + const LOG_TARGET: &'static str = LOG_TARGET; +} + +/// Filters used by the chain extension. +pub struct Filter; + +impl Contains for Filter { + fn contains(c: &RuntimeCall) -> bool { + use fungibles::Call::*; + matches!( + c, + RuntimeCall::Fungibles( + transfer { .. } + | transfer_from { .. } + | approve { .. } | increase_allowance { .. } + | decrease_allowance { .. } + | create { .. } | set_metadata { .. } + | start_destroy { .. } + | clear_metadata { .. } + | mint { .. } | burn { .. } + ) + ) + } +} + +impl Contains for Filter { + fn contains(r: &RuntimeRead) -> bool { + use fungibles::Read::*; + matches!( + r, + RuntimeRead::Fungibles( + TotalSupply(..) + | BalanceOf { .. } | Allowance { .. } + | TokenName(..) | TokenSymbol(..) + | TokenDecimals(..) | AssetExists(..) + ) + ) + } +} diff --git a/runtime/devnet/src/config/api/versioning.rs b/runtime/devnet/src/config/api/versioning.rs new file mode 100644 index 00000000..a25a0f38 --- /dev/null +++ b/runtime/devnet/src/config/api/versioning.rs @@ -0,0 +1,208 @@ +use super::*; +use sp_runtime::ModuleError; + +type Version = u8; + +/// Versioned runtime calls. +#[derive(Decode, Debug)] +pub enum VersionedRuntimeCall { + /// Version zero of runtime calls. + #[codec(index = 0)] + V0(RuntimeCall), +} + +impl From for RuntimeCall { + fn from(value: VersionedRuntimeCall) -> Self { + // Allows mapping from some previous runtime call shape to a current valid runtime call + match value { + VersionedRuntimeCall::V0(call) => call, + } + } +} + +/// Versioned runtime state reads. +#[derive(Decode, Debug)] +pub enum VersionedRuntimeRead { + /// Version zero of runtime state reads. + #[codec(index = 0)] + V0(RuntimeRead), +} + +impl From for RuntimeRead { + fn from(value: VersionedRuntimeRead) -> Self { + // Allows mapping from some previous runtime read shape to a current valid runtime read + match value { + VersionedRuntimeRead::V0(read) => read, + } + } +} + +/// Versioned runtime state read results. +#[derive(Debug)] +pub enum VersionedRuntimeResult { + /// Version zero of runtime read results. + V0(RuntimeResult), +} + +impl From<(RuntimeResult, Version)> for VersionedRuntimeResult { + fn from(value: (RuntimeResult, Version)) -> Self { + let (result, version) = value; + match version { + // Allows mapping from current `RuntimeResult` to a specific/prior version + 0 => VersionedRuntimeResult::V0(result), + // TODO: should never occur due to version processing/validation when request received + _ => unimplemented!(), + } + } +} + +impl From for Vec { + fn from(result: VersionedRuntimeResult) -> Self { + match result { + // Simply unwrap and return the encoded result + VersionedRuntimeResult::V0(result) => result.encode(), + } + } +} + +/// Versioned errors. +#[derive(Debug)] +pub enum VersionedError { + /// Version zero of errors. + V0(pop_primitives::v0::Error), +} + +impl From<(DispatchError, Version)> for VersionedError { + fn from(value: (DispatchError, Version)) -> Self { + let (error, version) = value; + match version { + // Allows mapping from current `DispatchError` to a specific/prior version of `Error` + 0 => VersionedError::V0(V0Error::from(error).0), + // TODO: should never occur due to version processing/validation when request received + _ => unimplemented!(), + } + } +} + +impl From for u32 { + fn from(value: VersionedError) -> Self { + match value { + VersionedError::V0(error) => error.into(), + } + } +} + +struct V0Error(pop_primitives::v0::Error); +impl From for V0Error { + fn from(error: DispatchError) -> Self { + use pop_primitives::v0::*; + use sp_runtime::{ArithmeticError::*, TokenError::*, TransactionalError::*}; + use DispatchError::*; + // Mappings exist here to avoid taking a dependency of sp_runtime on pop-primitives + Self(match error { + Other(_message) => { + // Note: lossy conversion: message not used due to returned contract status code size limitation + Error::Other + }, + CannotLookup => Error::CannotLookup, + BadOrigin => Error::BadOrigin, + Module(error) => { + // Note: message not used + let ModuleError { index, error, message: _message } = error; + // Map pallet-contracts::Error::DecodingFailed to Error::DecodingFailed + if index as usize + == ::index() + && error == [11, 0, 0, 0] + { + Error::DecodingFailed + } else { + // Note: lossy conversion of error value due to returned contract status code size limitation + Error::Module { index, error: [error[0], error[1]] } + } + }, + ConsumerRemaining => Error::ConsumerRemaining, + NoProviders => Error::NoProviders, + TooManyConsumers => Error::TooManyConsumers, + Token(error) => Error::Token(match error { + FundsUnavailable => TokenError::FundsUnavailable, + OnlyProvider => TokenError::OnlyProvider, + BelowMinimum => TokenError::BelowMinimum, + CannotCreate => TokenError::CannotCreate, + UnknownAsset => TokenError::UnknownAsset, + Frozen => TokenError::Frozen, + Unsupported => TokenError::Unsupported, + CannotCreateHold => TokenError::CannotCreateHold, + NotExpendable => TokenError::NotExpendable, + Blocked => TokenError::Blocked, + }), + Arithmetic(error) => Error::Arithmetic(match error { + Underflow => ArithmeticError::Underflow, + Overflow => ArithmeticError::Overflow, + DivisionByZero => ArithmeticError::DivisionByZero, + }), + Transactional(error) => Error::Transactional(match error { + LimitReached => TransactionalError::LimitReached, + NoLayer => TransactionalError::NoLayer, + }), + Exhausted => Error::Exhausted, + Corruption => Error::Corruption, + Unavailable => Error::Unavailable, + RootNotAllowed => Error::RootNotAllowed, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use pop_primitives::{ArithmeticError::*, Error, TokenError::*, TransactionalError::*}; + use sp_runtime::ModuleError; + use DispatchError::*; + + // Compare all the different `DispatchError` variants with the expected `Error`. + #[test] + fn dispatch_error_to_error() { + let test_cases = vec![ + (Other(""), (Error::Other)), + (Other("UnknownCall"), Error::Other), + (Other("DecodingFailed"), Error::Other), + (Other("Random"), (Error::Other)), + (CannotLookup, Error::CannotLookup), + (BadOrigin, Error::BadOrigin), + ( + Module(ModuleError { index: 1, error: [2, 0, 0, 0], message: Some("hallo") }), + Error::Module { index: 1, error: [2, 0] }, + ), + ( + Module(ModuleError { index: 1, error: [2, 2, 0, 0], message: Some("hallo") }), + Error::Module { index: 1, error: [2, 2] }, + ), + ( + Module(ModuleError { index: 1, error: [2, 2, 2, 0], message: Some("hallo") }), + Error::Module { index: 1, error: [2, 2] }, + ), + ( + Module(ModuleError { index: 1, error: [2, 2, 2, 4], message: Some("hallo") }), + Error::Module { index: 1, error: [2, 2] }, + ), + (pallet_contracts::Error::::DecodingFailed.into(), Error::DecodingFailed), + (ConsumerRemaining, Error::ConsumerRemaining), + (NoProviders, Error::NoProviders), + (TooManyConsumers, Error::TooManyConsumers), + (Token(sp_runtime::TokenError::BelowMinimum), Error::Token(BelowMinimum)), + (Arithmetic(sp_runtime::ArithmeticError::Overflow), Error::Arithmetic(Overflow)), + ( + Transactional(sp_runtime::TransactionalError::LimitReached), + Error::Transactional(LimitReached), + ), + (Exhausted, Error::Exhausted), + (Corruption, Error::Corruption), + (Unavailable, Error::Unavailable), + (RootNotAllowed, Error::RootNotAllowed), + ]; + for (dispatch_error, expected) in test_cases { + let error = V0Error::from(dispatch_error).0; + assert_eq!(error, expected); + } + } +} diff --git a/runtime/devnet/src/config/assets.rs b/runtime/devnet/src/config/assets.rs index 34035c1f..78aed8b5 100644 --- a/runtime/devnet/src/config/assets.rs +++ b/runtime/devnet/src/config/assets.rs @@ -1,7 +1,3 @@ -use crate::{ - deposit, AccountId, Assets, Balance, Balances, BlockNumber, Nfts, Runtime, RuntimeEvent, - RuntimeHoldReason, DAYS, EXISTENTIAL_DEPOSIT, UNIT, -}; use frame_support::{ parameter_types, traits::{AsEnsureOriginWithArg, ConstU32}, @@ -12,6 +8,11 @@ use pallet_nfts::PalletFeatures; use parachains_common::{AssetIdForTrustBackedAssets, CollectionId, ItemId, Signature}; use sp_runtime::traits::Verify; +use crate::{ + deposit, AccountId, Assets, Balance, Balances, BlockNumber, Nfts, Runtime, RuntimeEvent, + RuntimeHoldReason, DAYS, EXISTENTIAL_DEPOSIT, UNIT, +}; + /// We allow root to execute privileged asset operations. pub type AssetsForceOrigin = EnsureRoot; @@ -84,8 +85,8 @@ impl pallet_nft_fractionalization::Config for Runtime { type StringLimit = AssetsStringLimit; type NftCollectionId = ::CollectionId; type NftId = ::ItemId; - type AssetBalance = >::Balance; - type AssetId = >::AssetId; + type AssetBalance = >::Balance; + type AssetId = >::AssetId; type Assets = Assets; type Nfts = Nfts; type PalletId = NftFractionalizationPalletId; @@ -95,9 +96,9 @@ impl pallet_nft_fractionalization::Config for Runtime { type BenchmarkHelper = (); } -pub type TrustBackedAssets = pallet_assets::Instance1; -pub type TrustBackedAssetsCall = pallet_assets::Call; -impl pallet_assets::Config for Runtime { +pub type TrustBackedAssetsInstance = pallet_assets::Instance1; +pub(crate) type AssetsCall = pallet_assets::Call; +impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; type AssetId = AssetIdForTrustBackedAssets; diff --git a/runtime/devnet/src/config/contracts.rs b/runtime/devnet/src/config/contracts.rs index 8e5b2695..f3a721be 100644 --- a/runtime/devnet/src/config/contracts.rs +++ b/runtime/devnet/src/config/contracts.rs @@ -1,6 +1,7 @@ +use super::api::{self, Config}; use crate::{ - deposit, extensions, Balance, Balances, BalancesCall, Perbill, Runtime, RuntimeCall, - RuntimeEvent, RuntimeHoldReason, Timestamp, + deposit, Balance, Balances, BalancesCall, Perbill, Runtime, RuntimeCall, RuntimeEvent, + RuntimeHoldReason, Timestamp, }; use frame_support::{ parameter_types, @@ -63,7 +64,7 @@ impl pallet_contracts::Config for Runtime { type CallStack = [pallet_contracts::Frame; 23]; type WeightPrice = pallet_transaction_payment::Pallet; type WeightInfo = pallet_contracts::weights::SubstrateWeight; - type ChainExtension = extensions::PopApiExtension; + type ChainExtension = api::Extension; type Schedule = Schedule; type AddressGenerator = pallet_contracts::DefaultAddressGenerator; // This node is geared towards development and testing of contracts. @@ -84,6 +85,7 @@ impl pallet_contracts::Config for Runtime { type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; type MaxDelegateDependencies = ConstU32<32>; type RuntimeHoldReason = RuntimeHoldReason; + type MaxTransientStorageSize = (); type ApiVersion = (); type Environment = (); diff --git a/runtime/devnet/src/config/mod.rs b/runtime/devnet/src/config/mod.rs index a3a64c92..1ef83bc1 100644 --- a/runtime/devnet/src/config/mod.rs +++ b/runtime/devnet/src/config/mod.rs @@ -1,4 +1,6 @@ -mod assets; +mod api; +// Public due to pop api integration tests crate. +pub mod assets; mod contracts; mod proxy; // Public due to integration tests crate. diff --git a/runtime/devnet/src/config/proxy.rs b/runtime/devnet/src/config/proxy.rs index a4fd479a..07d5f0f8 100644 --- a/runtime/devnet/src/config/proxy.rs +++ b/runtime/devnet/src/config/proxy.rs @@ -1,4 +1,4 @@ -use super::assets::TrustBackedAssetsCall; +use super::assets::AssetsCall; use crate::{Balances, Runtime, RuntimeCall, RuntimeEvent}; use frame_support::traits::InstanceFilter; use pop_runtime_common::proxy::{ @@ -34,16 +34,16 @@ impl InstanceFilter for ProxyType { }, ProxyType::AssetOwner => matches!( c, - RuntimeCall::Assets(TrustBackedAssetsCall::create { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::start_destroy { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::destroy_accounts { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::destroy_approvals { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::finish_destroy { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::transfer_ownership { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::set_team { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::set_metadata { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::clear_metadata { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::set_min_balance { .. }) + RuntimeCall::Assets(AssetsCall::create { .. }) + | RuntimeCall::Assets(AssetsCall::start_destroy { .. }) + | RuntimeCall::Assets(AssetsCall::destroy_accounts { .. }) + | RuntimeCall::Assets(AssetsCall::destroy_approvals { .. }) + | RuntimeCall::Assets(AssetsCall::finish_destroy { .. }) + | RuntimeCall::Assets(AssetsCall::transfer_ownership { .. }) + | RuntimeCall::Assets(AssetsCall::set_team { .. }) + | RuntimeCall::Assets(AssetsCall::set_metadata { .. }) + | RuntimeCall::Assets(AssetsCall::clear_metadata { .. }) + | RuntimeCall::Assets(AssetsCall::set_min_balance { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::create { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::destroy { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::redeposit { .. }) @@ -56,15 +56,15 @@ impl InstanceFilter for ProxyType { ), ProxyType::AssetManager => matches!( c, - RuntimeCall::Assets(TrustBackedAssetsCall::mint { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::burn { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::freeze { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::block { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::thaw { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::freeze_asset { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::thaw_asset { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::touch_other { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::refund_other { .. }) + RuntimeCall::Assets(AssetsCall::mint { .. }) + | RuntimeCall::Assets(AssetsCall::burn { .. }) + | RuntimeCall::Assets(AssetsCall::freeze { .. }) + | RuntimeCall::Assets(AssetsCall::block { .. }) + | RuntimeCall::Assets(AssetsCall::thaw { .. }) + | RuntimeCall::Assets(AssetsCall::freeze_asset { .. }) + | RuntimeCall::Assets(AssetsCall::thaw_asset { .. }) + | RuntimeCall::Assets(AssetsCall::touch_other { .. }) + | RuntimeCall::Assets(AssetsCall::refund_other { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::force_mint { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::update_mint_settings { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::mint_pre_signed { .. }) diff --git a/runtime/devnet/src/extensions.rs b/runtime/devnet/src/extensions.rs deleted file mode 100644 index 8a2e0fbd..00000000 --- a/runtime/devnet/src/extensions.rs +++ /dev/null @@ -1,193 +0,0 @@ -use frame_support::traits::{Contains, OriginTrait}; -use frame_support::{ - dispatch::{GetDispatchInfo, RawOrigin}, - pallet_prelude::*, -}; -use pallet_contracts::chain_extension::{ - BufInBufOutState, ChainExtension, ChargedAmount, Environment, Ext, InitState, RetVal, -}; -use pallet_contracts::WeightInfo; -use pop_primitives::storage_keys::RuntimeStateKeys; -use sp_core::crypto::UncheckedFrom; -use sp_runtime::{traits::Dispatchable, DispatchError}; -use sp_std::vec::Vec; - -use crate::{AccountId, AllowedApiCalls, RuntimeCall, RuntimeOrigin}; - -const LOG_TARGET: &str = "pop-api::extension"; - -#[derive(Default)] -pub struct PopApiExtension; - -impl ChainExtension for PopApiExtension -where - T: pallet_contracts::Config - + frame_system::Config< - RuntimeOrigin = RuntimeOrigin, - AccountId = AccountId, - RuntimeCall = RuntimeCall, - >, - T::AccountId: UncheckedFrom + AsRef<[u8]>, -{ - fn call(&mut self, env: Environment) -> Result - where - E: Ext, - { - log::debug!(target:LOG_TARGET, " extension called "); - match v0::FuncId::try_from(env.func_id())? { - v0::FuncId::Dispatch => { - match dispatch::(env) { - Ok(()) => Ok(RetVal::Converging(0)), - Err(DispatchError::Module(error)) => { - // encode status code = pallet index in runtime + error index, allowing for - // 999 errors - Ok(RetVal::Converging( - (error.index as u32 * 1_000) + u32::from_le_bytes(error.error), - )) - }, - Err(e) => Err(e), - } - }, - v0::FuncId::ReadState => { - read_state::(env)?; - Ok(RetVal::Converging(0)) - }, - } - } -} - -pub mod v0 { - #[derive(Debug)] - pub enum FuncId { - Dispatch, - ReadState, - } -} - -impl TryFrom for v0::FuncId { - type Error = DispatchError; - - fn try_from(func_id: u16) -> Result { - let id = match func_id { - 0x0 => Self::Dispatch, - 0x1 => Self::ReadState, - _ => { - log::error!("called an unregistered `func_id`: {:}", func_id); - return Err(DispatchError::Other("unimplemented func_id")); - }, - }; - - Ok(id) - } -} - -fn dispatch_call( - env: &mut Environment, - call: RuntimeCall, - mut origin: RuntimeOrigin, - log_prefix: &str, -) -> Result<(), DispatchError> -where - E: Ext, -{ - let charged_dispatch_weight = env.charge_weight(call.get_dispatch_info().weight)?; - - log::debug!(target:LOG_TARGET, "{} inputted RuntimeCall: {:?}", log_prefix, call); - - origin.add_filter(AllowedApiCalls::contains); - - match call.dispatch(origin) { - Ok(info) => { - log::debug!(target:LOG_TARGET, "{} success, actual weight: {:?}", log_prefix, info.actual_weight); - - // refund weight if the actual weight is less than the charged weight - if let Some(actual_weight) = info.actual_weight { - env.adjust_weight(charged_dispatch_weight, actual_weight); - } - - Ok(()) - }, - Err(err) => { - log::debug!(target:LOG_TARGET, "{} failed: error: {:?}", log_prefix, err.error); - Err(err.error) - }, - } -} - -fn charge_overhead_weight( - env: &mut Environment, - len: u32, - log_prefix: &str, -) -> Result -where - T: pallet_contracts::Config, - E: Ext, -{ - // calculate weight for reading bytes of `len` - // reference: https://github.com/paritytech/polkadot-sdk/pull/4233/files#:~:text=CopyToContract(len)%20%3D%3E%20T%3A%3AWeightInfo%3A%3Aseal_input(len)%2C - let base_weight: Weight = T::WeightInfo::seal_return(len); - - // debug_message weight is a good approximation of the additional overhead of going - // from contract layer to substrate layer. - // reference: https://github.com/paritytech/polkadot-sdk/pull/4233/files#:~:text=DebugMessage(len)%20%3D%3E%20T%3A%3AWeightInfo%3A%3Aseal_debug_message(len)%2C - let overhead = T::WeightInfo::seal_debug_message(len); - - let charged_weight = env.charge_weight(base_weight.saturating_add(overhead))?; - log::debug!(target: LOG_TARGET, "{} charged weight: {:?}", log_prefix, charged_weight); - - Ok(charged_weight) -} - -fn dispatch(env: Environment) -> Result<(), DispatchError> -where - T: pallet_contracts::Config, - RuntimeOrigin: From>, - E: Ext, -{ - const LOG_PREFIX: &str = " dispatch |"; - - let mut env = env.buf_in_buf_out(); - let len = env.in_len(); - - charge_overhead_weight::(&mut env, len, LOG_PREFIX)?; - - // read the input as RuntimeCall - let call: RuntimeCall = env.read_as_unbounded(len)?; - - // contract is the origin by default - let origin: RuntimeOrigin = RawOrigin::Signed(env.ext().address().clone()).into(); - - dispatch_call::(&mut env, call, origin, LOG_PREFIX) -} - -fn read_state(env: Environment) -> Result<(), DispatchError> -where - T: pallet_contracts::Config, - E: Ext, -{ - const LOG_PREFIX: &str = " read_state |"; - - let mut env = env.buf_in_buf_out(); - - // To be conservative, we charge the weight for reading the input bytes of a fixed-size type. - let base_weight: Weight = T::WeightInfo::seal_return(env.in_len()); - let charged_weight = env.charge_weight(base_weight)?; - - log::debug!(target:LOG_TARGET, "{} charged weight: {:?}", LOG_PREFIX, charged_weight); - - let key: RuntimeStateKeys = env.read_as()?; - - let result = match key { - _ => Vec::::default(), - } - .encode(); - - log::trace!( - target:LOG_TARGET, - "{} result: {:?}.", LOG_PREFIX, result - ); - env.write(&result, false, None).map_err(|e| { - log::trace!(target: LOG_TARGET, "{:?}", e); - DispatchError::Other("unable to write results to contract memory") - }) -} diff --git a/runtime/devnet/src/lib.rs b/runtime/devnet/src/lib.rs index 57ef9638..e43e9d8d 100644 --- a/runtime/devnet/src/lib.rs +++ b/runtime/devnet/src/lib.rs @@ -8,7 +8,6 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); // Public due to integration tests crate. pub mod config; -mod extensions; mod weights; use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; @@ -73,6 +72,8 @@ use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}; // XCM Imports use xcm::latest::prelude::BodyId; +use pallet_api::fungibles; + /// Some way of identifying an account on the chain. We intentionally make it equivalent /// to the public key of our transaction signing scheme. pub type AccountId = <::Signer as IdentifyAccount>::AccountId; @@ -252,14 +253,6 @@ impl Contains for FilteredCalls { } } -/// A type to identify allowed calls to the Runtime from contracts. Used by Pop API -pub struct AllowedApiCalls; -impl Contains for AllowedApiCalls { - fn contains(_c: &RuntimeCall) -> bool { - false - } -} - /// The default types are being injected by [`derive_impl`](`frame_support::derive_impl`) from /// [`ParaChainDefaultConfig`](`struct@frame_system::config_preludes::ParaChainDefaultConfig`), /// but overridden as needed. @@ -633,12 +626,17 @@ mod runtime { pub type NftFractionalization = pallet_nft_fractionalization::Pallet; #[runtime::pallet_index(52)] pub type Assets = pallet_assets::Pallet; + + // Pop API + #[runtime::pallet_index(150)] + pub type Fungibles = pallet_api::fungibles::Pallet; } #[cfg(feature = "runtime-benchmarks")] mod benches { frame_benchmarking::define_benchmarks!( [frame_system, SystemBench::] + [fungibles, Fungibles] [pallet_balances, Balances] [pallet_session, SessionBench::] [pallet_timestamp, Timestamp] @@ -1003,3 +1001,22 @@ cumulus_pallet_parachain_system::register_validate_block! { Runtime = Runtime, BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, } + +#[cfg(test)] +mod tests { + use crate::Runtime; + use std::any::TypeId; + + // Ensures that the account id lookup does not perform any state reads. When this changes, + // `pallet_api::fungibles` dispatchables need to be re-evaluated. + #[test] + fn test_lookup_config() { + type ExpectedLookup = sp_runtime::traits::AccountIdLookup; + type ConfigLookup = ::Lookup; + + let expected_type_id = TypeId::of::(); + let config_type_id = TypeId::of::(); + + assert_eq!(config_type_id, expected_type_id); + } +} diff --git a/runtime/testnet/Cargo.toml b/runtime/testnet/Cargo.toml index 9d33d3ef..f6ca1806 100644 --- a/runtime/testnet/Cargo.toml +++ b/runtime/testnet/Cargo.toml @@ -23,7 +23,7 @@ smallvec.workspace = true # Local pop-primitives.workspace = true -pop-runtime-common = { workspace = true, default-features = false } +pop-runtime-common.workspace = true # Substrate frame-benchmarking.workspace = true @@ -92,7 +92,6 @@ parachain-info.workspace = true [dev-dependencies] env_logger = "0.11.2" hex = "0.4.3" -enumflags2 = "0.7.9" [features] default = ["std"] diff --git a/runtime/testnet/src/config/assets.rs b/runtime/testnet/src/config/assets.rs index 34035c1f..2c8ea952 100644 --- a/runtime/testnet/src/config/assets.rs +++ b/runtime/testnet/src/config/assets.rs @@ -84,8 +84,8 @@ impl pallet_nft_fractionalization::Config for Runtime { type StringLimit = AssetsStringLimit; type NftCollectionId = ::CollectionId; type NftId = ::ItemId; - type AssetBalance = >::Balance; - type AssetId = >::AssetId; + type AssetBalance = >::Balance; + type AssetId = >::AssetId; type Assets = Assets; type Nfts = Nfts; type PalletId = NftFractionalizationPalletId; @@ -95,9 +95,9 @@ impl pallet_nft_fractionalization::Config for Runtime { type BenchmarkHelper = (); } -pub type TrustBackedAssets = pallet_assets::Instance1; -pub type TrustBackedAssetsCall = pallet_assets::Call; -impl pallet_assets::Config for Runtime { +pub type TrustBackedAssetsInstance = pallet_assets::Instance1; +pub(crate) type AssetsCall = pallet_assets::Call; +impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; type AssetId = AssetIdForTrustBackedAssets; diff --git a/runtime/testnet/src/config/proxy.rs b/runtime/testnet/src/config/proxy.rs index a4fd479a..07d5f0f8 100644 --- a/runtime/testnet/src/config/proxy.rs +++ b/runtime/testnet/src/config/proxy.rs @@ -1,4 +1,4 @@ -use super::assets::TrustBackedAssetsCall; +use super::assets::AssetsCall; use crate::{Balances, Runtime, RuntimeCall, RuntimeEvent}; use frame_support::traits::InstanceFilter; use pop_runtime_common::proxy::{ @@ -34,16 +34,16 @@ impl InstanceFilter for ProxyType { }, ProxyType::AssetOwner => matches!( c, - RuntimeCall::Assets(TrustBackedAssetsCall::create { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::start_destroy { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::destroy_accounts { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::destroy_approvals { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::finish_destroy { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::transfer_ownership { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::set_team { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::set_metadata { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::clear_metadata { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::set_min_balance { .. }) + RuntimeCall::Assets(AssetsCall::create { .. }) + | RuntimeCall::Assets(AssetsCall::start_destroy { .. }) + | RuntimeCall::Assets(AssetsCall::destroy_accounts { .. }) + | RuntimeCall::Assets(AssetsCall::destroy_approvals { .. }) + | RuntimeCall::Assets(AssetsCall::finish_destroy { .. }) + | RuntimeCall::Assets(AssetsCall::transfer_ownership { .. }) + | RuntimeCall::Assets(AssetsCall::set_team { .. }) + | RuntimeCall::Assets(AssetsCall::set_metadata { .. }) + | RuntimeCall::Assets(AssetsCall::clear_metadata { .. }) + | RuntimeCall::Assets(AssetsCall::set_min_balance { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::create { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::destroy { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::redeposit { .. }) @@ -56,15 +56,15 @@ impl InstanceFilter for ProxyType { ), ProxyType::AssetManager => matches!( c, - RuntimeCall::Assets(TrustBackedAssetsCall::mint { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::burn { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::freeze { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::block { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::thaw { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::freeze_asset { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::thaw_asset { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::touch_other { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::refund_other { .. }) + RuntimeCall::Assets(AssetsCall::mint { .. }) + | RuntimeCall::Assets(AssetsCall::burn { .. }) + | RuntimeCall::Assets(AssetsCall::freeze { .. }) + | RuntimeCall::Assets(AssetsCall::block { .. }) + | RuntimeCall::Assets(AssetsCall::thaw { .. }) + | RuntimeCall::Assets(AssetsCall::freeze_asset { .. }) + | RuntimeCall::Assets(AssetsCall::thaw_asset { .. }) + | RuntimeCall::Assets(AssetsCall::touch_other { .. }) + | RuntimeCall::Assets(AssetsCall::refund_other { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::force_mint { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::update_mint_settings { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::mint_pre_signed { .. }) diff --git a/runtime/testnet/src/extensions.rs b/runtime/testnet/src/extensions.rs index 9e5af893..5b960785 100644 --- a/runtime/testnet/src/extensions.rs +++ b/runtime/testnet/src/extensions.rs @@ -7,7 +7,6 @@ use pallet_contracts::chain_extension::{ BufInBufOutState, ChainExtension, ChargedAmount, Environment, Ext, InitState, RetVal, }; use pallet_contracts::WeightInfo; -use pop_primitives::storage_keys::RuntimeStateKeys; use sp_core::crypto::UncheckedFrom; use sp_runtime::{traits::Dispatchable, DispatchError}; use sp_std::vec::Vec; @@ -175,12 +174,9 @@ where log::debug!(target:LOG_TARGET, "{} charged weight: {:?}", LOG_PREFIX, charged_weight); - let key: RuntimeStateKeys = env.read_as()?; - - let result = match key { - _ => Vec::::default(), - } - .encode(); + // TODO: always returning an empty vec. Chainextension will be refactored into one for both + // runtimes before pop api implementation gets merged into main. + let result = Vec::::default().encode(); log::trace!( target:LOG_TARGET, diff --git a/scripts/pallet-weights-template.hbs b/scripts/pallet-weights-template.hbs new file mode 100644 index 00000000..9e1e5a46 --- /dev/null +++ b/scripts/pallet-weights-template.hbs @@ -0,0 +1,122 @@ +{{header}} +//! Autogenerated weights for `{{pallet}}` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION {{version}} +//! DATE: {{date}}, STEPS: `{{cmd.steps}}`, REPEAT: `{{cmd.repeat}}`, LOW RANGE: `{{cmd.lowest_range_values}}`, HIGH RANGE: `{{cmd.highest_range_values}}` +//! WORST CASE MAP SIZE: `{{cmd.worst_case_map_values}}` +//! HOSTNAME: `R0GUE`, CPU: `{{cpuname}}` +//! WASM-EXECUTION: `{{cmd.wasm_execution}}`, CHAIN: `{{cmd.chain}}`, DB CACHE: `{{cmd.db_cache}}` + +// Executed Command: +{{#each args as |arg|}} +// {{arg}} +{{/each}} + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use core::marker::PhantomData; + +/// Weight functions needed for `{{pallet}}`. +pub trait WeightInfo { + {{#each benchmarks as |benchmark|}} + fn {{benchmark.name~}} + ( + {{~#each benchmark.components as |c| ~}} + {{c.name}}: u32, {{/each~}} + ) -> Weight; + {{/each}} +} + +/// Weights for `{{pallet}}` using the Substrate node and recommended hardware. +pub struct SubstrateWeight(PhantomData); +{{#if (eq pallet "frame_system")}} +impl WeightInfo for SubstrateWeight { +{{else}} +impl WeightInfo for SubstrateWeight { +{{/if}} + {{#each benchmarks as |benchmark|}} + {{#each benchmark.comments as |comment|}} + /// {{comment}} + {{/each}} + {{#each benchmark.component_ranges as |range|}} + /// The range of component `{{range.name}}` is `[{{range.min}}, {{range.max}}]`. + {{/each}} + fn {{benchmark.name~}} + ( + {{~#each benchmark.components as |c| ~}} + {{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}} + ) -> Weight { + // Proof Size summary in bytes: + // Measured: `{{benchmark.base_recorded_proof_size}}{{#each benchmark.component_recorded_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}` + // Estimated: `{{benchmark.base_calculated_proof_size}}{{#each benchmark.component_calculated_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}` + // Minimum execution time: {{underscore benchmark.min_execution_time}}_000 picoseconds. + Weight::from_parts({{underscore benchmark.base_weight}}, {{benchmark.base_calculated_proof_size}}) + {{#each benchmark.component_weight as |cw|}} + // Standard Error: {{underscore cw.error}} + .saturating_add(Weight::from_parts({{underscore cw.slope}}, 0).saturating_mul({{cw.name}}.into())) + {{/each}} + {{#if (ne benchmark.base_reads "0")}} + .saturating_add(T::DbWeight::get().reads({{benchmark.base_reads}}_u64)) + {{/if}} + {{#each benchmark.component_reads as |cr|}} + .saturating_add(T::DbWeight::get().reads(({{cr.slope}}_u64).saturating_mul({{cr.name}}.into()))) + {{/each}} + {{#if (ne benchmark.base_writes "0")}} + .saturating_add(T::DbWeight::get().writes({{benchmark.base_writes}}_u64)) + {{/if}} + {{#each benchmark.component_writes as |cw|}} + .saturating_add(T::DbWeight::get().writes(({{cw.slope}}_u64).saturating_mul({{cw.name}}.into()))) + {{/each}} + {{#each benchmark.component_calculated_proof_size as |cp|}} + .saturating_add(Weight::from_parts(0, {{cp.slope}}).saturating_mul({{cp.name}}.into())) + {{/each}} + } + {{/each}} +} + +// For backwards compatibility and tests. +impl WeightInfo for () { + {{#each benchmarks as |benchmark|}} + {{#each benchmark.comments as |comment|}} + /// {{comment}} + {{/each}} + {{#each benchmark.component_ranges as |range|}} + /// The range of component `{{range.name}}` is `[{{range.min}}, {{range.max}}]`. + {{/each}} + fn {{benchmark.name~}} + ( + {{~#each benchmark.components as |c| ~}} + {{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}} + ) -> Weight { + // Proof Size summary in bytes: + // Measured: `{{benchmark.base_recorded_proof_size}}{{#each benchmark.component_recorded_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}` + // Estimated: `{{benchmark.base_calculated_proof_size}}{{#each benchmark.component_calculated_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}` + // Minimum execution time: {{underscore benchmark.min_execution_time}}_000 picoseconds. + Weight::from_parts({{underscore benchmark.base_weight}}, {{benchmark.base_calculated_proof_size}}) + {{#each benchmark.component_weight as |cw|}} + // Standard Error: {{underscore cw.error}} + .saturating_add(Weight::from_parts({{underscore cw.slope}}, 0).saturating_mul({{cw.name}}.into())) + {{/each}} + {{#if (ne benchmark.base_reads "0")}} + .saturating_add(RocksDbWeight::get().reads({{benchmark.base_reads}}_u64)) + {{/if}} + {{#each benchmark.component_reads as |cr|}} + .saturating_add(RocksDbWeight::get().reads(({{cr.slope}}_u64).saturating_mul({{cr.name}}.into()))) + {{/each}} + {{#if (ne benchmark.base_writes "0")}} + .saturating_add(RocksDbWeight::get().writes({{benchmark.base_writes}}_u64)) + {{/if}} + {{#each benchmark.component_writes as |cw|}} + .saturating_add(RocksDbWeight::get().writes(({{cw.slope}}_u64).saturating_mul({{cw.name}}.into()))) + {{/each}} + {{#each benchmark.component_calculated_proof_size as |cp|}} + .saturating_add(Weight::from_parts(0, {{cp.slope}}).saturating_mul({{cp.name}}.into())) + {{/each}} + } + {{/each}} +} +